Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add drawing generation and improve annotation layout
Yuechen Lic5b61fc64351
diff --git a/Aetheris.CLI.Tests/DrawingGenerationCliTests.cs b/Aetheris.CLI.Tests/DrawingGenerationCliTests.csnew file mode 100644index 00000000..7fa7c503--- /dev/null+++ b/Aetheris.CLI.Tests/DrawingGenerationCliTests.cs@@ -0,0 +1,39 @@+using System.Text.Json;++namespace Aetheris.CLI.Tests;++public sealed class DrawingGenerationCliTests+{+ [Fact]+ public void GenerateProducesPdfSvgPptxAndHonestLayoutEvidence()+ {+ var root = new DirectoryInfo(AppContext.BaseDirectory);+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx"))) root = root.Parent;+ var output = Path.Combine(root!.FullName, "artifacts/local/tests/drawing-cli", Guid.NewGuid().ToString("N"));+ try+ {+ 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));+ using var json = JsonDocument.Parse(stdout.ToString()); var result = json.RootElement;+ Assert.True(result.GetProperty("success").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()!));+ var roles = ir.RootElement.GetProperty("metadata").GetProperty("signoff");+ Assert.Equal("Codex (AI)", roles.GetProperty("drawn").GetProperty("name").GetString());+ Assert.Equal(JsonValueKind.Null, roles.GetProperty("approved").GetProperty("name").ValueKind);+ Assert.Equal("", stderr.ToString());+ }+ finally { if (Directory.Exists(output)) Directory.Delete(output, true); }+ }++ [Fact]+ public void DrawingHelpAdvertisesGenerationAlongsideAuthoredCompilation()+ {+ using var stdout = new StringWriter(); using var stderr = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["drawing", "--help"], stdout, stderr));+ Assert.Contains("generate", stdout.ToString(), StringComparison.Ordinal);+ Assert.Contains("compile", stdout.ToString(), StringComparison.Ordinal);+ }+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 9009b420..e7f9637d 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -167,7 +167,7 @@ public static class CliRunnerprivate 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 <drawing.firmament> --out-dir <directory> [--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] | 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]";@@ -1164,13 +1164,13 @@ Model CanonicalPanel {private static int RunDrawing(string[] args, TextWriter stdout, TextWriter stderr){- if (args.Length > 0 && args[0] is not "compile") return DrawingNotesCli.Run(args, stdout, stderr);+ if (args.Length > 0 && args[0] is not ("compile" or "generate") && !IsHelpFlag(args[0])) return DrawingNotesCli.Run(args, stdout, stderr);if (args.Length == 0 || IsHelpFlag(args[0])){(args.Length == 0 ? stderr : stdout).WriteLine(DrawingUsage);return args.Length == 0 ? 1 : 0;}- if (!string.Equals(args[0], "compile", StringComparison.Ordinal) || args.Length < 2)+ if (args[0] is not ("compile" or "generate") || args.Length < 2){stderr.WriteLine(DrawingUsage);return 1;@@ -1178,14 +1178,21 @@ Model CanonicalPanel {var source = args[1];string? output = null;var json = false;+ var signoffValues = new Dictionary<string, string>(StringComparer.Ordinal);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] 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; }}- output ??= Path.Combine(Path.GetDirectoryName(Path.GetFullPath(source))!, "drawing-output");- var result = FirmamentDrawingCompiler.Compile(source, output);+ output ??= Path.GetFullPath(Path.Combine("artifacts", "local", "drawing", Path.GetFileNameWithoutExtension(source)));+ DrawingSignoffIr? signoff = signoffValues.Count == 0 ? null : new(+ 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 (!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));diff --git a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs b/Aetheris.Kernel.Core/Step242/Step242Exporter.csindex ed42e347..15ca18f6 100644--- a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs@@ -545,7 +545,7 @@ public static class Step242Exportervar propertyDefinitionId = writer.AddEntity("PROPERTY_DEFINITION",Step242TextWriter.String($"diameter:{hole.FeatureId}"),- Step242TextWriter.String("semantic PMI diameter"),+ Step242TextWriter.String(hole.Name is null ? "semantic PMI diameter" : $"semantic PMI diameter name={hole.Name}"),Step242TextWriter.Ref(featureShapeAspectId));var measureItemId = writer.AddEntity("MEASURE_REPRESENTATION_ITEM",diff --git a/Aetheris.Kernel.Core/Step242/Step242SemanticPmi.cs b/Aetheris.Kernel.Core/Step242/Step242SemanticPmi.csindex a767773d..83ee12ae 100644--- a/Aetheris.Kernel.Core/Step242/Step242SemanticPmi.cs+++ b/Aetheris.Kernel.Core/Step242/Step242SemanticPmi.cs@@ -13,7 +13,10 @@ public sealed record Step242SemanticPmiHole(string? HoleFamily,double? TolerancePlus,double? ToleranceMinus,- int? Quantity = null) : Step242SemanticPmi(FeatureId);+ int? Quantity = null) : Step242SemanticPmi(FeatureId)+{+ public string? Name { get; init; }+}public sealed record Step242SemanticPmiDimension(string FeatureId,diff --git a/Aetheris.Kernel.Core/Step242/Step242SemanticPmiInspector.cs b/Aetheris.Kernel.Core/Step242/Step242SemanticPmiInspector.csindex 297c92a8..9700d3b8 100644--- a/Aetheris.Kernel.Core/Step242/Step242SemanticPmiInspector.cs+++ b/Aetheris.Kernel.Core/Step242/Step242SemanticPmiInspector.cs@@ -13,6 +13,9 @@ public sealed record Step242SemanticPmiInspectionItem(string? Text){public IReadOnlyList<int> GeometricFaceEntityIds { get; init; } = [];+ public string? DimensionKind { get; init; }+ public string? AuthoredName { get; init; }+ public double? Depth { get; init; }}public sealed record Step242SemanticPmiInspectionResult(@@ -71,7 +74,9 @@ public static class Step242SemanticPmiInspectortarget = propertyName["diameter:".Length..];var nominal = representations.GetValueOrDefault(propertyName);var tolerance = representations.GetValueOrDefault($"diameter_tolerance:{target}");- items.Add(new(entity.Id, "Diameter", propertyName, target, nominal?.FirstOrDefault(), tolerance?.ElementAtOrDefault(0), tolerance?.ElementAtOrDefault(1), Quantity(quantities, target), [], null));+ var name = String(property, 1) is { } description && description.Length > 27 && description.StartsWith("semantic PMI diameter name=", StringComparison.Ordinal)+ ? description[27..] : null;+ items.Add(new Step242SemanticPmiInspectionItem(entity.Id, "Diameter", propertyName, target, nominal is { Count: > 0 } ? nominal[0] : null, tolerance?.ElementAtOrDefault(0), tolerance?.ElementAtOrDefault(1), Quantity(quantities, target), [], null) { AuthoredName = name, Depth = representations.GetValueOrDefault($"depth:{target}") is { Count: > 0 } depths ? depths[0] : null });}else if (propertyName.StartsWith("dimension:", StringComparison.Ordinal)){@@ -81,7 +86,9 @@ public static class Step242SemanticPmiInspectortarget = parts[2];var nominal = representations.GetValueOrDefault($"dimension:{name}");var tolerance = representations.GetValueOrDefault($"dimension_tolerance:{name}");- items.Add(new(entity.Id, "Dimension", name, target, nominal?.FirstOrDefault(), tolerance?.ElementAtOrDefault(0), tolerance?.ElementAtOrDefault(1), Quantity(quantities, target), [], null));+ items.Add(new Step242SemanticPmiInspectionItem(entity.Id, "Dimension", name, target, nominal is { Count: > 0 } ? nominal[0] : null, tolerance?.ElementAtOrDefault(0), tolerance?.ElementAtOrDefault(1), Quantity(quantities, target), [], null)+ { DimensionKind = String(property, 1) is { } description && description.StartsWith("semantic PMI ", StringComparison.Ordinal)+ && description.Length > 23 && description.EndsWith(" dimension", StringComparison.Ordinal) ? description[13..^10] : null });}else if (propertyName.StartsWith("note:", StringComparison.Ordinal)){diff --git a/Aetheris.Kernel.Core/Visualization/BrepWireframeSvgRenderer.cs b/Aetheris.Kernel.Core/Visualization/BrepWireframeSvgRenderer.csindex 9cfb375d..a9ec6143 100644--- a/Aetheris.Kernel.Core/Visualization/BrepWireframeSvgRenderer.cs+++ b/Aetheris.Kernel.Core/Visualization/BrepWireframeSvgRenderer.cs@@ -40,6 +40,11 @@ public sealed record BrepWireframeEvidence(public sealed record BrepWireframeResult(string Svg, BrepWireframeEvidence Evidence);+/// <summary>World-space presentation samples; exact topology remains authority.</summary>+public sealed record BrepWireframePolyline(string Identity, IReadOnlyList<Point3D> Points, int? EdgeId = null, int? FaceId = null);+public sealed record BrepWireframeGeometry(IReadOnlyList<BrepWireframePolyline> Boundaries,+ IReadOnlyList<BrepWireframePolyline> Isolines, BrepWireframeEvidence Evidence);+/// <summary>/// Deterministic diagnostic SVG renderer for exact BRep models. Topology edges are sampled from/// their authoritative 3D curves. Face isolines are sampled from exact supports and clipped in UV@@ -65,6 +70,17 @@ public static class BrepWireframeSvgRenderer}public static BrepWireframeResult Render(BrepBody body, BrepWireframeOptions? options = null)+ {+ options ??= new();+ var geometry = SampleGeometry(body, options);+ var boundaries = geometry.Boundaries.Select(line => line.Points).ToArray();+ var iso = geometry.Isolines.Select(line => line.Points).ToArray();+ var svg = ComposeSvg(boundaries.Concat(iso).SelectMany(points => points).ToArray(), iso, boundaries, options);+ var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(svg))).ToLowerInvariant();+ return new(svg, geometry.Evidence with { Sha256 = hash });+ }++ public static BrepWireframeGeometry SampleGeometry(BrepBody body, BrepWireframeOptions? options = null){ArgumentNullException.ThrowIfNull(body);options ??= new();@@ -81,6 +97,8 @@ public static class BrepWireframeSvgRenderervar families = body.Topology.Faces.Select(face => body.TryGetFaceSurfaceGeometry(face.Id, out var surface) ? surface?.Kind.ToString() ?? "Unbound" : "Unbound").GroupBy(name => name, StringComparer.Ordinal).ToDictionary(group => group.Key, group => group.Count(), StringComparer.Ordinal);var trimmedFaces = 0;+ var boundaryOwners = new List<int>();+ var isoOwners = new List<int>();foreach (var edge in body.Topology.Edges.OrderBy(edge => edge.Id.Value)){@@ -90,7 +108,7 @@ public static class BrepWireframeSvgRenderervar interval = binding.TrimInterval ?? CurveDomain(curve);if (interval is null) continue;var points = SampleCurve(curve, interval.Value, options.CurveSamples).ToArray();- if (points.Length > 1) boundaries.Add(points);+ if (points.Length > 1) { boundaries.Add(points); boundaryOwners.Add(edge.Id.Value); }}foreach (var face in body.Topology.Faces.OrderBy(face => face.Id.Value))@@ -113,15 +131,15 @@ public static class BrepWireframeSvgRenderervar v = v0 + (v1 - v0) * line / options.Density;AddTrimmedIso(iso, loops, options.CurveSamples, t => new(u0 + (u1 - u0) * t, v), point => Evaluate(surface, point.U, point.V));}- if (iso.Count > before) trimmedFaces++;+ if (iso.Count > before) { trimmedFaces++; isoOwners.AddRange(Enumerable.Repeat(face.Id.Value, iso.Count - before)); }}var all = boundaries.Concat(iso).SelectMany(points => points).ToArray();if (all.Length == 0) throw new InvalidOperationException("The BRep contains no renderable bound curves or trimmed surface supports.");- var svg = ComposeSvg(all, iso, boundaries, options);- var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(svg))).ToLowerInvariant();- return new(svg, new(options.View, options.Density, body.Topology.Faces.Count(), trimmedFaces,- body.Topology.Edges.Count(), iso.Count, boundaries.Count, families, unsupported.ToArray(), unsupportedCurves.ToArray(), hash));+ return new(boundaries.Select((points, i) => new BrepWireframePolyline($"edge:{boundaryOwners[i]}", points, boundaryOwners[i])).ToArray(),+ iso.Select((points, i) => new BrepWireframePolyline($"face:{isoOwners[i]}:iso:{i}", points, FaceId: isoOwners[i])).ToArray(),+ new(options.View, options.Density, body.Topology.Faces.Count(), trimmedFaces,+ body.Topology.Edges.Count(), iso.Count, boundaries.Count, families, unsupported.ToArray(), unsupportedCurves.ToArray(), ""));}private static IEnumerable<IReadOnlyList<SurfaceParameterPoint>> TrimLoops(BrepBody body, Face face)diff --git a/Aetheris.Kernel.Firmament.Tests/DrawingGenerationTests.cs b/Aetheris.Kernel.Firmament.Tests/DrawingGenerationTests.csnew file mode 100644index 00000000..8d8843ad--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/DrawingGenerationTests.cs@@ -0,0 +1,266 @@+using System.Text.RegularExpressions;+using Aetheris.Kernel.Firmament.Drawing;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class DrawingGenerationTests+{+ [Fact]+ public void PartAndAp242ProduceTheSameLocatedPmiAndGeometry()+ {+ using var scratch = new Scratch();+ var part = FirmamentDrawingCompiler.Generate(Fixture(), Path.Combine(scratch.Path, "part"));+ Assert.True(part.IsSuccess, string.Join("\n", part.Diagnostics));+ var compiled = FirmamentBuildAndExport.CompileSource(File.ReadAllText(Fixture()));+ Assert.True(compiled.IsSuccess);+ var readback = Aetheris.Kernel.Core.Step242.Step242SemanticPmiInspector.Inspect(compiled.Value.StepText);+ Assert.All(readback.Items.Where(i => i.Kind == "Diameter"), i => Assert.StartsWith("diameter:", i.Name));+ Assert.Equal(10, readback.Items.Count(i => i.AuthoredName is not null));+ var step = Path.Combine(scratch.Path, "InspectionPlate.step"); File.WriteAllText(step, compiled.Value.StepText);+ 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+ 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(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));+ Assert.Equal(0, drawing.LayoutEvidence.TextModelCollisionsAfter);+ 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.DimensionLines.Count > 0);+ Assert.Contains(drawing.Pages.SelectMany(p => p.Views).SelectMany(v => v.Primitives), p => p.Kind == DrawingPrimitiveKind.SurfaceGrid);+ 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)+ {+ var labels = page.Annotations.Select(a => a.SelectedCandidate.Body).ToArray();+ for (var i = 0; i < labels.Length; i++) for (var j = i + 1; j < labels.Length; j++) Assert.False(labels[i].Intersects(labels[j]));+ }+ 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);+ }++ [Fact]+ public void UnlocatedPmiRejectsRatherThanInventingACenterLeader()+ {+ using var scratch = new Scratch();+ var compiled = FirmamentBuildAndExport.CompileSource(File.ReadAllText(Fixture())); Assert.True(compiled.IsSuccess);+ var step = Regex.Replace(compiled.Value.StepText, @"(?m)^.*=GEOMETRIC_ITEM_SPECIFIC_USAGE\(.*\r?\n?", "");+ Assert.NotEqual(compiled.Value.StepText, step);+ var source = Path.Combine(scratch.Path, "unlocated.step"); File.WriteAllText(source, step);+ var output = Path.Combine(scratch.Path, "out");+ var result = FirmamentDrawingCompiler.Generate(source, output);+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, d => d.StartsWith("drawing-pmi-target-unlocated:", StringComparison.Ordinal));+ Assert.False(Directory.Exists(output));+ }++ [Fact]+ public void GenerationIsDeterministicAndDoesNotMutateSource()+ {+ using var scratch = new Scratch(); var before = File.ReadAllBytes(Fixture());+ var a = FirmamentDrawingCompiler.Generate(Fixture(), Path.Combine(scratch.Path, "a"));+ var b = FirmamentDrawingCompiler.Generate(Fixture(), Path.Combine(scratch.Path, "b"));+ Assert.True(a.IsSuccess, string.Join("\n", a.Diagnostics)); Assert.True(b.IsSuccess, string.Join("\n", b.Diagnostics));+ Assert.Equal(a.Artifacts!.PdfSha256, b.Artifacts!.PdfSha256);+ Assert.Equal(a.Artifacts.DrawingIrSha256, b.Artifacts.DrawingIrSha256);+ Assert.Equal(a.Artifacts.PptxSha256, b.Artifacts.PptxSha256);+ Assert.Equal(before, File.ReadAllBytes(Fixture()));+ }++ [Fact]+ public void GeometryWithoutPmiIsExplicitlyLabeled()+ {+ using var scratch = new Scratch(); var path = Path.Combine(scratch.Path, "plain.firmament");+ 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));+ }++ [Fact]+ public void LongCalloutUsesItsActualFontWidth()+ {+ 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"));+ 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);+ }++ [Fact]+ public void ForeignPmiUnitsCannotBeMislabeledAsMillimetres()+ {+ using var scratch = new Scratch();+ var compiled = FirmamentBuildAndExport.CompileSource(File.ReadAllText(Fixture())); Assert.True(compiled.IsSuccess);+ var text = compiled.Value.StepText.Replace(".MILLI.,.METRE.", ".CENTI.,.METRE.", StringComparison.Ordinal);+ Assert.NotEqual(compiled.Value.StepText, text);+ var path = Path.Combine(scratch.Path, "centimetres.step"); File.WriteAllText(path, text);+ var result = FirmamentDrawingCompiler.Generate(path, Path.Combine(scratch.Path, "out"));+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, d => d.StartsWith("drawing-pmi-units-unsupported:", StringComparison.Ordinal));+ }++ [Fact]+ public void HoleDepthAlreadyPresentInAp242SurvivesTheDrawing()+ {+ using var scratch = new Scratch();+ var compiled = FirmamentBuildAndExport.CompileSource(File.ReadAllText(Fixture())); Assert.True(compiled.IsSuccess);+ var body = Aetheris.Kernel.Core.Step242.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 = Aetheris.Kernel.Core.Step242.Step242Exporter.ExportBody(body,+ [new Aetheris.Kernel.Core.Step242.Step242SemanticPmiHole("Stock.H1", 4, 8, "through", .05, .02) { GeometricFaceIds = [wall.Id.Value] }]);+ Assert.True(exported.IsSuccess);+ 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));+ }++ [Fact]+ public void SignoffUsesARealTableWithBlankUnperformedApprovals()+ {+ using var scratch = new Scratch();+ var signoff = new DrawingSignoffIr(new("Codex (AI)", "2026-10-18"), new(), new());+ var result = FirmamentDrawingCompiler.Generate(Fixture(), Path.Combine(scratch.Path, "out"), signoff);+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));+ foreach (var page in result.Artifacts!.Drawing.Pages)+ {+ var table = page.InformationBlock!.Table!; Assert.NotNull(table);+ Assert.Equal(5, table.Rows.Count);+ Assert.All(table.Rows, row => Assert.Equal(6, row.Cells.Sum(c => c.ColumnSpan)));+ var cells = table.Rows.SelectMany(r => r.Cells).ToDictionary(c => c.Key);+ Assert.Equal("Codex (AI)", cells["DrawnBy"].Value); Assert.Equal("2026-10-18", cells["DrawnDate"].Value);+ foreach (var key in new[] { "CheckedBy", "CheckedDate", "ApprovedBy", "ApprovedDate" }) Assert.Equal("", cells[key].Value);+ }+ using var archive = System.IO.Compression.ZipFile.OpenRead(result.Artifacts.PptxPath);+ var slides = archive.Entries.Where(e => e.FullName.StartsWith("ppt/slides/slide", StringComparison.Ordinal) && e.FullName.EndsWith(".xml", StringComparison.Ordinal)).ToArray();+ foreach (var slide in slides)+ {+ 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"));+ Assert.Equal(6, table.Descendants(a + "gridCol").Count());+ Assert.All(table.Elements(a + "tr"), row => Assert.Equal(6, row.Elements(a + "tc").Count()));+ }+ using var core = new StreamReader(archive.GetEntry("docProps/core.xml")!.Open());+ Assert.Contains("Codex (AI)", core.ReadToEnd(), StringComparison.Ordinal);+ }++ [Theory]+ [InlineData("Checker", null, "drawing-signoff-incomplete")]+ [InlineData(null, "2026-10-18", "drawing-signoff-incomplete")]+ [InlineData("Checker", "yesterday", "drawing-date-iso-invalid")]+ public void SignoffCannotInventAMissingPersonOrDate(string? name, string? date, string code)+ {+ using var scratch = new Scratch();+ var result = FirmamentDrawingCompiler.Generate(Fixture(), Path.Combine(scratch.Path, "out"), new(new(), new(name, date), new()));+ Assert.False(result.IsSuccess); Assert.Contains(result.Diagnostics, d => d.StartsWith(code, StringComparison.Ordinal));+ Assert.False(Directory.Exists(Path.Combine(scratch.Path, "out")));+ }++ [Fact]+ public void LargeDiameterWitnessMeasuresTheActualProjectedCylinder()+ {+ using var scratch = new Scratch(); var path = Path.Combine(scratch.Path, "large-bore.firmament");+ File.WriteAllText(path, """+ Model Bore {+ units: mm+ Box Stock { size: [40mm, 30mm, 8mm] }+ Modify Stock {+ Hole<Shaft> H { on: +Z; center: Point2(0mm, 0mm); diameter: 12mm; end: ThroughAll }+ }+ Pmi {+ HoleDiameter BoreSize {+ target: face(H.Wall)+ value: 12mm+ }+ }+ }+ """);+ var result = FirmamentDrawingCompiler.Generate(path, Path.Combine(scratch.Path, "out"));+ 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);+ var line = Assert.Single(annotation.DimensionLines); var scale = page.Views.Single().Scale;+ Assert.Equal(12, Math.Abs(line.End.X - line.Start.X) / scale, 8);+ Assert.Equal(line.Start.Y, line.End.Y, 8);+ Assert.True(line.ArrowStart && line.ArrowEnd);+ }++ [Fact]+ public void AuthoredMetadataCarriesCheckerAndDateWithoutAnApproval()+ {+ using var scratch = new Scratch();+ var source = File.ReadAllText(Path.Combine(Root(), "fixtures/Canonical/Drawings/bearing-block-production-drawing.firmament"))+ .Replace("Material: String", "Material: String\n DrawnBy: String\n DrawnDate: Date\n CheckedBy: String\n CheckedDate: Date", StringComparison.Ordinal)+ .Replace("Material: \"PER PRODUCT\"", "Material: \"PER PRODUCT\"\n DrawnBy: \"Test Preparer\"\n DrawnDate: 2026-10-18\n CheckedBy: \"Test Checker\"\n CheckedDate: 2026-10-18", StringComparison.Ordinal);+ var path = Path.Combine(scratch.Path, "checked.firmament"); File.WriteAllText(path, source);+ var result = FirmamentDrawingCompiler.Compile(path, Path.Combine(scratch.Path, "out"));+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));+ Assert.Equal("Test Checker", result.Artifacts!.Drawing.Metadata.Signoff!.Checked.Name);+ Assert.Equal("2026-10-18", result.Artifacts.Drawing.Metadata.Signoff.Checked.Date);+ Assert.Null(result.Artifacts.Drawing.Metadata.Signoff.Approved.Name);+ Assert.Equal("Test Preparer", result.Artifacts.Drawing.Metadata.Signoff.Drawn.Name);+ Assert.Contains("/Author (Test Preparer)", File.ReadAllText(result.Artifacts.PdfPath), StringComparison.Ordinal);+ }++ [Fact]+ public void MissingNominalDoesNotBecomeAnImaginaryZeroDimension()+ {+ using var scratch = new Scratch();+ var compiled = FirmamentBuildAndExport.CompileSource(File.ReadAllText(Fixture())); Assert.True(compiled.IsSuccess);+ var text = compiled.Value.StepText.Replace("MEASURE_REPRESENTATION_ITEM('diameter',4,", "MEASURE_REPRESENTATION_ITEM('diameter',$,", StringComparison.Ordinal);+ Assert.NotEqual(compiled.Value.StepText, text);+ var path = Path.Combine(scratch.Path, "missing-nominal.step"); File.WriteAllText(path, text);+ var result = FirmamentDrawingCompiler.Generate(path, Path.Combine(scratch.Path, "out"));+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, d => d.StartsWith("drawing-pmi-value-unavailable:", StringComparison.Ordinal));+ }++ [Theory]+ [InlineData("Angle", false)]+ [InlineData("diameter", true)]+ public void DimensionKindControlsAdmissionAndPresentation(string kind, bool admitted)+ {+ using var scratch = new Scratch();+ var compiled = FirmamentBuildAndExport.CompileSource(File.ReadAllText(Fixture())); Assert.True(compiled.IsSuccess);+ var body = Aetheris.Kernel.Core.Step242.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 = Aetheris.Kernel.Core.Step242.Step242Exporter.ExportBody(body,+ [new Aetheris.Kernel.Core.Step242.Step242SemanticPmiDimension("Stock.H1", "Size", kind, 4, null, null) { GeometricFaceIds = [wall.Id.Value] }]);+ Assert.True(exported.IsSuccess);+ var path = Path.Combine(scratch.Path, "kind.step"); File.WriteAllText(path, exported.Value);+ var result = FirmamentDrawingCompiler.Generate(path, Path.Combine(scratch.Path, "out"));+ 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));+ else+ {+ Assert.Contains(result.Diagnostics, d => d.StartsWith("drawing-pmi-family-unsupported:", StringComparison.Ordinal));+ Assert.False(Directory.Exists(Path.Combine(scratch.Path, "out")));+ }+ }++ private static string Root()+ {+ var d = new DirectoryInfo(AppContext.BaseDirectory);+ while (d is not null && !File.Exists(System.IO.Path.Combine(d.FullName, "Aetheris.slnx"))) d = d.Parent;+ return d!.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-generation", Guid.NewGuid().ToString("N"));+ public Scratch() => Directory.CreateDirectory(Path);+ public void Dispose() => Directory.Delete(Path, true);+ }+}diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingAnnotationGeometry.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingAnnotationGeometry.csnew file mode 100644index 00000000..c9de2fb9--- /dev/null+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingAnnotationGeometry.cs@@ -0,0 +1,28 @@+namespace Aetheris.Kernel.Firmament.Drawing;++/// <summary>Shared paper-space annotation strokes for PDF, SVG and editable PPTX.</summary>+internal static class DrawingAnnotationGeometry+{+ public static IEnumerable<DrawingDimensionLineIr> Strokes(DrawingAnnotationIr annotation)+ {+ var leader = annotation.SelectedCandidate.Leader;+ for (var i = 1; i < leader.Count; i++)+ foreach (var line in Expand(new(leader[i - 1], leader[i], ArrowStart: i == 1))) yield return line;+ foreach (var dimension in annotation.DimensionLines)+ foreach (var line in Expand(dimension)) yield return line;+ }++ private static IEnumerable<DrawingDimensionLineIr> Expand(DrawingDimensionLineIr line)+ {+ yield return line with { ArrowStart = false, ArrowEnd = false };+ foreach (var (tip, tail) in new[] { (line.Start, line.End, line.ArrowStart), (line.End, line.Start, line.ArrowEnd) }+ .Where(a => a.Item3).Select(a => (a.Item1, a.Item2)))+ {+ var dx = tail.X - tip.X; var dy = tail.Y - tip.Y; var length = Math.Sqrt(dx * dx + dy * dy);+ if (length < 1e-9) continue;+ var ux = dx / length; var uy = dy / length; var size = Math.Min(2.5, length / 3);+ yield return new(tip, new(tip.X + ux * size - uy * size / 3, tip.Y + uy * size + ux * size / 3));+ yield return new(tip, new(tip.X + ux * size + uy * size / 3, tip.Y + uy * size - ux * size / 3));+ }+ }+}diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingAnnotationLayout.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingAnnotationLayout.csindex 675943a8..7b83dfa9 100644--- a/Aetheris.Kernel.Firmament/Drawing/DrawingAnnotationLayout.cs+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingAnnotationLayout.cs@@ -1,3 +1,5 @@+using Aetheris.Kernel.Core.Judgment;+namespace Aetheris.Kernel.Firmament.Drawing;internal static class DrawingAnnotationLayout@@ -7,7 +9,6 @@ internal static class DrawingAnnotationLayoutpublic static Result Layout(IReadOnlyList<DrawingPageIr> pages, IReadOnlyDictionary<string, FirmamentDrawingCompiler.PmiPresentation> pmi){- var occupied = new List<DrawingRect>();var laneOccupancy = new Dictionary<string, int>(StringComparer.Ordinal);var rejected = 0; var failed = 0; var before = 0;var output = new List<DrawingPageIr>();@@ -15,7 +16,22 @@ internal static class DrawingAnnotationLayoutforeach (var page in pages){- var annotations = new List<DrawingAnnotationIr>();+ // Page coordinates are independent. Titles, notes and information blocks are real keepouts.+ var occupied = new List<DrawingRect>();+ 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);+ 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)))+ {+ failed++;+ diagnostics.Add($"{FirmamentDrawingCompiler.DrawingLayoutImpossible}: Reference measurement '{seed.Identity}' exceeds its sheet allocation or overlaps geometry.");+ }+ }foreach (var view in page.Views){foreach (var reference in view.AssignedPmi)@@ -23,7 +39,7 @@ internal static class DrawingAnnotationLayoutvar semantic = pmi[reference];var anchor = view.SemanticAnchors.GetValueOrDefault(reference,new(view.GeometryBounds.X + view.GeometryBounds.Width / 2, view.GeometryBounds.Y + view.GeometryBounds.Height / 2));- if (semantic.Kind == DrawingAnnotationKind.Datum)+ if (semantic.Kind == DrawingAnnotationKind.Datum && semantic.Provenance == "Firmament Semantic PMI")anchor = new(view.GeometryBounds.X + view.GeometryBounds.Width / 2, view.GeometryBounds.Bottom);var candidates = GenerateCandidates(view, semantic, anchor);before += CollidesModel(candidates[0].Body, view) ? 1 : 0;@@ -33,13 +49,21 @@ internal static class DrawingAnnotationLayout{var rejections = new List<string>();if (!Contains(view.Viewport, candidate.Body)) rejections.Add("outside-view-allocation");- if (CollidesModel(candidate.Body, view)) rejections.Add("text-model-overlap");- if (occupied.Any(rect => rect.Intersects(candidate.Body))) rejections.Add("text-text-overlap");- var current = candidate with { Rejections = rejections };+ if (page.Views.Any(v => CollidesModel(candidate.Body, v))) rejections.Add("text-model-overlap");+ if (occupied.Any(rect => Pad(rect).Intersects(candidate.Body))) rejections.Add("text-text-overlap");+ if (annotations.Any(a => a.Strokes.Any(s => SegmentIntersects(s.Start, s.End, Pad(candidate.Body))))) rejections.Add("text-leader-overlap");+ if (occupied.Any(rect => Segments(candidate.Leader).Any(s => SegmentIntersects(s.A, s.B, Pad(rect))))) rejections.Add("leader-text-overlap");+ var crossings = annotations.Sum(a => a.Strokes.Sum(old => Segments(candidate.Leader).Count(next => Crosses(old.Start, old.End, next.A, next.B))));+ var modelCrossings = page.Views.SelectMany(v => v.Primitives).Sum(primitive =>+ Segments(primitive.Points).Sum(edge => Segments(candidate.Leader).Count(leader => Crosses(edge.A, edge.B, leader.A, leader.B))));+ var current = candidate with { Rejections = rejections, Cost = candidate.Cost + crossings * 100 + modelCrossings * 20 };evaluated.Add(current);- if (rejections.Count == 0 && selected is null) selected = current;- else if (rejections.Count > 0) rejected++;+ if (rejections.Count > 0) rejected++;}+ var judgment = new JudgmentEngine<int>().Evaluate(0, evaluated.Select((c, i) =>+ new JudgmentCandidate<int>(c.Identity, _ => c.Rejections.Count == 0, _ => -c.Cost,+ _ => string.Join(",", c.Rejections), i)).ToArray());+ if (judgment.IsSuccess) selected = evaluated.Single(c => c.Identity == judgment.Selection!.Value.Candidate.Name);if (selected is null){failed++;@@ -55,8 +79,14 @@ internal static class DrawingAnnotationLayoutoutput.Add(page with { Annotations = annotations });}- var evidence = new DrawingLayoutEvidenceIr(output.Sum(page => page.Annotations.Count), before, 0, 0,- laneOccupancy, rejected, failed);+ var modelAfter = output.Sum(page => page.Annotations.Count(a => page.Views.Any(v => CollidesModel(a.SelectedCandidate.Body, v))));+ var textAfter = output.Sum(page => page.Annotations.SelectMany((a, i) => page.Annotations.Skip(i + 1).Select(b => a.SelectedCandidate.Body.Intersects(b.SelectedCandidate.Body))).Count(c => c));+ var leaderAfter = output.Sum(page => page.Annotations.Sum(a => page.Annotations.Where(b => b.Identity != a.Identity)+ .Count(b => b.Strokes.Any(s => SegmentIntersects(s.Start, s.End, Pad(a.SelectedCandidate.Body))))));+ if (modelAfter + textAfter + leaderAfter > 0)+ diagnostics.Add($"{FirmamentDrawingCompiler.DrawingLayoutImpossible}: Final layout audit found text/model={modelAfter}, text/text={textAfter}, text/stroke={leaderAfter} overlaps.");+ var evidence = new DrawingLayoutEvidenceIr(output.Sum(page => page.Annotations.Count), before, modelAfter, textAfter,+ laneOccupancy, rejected, failed) { TextLeaderCollisionsAfter = leaderAfter };return new(output, evidence, diagnostics);}@@ -64,7 +94,7 @@ internal static class DrawingAnnotationLayoutDrawingViewIr view, FirmamentDrawingCompiler.PmiPresentation pmi, DrawingPoint2 anchor){// The same embedded Inter advance widths drive both layout and native PDF text.- var width = Math.Clamp(Inter.Value.MeasureMillimetres(pmi.Display, 3.2) + 3, 18, 58);+ var width = Math.Max(18, Inter.Value.MeasureMillimetres(pmi.Display, 3.2) + 3);const double height = 6;var bounds = view.GeometryBounds;var candidates = new List<DrawingAnnotationCandidateIr>();@@ -72,11 +102,12 @@ internal static class DrawingAnnotationLayoutvoid Add(string lane, int laneIndex, double x, double y){var body = new DrawingRect(x, y, width, height);- var attach = new DrawingPoint2(Math.Clamp(anchor.X, body.X, body.Right), Math.Clamp(anchor.Y, body.Y, body.Bottom));+ var attach = new DrawingPoint2(anchor.X <= body.Center.X ? body.X : body.Right, body.Center.Y);+ var elbow = new DrawingPoint2(attach.X + (attach.X == body.X ? -3 : 3), attach.Y);var length = Math.Sqrt(Math.Pow(anchor.X - attach.X, 2) + Math.Pow(anchor.Y - attach.Y, 2));var edgePenalty = Math.Min(Math.Min(body.X - view.Viewport.X, view.Viewport.Right - body.Right),Math.Min(body.Y - view.Viewport.Y, view.Viewport.Bottom - body.Bottom)) < 3 ? 20 : 0;- candidates.Add(new($"candidate:{ordinal++}:{lane}:{laneIndex}", body, [anchor, attach], lane, laneIndex,+ candidates.Add(new($"candidate:{ordinal++}:{lane}:{laneIndex}", body, [anchor, elbow, attach], lane, laneIndex,length + laneIndex * 8 + edgePenalty + ordinal * 1e-5, []));}@@ -94,25 +125,42 @@ internal static class DrawingAnnotationLayoutAdd("left", lane, bounds.X - width - 3 - (lane - 1) * 8, bounds.Y + (bounds.Height - height) / 2);Add("right", lane, bounds.Right + 3 + (lane - 1) * 8, bounds.Y + (bounds.Height - height) / 2);}+ // Deterministic callout-column slots support dense PMI without reducing text size.+ for (var row = 0; row < 16; row++)+ {+ Add("column-right", row, view.Viewport.Right - width - 2, view.Viewport.Y + 9 + row * 8);+ Add("column-left", row, view.Viewport.X + 2, view.Viewport.Y + 9 + row * 8);+ }return candidates.OrderBy(candidate => candidate.Cost).ThenBy(candidate => candidate.Identity, StringComparer.Ordinal).ToArray();}private static bool Contains(DrawingRect outer, DrawingRect inner) => inner.X >= outer.X && inner.Y >= outer.Y && inner.Right <= outer.Right && inner.Bottom <= outer.Bottom;- private static bool CollidesModel(DrawingRect body, DrawingViewIr view)+ private static DrawingRect Pad(DrawingRect r) => new(r.X - .7, r.Y - .7, r.Width + 1.4, r.Height + 1.4);+ private static IEnumerable<(DrawingPoint2 A, DrawingPoint2 B)> Segments(IReadOnlyList<DrawingPoint2> points)+ { for (var i = 1; i < points.Count; i++) yield return (points[i - 1], points[i]); }++ private static bool Crosses(DrawingPoint2 a, DrawingPoint2 b, DrawingPoint2 c, DrawingPoint2 d)+ {+ static double Side(DrawingPoint2 p, DrawingPoint2 q, DrawingPoint2 r) => (q.X - p.X) * (r.Y - p.Y) - (q.Y - p.Y) * (r.X - p.X);+ return Side(a, b, c) * Side(a, b, d) < -1e-8 && Side(c, d, a) * Side(c, d, b) < -1e-8;+ }++ internal static bool SegmentIntersects(DrawingPoint2 a, DrawingPoint2 b, DrawingRect rect){- // Text uses a small safety margin; leaders may cross geometry as a penalized M0 fallback,- // but annotation bodies never may.- var expanded = new DrawingRect(body.X - 1, body.Y - 1, body.Width + 2, body.Height + 2);- foreach (var primitive in view.Primitives)+ double t0 = 0, t1 = 1;+ bool Clip(double p, double q){- for (var i = 1; i < primitive.Points.Count; i++)- {- var a = primitive.Points[i - 1]; var b = primitive.Points[i];- var segmentBounds = new DrawingRect(Math.Min(a.X, b.X), Math.Min(a.Y, b.Y), Math.Max(0.15, Math.Abs(a.X - b.X)), Math.Max(0.15, Math.Abs(a.Y - b.Y)));- if (expanded.Intersects(segmentBounds)) return true;- }+ if (Math.Abs(p) < 1e-12) return q >= 0;+ var r = q / p;+ if (p < 0) { if (r > t1) return false; t0 = Math.Max(t0, r); }+ else { if (r < t0) return false; t1 = Math.Min(t1, r); }+ return true;}- return false;+ var dx = b.X - a.X; var dy = b.Y - a.Y;+ return Clip(-dx, a.X - rect.X) && Clip(dx, rect.Right - a.X) && Clip(-dy, a.Y - rect.Y) && Clip(dy, rect.Bottom - a.Y);}++ private static bool CollidesModel(DrawingRect body, DrawingViewIr view) => view.Primitives.Any(primitive =>+ Segments(primitive.Points).Any(s => SegmentIntersects(s.A, s.B, Pad(body))));}diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingGeneration.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingGeneration.csnew file mode 100644index 00000000..73934e61--- /dev/null+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingGeneration.cs@@ -0,0 +1,271 @@+using System.Globalization;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Judgment;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Core.Visualization;++namespace Aetheris.Kernel.Firmament.Drawing;++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)+ {+ if (DrawingTitleBlockLayout.ValidateSignoff(signoff) is { } error) return Failure(error);+ try { return GenerateCore(sourcePath, outputDirectory, signoff); }+ catch (InvalidOperationException e) when (e.Message.StartsWith("drawing-", StringComparison.Ordinal)) { return Failure(e.Message); }+ }++ private static DrawingCompileResult GenerateCore(string sourcePath, string outputDirectory, DrawingSignoffIr? signoff)+ {+ var path = Path.GetFullPath(sourcePath);+ if (!File.Exists(path)) return Failure($"drawing-source-file-missing: {path}");+ var source = File.ReadAllText(path);+ var name = Path.GetFileNameWithoutExtension(path);+ var step = source;+ var sourceKind = "AP242";+ IReadOnlyList<string> expectedPmi = [];+ if (Path.GetExtension(path).Equals(".firmament", StringComparison.OrdinalIgnoreCase))+ {+ if (IsDrawingSource(source)) 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;+ expectedPmi = (bound?.Datums ?? []).Concat(bound?.Dimensions ?? []).Concat(bound?.Controls ?? []).Select(p => p.Name).ToArray();+ step = compiled.Value.StepText;+ name = compiled.Value.DocumentName ?? name;+ sourceKind = "FirmamentPart";+ }+ else if (Path.GetExtension(path).ToLowerInvariant() is not (".step" or ".stp"))+ return Failure("drawing-input-unsupported: Generate expects a Firmament part or STEP BRep; use drawing compile for authored Assembly drawings.");++ var imported = Step242Importer.ImportBody(step);+ if (!imported.IsSuccess) return new(false, null, imported.Diagnostics.Select(d => $"{d.Source}: {d.Message}").ToArray());+ var inspected = Step242SemanticPmiInspector.Inspect(step);+ if (!inspected.Success) return new(false, null, inspected.Diagnostics);+ // The inspector's bounded emitted subset uses file-unit measure values. Do not+ // silently label foreign unit measures as mm before per-measure unit binding exists.+ var missingPmi = expectedPmi.Where(name => !inspected.Items.Any(item => (item.AuthoredName ?? item.Name) == name)).ToArray();+ if (missingPmi.Length > 0) return Failure($"drawing-pmi-not-exported: Authored PMI has no supported AP242 projection: {string.Join(", ", missingPmi)}. Use an authored Drawing or qualify the missing PMI export family before automatic generation.");+ var parsed = Step242SubsetParser.Parse(step);+ var unsupportedPmi = parsed.Value.Entities.Where(entity =>+ (Step242SubsetDecoder.TryGetConstructor(entity.Instance, "DIMENSIONAL_SIZE") is not null+ || Step242SubsetDecoder.TryGetConstructor(entity.Instance, "DIMENSIONAL_LOCATION") is not null+ || Step242SubsetDecoder.TryGetConstructor(entity.Instance, "GEOMETRIC_TOLERANCE") is not null+ || Step242SubsetDecoder.TryGetConstructor(entity.Instance, "DATUM_FEATURE") is not null)+ && !inspected.Items.Any(item => item.EntityId == entity.Id)).Select(entity => $"#{entity.Id}:{entity.Name}").ToArray();+ if (unsupportedPmi.Length > 0) return Failure($"drawing-pmi-family-unsupported: These AP242 semantic entities require a qualified readback adapter: {string.Join(", ", unsupportedPmi)}. They were not omitted from a successful drawing.");+ if (inspected.Items.Count > 0 && Math.Abs(parsed.Value.SourceMillimetresPerUnit - 1) > 1e-12)+ return Failure("drawing-pmi-units-unsupported: Semantic PMI generation currently requires millimetre AP242 measures. Geometry-only reference views can use normalized imported units.");++ 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 (samples.Evidence.UnsupportedCurveFamilies.Count > 0)+ return Failure($"drawing-edge-projection-unsupported: {string.Join(", ", samples.Evidence.UnsupportedCurveFamilies)}");+ var definitions = new[]+ {+ (Name: "TOP", Direction: new double[] { 0, 0, 1 }),+ (Name: "FRONT", Direction: new double[] { 0, -1, 0 }),+ (Name: "RIGHT", Direction: new double[] { 1, 0, 0 })+ };+ var pmi = new Dictionary<string, PmiPresentation>(StringComparer.Ordinal);+ var targets = new Dictionary<string, IReadOnlyList<Point3D>>(StringComparer.Ordinal);+ var cylinders = new Dictionary<string, CylinderSurface>(StringComparer.Ordinal);+ var assigned = definitions.ToDictionary(v => v.Name, _ => new List<string>());+ foreach (var inspectedItem in inspected.Items)+ {+ 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();+ if (points.Length == 0) return Failure($"drawing-pmi-target-unprojectable: '{item.Name}' has no supported bound edge samples.");+ var kind = dimensionKind is "holediameter" or "diameter" ? DrawingAnnotationKind.DiameterDimension : item.Kind switch+ {+ "Diameter" => DrawingAnnotationKind.DiameterDimension,+ "Datum" => DrawingAnnotationKind.Datum,+ "Position" => DrawingAnnotationKind.FeatureControlFrame,+ "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);+ var first = faces[0];+ body.TryGetFaceSurfaceGeometry(first.Id, out var surface);+ var axis = surface?.Cylinder?.Axis.ToVector() ?? surface?.Plane?.Normal.ToVector();+ if (kind == DrawingAnnotationKind.DiameterDimension && surface?.Cylinder is { } cylinder+ && item.Value is { } nominal && Math.Abs(nominal - 2 * cylinder.Radius) < 1e-6)+ cylinders[reference] = cylinder;+ var candidates = definitions.Select((view, i) => new JudgmentCandidate<int>(view.Name, _ => true,+ _ => axis is { } a ? Math.Abs(a.X * view.Direction[0] + a.Y * view.Direction[1] + a.Z * view.Direction[2]) : 0,+ TieBreakerPriority: i)).ToArray();+ var selected = new JudgmentEngine<int>().Evaluate(0, candidates).Selection!.Value.Candidate.Name;+ assigned[selected].Add(reference);+ }++ var width = 297d; var height = 210d;+ var metadata = new DrawingMetadataIr(name + " - engineering views", name, null, null, null,+ name + "Drawing", "AutomaticPmiSheets", Author: signoff?.Drawn.Name, Date: signoff?.Drawn.Date,+ 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.",+ 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)>();+ foreach (var view in definitions)+ {+ var chunks = assigned[view.Name].Chunk(6).ToArray();+ foreach (var chunk in chunks) requested.Add((view.Name, view.Direction, DrawingProjectionKind.Orthographic, chunk));+ }+ var pages = new List<DrawingPageIr>();+ var overviewSpecs = new[] { (Name: "TOP", Direction: new double[] { 0, 0, 1 }, Projection: DrawingProjectionKind.Orthographic),+ (Name: "ISOMETRIC WIREFRAME", Direction: new double[] { 1, 1, 1 }, Projection: DrawingProjectionKind.Isometric),+ (Name: "FRONT", Direction: new double[] { 0, -1, 0 }, Projection: DrawingProjectionKind.Orthographic),+ (Name: "RIGHT", Direction: new double[] { 1, 0, 0 }, Projection: DrawingProjectionKind.Orthographic) };+ var overview = overviewSpecs.Select((spec, i) =>+ {+ var allocation = new DrawingRect(12 + i % 2 * 138, 20 + i / 2 * 66, 135, 64);+ return DrawingProjectionEngine.Project([new(name, name, body)], spec.Name, spec.Projection, DrawingHiddenLinePolicy.Wireframe,+ spec.Direction, [], new(allocation.X + 5, allocation.Y, allocation.Width - 10, allocation.Height), new(1, "B2")) with { Viewport = allocation };+ }).ToArray();+ var commonScale = StandardScale(overview.Where(v => v.Projection == DrawingProjectionKind.Orthographic).Min(v => v.Scale));+ overview = overview.Select(view => AtScale(view, view.Projection == DrawingProjectionKind.Orthographic ? commonScale : StandardScale(view.Scale))).ToArray();+ 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")),+ LocateNotes(notes, 1, overviewScheme, DrawingTitleBlockLayout.NotesArea(width, height))));+ foreach (var request in requested)+ {+ var page = pages.Count + 1;+ var scheme = Zones(width, height);+ var viewport = new DrawingRect(12, 20, 273, 134);+ // Reserve a real callout column rather than squeezing every label around a full-width model.+ var geometryViewport = new DrawingRect(18, 26, 175, 117);+ var view = DrawingProjectionEngine.Project([new(name, name, body)], request.Name, request.Projection,+ DrawingHiddenLinePolicy.Wireframe, request.Direction, request.Pmi, geometryViewport, new(page, "B2"));+ view = AtScale(view, StandardScale(view.Scale));+ DrawingPoint2 Project(Point3D p)+ {+ var c = view.Camera!;+ return new(c.OriginX + view.Scale * (p.X * c.Right[0] + p.Y * c.Right[1] + p.Z * c.Right[2]),+ c.OriginY - view.Scale * (p.X * c.Up[0] + p.Y * c.Up[1] + p.Z * c.Up[2]));+ }+ var anchors = request.Pmi.ToDictionary(reference => reference, reference => targets[reference].Select(Project)+ .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" };+ 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))));+ }+ var layout = DrawingAnnotationLayout.Layout(pages, pmi);+ if (layout.Diagnostics.Count > 0) return new(false, null, layout.Diagnostics);+ var dimensioned = layout.Pages.Select(page => page with+ {+ Annotations = page.Annotations.Select(annotation =>+ {+ if (!cylinders.TryGetValue(annotation.SemanticReference, out var cylinder)) return annotation;+ var view = page.Views.Single(v => v.Identity == annotation.AssignedView);+ var axis = cylinder.Axis.ToVector(); var direction = view.Direction3;+ if (Math.Abs(axis.X * direction[0] + axis.Y * direction[1] + axis.Z * direction[2]) < 1 - 1e-8) return annotation;+ var points = targets[annotation.SemanticReference];+ var v = points.Max(p => (p - cylinder.Origin).Dot(axis) * (axis.X * direction[0] + axis.Y * direction[1] + axis.Z * direction[2]));+ v *= axis.X * direction[0] + axis.Y * direction[1] + axis.Z * direction[2];+ var center = cylinder.Origin + axis * v;+ var camera = view.Camera!;+ var projected = new DrawingPoint2(camera.OriginX + view.Scale * (center.X * camera.Right[0] + center.Y * camera.Right[1] + center.Z * camera.Right[2]),+ camera.OriginY - view.Scale * (center.X * camera.Up[0] + center.Y * camera.Up[1] + center.Z * camera.Up[2]));+ var r = cylinder.Radius * view.Scale;+ // Small holes use the rim leader alone; three arrowheads inside a tiny circle are unreadable.+ if (2 * r < 8) return annotation;+ return annotation with { DimensionLines = [new(new(projected.X - r, projected.Y), new(projected.X + r, projected.Y), true, true)] };+ }).ToArray()+ }).ToArray();+ var drawing = new DrawingIr(name + "Drawing", metadata,+ 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 }));+ return WriteArtifacts(drawing, Path.GetFullPath(outputDirectory), 1, 0);+ }++ private static double StandardScale(double fit)+ {+ var decade = Math.Pow(10, Math.Floor(Math.Log10(fit)));+ return new[] { 1d, 2d, 5d }.Where(m => m * decade <= fit * (1 + 1e-12)).Max() * decade;+ }++ private static DrawingViewIr AtScale(DrawingViewIr view, double scale)+ {+ var ratio = scale / view.Scale; var center = view.GeometryBounds.Center;+ DrawingPoint2 Map(DrawingPoint2 p) => new(center.X + (p.X - center.X) * ratio, center.Y + (p.Y - center.Y) * ratio);+ var topLeft = Map(new(view.GeometryBounds.X, view.GeometryBounds.Y)); var camera = view.Camera!;+ var origin = Map(new(camera.OriginX, camera.OriginY));+ return view with { Scale = scale,+ Primitives = view.Primitives.Select(p => p with { Points = p.Points.Select(Map).ToArray() }).ToArray(),+ GeometryBounds = new(topLeft.X, topLeft.Y, view.GeometryBounds.Width * ratio, view.GeometryBounds.Height * ratio),+ Camera = camera with { OriginX = origin.X, OriginY = origin.Y } };+ }++ private static IReadOnlyList<DrawingAnnotationIr> ReferenceEnvelope(DrawingViewIr view)+ {+ var result = new List<DrawingAnnotationIr>(); var b = view.GeometryBounds;+ void Add(string axis, bool horizontal)+ {+ var text = FormattableString.Invariant($"~{(horizontal ? b.Width : b.Height) / view.Scale:0.###} mm REF ({axis})");+ var width = DrawingInterFont.Load().MeasureMillimetres(text, 3.2) + 3;+ var body = horizontal ? new DrawingRect(b.Center.X - width / 2, b.Bottom + 5, width, 6)+ : new DrawingRect(b.Right - width, b.Bottom + 15, width, 6);+ var start = horizontal ? new DrawingPoint2(b.X, b.Bottom + 8) : new DrawingPoint2(b.Right + 6, b.Y);+ var end = horizontal ? new DrawingPoint2(b.Right, b.Bottom + 8) : new DrawingPoint2(b.Right + 6, b.Bottom);+ var lines = horizontal+ ? new DrawingDimensionLineIr[] { new(start, end, true, true), new(new(b.X, b.Bottom + 1), new(b.X, b.Bottom + 10)), new(new(b.Right, b.Bottom + 1), new(b.Right, b.Bottom + 10)) }+ : new DrawingDimensionLineIr[] { new(start, end, true, true), new(new(b.Right + 1, b.Y), new(b.Right + 8, b.Y)), new(new(b.Right + 1, b.Bottom), new(b.Right + 8, b.Bottom)) };+ var leader = horizontal ? Array.Empty<DrawingPoint2>() : new[] { end, new DrawingPoint2(b.Right + 6, body.Center.Y), new DrawingPoint2(body.Right, body.Center.Y) };+ var candidate = new DrawingAnnotationCandidateIr("reference-envelope", body, leader, "reference", 0, 0, []);+ result.Add(new($"reference:{view.Identity}:{axis}", $"reference:{axis}", view.Identity, DrawingAnnotationKind.LinearDimension, text, start, candidate, [candidate],+ "Sampled projected-curve envelope; approximate reference only; no tolerance or manufacturing authority") { DimensionLines = lines });+ }+ if (view.Identity == "TOP") { Add("X", true); Add("Y", false); }+ if (view.Identity == "FRONT") Add("Z", false);+ return result;+ }++ private static string FormatStepPmi(Step242SemanticPmiInspectionItem item)+ {+ var quantity = item.Quantity is > 1 ? $"{item.Quantity}x " : "";+ if (item.Kind == "Datum") return $"DATUM {item.Name}";+ if (item.Kind == "Annotation") return $"{item.Name}: {item.Text}";+ if (item.Kind == "Position") return FormattableString.Invariant($"POSITION | {item.Value:0.###} | {string.Join(" | ", item.DatumReferences)}");+ var dimension = FormattableString.Invariant($"{item.Value:0.###} mm");+ if (item.TolerancePlus is not null || item.ToleranceMinus is not null)+ {+ var p = Math.Abs(item.TolerancePlus ?? 0); var m = Math.Abs(item.ToleranceMinus ?? 0);+ dimension += Math.Abs(p - m) < 1e-12 ? FormattableString.Invariant($" ±{p:0.###}") : FormattableString.Invariant($" +{p:0.###}/-{m:0.###}");+ }+ if (item.Depth is { } depth) dimension += FormattableString.Invariant($" DEPTH {depth:0.###} mm");+ return quantity + item.Name + ": " + (item.Kind == "Diameter" || item.DimensionKind?.ToLowerInvariant() is "holediameter" or "diameter" ? "Ø" : "") + dimension;+ }+}diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingIr.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingIr.csindex d2dc7c51..f2ff6566 100644--- a/Aetheris.Kernel.Firmament/Drawing/DrawingIr.cs+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingIr.cs@@ -4,8 +4,8 @@ namespace Aetheris.Kernel.Firmament.Drawing;public enum DrawingPageOrientation { Portrait, Landscape }public enum DrawingProjectionKind { Orthographic, Isometric }-public enum DrawingHiddenLinePolicy { VisibleOnly, VisibleAndHidden }-public enum DrawingPrimitiveKind { Visible, Silhouette, Hidden }+public enum DrawingHiddenLinePolicy { VisibleOnly, VisibleAndHidden, Wireframe }+public enum DrawingPrimitiveKind { Visible, Silhouette, Hidden, SurfaceGrid }public enum DrawingAnnotationKind { LinearDimension, DiameterDimension, RadiusDimension, Datum, FeatureControlFrame, Note }public enum DrawingTableKind { Design, BillOfMaterials }@@ -36,7 +36,13 @@ public sealed record DrawingMetadataIr(string? Date = null,string? Description = null,string? StaticIdentity = null,- string? StaticProvenance = null);+ string? StaticProvenance = null)+{+ public DrawingSignoffIr? Signoff { get; init; }+}++public sealed record DrawingSignoffEntryIr(string? Name = null, string? Date = null);+public sealed record DrawingSignoffIr(DrawingSignoffEntryIr Drawn, DrawingSignoffEntryIr Checked, DrawingSignoffEntryIr Approved);public sealed record DrawingLocationIr(int Page, string Zone);public sealed record DrawingPageZoneIr(string Address, DrawingRect Bounds);@@ -50,7 +56,15 @@ public sealed record DrawingPageZoneSchemeIr(public sealed record DrawingInformationBlockIr(DrawingRect Bounds,DrawingLocationIr Location,- IReadOnlyDictionary<string, string> Fields);+ IReadOnlyDictionary<string, string> Fields)+{+ public DrawingTitleBlockTableIr? Table { get; init; }+}++public sealed record DrawingTitleBlockTableIr(IReadOnlyList<double> ColumnWidths, IReadOnlyList<DrawingTitleBlockRowIr> Rows);+public sealed record DrawingTitleBlockRowIr(double Height, IReadOnlyList<DrawingTitleBlockCellIr> Cells);+public sealed record DrawingTitleBlockCellIr(string Key, string Label, string Value, int ColumnSpan,+ DrawingRect Bounds, IReadOnlyList<string> ValueLines, double ValueSizeMillimetres, bool Emphasized = false);public sealed record DrawingNoteIr(string Identity, string Text, DrawingRect Bounds, DrawingLocationIr Location);@@ -95,7 +109,12 @@ public sealed record DrawingViewIr(IReadOnlyDictionary<string, DrawingPoint2> SemanticAnchors,IReadOnlyList<string> AssignedPmi,DrawingLocationIr? Location = null,- DrawingVisibilityEvidenceIr? VisibilityEvidence = null);+ DrawingVisibilityEvidenceIr? VisibilityEvidence = null)+{+ public DrawingCameraIr? Camera { get; init; }+}++public sealed record DrawingCameraIr(IReadOnlyList<double> Right, IReadOnlyList<double> Up, double OriginX, double OriginY);public sealed record DrawingAnnotationCandidateIr(string Identity,@@ -116,7 +135,13 @@ public sealed record DrawingAnnotationIr(DrawingAnnotationCandidateIr SelectedCandidate,IReadOnlyList<DrawingAnnotationCandidateIr> Candidates,string Provenance,- DrawingLocationIr? Location = null);+ DrawingLocationIr? Location = null)+{+ public IReadOnlyList<DrawingDimensionLineIr> DimensionLines { get; init; } = [];+ public IReadOnlyList<DrawingDimensionLineIr> Strokes => DrawingAnnotationGeometry.Strokes(this).ToArray();+}++public sealed record DrawingDimensionLineIr(DrawingPoint2 Start, DrawingPoint2 End, bool ArrowStart = false, bool ArrowEnd = false);public sealed record DrawingTableIr(string Identity,@@ -165,7 +190,10 @@ public sealed record DrawingLayoutEvidenceIr(int TextTextCollisionsAfter,IReadOnlyDictionary<string, int> LaneOccupancy,int RejectedCandidateCount,- int FailedAnnotationCount);+ int FailedAnnotationCount)+{+ public int TextLeaderCollisionsAfter { get; init; }+}public sealed record DrawingTypographyIr(string Family,diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingPptxWriter.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingPptxWriter.csindex fcdd5856..f09b1485 100644--- a/Aetheris.Kernel.Firmament/Drawing/DrawingPptxWriter.cs+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingPptxWriter.cs@@ -16,7 +16,7 @@ public static partial class DrawingPptxWriterpublic static void WriteDrawing(DrawingIr drawing, string path, bool includeReviews){var pages = drawing.Pages.Select((page, index) => DrawingSlide(drawing, page, index, includeReviews)).ToArray();- WritePackage(path, pages, drawing.Pages[0].WidthMillimetres, drawing.Pages[0].HeightMillimetres, drawing.Metadata.Title);+ WritePackage(path, pages, drawing.Pages[0].WidthMillimetres, drawing.Pages[0].HeightMillimetres, drawing.Metadata.Title, drawing.Metadata);}public static void WriteDfmDeck(DrawingIr drawing, string path)@@ -28,7 +28,7 @@ public static partial class DrawingPptxWritervar slides = entries.Length == 0? [DfmSlide(drawing, null, null, 0, width, height)]: entries.Select((item, index) => DfmSlide(drawing, item.Thread, item.Entry, index, width, height)).ToArray();- WritePackage(path, slides, width, height, $"{drawing.Metadata.Title} — DFM Review");+ WritePackage(path, slides, width, height, $"{drawing.Metadata.Title} — DFM Review", drawing.Metadata);}public static object Inspect(string path)@@ -82,22 +82,27 @@ 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], primitive.Points[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);});foreach (var annotation in page.Annotations)slide.Group($"PMI.{Safe(annotation.Identity)}", group =>{var leader = annotation.SelectedCandidate.Leader;- for (var index = 1; index < leader.Count; index++) group.Line($"PMI.{Safe(annotation.Identity)}.Leader.{index}", leader[index - 1], leader[index], arrowEnd: index == leader.Count - 1);+ var strokeIndex = 0;+ foreach (var stroke in DrawingAnnotationGeometry.Strokes(annotation))+ group.Line($"PMI.{Safe(annotation.Identity)}.Leader.{strokeIndex++}", stroke.Start, stroke.End);var body = annotation.SelectedCandidate.Body;- group.Text($"PMI.{Safe(annotation.Identity)}.Text", annotation.EngineeringDisplay, body.X, body.Y, body.Width, body.Height, 2.8, centered: true, border: annotation.Kind is DrawingAnnotationKind.Datum or DrawingAnnotationKind.FeatureControlFrame);+ 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);if (page.InformationBlock is not null)slide.Group("Metadata.DrawingInfo", group =>{- var block = page.InformationBlock; group.Rect("Metadata.DrawingInfo.Border", block.Bounds.X, block.Bounds.Y, block.Bounds.Width, block.Bounds.Height);+ var block = page.InformationBlock;+ if (block.Table is not null) { group.TitleBlockTable("Metadata.DrawingInfo.Table", block); return; }+ group.Rect("Metadata.DrawingInfo.Border", block.Bounds.X, block.Bounds.Y, block.Bounds.Width, block.Bounds.Height);var fields = block.Fields.ToArray(); var rowHeight = block.Bounds.Height / Math.Max(1, fields.Length);for (var index = 0; index < fields.Length; index++)group.Text($"Metadata.DrawingInfo.{Safe(fields[index].Key)}", $"{fields[index].Key}: {fields[index].Value}", block.Bounds.X + 1, block.Bounds.Y + index * rowHeight, block.Bounds.Width - 2, rowHeight, 2.2);@@ -164,7 +169,7 @@ public static partial class DrawingPptxWriterreturn slide.Build();}- private static void WritePackage(string path, IReadOnlyList<string> slides, double widthMm, double heightMm, string title)+ private static void WritePackage(string path, IReadOnlyList<string> slides, double widthMm, double heightMm, string title, DrawingMetadataIr? metadata = null){Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);if (File.Exists(path)) File.Delete(path);@@ -172,7 +177,7 @@ public static partial class DrawingPptxWriterAdd(archive, "[Content_Types].xml", ContentTypes(slides.Count));Add(archive, "_rels/.rels", RootRelationships());Add(archive, "docProps/app.xml", AppProperties(slides.Count));- Add(archive, "docProps/core.xml", CoreProperties(title));+ Add(archive, "docProps/core.xml", CoreProperties(title, metadata));Add(archive, "ppt/presentation.xml", Presentation(slides.Count, Mm(widthMm), Mm(heightMm)));Add(archive, "ppt/_rels/presentation.xml.rels", PresentationRelationships(slides.Count));Add(archive, "ppt/slideMasters/slideMaster1.xml", SlideMaster());@@ -236,6 +241,23 @@ public static partial class DrawingPptxWritervar rowXml = $"<a:tr h=\"{Mm(table.Bounds.Height / rows)}\">{string.Concat(table.Columns.Select(value => Cell(value, true)))}</a:tr>" + string.Concat(table.Rows.Select(row => $"<a:tr h=\"{Mm(table.Bounds.Height / rows)}\">{string.Concat(row.Select(value => Cell(value, false)))}</a:tr>"));shapes.Append($"<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id=\"{id++}\" name=\"{X(name)}\"/><p:cNvGraphicFramePr/><p:nvPr/></p:nvGraphicFramePr><p:xfrm><a:off x=\"{Mm(table.Bounds.X)}\" y=\"{Mm(table.Bounds.Y)}\"/><a:ext cx=\"{Mm(table.Bounds.Width)}\" cy=\"{Mm(table.Bounds.Height)}\"/></p:xfrm><a:graphic><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/table\"><a:tbl><a:tblPr firstRow=\"1\" bandRow=\"1\"/><a:tblGrid>{grid}</a:tblGrid>{rowXml}</a:tbl></a:graphicData></a:graphic></p:graphicFrame>");}+ public void TitleBlockTable(string name, DrawingInformationBlockIr block)+ {+ var table = block.Table!;+ string Paragraph(string value, double size, bool label, bool bold = false) =>+ $"<a:p><a:pPr><a:lnSpc><a:spcPct val=\"115000\"/></a:lnSpc><a:spcBef><a:spcPts val=\"0\"/></a:spcBef><a:spcAft><a:spcPts val=\"0\"/></a:spcAft></a:pPr><a:r><a:rPr lang=\"en-US\" sz=\"{(int)Math.Round(size * 72 / 25.4 * 100)}\"{(bold ? " b=\"1\"" : "")}><a:solidFill><a:srgbClr val=\"{(label ? "64748B" : "111827")}\"/></a:solidFill><a:latin typeface=\"Inter\"/></a:rPr><a:t>{X(value)}</a:t></a:r><a:endParaRPr/></a:p>";+ string Cell(DrawingTitleBlockCellIr cell)+ {+ var body = Paragraph(cell.Label, 1.8, true) + string.Concat(cell.ValueLines.Select(line => Paragraph(line, cell.ValueSizeMillimetres, false, cell.Emphasized)));+ var borders = string.Concat(new[] { "L", "R", "T", "B" }.Select(edge => $"<a:ln{edge} w=\"5400\"><a:solidFill><a:srgbClr val=\"475569\"/></a:solidFill></a:ln{edge}>"));+ var master = $"<a:tc gridSpan=\"{cell.ColumnSpan}\"><a:txBody><a:bodyPr/><a:lstStyle/>{body}</a:txBody><a:tcPr marL=\"{Mm(.8)}\" marR=\"{Mm(.8)}\" marT=\"{Mm(.1)}\" marB=\"0\" anchor=\"t\">{borders}<a:solidFill><a:srgbClr val=\"{(cell.Emphasized ? "F1F5F9" : "FFFFFF")}\"/></a:solidFill></a:tcPr></a:tc>";+ return master + string.Concat(Enumerable.Range(1, cell.ColumnSpan - 1).Select(_ => "<a:tc hMerge=\"1\"><a:txBody><a:bodyPr/><a:lstStyle/><a:p/></a:txBody><a:tcPr/></a:tc>"));+ }+ var grid = string.Concat(table.ColumnWidths.Select(w => $"<a:gridCol w=\"{Mm(w)}\"/>"));+ var rows = string.Concat(table.Rows.Select(row => $"<a:tr h=\"{Mm(row.Height)}\">{string.Concat(row.Cells.Select(Cell))}</a:tr>"));+ shapes.Append($"<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id=\"{id++}\" name=\"{X(name)}\"/><p:cNvGraphicFramePr/><p:nvPr/></p:nvGraphicFramePr><p:xfrm><a:off x=\"{Mm(block.Bounds.X)}\" y=\"{Mm(block.Bounds.Y)}\"/><a:ext cx=\"{Mm(block.Bounds.Width)}\" cy=\"{Mm(block.Bounds.Height)}\"/></p:xfrm><a:graphic><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/table\"><a:tbl><a:tblPr/><a:tblGrid>{grid}</a:tblGrid>{rows}</a:tbl></a:graphicData></a:graphic></p:graphicFrame>");+ }+public string Build() => $"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><p:sld xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:p=\"http://schemas.openxmlformats.org/presentationml/2006/main\"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id=\"1\" name=\"Slide\"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/>{shapes}</p:spTree></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>";}@@ -248,7 +270,15 @@ public static partial class DrawingPptxWriterprivate static string SlideLayout() => "<?xml version=\"1.0\" encoding=\"UTF-8\"?><p:sldLayout xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:p=\"http://schemas.openxmlformats.org/presentationml/2006/main\" type=\"blank\"><p:cSld name=\"Blank\"><p:spTree><p:nvGrpSpPr><p:cNvPr id=\"1\" name=\"Layout\"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/></p:spTree></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>";private static string LayoutRelationships() => "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\"><Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster\" Target=\"../slideMasters/slideMaster1.xml\"/></Relationships>";private static string SlideRelationships() => "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\"><Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout\" Target=\"../slideLayouts/slideLayout1.xml\"/></Relationships>";- private static string CoreProperties(string title) => $"<?xml version=\"1.0\" encoding=\"UTF-8\"?><cp:coreProperties xmlns:cp=\"http://schemas.openxmlformats.org/package/2006/metadata/core-properties\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><dc:title>{X(title)}</dc:title><dc:creator>Aetheris</dc:creator><dcterms:created xsi:type=\"dcterms:W3CDTF\">2000-01-01T00:00:00Z</dcterms:created><dcterms:modified xsi:type=\"dcterms:W3CDTF\">2000-01-01T00:00:00Z</dcterms:modified></cp:coreProperties>";+ private static string CoreProperties(string title, DrawingMetadataIr? metadata = null)+ {+ var creator = metadata?.Signoff?.Drawn.Name ?? metadata?.Author ?? "Aetheris";+ var date = metadata?.Signoff?.Drawn.Date ?? metadata?.Date;+ var dates = DateOnly.TryParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var value)+ ? $"<dcterms:created xsi:type=\"dcterms:W3CDTF\">{value:yyyy-MM-dd}T00:00:00Z</dcterms:created><dcterms:modified xsi:type=\"dcterms:W3CDTF\">{value:yyyy-MM-dd}T00:00:00Z</dcterms:modified>" : "";+ return $"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><cp:coreProperties xmlns:cp=\"http://schemas.openxmlformats.org/package/2006/metadata/core-properties\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><dc:title>{X(title)}</dc:title><dc:creator>{X(creator)}</dc:creator>{dates}</cp:coreProperties>";+ }+private static string AppProperties(int count) => $"<?xml version=\"1.0\" encoding=\"UTF-8\"?><Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties\" xmlns:vt=\"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes\"><Application>Aetheris</Application><PresentationFormat>Custom</PresentationFormat><Slides>{count}</Slides><Notes>0</Notes><HiddenSlides>0</HiddenSlides><MMClips>0</MMClips><ScaleCrop>false</ScaleCrop></Properties>";private static string Theme() => "<?xml version=\"1.0\" encoding=\"UTF-8\"?><a:theme xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" name=\"Aetheris Inter\"><a:themeElements><a:clrScheme name=\"Aetheris\"><a:dk1><a:srgbClr val=\"111111\"/></a:dk1><a:lt1><a:srgbClr val=\"FFFFFF\"/></a:lt1><a:dk2><a:srgbClr val=\"333333\"/></a:dk2><a:lt2><a:srgbClr val=\"F7F8FA\"/></a:lt2><a:accent1><a:srgbClr val=\"185FA5\"/></a:accent1><a:accent2><a:srgbClr val=\"FF8A00\"/></a:accent2><a:accent3><a:srgbClr val=\"2E7D32\"/></a:accent3><a:accent4><a:srgbClr val=\"6A1B9A\"/></a:accent4><a:accent5><a:srgbClr val=\"00838F\"/></a:accent5><a:accent6><a:srgbClr val=\"C62828\"/></a:accent6><a:hlink><a:srgbClr val=\"0563C1\"/></a:hlink><a:folHlink><a:srgbClr val=\"954F72\"/></a:folHlink></a:clrScheme><a:fontScheme name=\"Inter\"><a:majorFont><a:latin typeface=\"Inter\"/><a:ea typeface=\"\"/><a:cs typeface=\"\"/></a:majorFont><a:minorFont><a:latin typeface=\"Inter\"/><a:ea typeface=\"\"/><a:cs typeface=\"\"/></a:minorFont></a:fontScheme><a:fmtScheme name=\"Aetheris\"><a:fillStyleLst><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill></a:fillStyleLst><a:lnStyleLst><a:ln w=\"12700\"><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill></a:ln><a:ln w=\"25400\"><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill></a:ln><a:ln w=\"38100\"><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill></a:ln></a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill><a:solidFill><a:schemeClr val=\"phClr\"/></a:solidFill></a:bgFillStyleLst></a:fmtScheme></a:themeElements></a:theme>";}diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingProjectionEngine.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingProjectionEngine.csindex 6737f142..dae89392 100644--- a/Aetheris.Kernel.Firmament/Drawing/DrawingProjectionEngine.cs+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingProjectionEngine.cs@@ -5,6 +5,7 @@ using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Brep.Tessellation;using Aetheris.Kernel.Core.Geometry;using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Visualization;namespace Aetheris.Kernel.Firmament.Drawing;@@ -43,18 +44,23 @@ internal static class DrawingProjectionEngineforeach (var projectionBody in bodies.OrderBy(body => body.OccurrenceIdentity, StringComparer.Ordinal)){var body = projectionBody.Body;- foreach (var edge in body.Topology.Edges.OrderBy(edge => edge.Id.Value))+ var samples = BrepWireframeSvgRenderer.SampleGeometry(body, new(CurveSamples: 64, Density: 5));+ unsupported.AddRange(samples.Evidence.UnsupportedCurveFamilies.Select(kind => $"{projectionBody.OccurrenceIdentity}:curve:{kind}"));+ foreach (var line in samples.Boundaries){+ var edge = body.Topology.Edges.Single(e => e.Id.Value == line.EdgeId);if (IsCoplanarInternalEdge(body, edge.Id)) continue;- if (!body.TryGetVertexPoint(edge.StartVertexId, out var start) || !body.TryGetVertexPoint(edge.EndVertexId, out var end)) continue;- IReadOnlyList<Point3D> points;- var curved = false;- if (body.TryGetEdgeCurveGeometry(edge.Id, out var curve) && curve?.Kind == CurveGeometryKind.Circle3 && curve.Circle3 is { } circle)- { points = Enumerable.Range(0, 65).Select(i => circle.Evaluate(i * Math.Tau / 64d)).ToArray(); curved = true; }- else if (body.TryGetEdgeCurveGeometry(edge.Id, out curve) && curve?.Kind == CurveGeometryKind.Ellipse3 && curve.Ellipse3 is { } ellipse)- { points = Enumerable.Range(0, 65).Select(i => ellipse.Evaluate(i * Math.Tau / 64d)).ToArray(); curved = true; }- else points = [start, end];- raw.Add(new($"edge:{edge.Id.Value}", projectionBody.OccurrenceIdentity, projectionBody.DefinitionIdentity, points.Select(Camera).ToArray(), curved));+ var curved = body.TryGetEdgeCurveGeometry(edge.Id, out var curve) && curve?.Kind != CurveGeometryKind.Line3;+ var points = curved ? line.Points : new[] { line.Points[0], line.Points[^1] };+ raw.Add(new(line.Identity, projectionBody.OccurrenceIdentity, projectionBody.DefinitionIdentity, points.Select(Camera).ToArray(), curved));+ }+ if (hiddenPolicy == DrawingHiddenLinePolicy.Wireframe)+ {+ if (projection == DrawingProjectionKind.Isometric)+ foreach (var line in samples.Isolines)+ raw.Add(new(line.Identity, projectionBody.OccurrenceIdentity, projectionBody.DefinitionIdentity, line.Points.Select(Camera).ToArray(), false));+ unsupported.AddRange(samples.Evidence.UnsupportedSurfaceFamilies.Select(kind => $"{projectionBody.OccurrenceIdentity}:surface:{kind}"));+ continue;}// The admitted tessellator is the deterministic support-family bound. Avoid a@@ -88,7 +94,16 @@ internal static class DrawingProjectionEnginevar primitives = new List<DrawingProjectedPrimitiveIr>();var candidateSegments = 0; var visibleSegments = 0; var hiddenSegments = 0; var splitPoints = 0;- foreach (var edge in raw.OrderBy(edge => edge.Occurrence, StringComparer.Ordinal).ThenBy(edge => edge.Id, StringComparer.Ordinal))+ if (hiddenPolicy == DrawingHiddenLinePolicy.Wireframe)+ {+ foreach (var edge in raw.OrderBy(edge => edge.Occurrence, StringComparer.Ordinal).ThenBy(edge => edge.Id, StringComparer.Ordinal))+ primitives.Add(new($"{edge.Occurrence}:{edge.Id}:wireframe", edge.Id.StartsWith("face:", StringComparison.Ordinal) ? DrawingPrimitiveKind.SurfaceGrid : DrawingPrimitiveKind.Visible,+ edge.Points.Select(Page).ToArray(), edge.Occurrence, edge.Points.Average(p => p.Depth), edge.Definition,+ edge.Id.StartsWith("edge:", StringComparison.Ordinal) ? edge.Id : null));+ candidateSegments = raw.Sum(edge => edge.Points.Count - 1);+ visibleSegments = candidateSegments;+ }+ else foreach (var edge in raw.OrderBy(edge => edge.Occurrence, StringComparer.Ordinal).ThenBy(edge => edge.Id, StringComparer.Ordinal))for (var segment = 1; segment < edge.Points.Count; segment++){candidateSegments++;@@ -125,9 +140,11 @@ internal static class DrawingProjectionEnginevar hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(evidenceSource))).ToLowerInvariant();var evidence = new DrawingVisibilityEvidenceIr(candidateSegments, visibleSegments, hiddenSegments, splitPoints, triangles.Count,unsupported.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(),- "Exact B-rep edge intervals classified against deterministic bounded face triangles; depth epsilon 1e-5 mm.", hash);- return new(name, projection, hiddenPolicy, new(direction.X, direction.Y), directionSource, viewport, geometryBounds, scale,- primitives, anchors, pmi, location, evidence);+ hiddenPolicy == DrawingHiddenLinePolicy.Wireframe ? "Trimmed BRep curves with optional sampled surface isolines; rear edges retained; no hidden-line classification."+ : "Exact B-rep edge intervals classified against deterministic bounded face triangles; depth epsilon 1e-5 mm.", hash);+ return new DrawingViewIr(name, projection, hiddenPolicy, new(direction.X, direction.Y), directionSource, viewport, geometryBounds, scale,+ primitives, anchors, pmi, location, evidence)+ { Camera = new([right.X, right.Y, right.Z], [up.X, up.Y, up.Z], originX, originY) };}private static void AddIntersection(CameraPoint a, CameraPoint b, CameraPoint c, CameraPoint d, List<double> values)diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingSvgRenderer.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingSvgRenderer.csindex d3155bbd..de251f1e 100644--- a/Aetheris.Kernel.Firmament/Drawing/DrawingSvgRenderer.cs+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingSvgRenderer.cs@@ -12,7 +12,7 @@ public static class DrawingSvgRenderervar 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}.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}.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){@@ -44,7 +44,25 @@ public static class DrawingSvgRendererprivate static void RenderInformationBlock(StringBuilder builder, DrawingInformationBlockIr? block){- if (block is null) return; builder.AppendLine($"<g data-information-block=\"true\" data-zone=\"{E(block.Location.Zone)}\"><rect x=\"{F(block.Bounds.X)}\" y=\"{F(block.Bounds.Y)}\" width=\"{F(block.Bounds.Width)}\" height=\"{F(block.Bounds.Height)}\" fill=\"#fff\" stroke=\"#334155\" stroke-width=\".3\"/>");+ if (block is null) return;+ if (block.Table is { } table)+ {+ builder.AppendLine($"<g role=\"table\" aria-label=\"Drawing title block\" data-title-block=\"true\" data-zone=\"{E(block.Location.Zone)}\">");+ foreach (var row in table.Rows)+ {+ builder.AppendLine("<g role=\"row\">");+ foreach (var cell in row.Cells)+ {+ builder.AppendLine($"<g role=\"cell\" data-field=\"{E(cell.Key)}\"><rect x=\"{F(cell.Bounds.X)}\" y=\"{F(cell.Bounds.Y)}\" width=\"{F(cell.Bounds.Width)}\" height=\"{F(cell.Bounds.Height)}\" fill=\"{(cell.Emphasized ? "#f1f5f9" : "white")}\" stroke=\"#475569\" stroke-width=\".15\"/>");+ builder.AppendLine($"<text x=\"{F(cell.Bounds.X + 1)}\" y=\"{F(cell.Bounds.Y + 2.2)}\" fill=\"#64748b\" style=\"font:1.8px Inter,Arial,sans-serif\">{E(cell.Label)}</text>");+ for (var i = 0; i < cell.ValueLines.Count; i++) builder.AppendLine($"<text x=\"{F(cell.Bounds.X + 1)}\" y=\"{F(cell.Bounds.Y + 3 + cell.ValueSizeMillimetres + i * cell.ValueSizeMillimetres * 1.15)}\" fill=\"#111827\" style=\"font:{F(cell.ValueSizeMillimetres)}px Inter,Arial,sans-serif\">{E(cell.ValueLines[i])}</text>");+ builder.AppendLine("</g>");+ }+ builder.AppendLine("</g>");+ }+ builder.AppendLine($"<rect x=\"{F(block.Bounds.X)}\" y=\"{F(block.Bounds.Y)}\" width=\"{F(block.Bounds.Width)}\" height=\"{F(block.Bounds.Height)}\" fill=\"none\" stroke=\"#334155\" stroke-width=\".4\"/></g>");+ return;+ } builder.AppendLine($"<g data-information-block=\"true\" data-zone=\"{E(block.Location.Zone)}\"><rect x=\"{F(block.Bounds.X)}\" y=\"{F(block.Bounds.Y)}\" width=\"{F(block.Bounds.Width)}\" height=\"{F(block.Bounds.Height)}\" fill=\"#fff\" stroke=\"#334155\" stroke-width=\".3\"/>");var entries = block.Fields.ToArray(); var columns = 3; var cellWidth = block.Bounds.Width / columns; var rows = (int)Math.Ceiling(entries.Length / (double)columns); var cellHeight = block.Bounds.Height / rows;for (var i = 0; i < entries.Length; i++) { var x = block.Bounds.X + i % columns * cellWidth; var y = block.Bounds.Y + i / columns * cellHeight; builder.AppendLine($"<rect x=\"{F(x)}\" y=\"{F(y)}\" width=\"{F(cellWidth)}\" height=\"{F(cellHeight)}\" fill=\"none\" stroke=\"#94a3b8\" stroke-width=\".12\"/><text class=\"info-key\" x=\"{F(x + .8)}\" y=\"{F(y + 2.2)}\">{E(entries[i].Key.ToUpperInvariant())}</text><text class=\"info-value\" x=\"{F(x + .8)}\" y=\"{F(y + 5)}\">{E(entries[i].Value)}</text>"); }builder.AppendLine("</g>");@@ -66,8 +84,9 @@ public static class DrawingSvgRenderer{var leader = string.Join(" ", annotation.SelectedCandidate.Leader.Select(point => $"{F(point.X)},{F(point.Y)}"));builder.AppendLine($"<g data-annotation=\"{E(annotation.Identity)}\" data-semantic-reference=\"{E(annotation.SemanticReference)}\">");- builder.AppendLine($"<polyline class=\"leader\" points=\"{leader}\"/>");- builder.AppendLine($"<rect x=\"{F(annotation.SelectedCandidate.Body.X)}\" y=\"{F(annotation.SelectedCandidate.Body.Y)}\" width=\"{F(annotation.SelectedCandidate.Body.Width)}\" height=\"{F(annotation.SelectedCandidate.Body.Height)}\" fill=\"white\" stroke=\"#374151\" stroke-width=\".18\"/>");+ foreach (var stroke in DrawingAnnotationGeometry.Strokes(annotation))+ builder.AppendLine($"<path class=\"leader\" d=\"M {F(stroke.Start.X)} {F(stroke.Start.Y)} L {F(stroke.End.X)} {F(stroke.End.Y)}\"/>");+ builder.AppendLine($"<rect x=\"{F(annotation.SelectedCandidate.Body.X)}\" y=\"{F(annotation.SelectedCandidate.Body.Y)}\" width=\"{F(annotation.SelectedCandidate.Body.Width)}\" height=\"{F(annotation.SelectedCandidate.Body.Height)}\" fill=\"white\" stroke=\"{(annotation.Kind is DrawingAnnotationKind.Datum or DrawingAnnotationKind.FeatureControlFrame ? "#374151" : "none")}\" stroke-width=\".18\"/>");builder.AppendLine($"<text class=\"annotation\" x=\"{F(annotation.SelectedCandidate.Body.X + 1.2)}\" y=\"{F(annotation.SelectedCandidate.Body.Y + 4)}\">{E(annotation.EngineeringDisplay)}</text>");builder.AppendLine("</g>");}diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingTitleBlockLayout.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingTitleBlockLayout.csnew file mode 100644index 00000000..b81b5c63--- /dev/null+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingTitleBlockLayout.cs@@ -0,0 +1,85 @@+using System.Globalization;++namespace Aetheris.Kernel.Firmament.Drawing;++/// <summary>One table model and measured paper-space layout for all drawing backends.</summary>+internal static class DrawingTitleBlockLayout+{+ private static readonly Lazy<DrawingInterFont> Font = new(DrawingInterFont.Load);+ public static DrawingRect Bounds(double width, double height) => new(width - 177, height - 53, 170, 41);+ public static double FooterTop(double width, double height) => width >= 270 ? height - 53 : height - 87;+ public static DrawingRect NotesArea(double width, double height) => width >= 270+ ? new(10, height - 51, width - 191, 39) : new(10, height - 85, width - 20, 30);++ public static DrawingInformationBlockIr Create(DrawingMetadataIr metadata, IReadOnlyDictionary<string, string> fields,+ double width, double height, DrawingLocationIr location)+ {+ var bounds = Bounds(width, height);+ var signoff = metadata.Signoff ?? new(new(metadata.Author, metadata.Date), new(), new());+ var values = new Dictionary<string, string>(fields, StringComparer.Ordinal)+ {+ ["DrawnBy"] = signoff.Drawn.Name ?? "", ["DrawnDate"] = signoff.Drawn.Date ?? "",+ ["CheckedBy"] = signoff.Checked.Name ?? "", ["CheckedDate"] = signoff.Checked.Date ?? "",+ ["ApprovedBy"] = signoff.Approved.Name ?? "", ["ApprovedDate"] = signoff.Approved.Date ?? ""+ };+ var rows = new List<DrawingTitleBlockRowIr>();+ var column = bounds.Width / 6; var y = bounds.Y;+ void Row(double h, params (string Key, string Label, string Value, int Span, double Size)[] specs)+ {+ var x = bounds.X; var cells = new List<DrawingTitleBlockCellIr>();+ foreach (var s in specs)+ {+ var rect = new DrawingRect(x, y, column * s.Span, h);+ var lines = Wrap(s.Value, rect.Width - 2, s.Size);+ if (lines.Count * s.Size * 1.15 + 3 > h)+ throw new InvalidOperationException($"drawing-title-block-overflow: '{s.Label}' does not fit its table cell. Shorten this presentation value; engineering data was not truncated.");+ cells.Add(new(s.Key, s.Label, s.Value, s.Span, rect, lines, s.Size, rows.Count == 0)); x += rect.Width;+ }+ rows.Add(new(h, cells)); y += h;+ }+ Row(11, ("Title", metadata.Company ?? "ENGINEERING DRAWING", metadata.Title, 4, 3.2),+ ("Drawing", "DRAWING", metadata.DrawingIdentity, 2, 2.6));+ Row(8, ("Material", "MATERIAL", metadata.Material ?? "", 3, 2.6),+ ("Part", "PART NUMBER", metadata.PartNumber ?? "", 2, 2.6), ("Revision", "REV", metadata.Revision?.ToString() ?? "", 1, 2.6));+ Row(7, ("Scale", "SCALE", fields.GetValueOrDefault("Scale", ""), 2, 2.4), ("Units", "UNITS", fields.GetValueOrDefault("Units", "mm"), 1, 2.4),+ ("Page", "SHEET", fields.GetValueOrDefault("Page", fields.GetValueOrDefault("Sheet", "")), 1, 2.4),+ ("Status", "STATUS", fields.GetValueOrDefault("Status", "ENGINEERING REVIEW"), 2, 2.4));+ Row(8, ("DrawnBy", "DRAWN BY", values["DrawnBy"], 2, 2.6), ("CheckedBy", "CHECKED BY", values["CheckedBy"], 2, 2.6),+ ("ApprovedBy", "APPROVED BY", values["ApprovedBy"], 2, 2.6));+ Row(7, ("DrawnDate", "DRAWN DATE", values["DrawnDate"], 2, 2.4), ("CheckedDate", "CHECKED DATE", values["CheckedDate"], 2, 2.4),+ ("ApprovedDate", "APPROVED DATE", values["ApprovedDate"], 2, 2.4));+ return new(bounds, location, values) { Table = new(Enumerable.Repeat(column, 6).ToArray(), rows) };+ }++ public static IReadOnlyList<string> Wrap(string text, double width, double size)+ {+ if (string.IsNullOrEmpty(text)) return [];+ var result = new List<string>(); var line = "";+ foreach (var word in text.Split(' ', StringSplitOptions.RemoveEmptyEntries))+ {+ var candidate = line.Length == 0 ? word : line + " " + word;+ if (Font.Value.MeasureMillimetres(candidate, size) <= width) { line = candidate; continue; }+ if (line.Length > 0) { result.Add(line); line = ""; }+ foreach (var c in word)+ {+ if (line.Length > 0 && Font.Value.MeasureMillimetres(line + c, size) > width) { result.Add(line); line = ""; }+ line += c;+ }+ }+ if (line.Length > 0) result.Add(line);+ return result;+ }++ public static string? ValidateSignoff(DrawingSignoffIr? signoff)+ {+ if (signoff is null) return null;+ foreach (var (role, entry) in new[] { ("Drawn", signoff.Drawn), ("Checked", signoff.Checked), ("Approved", signoff.Approved) })+ {+ if (string.IsNullOrWhiteSpace(entry.Name) != string.IsNullOrWhiteSpace(entry.Date))+ return $"drawing-signoff-incomplete: {role} requires both a name and date, or both must be blank.";+ if (!string.IsNullOrWhiteSpace(entry.Date) && !DateOnly.TryParseExact(entry.Date, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _))+ return $"drawing-date-iso-invalid: {role} date '{entry.Date}' must be yyyy-MM-dd.";+ }+ return null;+ }+}diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingVectorPdfWriter.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingVectorPdfWriter.csindex bcc0ce7e..9b481c3b 100644--- a/Aetheris.Kernel.Firmament/Drawing/DrawingVectorPdfWriter.cs+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingVectorPdfWriter.cs@@ -34,7 +34,7 @@ public static class DrawingVectorPdfWriter}objects[pagesObject] = Encoding.ASCII.GetBytes($"<< /Type /Pages /Count {pageObjects.Count} /Kids [{string.Join(" ", pageObjects.Select(value => $"{value} 0 R"))}] >>");var catalog = Add($"<< /Type /Catalog /Pages {pagesObject} 0 R >>");- var info = Add($"<< /Title ({PdfAscii(drawing.Metadata.Title)}) /Subject ({PdfAscii(drawing.Metadata.Description ?? drawing.Metadata.ProductName)}) /Author ({PdfAscii(drawing.Metadata.Author ?? "Aetheris")}) /Creator (Aetheris Drawing M0B) /Producer (Aetheris native vector PDF) /Keywords (Revision {drawing.Metadata.Revision?.ToString() ?? "-"}; Date {drawing.Metadata.Date ?? "-"}; Inter embedded) /CreationDate (D:20260810000000-07'00') /ModDate (D:20260810000000-07'00') >>");+ var info = Add($"<< /Title ({PdfAscii(drawing.Metadata.Title)}) /Subject ({PdfAscii(drawing.Metadata.Description ?? drawing.Metadata.ProductName)}) /Author ({PdfAscii(drawing.Metadata.Signoff?.Drawn.Name ?? drawing.Metadata.Author ?? "Aetheris")}) /Creator (Aetheris Drawing M0B) /Producer (Aetheris native vector PDF) /Keywords (Revision {drawing.Metadata.Revision?.ToString() ?? "-"}; Date {drawing.Metadata.Date ?? "-"}; Inter embedded) {PdfDateMetadata(drawing.Metadata)} >>");using var output = new MemoryStream(); Write(output, "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n"); var offsets = new long[objects.Count];for (var index = 1; index < objects.Count; index++) { offsets[index] = output.Position; Write(output, $"{index} 0 obj\n"); output.Write(objects[index]); Write(output, "\nendobj\n"); }var xref = output.Position; Write(output, $"xref\n0 {objects.Count}\n0000000000 65535 f \n"); for (var index = 1; index < objects.Count; index++) Write(output, $"{offsets[index]:0000000000} 00000 n \n");@@ -44,8 +44,8 @@ public static class DrawingVectorPdfWriterprivate static byte[] BuildPage(DrawingIr drawing, DrawingPageIr page){var b = new StringBuilder(); var inter = DrawingInterFont.Load(); double X(double mm) => Pt(mm); double Y(double mm) => Pt(page.HeightMillimetres - mm);- void Line(DrawingPoint2 a, DrawingPoint2 c, double width = .25, bool dashed = false) => b.Append($"{F(width)} w {(dashed ? "[5 3] 0 d" : "[] 0 d")} {F(X(a.X))} {F(Y(a.Y))} m {F(X(c.X))} {F(Y(c.Y))} l S\n");- void Rect(DrawingRect rect, double width = .2, bool fill = false) => b.Append($"{F(width)} w {F(X(rect.X))} {F(Y(rect.Bottom))} {F(X(rect.Width))} {F(X(rect.Height))} re {(fill ? "B" : "S")}\n");+ void Line(DrawingPoint2 a, DrawingPoint2 c, double width = .25, bool dashed = false) => b.Append($"{F(Pt(width))} w {(dashed ? "[5 3] 0 d" : "[] 0 d")} {F(X(a.X))} {F(Y(a.Y))} m {F(X(c.X))} {F(Y(c.Y))} l S\n");+ void Rect(DrawingRect rect, double width = .2, bool fill = false) => b.Append($"{F(Pt(width))} w {F(X(rect.X))} {F(Y(rect.Bottom))} {F(X(rect.Width))} {F(X(rect.Height))} re {(fill ? "B" : "S")}\n");void Text(double x, double y, string text, double size = 8) => b.Append($"BT /F1 {F(size)} Tf {F(X(x))} {F(Y(y))} Td <{Utf16Hex(text)}> Tj ET\n");void RightText(double right, double y, string text, double size = 8) => Text(right - inter.MeasureMillimetres(text, size / PointsPerMillimetre), y, text, size);RenderZones(page, Line, Rect, Text);@@ -53,12 +53,19 @@ public static class DrawingVectorPdfWriterforeach (var view in page.Views){Text(view.Viewport.X, view.Viewport.Y + 3.5, $"{view.Identity} SCALE ×{view.Scale:0.###}", 7);- foreach (var primitive in view.Primitives) for (var index = 1; index < primitive.Points.Count; index++) Line(primitive.Points[index - 1], primitive.Points[index], primitive.Kind == DrawingPrimitiveKind.Silhouette ? .55 : .35, primitive.Kind == DrawingPrimitiveKind.Hidden);+ 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);+ }+ b.Append("0 0 0 RG\n");}foreach (var annotation in page.Annotations){- for (var index = 1; index < annotation.SelectedCandidate.Leader.Count; index++) Line(annotation.SelectedCandidate.Leader[index - 1], annotation.SelectedCandidate.Leader[index], .25);- b.Append("1 1 1 rg "); Rect(annotation.SelectedCandidate.Body, .25, true); b.Append("0 0 0 rg\n"); Text(annotation.SelectedCandidate.Body.X + 1, annotation.SelectedCandidate.Body.Y + 4.2, annotation.EngineeringDisplay, 7);+ foreach (var stroke in DrawingAnnotationGeometry.Strokes(annotation)) Line(stroke.Start, stroke.End, .25);+ b.Append("1 1 1 rg "); b.Append($"{F(X(annotation.SelectedCandidate.Body.X))} {F(Y(annotation.SelectedCandidate.Body.Bottom))} {F(X(annotation.SelectedCandidate.Body.Width))} {F(X(annotation.SelectedCandidate.Body.Height))} re f\n");+ b.Append("0 0 0 rg\n");+ if (annotation.Kind is DrawingAnnotationKind.Datum or DrawingAnnotationKind.FeatureControlFrame) Rect(annotation.SelectedCandidate.Body); Text(annotation.SelectedCandidate.Body.X + 1, annotation.SelectedCandidate.Body.Y + 4.2, annotation.EngineeringDisplay, 3.2 * PointsPerMillimetre);}foreach (var table in page.Tables) RenderTable(table, page.ContentRect, b, Rect, Text);foreach (var note in page.LocatedNotes ?? []) Text(note.Bounds.X, note.Bounds.Y + 3, note.Text, 7);@@ -82,6 +89,20 @@ public static class DrawingVectorPdfWriterprivate static void RenderInformation(DrawingInformationBlockIr? block, StringBuilder b, Action<DrawingRect, double, bool> rect, Action<double, double, string, double> text){+ if (block is null) return;+ if (block.Table is { } table)+ {+ b.Append("0 0 0 RG 1 1 1 rg "); rect(block.Bounds, .4, true);+ foreach (var row in table.Rows) foreach (var cell in row.Cells)+ {+ b.Append(cell.Emphasized ? "0.94 0.96 0.98 rg " : "1 1 1 rg "); rect(cell.Bounds, .15, true);+ b.Append("0.35 0.40 0.46 rg "); text(cell.Bounds.X + 1, cell.Bounds.Y + 2.2, cell.Label, Pt(1.8));+ b.Append("0.07 0.09 0.12 rg ");+ for (var i = 0; i < cell.ValueLines.Count; i++) text(cell.Bounds.X + 1, cell.Bounds.Y + 3 + cell.ValueSizeMillimetres + i * cell.ValueSizeMillimetres * 1.15, cell.ValueLines[i], Pt(cell.ValueSizeMillimetres));+ }+ b.Append("0 0 0 rg\n"); rect(block.Bounds, .4, false);+ return;+ }if (block is null) return; b.Append("1 1 1 rg "); rect(block.Bounds, .35, true); b.Append("0 0 0 rg\n"); var entries = block.Fields.ToArray(); const int columns = 3; var rows = (int)Math.Ceiling(entries.Length / 3d); var width = block.Bounds.Width / columns; var height = block.Bounds.Height / rows;for (var index = 0; index < entries.Length; index++) { var cell = new DrawingRect(block.Bounds.X + index % columns * width, block.Bounds.Y + index / columns * height, width, height); rect(cell, .12, false); text(cell.X + .8, cell.Y + 2.2, entries[index].Key.ToUpperInvariant(), 4.8); text(cell.X + .8, cell.Y + 5, entries[index].Value, 6.2); }}@@ -104,6 +125,13 @@ public static class DrawingVectorPdfWriterprivate static string Utf16Hex(string value) => Convert.ToHexString(Encoding.BigEndianUnicode.GetBytes(value));private static double Pt(double millimetres) => millimetres * PointsPerMillimetre;private static string F(double value) => value.ToString("0.###", CultureInfo.InvariantCulture);+ private static string PdfDateMetadata(DrawingMetadataIr metadata)+ {+ var date = metadata.Signoff?.Drawn.Date ?? metadata.Date;+ return DateOnly.TryParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var value)+ ? $"/CreationDate (D:{value:yyyyMMdd}) /ModDate (D:{value:yyyyMMdd})" : "";+ }+private static string PdfAscii(string value) => string.Concat(value.Select(character => character is >= ' ' and <= '~' ? character : '?')).Replace("\\", "\\\\", StringComparison.Ordinal).Replace("(", "\\(", StringComparison.Ordinal).Replace(")", "\\)", StringComparison.Ordinal);private static void Write(Stream stream, string value) => stream.Write(Encoding.Latin1.GetBytes(value));}diff --git a/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingCompiler.cs b/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingCompiler.csindex 618d699f..7c127192 100644--- a/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingCompiler.cs+++ b/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingCompiler.cs@@ -38,12 +38,16 @@ public static partial class FirmamentDrawingCompilerpublic static bool IsDrawingSource(string source)=>source.Contains("Drawing",StringComparison.Ordinal)&& FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document).Any(d=>d.Type.Name.Text=="Drawing" && d.Modifiers.Count==0);- public static DrawingCompileResult Compile(string sourcePath, string outputDirectory)+ public static DrawingCompileResult Compile(string sourcePath, string outputDirectory) => Compile(sourcePath, outputDirectory, null);++ public static DrawingCompileResult Compile(string sourcePath, string outputDirectory, DrawingSignoffIr? signoff){var frontend=new List<FirmamentV2ValidationDiagnostic>();- return CompileCore(sourcePath,outputDirectory,frontend) with {FrontendDiagnostics=frontend};+ if (DrawingTitleBlockLayout.ValidateSignoff(signoff) is { } error) return Failure(error);+ try { return CompileCore(sourcePath, outputDirectory, frontend, signoff) with { FrontendDiagnostics = frontend }; }+ catch (InvalidOperationException e) when (e.Message.StartsWith("drawing-", StringComparison.Ordinal)) { return Failure(e.Message); }}- private static DrawingCompileResult CompileCore(string sourcePath,string outputDirectory,List<FirmamentV2ValidationDiagnostic> frontend)+ private static DrawingCompileResult CompileCore(string sourcePath,string outputDirectory,List<FirmamentV2ValidationDiagnostic> frontend, DrawingSignoffIr? signoff){var fullSourcePath = Path.GetFullPath(sourcePath); var output = Path.GetFullPath(outputDirectory);if (!File.Exists(fullSourcePath)) return Failure($"drawing-source-file-missing: {fullSourcePath}");@@ -61,6 +65,7 @@ public static partial class FirmamentDrawingCompilervar metadataResult = ResolveMetadata(drawingSourceText, drawingSource);if (metadataResult.Diagnostics.Count > 0) return new(false, null, metadataResult.Diagnostics);var metadata = metadataResult.Metadata!;+ if (signoff is not null) metadata = metadata with { Signoff = signoff, Author = signoff.Drawn.Name, Date = signoff.Drawn.Date };var geometrySource = EraseDrawingDeclarations(drawingSourceText, parse.Ranges);var sourceWatch = Stopwatch.StartNew();@@ -139,13 +144,19 @@ public static partial class FirmamentDrawingCompilernew(sourceWatch.Elapsed.TotalMilliseconds, projectionWatch.Elapsed.TotalMilliseconds, layoutWatch.Elapsed.TotalMilliseconds, 0, 0, bomMilliseconds), [],"Exact B-rep occurrence edges; bounded segment-split occlusion against deterministic face tessellation. Unsupported patches are conservative and explicit.", typography, reviewResult.Review);- var stem = Sanitize(drawingSource.Name); var irPath = Path.Combine(output, $"{stem}.drawing.json");+ return WriteArtifacts(preliminary, output, bodies.Count, bom?.Items.Count ?? 0);+ }++ private static DrawingCompileResult WriteArtifacts(DrawingIr preliminary, string output, int occurrenceCount, int bomRows)+ {+ Directory.CreateDirectory(output);+ var stem = Sanitize(preliminary.Identity); var irPath = Path.Combine(output, $"{stem}.drawing.json");var svgPath = Path.Combine(output, $"{stem}.svg"); var pdfPath = Path.Combine(output, $"{stem}.pdf");var validationPath = Path.Combine(output, $"{stem}.validation.json");var pptxPath = Path.Combine(output, $"{stem}.pptx");- var reviewPptxPath = reviewResult.Review!.Threads.Count == 0 ? null : Path.Combine(output, $"{stem.Replace("Production", "Review", StringComparison.Ordinal)}.pptx");- var dfmPptxPath = reviewResult.Review.Threads.Count == 0 ? null : Path.Combine(output, $"{stem.Replace("Production", "DfmReview", StringComparison.Ordinal)}.pptx");- var reviewIrPath = reviewResult.Review.Threads.Count == 0 ? null : Path.Combine(output, $"{stem}.review.json");+ var reviewPptxPath = (preliminary.Reviews?.Threads.Count ?? 0) == 0 ? null : Path.Combine(output, $"{stem.Replace("Production", "Review", StringComparison.Ordinal)}.pptx");+ var dfmPptxPath = (preliminary.Reviews?.Threads.Count ?? 0) == 0 ? null : Path.Combine(output, $"{stem.Replace("Production", "DfmReview", StringComparison.Ordinal)}.pptx");+ var reviewIrPath = (preliminary.Reviews?.Threads.Count ?? 0) == 0 ? null : Path.Combine(output, $"{stem}.review.json");var renderWatch = Stopwatch.StartNew(); File.WriteAllText(svgPath, DrawingSvgRenderer.Render(preliminary), new UTF8Encoding(false)); renderWatch.Stop();var pdfWatch = Stopwatch.StartNew(); DrawingVectorPdfWriter.Write(preliminary, pdfPath); pdfWatch.Stop();var measured = preliminary.Performance with { RenderMilliseconds = renderWatch.Elapsed.TotalMilliseconds, PdfMilliseconds = pdfWatch.Elapsed.TotalMilliseconds };@@ -155,20 +166,21 @@ public static partial class FirmamentDrawingCompilervar reviewPptxMilliseconds = 0d; var dfmDeckMilliseconds = 0d;if (reviewPptxPath is not null) { var watch = Stopwatch.StartNew(); DrawingPptxWriter.WriteDrawing(drawing, reviewPptxPath, includeReviews: true); watch.Stop(); reviewPptxMilliseconds = watch.Elapsed.TotalMilliseconds; }if (dfmPptxPath is not null) { var watch = Stopwatch.StartNew(); DrawingPptxWriter.WriteDfmDeck(drawing, dfmPptxPath); watch.Stop(); dfmDeckMilliseconds = watch.Elapsed.TotalMilliseconds; }- if (reviewIrPath is not null) File.WriteAllText(reviewIrPath, JsonSerializer.Serialize(reviewResult.Review, JsonOptions), new UTF8Encoding(false));+ if (reviewIrPath is not null) File.WriteAllText(reviewIrPath, JsonSerializer.Serialize(preliminary.Reviews, JsonOptions), new UTF8Encoding(false));var irHash = HashBytes(Encoding.UTF8.GetBytes(json)); var pdfHash = HashBytes(File.ReadAllBytes(pdfPath));var pptxHash = HashBytes(File.ReadAllBytes(pptxPath));var validation = new{- success = true, schema = drawing.SchemaVersion, authoritativeSource = drawing.Provenance.SourceProductIdentity, sourceKind,+ success = true, schema = drawing.SchemaVersion, authoritativeSource = drawing.Provenance.SourceProductIdentity, sourceKind = drawing.Provenance.SourceKind,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,pptx = DrawingPptxWriter.Inspect(pptxPath), reviewPptx = reviewPptxPath is null ? null : DrawingPptxWriter.Inspect(reviewPptxPath),- occurrenceCount = bodies.Count, bomRows = bom?.Items.Count ?? 0,+ occurrenceCount, bomRows,visibleSegments = drawing.Pages.SelectMany(page => page.Views).Sum(view => view.VisibilityEvidence?.VisibleSegments ?? 0),hiddenSegments = drawing.Pages.SelectMany(page => page.Views).Sum(view => view.VisibilityEvidence?.HiddenSegments ?? 0),splitPoints = drawing.Pages.SelectMany(page => page.Views).Sum(view => view.VisibilityEvidence?.SplitPointCount ?? 0),- drawing.LayoutEvidence.TextModelCollisionsAfter, drawing.LayoutEvidence.TextTextCollisionsAfter, drawing.LayoutEvidence.FailedAnnotationCount,+ drawing.LayoutEvidence.TextModelCollisionsAfter, drawing.LayoutEvidence.TextTextCollisionsAfter, drawing.LayoutEvidence.TextLeaderCollisionsAfter, drawing.LayoutEvidence.FailedAnnotationCount,drawingIrSha256 = irHash, pdfSha256 = pdfHash, pptxSha256 = pptxHash, measuredPerformance = measured,pptxPerformance = new { drawingMilliseconds = pptxWatch.Elapsed.TotalMilliseconds, reviewProjectionMilliseconds = reviewPptxMilliseconds, dfmDeckMilliseconds }};@@ -182,7 +194,7 @@ public static partial class FirmamentDrawingCompilervar landscape = drawing.Orientation == DrawingPageOrientation.Landscape;var width = landscape ? 297d : 210d; var height = landscape ? 210d : 297d;var content = new DrawingRect(10, 16, width - 20, height - 40); var scheme = Zones(width, height);- var viewAreaHeight = content.Height - 22; var columns = Math.Max(1, drawing.Views.Count <= 2 ? drawing.Views.Count : 2);+ var viewAreaHeight = DrawingTitleBlockLayout.FooterTop(width, height) - content.Y - 6; var columns = Math.Max(1, drawing.Views.Count <= 2 ? drawing.Views.Count : 2);var rows = (int)Math.Ceiling(drawing.Views.Count / (double)columns); const double gap = 8;var cellWidth = (content.Width - gap * Math.Max(0, columns - 1)) / columns;var cellHeight = (viewAreaHeight - gap * Math.Max(0, rows - 1)) / Math.Max(1, rows);@@ -194,9 +206,9 @@ public static partial class FirmamentDrawingCompilervar source = drawing.Views[index];views.Add(DrawingProjectionEngine.Project(bodies, source.Name, source.Projection, source.HiddenLines, source.Direction, source.Pmi, viewport, location));}- var notes = LocateNotes(drawing.Notes, 1, scheme, new DrawingRect(content.X, height - 31, Math.Max(20, content.Width - 100), 16));+ var notes = LocateNotes(drawing.Notes, 1, scheme, DrawingTitleBlockLayout.NotesArea(width, height));var tables = new List<DrawingTableIr>(designTables); if (bom is not null) tables.Add(bom.Table);- var rowCapacity = Math.Max(1, (int)Math.Floor((content.Height - 25) / 7d) - 1);+ var rowCapacity = Math.Max(1, (int)Math.Floor((DrawingTitleBlockLayout.FooterTop(width, height) - content.Y - 12) / 7d) - 1);var slices = new List<(DrawingTableIr Table, DrawingBomIr? Bom)>();foreach (var table in tables){@@ -215,7 +227,7 @@ public static partial class FirmamentDrawingCompilerfor (var index = 0; index < slices.Count; index++){var pageNumber = index + 2; var slice = slices[index];- var bounds = new DrawingRect(content.X, content.Y + 10, content.Width, Math.Min(content.Height - 25, 8 + slice.Table.Rows.Count * 7));+ var bounds = new DrawingRect(content.X, content.Y + 10, content.Width, Math.Min(DrawingTitleBlockLayout.FooterTop(width, height) - content.Y - 12, 8 + slice.Table.Rows.Count * 7));var located = slice.Table with { Bounds = bounds, Location = new(pageNumber, ZoneAt(scheme, bounds.Center)) };pages.Add(new(pageNumber, drawing.Orientation, width, height, content, [], [], [located], [], scheme,InfoBlock(metadata, drawing, views, pageNumber, width, height, scheme, totalPages), [], slice.Bom is null ? null : slice.Bom with { Table = located }));@@ -240,7 +252,7 @@ public static partial class FirmamentDrawingCompilerprivate static DrawingInformationBlockIr InfoBlock(DrawingMetadataIr metadata, ParsedDrawing drawing, IReadOnlyList<DrawingViewIr> views, int page, double width, double height, DrawingPageZoneSchemeIr scheme, int pageCount){- var bounds = new DrawingRect(width - 122, height - 34, 115, 22);+ var bounds = DrawingTitleBlockLayout.Bounds(width, height);var scales = views.Count == 0 ? "-" : views.All(view => Math.Abs(view.Scale - views[0].Scale) < 1e-6) ? $"×{views[0].Scale:0.###}" : "MULTIPLE";var fields = new Dictionary<string, string>(StringComparer.Ordinal){@@ -248,11 +260,16 @@ public static partial class FirmamentDrawingCompiler["Part"] = metadata.PartNumber ?? "-", ["Revision"] = metadata.Revision?.ToString() ?? "-", ["Author"] = metadata.Author ?? "-",["Date"] = metadata.Date ?? "-", ["Scale"] = scales, ["Page"] = $"{page}/{pageCount}"};- return new(bounds, new(page, ZoneAt(scheme, bounds.Center)), fields);+ return DrawingTitleBlockLayout.Create(metadata, fields, width, height, new(page, ZoneAt(scheme, bounds.Center)));}- private static IReadOnlyList<DrawingNoteIr> LocateNotes(IReadOnlyList<string> notes, int page, DrawingPageZoneSchemeIr scheme, DrawingRect area) => notes.Select((text, index) =>- new DrawingNoteIr($"note:{index + 1}", text, new(area.X, area.Y + index * 4, area.Width, 4), new(page, ZoneAt(scheme, new(area.X + area.Width / 2, area.Y + index * 4 + 2))))).ToArray();+ private static IReadOnlyList<DrawingNoteIr> LocateNotes(IReadOnlyList<string> notes, int page, DrawingPageZoneSchemeIr scheme, DrawingRect area)+ {+ var lines = notes.SelectMany((text, index) => DrawingTitleBlockLayout.Wrap(text, area.Width, 2.8).Select((line, n) => (Text: line, Identity: $"note:{index + 1}:{n}"))).ToArray();+ if (lines.Length * 4 > area.Height) throw new InvalidOperationException("drawing-notes-overflow: Notes exceed the reserved sheet area after wrapping. Use an authored notes/table sheet or shorten presentation notes.");+ return lines.Select((line, i) => new DrawingNoteIr(line.Identity, line.Text, new(area.X, area.Y + i * 4, area.Width, 4),+ new(page, ZoneAt(scheme, new(area.X + area.Width / 2, area.Y + i * 4 + 2))))).ToArray();+ }private static IReadOnlyList<DrawingPageIr> LocateAnnotations(IReadOnlyList<DrawingPageIr> pages) => pages.Select(page => page with{@@ -358,6 +375,10 @@ public static partial class FirmamentDrawingCompilervar date = Value("Date"); if (date is not null && !DateOnly.TryParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _)) diagnostics.Add($"{DrawingDateInvalid}: {date}");var metadata = new DrawingMetadataIr(Value("Title", drawing.Title ?? drawing.Name)!, drawing.Source, Value("PartNumber", drawing.PartNumber), revision,Value("Material", drawing.Material), drawing.Name, drawing.Template, Value("Company"), Value("Author"), date, Value("Description"), drawing.Metadata, provenance);+ var signoff = new DrawingSignoffIr(new(Value("DrawnBy", metadata.Author), Value("DrawnDate", metadata.Date)),+ new(Value("CheckedBy"), Value("CheckedDate")), new(Value("ApprovedBy"), Value("ApprovedDate")));+ if (DrawingTitleBlockLayout.ValidateSignoff(signoff) is { } signoffError) diagnostics.Add(signoffError);+ metadata = metadata with { Signoff = signoff };return new(metadata, diagnostics);}diff --git a/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingSyntax.cs b/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingSyntax.csindex 64d9a876..9c9428dc 100644--- a/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingSyntax.cs+++ b/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingSyntax.cs@@ -118,7 +118,7 @@ public static partial class FirmamentDrawingCompilervar projection=view.Word("Projection");if(projection is not (null or "Orthographic" or "Isometric"))view.Invalid("Projection");var hidden=view.Word("HiddenLines")??"VisibleOnly";- if(hidden is not ("VisibleOnly" or "VisibleAndHidden"))view.Invalid("HiddenLines");+ if(hidden is not ("VisibleOnly" or "VisibleAndHidden" or "Wireframe"))view.Invalid("HiddenLines");var pmi=List(view,"PMI",false);var kind=projection=="Isometric" || projection is null && direction.Count(v=>Math.Abs(v)>1e-12)>1?DrawingProjectionKind.Isometric:DrawingProjectionKind.Orthographic;views.Add(new(view.Name,direction,kind,hidden=="VisibleAndHidden"?DrawingHiddenLinePolicy.VisibleAndHidden:DrawingHiddenLinePolicy.VisibleOnly,pmi));diff --git a/Aetheris.Kernel.Firmament/Execution/FirmamentSelectorResolver.cs b/Aetheris.Kernel.Firmament/Execution/FirmamentSelectorResolver.csindex 184094cb..c68f9123 100644--- a/Aetheris.Kernel.Firmament/Execution/FirmamentSelectorResolver.cs+++ b/Aetheris.Kernel.Firmament/Execution/FirmamentSelectorResolver.cs@@ -1,5 +1,7 @@using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Topology;+using Aetheris.Kernel.Core.Math;using Aetheris.Kernel.Core.Geometry.Curves;using Aetheris.Kernel.Firmament.ParsedModel;using Aetheris.Kernel.Firmament.Validation;@@ -8,6 +10,19 @@ namespace Aetheris.Kernel.Firmament.Execution;internal static class FirmamentSelectorResolver{+ /// <summary>Resolve an existing axis-face port only when it denotes exactly one planar face.+ /// A stepped body with multiple same-facing planes remains ambiguous.</summary>+ internal static IReadOnlyList<FaceId> ResolveUniquePlanarFace(BrepBody body, string selector)+ {+ var port = selector[(selector.LastIndexOf('.') + 1)..];+ Vector3D? axis = port switch { "top_face" => new(0, 0, 1), "bottom_face" => new(0, 0, -1),+ "plus_x_face" => new(1, 0, 0), "minus_x_face" => new(-1, 0, 0), "plus_y_face" => new(0, 1, 0), "minus_y_face" => new(0, -1, 0), _ => null };+ if (axis is null) return [];+ var faces = body.Topology.Faces.Where(face => body.TryGetFaceSurfaceGeometry(face.Id, out var surface)+ && surface?.Plane is { } plane && plane.Normal.ToVector().Dot(axis.Value) > 1 - 1e-8).Select(face => face.Id).ToArray();+ return faces.Length == 1 ? faces : [];+ }+public static bool TryResolve(string selectorTarget,IReadOnlyDictionary<string, BrepBody> featureBodies,diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex feea6c89..ef7ca0f4 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -487,7 +487,7 @@ public static class FirmamentBuildAndExportif (!support.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(support.Diagnostics);var features = (stack.Feature.ShaftHoles ?? []).ToDictionary(hole => hole.Name, hole => hole.StableId, StringComparer.Ordinal);foreach (var hole in stack.Feature.CounterboreHoles ?? []) features[hole.Name] = hole.StableId;- semanticPmi = BuildV2SemanticPmi(v2Parse.Document, [], stack.Feature.Name, features, emitted.Correspondence).ToArray();+ semanticPmi = BuildV2SemanticPmi(v2Parse.Document, [], stack.Feature.Name, features, emitted.Correspondence, completedBody).ToArray();}var step = Step242Exporter.ExportBody(completedBody, semanticPmi);if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);@@ -605,7 +605,7 @@ public static class FirmamentBuildAndExportreturn KernelResult<FirmamentStepExportResult>.Failure(execution.Diagnostics);}- var semanticPmi = BuildV2SemanticPmi(v2Parse.Document, [], executedPrimitive.FeatureId);+ var semanticPmi = BuildV2SemanticPmi(v2Parse.Document, [], executedPrimitive.FeatureId, body: executedPrimitive.Body);var step = Step242Exporter.ExportBody(executedPrimitive.Body, semanticPmi);if (!step.IsSuccess){@@ -1131,7 +1131,7 @@ public static class FirmamentBuildAndExportif (!support.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(support.Diagnostics);var features = (stack.Feature.ShaftHoles ?? []).ToDictionary(hole => hole.Name, hole => hole.StableId, StringComparer.Ordinal);foreach (var hole in stack.Feature.CounterboreHoles ?? []) features[hole.Name] = hole.StableId;- semanticPmi = BuildV2SemanticPmi(canonicalDocument, [], stack.Feature.Name, features, plannedEmission.Correspondence).ToArray();+ semanticPmi = BuildV2SemanticPmi(canonicalDocument, [], stack.Feature.Name, features, plannedEmission.Correspondence, plannedEmission.Body).ToArray();}var plannedStep = Step242Exporter.ExportBody(plannedEmission.Body, semanticPmi, new Step242ExportOptions { ProductName = target.StableId, ApplicationName = "Aetheris.Firmament.ComposedProfileBoundaryChamfer.M3", BrepExportPreflightMode = BrepExportPreflightMode.Enforce, BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });if (!plannedStep.IsSuccess || plannedStep.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(plannedStep.Diagnostics);@@ -1494,7 +1494,7 @@ public static class FirmamentBuildAndExport{return KernelResult<FirmamentStepExportResult>.Failure(pmiSupport.Diagnostics);}- var semanticPmi = BuildV2SemanticPmi(document, holes, solid.Name);+ var semanticPmi = BuildV2SemanticPmi(document, holes, solid.Name, body: body);var step = Step242Exporter.ExportBody(body, semanticPmi);if (!step.IsSuccess || step.Value is null){@@ -1575,7 +1575,7 @@ public static class FirmamentBuildAndExportreturn CombinedFailure("CombinedFeatureMaterializerDiverged: fillet boundary failed analytic export preflight.", preflight.Diagnostics.Select(d => d.Message), finish.SourceSpan);var pmiSupport = ValidateV2PmiExportSupport(document);if (!pmiSupport.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(pmiSupport.Diagnostics);- var step = Step242Exporter.ExportBody(built.Value, BuildV2SemanticPmi(document, [], solid.Name));+ var step = Step242Exporter.ExportBody(built.Value, BuildV2SemanticPmi(document, [], solid.Name, body: built.Value));if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);var imported = Step242Importer.ImportBody(step.Value);if (!imported.IsSuccess || imported.Value is null || !FirmamentManifoldChecker.IsManifold(imported.Value))@@ -2290,7 +2290,7 @@ public static class FirmamentBuildAndExportreturn KernelResult<FirmamentStepExportResult>.Failure(semanticPmiValidation.Diagnostics);}- var semanticPmi = BuildV2SemanticPmi(document, [], solid.Name);+ var semanticPmi = BuildV2SemanticPmi(document, [], solid.Name, body: import.Value);var export = Step242Exporter.ExportBody(import.Value, semanticPmi, new Step242ExportOptions{ProductName = solid.Name,@@ -2677,7 +2677,7 @@ public static class FirmamentBuildAndExportif (!resolution.Succeeded)return SemanticHoleFailure([$"firmament-v2-hole-wall-role-unavailable:{selector.HoleName}:{resolution.Failure}"]);}- var semanticPmi = BuildV2SemanticPmi(document, semanticHoles, modifyTargets[0], correspondence: runtimeCorrespondence);+ var semanticPmi = BuildV2SemanticPmi(document, semanticHoles, modifyTargets[0], correspondence: runtimeCorrespondence, body: body);// Semantic-hole/profile-stack and bounded-Boolean routes remain Audit until their// historical coincident/seam topology is remediated producer-by-producer.var step = Step242Exporter.ExportBody(body, semanticPmi);@@ -2768,7 +2768,8 @@ public static class FirmamentBuildAndExportIReadOnlyList<Core.Air.AirHoleFeature> semanticHoles,string targetSolid,IReadOnlyDictionary<string, string>? explicitFeatureIds = null,- SemanticTopologyCorrespondence? correspondence = null)+ SemanticTopologyCorrespondence? correspondence = null,+ BrepBody? body = null){if (document.Pmi is null || document.Pmi.Count == 0){@@ -2788,19 +2789,19 @@ public static class FirmamentBuildAndExportvar toleranceMinus = boundPmi?.DimensionTolerance?.Minus;if (boundPmi?.HoleWallTarget is { } wallTarget && holeByName.TryGetValue(wallTarget.HoleName, out var wallHole)){- result.Add(new Step242SemanticPmiHole(wallHole.FeatureId, pmi.Value.Value, null, "explicit_v2_hole_wall_diameter", tolerancePlus, toleranceMinus));+ result.Add(new Step242SemanticPmiHole(wallHole.FeatureId, pmi.Value.Value, null, "explicit_v2_hole_wall_diameter", tolerancePlus, toleranceMinus) { Name = pmi.Name });}else if (holeByName.TryGetValue(pmi.Target, out var pmiHole)){- result.Add(new Step242SemanticPmiHole(pmiHole.FeatureId, pmi.Value.Value, null, "explicit_v2_semantic_hole_diameter", tolerancePlus, toleranceMinus));+ result.Add(new Step242SemanticPmiHole(pmiHole.FeatureId, pmi.Value.Value, null, "explicit_v2_semantic_hole_diameter", tolerancePlus, toleranceMinus) { Name = pmi.Name });}else if (explicitFeatureIds is not null && explicitFeatureIds.TryGetValue(pmi.Target, out var featureId)){- result.Add(new Step242SemanticPmiHole(featureId, pmi.Value.Value, null, "explicit_v2_semantic_hole_diameter", tolerancePlus, toleranceMinus));+ result.Add(new Step242SemanticPmiHole(featureId, pmi.Value.Value, null, "explicit_v2_semantic_hole_diameter", tolerancePlus, toleranceMinus) { Name = pmi.Name });}else if (TryResolveV2RecognizedRegionTarget(document, targetBinding, pmi.Target, out var importedTarget) || TryResolveV2ImportedFaceTarget(targetBinding, pmi.Target, out importedTarget)){- result.Add(new Step242SemanticPmiHole($"{targetSolid}.{pmi.Name}", pmi.Value.Value, null, $"imported_canonical_face:{importedTarget}", tolerancePlus, toleranceMinus));+ result.Add(new Step242SemanticPmiHole($"{targetSolid}.{pmi.Name}", pmi.Value.Value, null, $"imported_canonical_face:{importedTarget}", tolerancePlus, toleranceMinus) { Name = pmi.Name });}}else if (pmi.Kind == FirmamentV2PmiKind.DatumPlane)@@ -2810,10 +2811,11 @@ public static class FirmamentBuildAndExport}}- if (correspondence is null) return result;return result.Select(item => item with{- GeometricFaceIds = correspondence.Descendants+ GeometricFaceIds = item is Step242SemanticPmiDatum datum && body is not null+ ? FirmamentSelectorResolver.ResolveUniquePlanarFace(body, datum.Target).Select(id => id.Value).ToArray()+ : (correspondence?.Descendants ?? []).Where(descendant => descendant.Face.HasValue&& (string.Equals(descendant.SourceStableId, item.FeatureId, StringComparison.Ordinal)|| string.Equals(descendant.ParentStableId, item.FeatureId, StringComparison.Ordinal)))diff --git a/aetheris.client/src/__tests__/DrawingDocument.test.tsx b/aetheris.client/src/__tests__/DrawingDocument.test.tsxindex 797c9a30..7ba4e264 100644--- a/aetheris.client/src/__tests__/DrawingDocument.test.tsx+++ b/aetheris.client/src/__tests__/DrawingDocument.test.tsx@@ -105,4 +105,40 @@ describe("DrawingDocument", () => {expect(container.querySelector('[data-zone="D5"]')).toBeTruthy();expect(container.querySelector('[data-table-kind="BillOfMaterials"]')).toBeTruthy();});+ it("projects compiler-owned strokes and surface-grid primitives without recomputing layout", () => {+ const drawing: DrawingIr = { ...fixture, pages: [{ ...fixture.pages[0],+ views: [{ identity: "ISO", viewport: { x: 10, y: 20, width: 200, height: 120 }, primitives: [+ { stableId: "surface-grid", kind: "SurfaceGrid", points: [{ x: 30, y: 40 }, { x: 60, y: 70 }] }+ ] }],+ annotations: [{ identity: "diameter", semanticReference: "Size1", kind: "DiameterDimension", engineeringDisplay: "Ø4 mm ±0.05",+ selectedCandidate: { body: { x: 100, y: 40, width: 40, height: 6 }, leader: [] },+ strokes: [{ start: { x: 60, y: 40 }, end: { x: 100, y: 43 } }, { start: { x: 60, y: 40 }, end: { x: 62, y: 41 } }]+ }]+ }] };+ const { container } = render(<DrawingDocument drawing={drawing} />);+ expect(container.querySelectorAll("line.leader")).toHaveLength(2);+ expect(container.querySelector("polyline.surfacegrid")).toBeTruthy();+ expect(container.querySelector('[data-semantic-reference="Size1"] text')?.textContent).toBe("Ø4 mm ±0.05");+ expect(container.querySelector(".annotation-body")?.getAttribute("style")).toContain("stroke: none");+ });++ it("renders the compiler title block as a real table with unperformed approvals blank", () => {+ const bounds = { x: 120, y: 157, width: 170, height: 41 };+ const cell = (key: string, label: string, value: string) => ({ key, label, value, columnSpan: 2,+ bounds, valueLines: value ? [value] : [], valueSizeMillimetres: 2.6, emphasized: false });+ const drawing: DrawingIr = { ...fixture, pages: [{ ...fixture.pages[0], informationBlock: {+ bounds, location: { page: 1, zone: "D5" }, fields: {},+ table: { columnWidths: [1, 1, 1, 1, 1, 1], rows: [+ { height: 8, cells: [cell("DrawnBy", "DRAWN BY", "Codex (AI)"), cell("CheckedBy", "CHECKED BY", ""), cell("ApprovedBy", "APPROVED BY", "")] },+ { height: 7, cells: [cell("DrawnDate", "DRAWN DATE", "2026-10-18"), cell("CheckedDate", "CHECKED DATE", ""), cell("ApprovedDate", "APPROVED DATE", "")] }+ ] }+ } }] };+ const { container } = render(<DrawingDocument drawing={drawing} />);+ expect(screen.getByRole("table", { name: "Drawing title block" })).toBeTruthy();+ expect(container.querySelectorAll(".drawing-title-block td[colspan='2']")).toHaveLength(6);+ expect(container.querySelector('[data-field="DrawnBy"]')?.textContent).toContain("Codex (AI)");+ expect(container.querySelector('[data-field="DrawnDate"]')?.textContent).toContain("2026-10-18");+ expect(container.querySelector('[data-field="ApprovedBy"]')?.textContent).toBe("APPROVED BY");+ });+});diff --git a/aetheris.client/src/drawing/DrawingDocument.tsx b/aetheris.client/src/drawing/DrawingDocument.tsxindex 3ed08b12..adc0706f 100644--- a/aetheris.client/src/drawing/DrawingDocument.tsx+++ b/aetheris.client/src/drawing/DrawingDocument.tsx@@ -133,7 +133,7 @@ function DrawingPage({ drawing, page }: { drawing: DrawingIr; page: DrawingPageI</aside>)}</section>- {page.informationBlock && (+ {page.informationBlock?.table ? <DrawingTitleBlock block={page.informationBlock} /> : page.informationBlock && (<dlclassName="drawing-information-block"data-zone={page.informationBlock.location.zone}@@ -233,16 +233,30 @@ function DrawingZones({ page }: { page: DrawingPageIr }) {);}+function DrawingTitleBlock({ block }: { block: NonNullable<DrawingPageIr["informationBlock"]> }) {+ return <table className="drawing-title-block" aria-label="Drawing title block" data-zone={block.location.zone}+ style={{ left: `${block.bounds.x}mm`, top: `${block.bounds.y}mm`, width: `${block.bounds.width}mm`, height: `${block.bounds.height}mm` }}>+ <colgroup>{block.table!.columnWidths.map((width, i) => <col key={i} style={{ width: `${width}mm` }} />)}</colgroup>+ <tbody>{block.table!.rows.map((row, index) => <tr key={index} style={{ height: `${row.height}mm` }}>+ {row.cells.map(cell => <td key={cell.key} colSpan={cell.columnSpan} data-field={cell.key} className={cell.emphasized ? "emphasized" : undefined}>+ <span className="drawing-title-label">{cell.label}</span>+ {cell.valueLines.map((line, i) => <div key={i} style={{ fontSize: `${cell.valueSizeMillimetres}mm`, lineHeight: 1.15 }}>{line}</div>)}+ </td>)}+ </tr>)}</tbody>+ </table>;+}+function DrawingAnnotation({ annotation }: { annotation: DrawingAnnotationIr }) {const body = annotation.selectedCandidate.body;return (<g data-semantic-reference={annotation.semanticReference}>- <polyline- className="leader"- points={annotation.selectedCandidate.leader.map((p) => `${p.x},${p.y}`).join(" ")}- />+ {annotation.strokes ? annotation.strokes.map((stroke, index) => (+ <line key={index} className="leader" x1={stroke.start.x} y1={stroke.start.y} x2={stroke.end.x} y2={stroke.end.y} />+ )) : <polyline className="leader" points={annotation.selectedCandidate.leader.map((p) => `${p.x},${p.y}`).join(" ")} />}+<rectclassName="annotation-body"+ style={annotation.kind && !["Datum", "FeatureControlFrame"].includes(annotation.kind) ? { stroke: "none" } : undefined}x={body.x}y={body.y}width={body.width}diff --git a/aetheris.client/src/drawing/drawingDocument.css b/aetheris.client/src/drawing/drawingDocument.cssindex dfda6c88..db24ae3e 100644--- a/aetheris.client/src/drawing/drawingDocument.css+++ b/aetheris.client/src/drawing/drawingDocument.css@@ -170,3 +170,19 @@box-shadow: none;}}++.drawing-document .surfacegrid { fill: none; stroke: #94a3b8; stroke-width: .14; }++.drawing-content svg .leader { fill: none; stroke: #374151; stroke-width: .22; }++.drawing-page .drawing-title-block {+ position: absolute;+ table-layout: fixed;+ border-collapse: collapse;+ border: .4mm solid #334155;+ background: white;+ font-family: Inter, Arial, sans-serif;+}+.drawing-title-block td { border: .15mm solid #475569; padding: .3mm 1mm; vertical-align: top; color: #111827; }+.drawing-title-block .emphasized { background: #f1f5f9; }+.drawing-title-label { display: block; font-size: 1.8mm; line-height: 1.2; color: #64748b; margin-bottom: .4mm; }diff --git a/aetheris.client/src/drawing/drawingIr.ts b/aetheris.client/src/drawing/drawingIr.tsindex 2d6dfd68..e1495f17 100644--- a/aetheris.client/src/drawing/drawingIr.ts+++ b/aetheris.client/src/drawing/drawingIr.ts@@ -35,6 +35,11 @@ export type DrawingPageIr = {bounds: DrawingRect;location: DrawingLocationIr;fields: Record<string, string>;+ table?: {+ columnWidths: number[];+ rows: { height: number; cells: { key: string; label: string; value: string; columnSpan: number;+ bounds: DrawingRect; valueLines: string[]; valueSizeMillimetres: number; emphasized: boolean }[] }[];+ };};locatedNotes?: {identity: string;@@ -59,7 +64,7 @@ export type DrawingViewIr = {viewport: DrawingRect;primitives: {stableId: string;- kind: "Visible" | "Silhouette" | "Hidden";+ kind: "Visible" | "Silhouette" | "Hidden" | "SurfaceGrid";points: DrawingPoint2[];occurrenceIdentity?: string;definitionIdentity?: string;@@ -70,6 +75,8 @@ export type DrawingViewIr = {export type DrawingAnnotationIr = {identity: string;semanticReference: string;+ kind?: string;+ strokes?: { start: DrawingPoint2; end: DrawingPoint2 }[];engineeringDisplay: string;selectedCandidate: { body: DrawingRect; leader: DrawingPoint2[] };};diff --git a/docs/development/DRAWING-GENERATION-2026-10-18.md b/docs/development/DRAWING-GENERATION-2026-10-18.mdnew file mode 100644index 00000000..5c04caa2--- /dev/null+++ b/docs/development/DRAWING-GENERATION-2026-10-18.md@@ -0,0 +1,173 @@+# Drawing generation integration++Date: 2026-10-18.++## Existing owners and observed gaps++The repository already contained a Drawing IR, authored Part/Assembly drawing+compiler, bounded occlusion projection, annotation candidates, embedded Inter font,+vector PDF, SVG, editable PPTX and React projection. Reuse those owners.++Observed gaps:++- No automatic drawing entry point from a part or AP242 PMI.+- Generic model-center anchors did not communicate actual PMI face associations.+- Circle/ellipse projection sampled entire curves instead of their bound intervals.+- Label occupancy persisted between independent pages.+- Text width was capped at 58mm even when glyph advances required more space.+- Leaders were not obstacles for other labels, and PPTX arrows faced the label.+- Datum PMI in the V2 export bridge had no geometric association even where an+ existing axis-face selector could resolve uniquely.+- Explicit HoleDiameter authoring names were lost during STEP emission/readback.+- Named STEP dimensions did not retain their diameter kind in the inspector.++## Repairs and policy++`drawing generate` compiles parts or imports one BRep, reads semantic PMI, selects+orthographic view candidates with JudgmentEngine, projects real face-bound anchors,+and paginates six PMI entries per enlarged view. A compact overview combines three+orthographic views at a shared scale and an isometric surface wireframe.+Authored Drawing compilation remains the existing owner and shares artifact writing.++`BrepWireframeSvgRenderer.SampleGeometry` exposes the existing world-space samples,+edge/face identities and evidence. Both SVG previews and drawing projection use it.+No SVG parsing, triangle-edge substitution or independent curve evaluator was added.+Wireframe deliberately retains rear edges. Existing bounded HLR remains available.++Semantic export retains optional authored hole names in property metadata, preserving+the established diameter/target representation keys. Unique axis-face datum ports+resolve through the existing selector owner to geometric face associations. Ambiguous+planes stay unlocated. Engineering geometry is unchanged; affected STEP PMI metadata+is intentionally more complete, so those files need not retain whole-file hashes.++The existing annotation owner uses actual Inter advances, page-local keepouts,+text/leader rejection and deterministic Judgment utility. Reference envelope dimensions+are labeled approximate `REF`, never controlling tolerances. Shared paper-space strokes+include leaders, witness lines and arrowheads for PDF/SVG/PPTX/React.++## Honest admission boundaries++Unlocated PMI, unsupported AP242 semantic families, foreign PMI units and impossible+layout reject. No center-anchor fallback is admitted by automatic generation. Generic+linear face associations do not prove measurement endpoints. Current V2 export already+rejects unsupported authored PMI families; generation also verifies that expected+authored PMI survives exchange. Geometry-only sheets explicitly disclose absent PMI.++Section/detail views, automatic assembly drawings, general standards compliance,+universal third-party semantic PMI and DXF remain separate qualification work.+Existing authored Assembly drawings and BOMs are regression gates.+Authored drawings retain their existing semantic-center anchors where measurement+endpoints are unavailable; those legacy linear callouts are not new endpoint-based+dimension witnesses. The automatic path requires geometric face associations and+labels its sampled envelope dimensions as reference only.++## Syntax inconsistency surfaced++The new specimen initially used semicolon-separated inline PMI fields. Current+validation rejected it with `firmament-v2-pmi-diameter-invalid`, invalid target and+tolerance diagnostics. The same fields on separate lines validate/build. The specimen+now uses the documented accepted multiline form. This is recorded as frontend debt;+this pass does not add source rewrites or a second PMI parser.++## Labeling references++- [MIT engineering drawing guide](https://ocw.mit.edu/courses/2-007-design-and-manufacturing-i-spring-2009/pages/related-resources/drawing_and_sketching/):+ informative views, readable dimensions and nonredundant manufacturing information.+- [Engineering Working Drawings Basics, NASA-hosted lecture notes](https://s3vi.ndc.nasa.gov/ssri-kb/static/resources/Engineering%2BWorking%2BDrawing%2BBasics.pdf):+ grouped/spaced dimensions, outside placement where possible, true-shape views and+ avoiding dimensioning hidden features. Wireframe presentation is explicitly named+ rather than misrepresented as conventional HLR.++## Qualification++Generated evidence belongs under ignored `artifacts/local/drawing-generation/`.++| Check | Evidence |+| --- | --- |+| Solution Release build | `frozen-build.log`: zero errors; 22 existing nullable/xUnit/WebAssembly interop warnings |+| Firmament drawing focus | `frozen-focused.log`: 36 passed |+| CLI drawing focus | `frozen-cli.log`: 7 passed |+| Core fast lane | `frozen-fast.log`: 1,087 passed |+| Complete solution | `frozen-full.log`: 5,647 passed, zero failures/skips; includes 1,220 Core and 2,929 Firmament tests. FrictionLab reports no discovered tests. |+| Client TypeScript and full Vitest | Typecheck succeeded; 19 files / 91 tests passed (`client-typecheck.log`, `client-full.log`) |+| Existing FrontendX4 geometry corpus | `frozen-corpus.log`: 32/32 passed, including chimera/reference geometry; no baseline recording used |+| Real CLI | Part build; generation from part and STEP; authored bearing-block and Assembly drawings all succeeded |+| Presentation parity | Part and its STEP produce byte-identical PDF, SVG and PPTX |+| Body geometry parity | First 414 geometric entities match the pre-change STEP byte-for-byte; SHA256 `c7ec5a43100cdf5368016315bbd02bbca59c82855f68cb50737f8845a73efe9c` |+| Final generated example | Three A4 landscape pages; all ten named toleranced diameters present exactly once; located datum; zero text/model, text/text or text/stroke collisions; zero failed annotations |+| PDF inspection | Searchable text, embedded Inter, no image objects; correct author and signoff dates |+| Native PPTX | Three native title tables, six columns/five rows with merges; existing Open XML validator tests pass; no raster replacement |+| Visual review | All seven rendered pages inspected: generated plate (3), authored part (2), authored Assembly/BOM (2) |++Final example: `final/InspectionPlateDrawing.pdf`, `.svg`, `.pptx`, `.drawing.json`+and `.validation.json`. `artifact-qualification.json` records cross-format hashes,+geometry parity and render paths. No canonical source or geometry baseline was+rewritten. PowerPoint desktop rendering/editing was not exercised; PDF rendering,+package structure and Open XML validity are the qualification performed here.++Negative regressions cover missing geometric association, foreign PMI units,+missing nominal values, unqualified dimension kinds, and incomplete/invalid+signoff dates. Positive regressions cover source immutability, deterministic+artifacts, retained authored names/depth, measured long labels, a true projected+diameter witness, native tables, and authored checker/date metadata.++The final lanes ran serially with `MSBUILDDISABLENODEREUSE=1` and+`DOTNET_PROCESSOR_COUNT=2`:++```powershell+dotnet build Aetheris.slnx -c Release --no-restore -m:1 -nr:false -p:UseSharedCompilation=false+dotnet test Aetheris.Kernel.Firmament.Tests -c Release --no-build -m:1 --filter Drawing+dotnet test Aetheris.CLI.Tests -c Release --no-build -m:1 --filter Drawing+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build -m:1 --filter "Category!=SlowCorpus"+dotnet test Aetheris.slnx -c Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1+python fixtures/Regression/FrontendX4/run.py+```++`git diff --check` passes. At closeout there are no remaining dotnet, testhost,+MSBuild or VBCSCompiler processes. Superseded task-owned qualification process trees+were stopped before replacement runs; no unrelated runtime hosts were terminated.++## Title table and signoff follow-up++The user's review requested an actual title table and Drawn/Checked/Approved+traceability. The shared IR now contains a six-column table with merged cells,+measured text lines and paper-space cell bounds. PDF/SVG project it directly;+PPTX emits a native DrawingML table and React an HTML table. Legacy Fields and the+two-argument Compile API remain available for compatibility.++Role names and ISO dates are explicit paired inputs. The published specimen credits+`Codex (AI)` with drawn date `2026-10-18`; checked and approved remain blank. Authored+metadata can supply role pairs and keeps Author/Date fallback. PDF and PPTX document+metadata also retain the provided preparer/date; the previous unrelated hardcoded+PDF/PPTX creation dates are removed. This is traceability, not signature validation.++The PDF backend previously wrote numeric millimetre line weights directly as PDF+points. Conversion is now explicit, matching the SVG/PPTX paper units. Surface grids+are lighter, primary boundaries stronger and title cells use muted label text with+a pale header band. Small holes use a rim leader without redundant interior arrowheads;+a sufficiently large face-on diameter may carry a measured two-arrow witness.++## Code-quality review++The existing semantic exporter/selector owns PMI associations, the shared BRep+sampler owns curve evaluation, the existing drawing compiler owns artifact writing,+and the Drawing IR owns table cells and annotation strokes. There is no new parser,+source rewrite, geometry solver, renderer-side PMI interpreter or global mutable+layout state. The original two-argument Compile entry point and inspector Name+representation remain compatible; new metadata is additive. Drawing presentation+changes do not mutate source or BRep geometry.++## Verdict++**Success for the bounded integration and title-table/signoff pass.** The real CLI+generates searchable vector PDF, SVG and native editable PPTX from a part or its+supported AP242 PMI. The motivating dense plate retains all ten named toleranced+diameters, source-associated anchors and body geometry, with readable sheets and+explicit preparation credit. Existing authored part/Assembly drawings, tables,+BOMs and review packages remain qualified by the regression suite.++This is not a claim of complete manufacturing dimension coverage or standards+certification. Broader V2 distance/control export, endpoint-based linear dimensions,+automatic section/detail/assembly view selection, general third-party PMI adapters+and DXF remain explicit follow-up work. Unsupported intent rejects instead of+receiving guessed units, anchors, dimensions or approvals.diff --git a/docs/public/README.md b/docs/public/README.mdindex a290af7d..29b17b07 100644--- a/docs/public/README.md+++ b/docs/public/README.md@@ -10,6 +10,7 @@ Start with [Getting Started](getting-started.md), then use these guides:- Interoperability: [Forge Host Protocol v1](forge/interop.md)- Mechanisms: [Editable V8, prescribed motion and assembly mesh export](firmament/editable-mechanisms.md)- Showcase: [Difference Engine, real hierarchical CAD and prescribed browser animation](demos/difference-engine-showcase.md), [single-cut carved electric guitar, STEP/USD and Cycles](demos/guitar-surfacing-x0.md)+- Drawings: [Generate PDF/SVG/PPTX from parts and semantic PMI](drawings.md)- Inspection: [Cadmata](cadmata/overview.md), [Cadmata PMI](cadmata/pmi.md), and [Three Telos display migration](three-telos.md)- Reference: [CLI](reference/cli.md), [wireframe SVG previews](reference/wireframe.md), [targets/selectors](reference/targets.md), [diagnostics](reference/diagnostics.md), [supported features](reference/supported-features.md), [known issues](reference/known-issues.md), and [release notes](reference/release-notes.md)diff --git a/docs/public/drawings.md b/docs/public/drawings.mdnew file mode 100644index 00000000..85e26d56--- /dev/null+++ b/docs/public/drawings.md@@ -0,0 +1,112 @@+# Generate 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:++```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+```++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.++## Title table and traceability++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.++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`:++- `--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.++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.diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex 0a286a62..67298c80 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 sameanalysis compiler and the existing solver, writing analysis artifacts to the`--out` directory. `fea --out-dir` remains the dedicated spelling. Static bindingdoes not promise solver convergence. Drawing sources also dispatch through their production owner in `validate` and-`build`; `drawing compile --out-dir` remains available. Their output is a+`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 amanufacturing drawing artifact directory. Passing a `.step` output path to anAnalysis or Drawing build rejects explicitly; export the geometry source separately.diff --git a/docs/public/reference/cli.md b/docs/public/reference/cli.mdindex 264ab499..7d253d90 100644--- a/docs/public/reference/cli.md+++ b/docs/public/reference/cli.md@@ -49,3 +49,7 @@ Generic STEP analysis reports analytic placement and size information where it i## Assembly display meshes`aetheris mesh <assembly.firmament|assembly.firmasm> --format assembly-json --output <file.mesh.json> --json` exports shared local definition meshes and stable world-space occurrences. Failed geometry is not omitted. The default destination is `artifacts/local/mesh/<name>.mesh.json`. See [editable mechanisms](../firmament/editable-mechanisms.md) for the schema and a working consumer.++## 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.diff --git a/docs/public/reference/diagnostics.md b/docs/public/reference/diagnostics.mdindex c2baff4c..ff7357cf 100644--- a/docs/public/reference/diagnostics.md+++ b/docs/public/reference/diagnostics.md@@ -122,6 +122,11 @@ Common recovery patterns:| `firmament-v2-ellipsoid-radii-invalid` | Supply three finite positive X/Y/Z semiaxes with length units in `radii`. || `firmament-v2-uniform-stock-fillet-unsupported` | Use one `EdgeFinish<Fillet>` with `target: AllEdges`, positive `radius` and no face selector on untouched direct Box or regular Polyhedron stock. Arbitrary bodies, hollow stock, other edits and construction adapters are outside this capability. || `UniformFilletRadiusTooLarge` | Reduce the radius below the reported stock inradius; this construction requires positive remaining planar faces and edge spans. |+| `drawing-pmi-target-unlocated` | The PMI needs a geometric face association. Automatic generation refuses a model-center leader. |+| `drawing-pmi-value-unavailable` | Supply an admitted finite PMI nominal/depth; a missing measure is not interpreted as zero. |+| `drawing-layout-impossible` | Use fewer PMI entries per authored view or a larger allocation; labels, strokes and sheet keepouts must remain clear. |+| `drawing-title-block-overflow` / `drawing-notes-overflow` | Shorten presentation metadata/notes or use an additional authored sheet. Text was not truncated. |+| `drawing-signoff-incomplete` | Provide both a role name and its ISO date, or leave both blank; unperformed reviews must remain blank. || unknown material | one of the four exact catalog references in the materials guide || unresolved PMI target | named hole/face selector exists in the same semantic domain || invalid tolerance | `PlusMinus(plus, minus)` uses Length values for a diameter |diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.mdindex ece7a832..6fc2133f 100644--- a/docs/public/reference/supported-features.md+++ b/docs/public/reference/supported-features.md@@ -5,6 +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). || 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/inspection-plate.firmament b/fixtures/Regression/DrawingGeneration/inspection-plate.firmamentnew file mode 100644index 00000000..dac5d445--- /dev/null+++ b/fixtures/Regression/DrawingGeneration/inspection-plate.firmament@@ -0,0 +1,119 @@+Model InspectionPlate {+ units: mm+ Box Stock { size: [100mm, 70mm, 8mm] }+ Modify Stock {+ Hole<Shaft> H1 {+ on: +Z+ center: Point2(-36mm, -18mm)+ diameter: 4mm+ end: ThroughAll+ }+ Hole<Shaft> H2 {+ on: +Z+ center: Point2(-18mm, -18mm)+ diameter: 4mm+ end: ThroughAll+ }+ Hole<Shaft> H3 {+ on: +Z+ center: Point2(0mm, -18mm)+ diameter: 4mm+ end: ThroughAll+ }+ Hole<Shaft> H4 {+ on: +Z+ center: Point2(18mm, -18mm)+ diameter: 4mm+ end: ThroughAll+ }+ Hole<Shaft> H5 {+ on: +Z+ center: Point2(36mm, -18mm)+ diameter: 4mm+ end: ThroughAll+ }+ Hole<Shaft> H6 {+ on: +Z+ center: Point2(-36mm, 18mm)+ diameter: 4mm+ end: ThroughAll+ }+ Hole<Shaft> H7 {+ on: +Z+ center: Point2(-18mm, 18mm)+ diameter: 4mm+ end: ThroughAll+ }+ Hole<Shaft> H8 {+ on: +Z+ center: Point2(0mm, 18mm)+ diameter: 4mm+ end: ThroughAll+ }+ Hole<Shaft> H9 {+ on: +Z+ center: Point2(18mm, 18mm)+ diameter: 4mm+ end: ThroughAll+ }+ Hole<Shaft> H10 {+ on: +Z+ center: Point2(36mm, 18mm)+ diameter: 4mm+ end: ThroughAll+ }+ }+ Pmi {+ Datum A { target: face(+Z) }+ HoleDiameter Size1 {+ target: face(H1.Wall)+ value: 4mm+ tolerance: PlusMinus(0.05mm, 0.02mm)+ }+ HoleDiameter Size2 {+ target: face(H2.Wall)+ value: 4mm+ tolerance: PlusMinus(0.05mm, 0.02mm)+ }+ HoleDiameter Size3 {+ target: face(H3.Wall)+ value: 4mm+ tolerance: PlusMinus(0.05mm, 0.02mm)+ }+ HoleDiameter Size4 {+ target: face(H4.Wall)+ value: 4mm+ tolerance: PlusMinus(0.05mm, 0.02mm)+ }+ HoleDiameter Size5 {+ target: face(H5.Wall)+ value: 4mm+ tolerance: PlusMinus(0.05mm, 0.02mm)+ }+ HoleDiameter Size6 {+ target: face(H6.Wall)+ value: 4mm+ tolerance: PlusMinus(0.05mm, 0.02mm)+ }+ HoleDiameter Size7 {+ target: face(H7.Wall)+ value: 4mm+ tolerance: PlusMinus(0.05mm, 0.02mm)+ }+ HoleDiameter Size8 {+ target: face(H8.Wall)+ value: 4mm+ tolerance: PlusMinus(0.05mm, 0.02mm)+ }+ HoleDiameter Size9 {+ target: face(H9.Wall)+ value: 4mm+ tolerance: PlusMinus(0.05mm, 0.02mm)+ }+ HoleDiameter Size10 {+ target: face(H10.Wall)+ value: 4mm+ tolerance: PlusMinus(0.05mm, 0.02mm)+ }+ }+}