Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Improve CAD geometry workflows and interface
Yuechen Li5502328037a7
diff --git a/Aetheris.CLI.Tests/AssemblyM0CliTests.cs b/Aetheris.CLI.Tests/AssemblyM0CliTests.csindex 071f8be2..618807f0 100644--- a/Aetheris.CLI.Tests/AssemblyM0CliTests.cs+++ b/Aetheris.CLI.Tests/AssemblyM0CliTests.cs@@ -4,6 +4,36 @@ namespace Aetheris.CLI.Tests;public sealed class AssemblyM0CliTests{+ [Fact]+ public void BuildAndAnalyzeAssemblyRecoverSourceAuthoredReleaseAndPmiNotes()+ {+ var repo = FindRepoRoot();+ var fixture = Path.Combine(repo, "fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/product-notes.firmasm");+ var directory = Path.Combine(repo, "artifacts/local/assembly-pmi-tests", Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(directory);+ try+ {+ var step = Path.Combine(directory, "product.step");+ var stdout = new StringWriter(); var stderr = new StringWriter();+ Assert.Equal(0, Aetheris.CLI.CliRunner.Run(["build", fixture, "--output", step, "--json"], stdout, stderr));+ Assert.Empty(stderr.ToString());+ stdout = new();+ Assert.Equal(0, Aetheris.CLI.CliRunner.Run(["analyze", "assembly", step, "--json"], stdout, stderr));+ using var json = JsonDocument.Parse(stdout.ToString());+ var report = json.RootElement;+ Assert.Equal(1, report.GetProperty("definitionCount").GetInt32());+ Assert.Equal(2, report.GetProperty("bodyCount").GetInt32());+ var pmi = report.GetProperty("semanticPmi");+ Assert.True(pmi.GetProperty("success").GetBoolean());+ Assert.Equal(7, pmi.GetProperty("annotationCount").GetInt32());+ var notes = pmi.GetProperty("items").EnumerateArray().ToArray();+ Assert.Equal("GPT 6.1 Sol Codex", notes.Single(n => n.GetProperty("name").GetString() == "Release.Author").GetProperty("text").GetString());+ Assert.Equal("Product.A", notes.Single(n => n.GetProperty("name").GetString() == "Finish").GetProperty("target").GetString());+ Assert.Empty(stderr.ToString());+ }+ finally { Directory.Delete(directory, true); }+ }+[Fact]public void AnalyzeAssembly_ReportsSourceHierarchyWithoutWritingPackage(){diff --git a/Aetheris.CLI.Tests/CompositionRootCliTests.cs b/Aetheris.CLI.Tests/CompositionRootCliTests.csnew file mode 100644index 00000000..9adc4d71--- /dev/null+++ b/Aetheris.CLI.Tests/CompositionRootCliTests.cs@@ -0,0 +1,45 @@+using System.Text.Json;++namespace Aetheris.CLI.Tests;++public sealed class CompositionRootCliTests+{+ [Fact]+ public void RootInspectReportsColdWarmDefinitionReuseAndBuildExportsAssembly()+ {+ var root = RepoRoot();+ var source = Path.Combine(root, "fixtures", "Canonical", "AssemblyInterfaces", "AuthoringFoundation", "linear-stations.firmament");+ var stdout = new StringWriter(); var stderr = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["inspect", source, "--json", "--profile", "--repeat", "2"], stdout, stderr));+ Assert.Empty(stderr.ToString());+ using var json = JsonDocument.Parse(stdout.ToString());+ var builds = json.RootElement.GetProperty("builds");+ Assert.Equal(2, builds.GetArrayLength());+ Assert.Equal(2, builds[0].GetProperty("reuse").GetProperty("rebuiltDefinitions").GetInt32());+ Assert.Equal(2, builds[1].GetProperty("reuse").GetProperty("reusedDefinitions").GetInt32());+ Assert.Equal(0, builds[1].GetProperty("reuse").GetProperty("rebuiltDefinitions").GetInt32());+ var output = Path.Combine(root, "artifacts", "local", "owl", "cli-tests", Guid.NewGuid() + ".step");+ stdout.GetStringBuilder().Clear();+ Assert.Equal(0, CliRunner.Run(["build", source, "--output", output, "--json"], stdout, stderr));+ Assert.Contains("ISO-10303-21", File.ReadAllText(output), StringComparison.Ordinal);+ }++ [Fact]+ public void RootInspectReportsGeneratedSectionKeys()+ {+ var path = Path.Combine(RepoRoot(), "fixtures", "Canonical", "AssemblyInterfaces", "GuitarX0", "Neck.firmament");+ var stdout = new StringWriter(); var stderr = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["inspect", path, "--json"], stdout, stderr));+ using var json = JsonDocument.Parse(stdout.ToString());+ var pattern = json.RootElement.GetProperty("patterns")[0];+ Assert.Equal(8, pattern.GetProperty("generatedCount").GetInt32());+ Assert.Equal("Nut", pattern.GetProperty("associations")[7].GetProperty("sourceEntry").GetString());+ }++ private static string RepoRoot()+ {+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;+ return directory?.FullName ?? throw new DirectoryNotFoundException();+ }+}diff --git a/Aetheris.CLI.Tests/ConventionFormatCliTests.cs b/Aetheris.CLI.Tests/ConventionFormatCliTests.csnew file mode 100644index 00000000..336d575f--- /dev/null+++ b/Aetheris.CLI.Tests/ConventionFormatCliTests.cs@@ -0,0 +1,34 @@+using System.Text.Json;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.CLI.Tests;++public sealed class ConventionFormatCliTests+{+ [Fact]+ public void ConventionBatchIsDryByDefaultPreparesBeforeWritesAndIsIdempotent()+ {+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;+ var output = Path.Combine(directory!.FullName, "artifacts", "local", "casing", "cli-tests", Guid.NewGuid().ToString());+ Directory.CreateDirectory(output);+ var path = Path.Combine(output, "part.firmament");+ const string source = "Model Witness { Units: mm; Box Body { Size: [10mm,8mm,4mm] } }";+ File.WriteAllText(path, source);+ var stdout = new StringWriter(); var stderr = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["format", path, "--json"], stdout, stderr));+ Assert.Equal(source, File.ReadAllText(path));+ Assert.Equal(1, CliRunner.Run(["format", path, Path.Combine(output, "missing.firmament"), "--write"], stdout, stderr));+ Assert.Equal(source, File.ReadAllText(path));+ stdout.GetStringBuilder().Clear(); stderr.GetStringBuilder().Clear();+ Assert.Equal(0, CliRunner.Run(["format", path, "--write", "--json"], stdout, stderr));+ var preferred = File.ReadAllText(path);+ Assert.Contains("Box Body { size:", preferred);+ Assert.True(FirmamentV2Parser.Parse(preferred).IsSuccess);+ stdout.GetStringBuilder().Clear();+ Assert.Equal(0, CliRunner.Run(["format", path, "--write", "--json"], stdout, stderr));+ using var json = JsonDocument.Parse(stdout.ToString());+ Assert.False(json.RootElement.GetProperty("files")[0].GetProperty("changed").GetBoolean());+ Assert.Equal(preferred, File.ReadAllText(path));+ }+}diff --git a/Aetheris.CLI.Tests/FirmamentCanonicalDialectTests.cs b/Aetheris.CLI.Tests/FirmamentCanonicalDialectTests.csindex d3104d33..50d017b5 100644--- a/Aetheris.CLI.Tests/FirmamentCanonicalDialectTests.cs+++ b/Aetheris.CLI.Tests/FirmamentCanonicalDialectTests.cs@@ -5,7 +5,9 @@ namespace Aetheris.CLI.Tests;public sealed class FirmamentCanonicalDialectTests{private static readonly Regex NonCanonicalVocabulary = new(- @"(?m)^\s*(?:model|units|solid|modify|analysis|fixed|force|pmi)\b|\b(?:size|radius|height|body|material|region|components|vector|results|lattice|target|value|tolerance|datumrefs)\s*:",+ // Artifact/declaration vocabulary still distinguishes these samples+ // from the legacy grammar. Property casing is a convention, not a gate.+ @"(?m)^\s*(?:model|solid|modify|analysis|fixed|force|pmi)\b|^\s*units\s+(?!:)",RegexOptions.CultureInvariant);private static readonly Regex FirmamentFence = new(@@ -17,7 +19,7 @@ public sealed class FirmamentCanonicalDialectTestsRegexOptions.CultureInvariant | RegexOptions.IgnoreCase);[Fact]- public void CanonicalFixtures_UseOnlyCanonicalOwnedVocabulary()+ public void CanonicalFixtures_UseArtifactFirstVocabulary(){var root = FindRoot();var files = Directory.GetFiles(Path.Combine(root, "fixtures", "Canonical"), "*.firmament", SearchOption.AllDirectories);@@ -27,7 +29,7 @@ public sealed class FirmamentCanonicalDialectTests}[Fact]- public void PublicFirmamentExamplesAndSnippets_UseOnlyCanonicalOwnedVocabulary()+ public void PublicFirmamentExamplesAndSnippets_UseArtifactFirstVocabulary(){var root = FindRoot();var examples = Directory.GetFiles(Path.Combine(root, "docs", "public"), "*.md", SearchOption.AllDirectories)diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 7ae8c4fa..107b5ac8 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -134,7 +134,7 @@ public static class CliRunnerstring? Classification = null,int? RigidRootCount = null);private const string TopLevelUsage = "Usage: aetheris <command> [options]";- private const string BuildUsage = "Usage: aetheris build <file.firmament> [--output <path>] [--json]";+ private const string BuildUsage = "Usage: aetheris build <file.firmament|file.firmasm> [--output <path>] [--json]";private const string MeshUsage = "Usage: aetheris mesh <file.firmament|file.firmfixture|file.firmasm|file.step> [--format stl|obj|assembly-json] [--output <path>] [--debug-ir <path>] [--json]";private const string ValidateUsage = "Usage: aetheris validate <file.firmament|file.firmfixture> [--forge-pack <path>] [--json]";private const string InspectProfileUsage = "Usage: aetheris inspect-profile <file.firmament> [--json]";@@ -150,14 +150,14 @@ public static class CliRunnerprivate const string AnalyzeAssemblyUsage = "Usage: aetheris analyze assembly <file.step> [--json]";private const string SectionsUsage = "Usage: aetheris sections <artifact.step> --axis Z --levels <z,...> [--epsilon <mm>] --json";private const string VerifyUsage = "Usage: aetheris verify <file.firmament|file.step> [--expected-volume <value>] [--cad-assistant] [--cad-assistant-path <path>] [--timeout <seconds>] [--evidence-dir <path>] [--require-external] [--json]";- private const string InspectUsage = "Usage: aetheris inspect <file.firmament|file.step> [--json]";+ private const string InspectUsage = "Usage: aetheris inspect <file.firmament|file.firmasm|file.step> [--json] [assembly: --profile --repeat <1..16>]";private const string ViewUsage = "Usage: aetheris view <file.firmament|file.step> [--cadmata-path <path>] [--json]";private const string MatchUsage = "Usage: aetheris match <file.step> <concept.firmament> [--linear-tolerance <mm>] [--angular-tolerance <deg>] [--json]";private const string TraceUsage = "Usage: aetheris trace (--case <name>|--fixture <path>) [--out-dir <dir>] [--json]";private const string CanonUsage = "Usage: aetheris canon <file.step> --out <canonical.step> [--mode deterministic|production] [--json]";private const string AsmExecUsage = "Usage: aetheris asm exec <file.firmasm> [--json]";private const string AsmExportUsage = "Usage: aetheris asm export <file.firmasm> --out <directory> [--json]";- private const string AsmInspectUsage = "Usage: aetheris asm inspect <assembly.firmament|assembly.firmasm> [--json] [--profile] [--out <report.json>]";+ private const string AsmInspectUsage = "Usage: aetheris asm inspect <assembly.firmament|assembly.firmasm> [--json] [--profile] [--repeat <1..16>] [--out <report.json>]";private const string AsmImportStepUsage = "Usage: aetheris asm import-step <assembly.step> --out <directory> [--json]";private const string AsmExportAp242Usage = "Usage: aetheris asm export-ap242 <assembly.firmament|assembly.firmasm> --out <assembly.step> [--json]";private const string ExperimentalUsage = "Usage: aetheris experimental <airchamfer-cube|airchamfer-corpus|prismatic-corpus|prismatic-map|loop-chamfer-corpus|heightfield-art> [options]";@@ -218,6 +218,7 @@ public static class CliRunner"build" => RunBuild(args.Skip(1).ToArray(), stdout, stderr),"mesh" => RunMesh(args.Skip(1).ToArray(), stdout, stderr),"validate" => RunValidate(args.Skip(1).ToArray(), stdout, stderr),+ "format" => RunFormat(args.Skip(1).ToArray(), stdout, stderr),"inspect" => RunInspect(args.Skip(1).ToArray(), stdout, stderr),"inspect-3dm" => ThreeDmCli.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),"recover-3dm" => ThreeDmCli.Recover(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),@@ -253,6 +254,30 @@ public static class CliRunner}}+ private static int RunFormat(string[] args, TextWriter stdout, TextWriter stderr)+ {+ const string usage = "Usage: aetheris format <file.firmament|file.firmasm>... [--write] [--json] (convention spellings; preserves layout and authored identities)";+ if (args.Length == 0 || IsHelpFlag(args[0])) { stdout.WriteLine(usage); return args.Length == 0 ? 1 : 0; }+ var write = args.Contains("--write", StringComparer.Ordinal);+ var json = args.Contains("--json", StringComparer.Ordinal);+ var paths = args.Where(a => a is not ("--write" or "--json")).ToArray();+ if (paths.Length == 0 || paths.Any(p => p.StartsWith('-') || Path.GetExtension(p) is not (".firmament" or ".firmasm")))+ { stderr.WriteLine(usage); return 1; }+ // Prepare the entire batch before writing; a missing input cannot leave a partial sweep.+ var formats = paths.Distinct(StringComparer.OrdinalIgnoreCase).Select(path =>+ {+ var fullPath = Path.GetFullPath(path);+ return FirmamentLanguageAnalysisService.FormatConventions(File.ReadAllText(fullPath), fullPath, "cli");+ }).ToArray();+ if (write)+ foreach (var format in formats.Where(f => f.Changed)) File.WriteAllText(format.Document, format.Text, new System.Text.UTF8Encoding(false));+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "format", mode = "conventions", written = write,+ validation = "spelling equivalence; validate the consuming project separately", files = formats.Select(f => new { path = f.Document, changed = f.Changed }) }, JsonOptions));+ else foreach (var format in formats)+ stdout.WriteLine(write ? $"{format.Document}: {(format.Changed ? "formatted" : "unchanged")}" : format.Text);+ return 0;+ }+private static int RunVerify(string[] args, TextWriter stdout, TextWriter stderr){if (args.Length == 0 || IsHelpFlag(args[0])) { WriteVerifyHelp(stdout); return args.Length == 0 ? 1 : 0; }@@ -459,6 +484,14 @@ public static class CliRunner}}+ if (File.Exists(sourcePath))+ {+ var source = File.ReadAllText(sourcePath);+ if (Path.GetExtension(sourcePath).Equals(".firmasm", StringComparison.OrdinalIgnoreCase) || FirmamentLanguageAnalysisService.HasAssemblyRoot(source))+ return RunAsmExportAp242([sourcePath, "--out", outPath ?? Path.GetFullPath(Path.Combine("artifacts", "local", "build", Path.GetFileNameWithoutExtension(sourcePath) + ".step")), .. (json ? new[] { "--json" } : [])], stdout, stderr);+ if (SectionChainAuthoringParser.IsSectionChainSource(source))+ return RunSectionChain(["build", sourcePath, .. (outPath is null ? Array.Empty<string>() : ["--out", outPath]), .. (json ? new[] { "--json" } : [])], stdout, stderr);+ }if (File.Exists(sourcePath) && PlasticShellFirmament.LooksLikePlasticShell(File.ReadAllText(sourcePath)))return RunPlasticShellBuild(sourcePath, outPath, json, stdout, stderr);if (File.Exists(sourcePath) && SheetMetalFirmament.LooksLikeSheetMetal(File.ReadAllText(sourcePath)))@@ -577,6 +610,7 @@ public static class CliRunnerSectionChain chain;IReadOnlyList<SectionChainProfileDerivation>? profileDerivations = null;IReadOnlyList<SectionChainBoundaryEditInspection>? boundaryEdits = null;+ IReadOnlyList<FirmamentV2CanonicalPatternDecl>? patterns = null;if (File.Exists(witness)){var authored = SectionChainAuthoringParser.CompileFile(witness);@@ -589,6 +623,7 @@ public static class CliRunnerchain = authored.Chain; materialized = authored.Materialization;profileDerivations = authored.ProfileDerivations;boundaryEdits = authored.BoundaryEdits;+ patterns = authored.Patterns;}else{@@ -617,6 +652,7 @@ public static class CliRunnercommand = $"section-chain {operation}", success = true, chain.StableId,profileDerivations,boundaryEdits,+ patterns,sections = chain.Sections.Select(section => new { section.SectionId, section.Frame, profile = section.Profile.StableId, spans = section.Profile.Spans.Select(span => span.SpanId), seam = section.Profile.SeamSpanId }),chain.Correspondence,resolvedCorrespondence = Enumerable.Range(0, chain.Sections.Count - 1).Select(index => new@@ -1364,6 +1400,8 @@ Model CanonicalPanel {}var input = args[0];+ if (File.Exists(input) && (Path.GetExtension(input).Equals(".firmasm", StringComparison.OrdinalIgnoreCase) || FirmamentLanguageAnalysisService.HasAssemblyRoot(File.ReadAllText(input))))+ return RunAsmInspect(args, stdout, stderr);var json = args.Skip(1).SequenceEqual(["--json"]);if (!json && args.Length > 1) { stderr.WriteLine($"Unknown inspect option '{args[1]}'."); stderr.WriteLine(InspectUsage); return 1; }if (!File.Exists(input)) { stderr.WriteLine($"Inspect input was not found: {input}"); return 1; }@@ -1379,6 +1417,8 @@ Model CanonicalPanel {}var source = File.ReadAllText(fullPath);+ if (SectionChainAuthoringParser.IsSectionChainSource(source))+ return RunSectionChain(["inspect", fullPath, .. args.Skip(1)], stdout, stderr);var frontend = FirmamentFrontendSchemas.Select(source);if (!frontend.IsSuccess){@@ -1433,11 +1473,7 @@ Model CanonicalPanel {}if (frontend.Schema == FirmamentFrontendSchema.SectionChain){- var section = SectionChainAuthoringParser.CompileFile(fullPath);- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "inspect", success = section.IsSuccess, input = fullPath, domain = "SectionChain", sectionChain = section.Chain?.StableId, diagnostics = section.Diagnostics }, JsonOptions));- else if (section.IsSuccess) stdout.WriteLine($"SectionChain {section.Chain!.StableId}: {section.Chain.Sections.Count} sections");- else foreach (var diagnostic in section.Diagnostics) stderr.WriteLine("error: " + diagnostic);- return section.IsSuccess ? 0 : 1;+ return RunSectionChain(["inspect", fullPath, .. args.Skip(1)], stdout, stderr);}if (PlateauAuthoring.IsSource(source) && !System.Text.RegularExpressions.Regex.IsMatch(source, @"\bAssembly\s+")){@@ -3879,17 +3915,24 @@ Model CanonicalPanel {var path = args[0];var json = false;var profile = false;+ var repeat = 1;+ var repeatRequested = false;string? outputPath = null;for (var i = 1; i < args.Length; i++){if (args[i] == "--json") json = true;else if (args[i] == "--profile") profile = true;+ else if (args[i] == "--repeat" && i + 1 < args.Length && int.TryParse(args[++i], out var count) && count is >= 1 and <= 16) { repeat = count; repeatRequested = true; }else if (args[i] == "--out" && i + 1 < args.Length) outputPath = args[++i];else { stderr.WriteLine(AsmInspectUsage); return 1; }}if (!File.Exists(path)) { stderr.WriteLine($"Assembly source '{path}' was not found."); return 1; }var sourceText = File.ReadAllText(path);var usesTemplateInstances = Regex.IsMatch(sourceText, @"<Part\s+[A-Za-z_]\w*\s*=\s*[A-Za-z_]\w*\s*<", RegexOptions.CultureInvariant);+ if (!usesTemplateInstances && !Path.GetExtension(path).Equals(".firmasm", StringComparison.OrdinalIgnoreCase) && FirmamentSourceSpelling.Normalize(sourceText).Contains("Include", StringComparison.Ordinal))+ usesTemplateInstances = new AssemblyM0Parser().ParseFile(path).Source is { } imported && NeedsMaterialization(imported.Root);+ static bool NeedsMaterialization(AssemblyMemberSource member) => member.Kind == AssemblyInstanceKind.Part && member.DefinitionIdentity.Contains('<')+ || member.Children.Any(NeedsMaterialization);var usesGearParts = GearAuthoring.ParseDefinitions(sourceText).Gears.Count > 0;var usesSheetMetalParts = sourceText.Contains("Use SheetMetal.ProductFamilies", StringComparison.Ordinal);AssemblyIr? assemblyIr;@@ -3897,7 +3940,24 @@ Model CanonicalPanel {IReadOnlyList<AssemblyDiagnostic> assemblyDiagnostics;AssemblyPerformanceIr? assemblyPerformance;bool success;- if (string.Equals(Path.GetExtension(path), ".firmasm", StringComparison.OrdinalIgnoreCase) && !usesSheetMetalParts)+ var builds = new List<object>();+ if (repeatRequested)+ {+ if (!FirmamentLanguageAnalysisService.HasAssemblyRoot(sourceText) || usesSheetMetalParts)+ { stderr.WriteLine("--repeat requires a canonical authored assembly using the ordinary M1 materializer."); return 1; }+ using var session = new FirmamentCompilationSession();+ AssemblyM1CompilationResult? last = null;+ for (var index = 0; index < repeat; index++)+ {+ var watch = System.Diagnostics.Stopwatch.StartNew();+ last = session.CompileFile(path);+ builds.Add(new { index, elapsedMilliseconds = watch.Elapsed.TotalMilliseconds, success = last.IsSuccess, reuse = last.Reuse, performance = profile ? last.Performance : null });+ if (!last.IsSuccess) break;+ }+ assemblyIr = last!.Ir; geometryArtifact = last.Geometry?.Artifact; assemblyDiagnostics = last.Diagnostics;+ assemblyPerformance = last.Performance; success = last.IsSuccess;+ }+ else if (string.Equals(Path.GetExtension(path), ".firmasm", StringComparison.OrdinalIgnoreCase) && !usesSheetMetalParts){var document = new FirmamentAssemblyDocumentCompiler().CompileFile(path);assemblyIr = document.Compilation.Ir;@@ -3924,7 +3984,7 @@ Model CanonicalPanel {assemblyPerformance = m0.Performance;success = m0.IsSuccess;}- var reportJson = JsonSerializer.Serialize(new { success, assemblyIr, geometryArtifact, diagnostics = assemblyDiagnostics, performance = profile ? assemblyPerformance : null }, JsonOptions);+ var reportJson = JsonSerializer.Serialize(new { success, assemblyIr, geometryArtifact, diagnostics = assemblyDiagnostics, performance = profile ? assemblyPerformance : null, builds }, JsonOptions);if (outputPath is not null){var fullOutputPath = Path.GetFullPath(outputPath);@@ -4753,7 +4813,8 @@ Model CanonicalPanel {stderr.WriteLine(AnalyzeAssemblyUsage);return 1;}- var imported = Step242AssemblyImporter.Import(File.ReadAllText(args[0]));+ var stepText = File.ReadAllText(args[0]);+ var imported = Step242AssemblyImporter.Import(stepText);if (!imported.IsSuccess){foreach (var diagnostic in imported.Diagnostics) stderr.WriteLine($"{diagnostic.Source}: {diagnostic.Message}");@@ -4799,6 +4860,7 @@ Model CanonicalPanel {maximum = new[] { points.Max(p => p.X), points.Max(p => p.Y), points.Max(p => p.Z) }},performance = structure.Performance,+ semanticPmi = Step242SemanticPmiInspector.Inspect(stepText),definitions = structure.Definitions.Select(item => new { item.StableId, item.Name, hasGeometry = item.Geometry is not null, item.ProductDefinitionEntityId }).ToArray(),occurrences = structure.Occurrences.Select(item => new { item.StableId, item.Name, item.ParentStableId, item.DefinitionStableId,item.LocalTransform, worldTransform = World(item).ToRowMajor(), item.StepEntityId }).ToArray()@@ -4948,6 +5010,7 @@ Model CanonicalPanel {stdout.WriteLine();stdout.WriteLine("Commands:");stdout.WriteLine(" validate Check Firmament source without materializing geometry.");+ stdout.WriteLine(" format Prefer mixed-case vocabulary spellings; preserve layout and authored names.");stdout.WriteLine(" build Compile Firmament to exact STEP AP242.");stdout.WriteLine(" mesh Export a supported exact B-rep as STL or topology-preserving OBJ.");stdout.WriteLine(" view Build/open a model in Cadmata.");diff --git a/Aetheris.Kernel.Core/Step242/Step242AssemblyProductStructure.cs b/Aetheris.Kernel.Core/Step242/Step242AssemblyProductStructure.csindex e2bb9272..f9ccc4d6 100644--- a/Aetheris.Kernel.Core/Step242/Step242AssemblyProductStructure.cs+++ b/Aetheris.Kernel.Core/Step242/Step242AssemblyProductStructure.cs@@ -24,7 +24,12 @@ public sealed record Step242AssemblyExportModel(string Name,string RootOccurrenceStableId,IReadOnlyList<Step242AssemblyDefinition> Definitions,- IReadOnlyList<Step242AssemblyOccurrence> Occurrences);+ IReadOnlyList<Step242AssemblyOccurrence> Occurrences,+ Step242HeaderMetadata? HeaderMetadata = null,+ IReadOnlyList<Step242AssemblyNote>? Notes = null);++/// <summary>A semantic annotation scoped to an assembly product, with an explicit occurrence path in its target.</summary>+public sealed record Step242AssemblyNote(string OccurrenceStableId, Step242SemanticPmiNote Note);public sealed record Step242ImportedProductDefinition(string StableId,@@ -60,6 +65,7 @@ public static class Step242AssemblyExportervar entities = new List<string>();var definitionRefs = new Dictionary<string, (int ProductDefinition, int Representation)>(StringComparer.Ordinal);+ var productShapes = new Dictionary<int, int>();foreach (var definition in model.Definitions.Where(item => item.Body is not null).OrderBy(item => item.StableId, StringComparer.Ordinal)){var exported = Step242Exporter.ExportBody(definition.Body!, options: new Step242ExportOptions@@ -76,6 +82,7 @@ public static class Step242AssemblyExportervar representation = FindEntityId(block, "SHAPE_REPRESENTATION") + offset;entities.AddRange(remapped);definitionRefs[definition.StableId] = (productDefinition, representation);+ productShapes[productDefinition] = FindEntityId(block, "PRODUCT_DEFINITION_SHAPE") + offset;}int Add(string name, params string[] args)@@ -108,6 +115,7 @@ public static class Step242AssemblyExportervar formation = Add("PRODUCT_DEFINITION_FORMATION", Str(""), Str(""), Ref(product));var productDefinition = Add("PRODUCT_DEFINITION", Str(definition.StableId), Str(""), Ref(formation), Ref(definitionContext));var shape = Add("PRODUCT_DEFINITION_SHAPE", Str(""), Str(""), Ref(productDefinition));+ productShapes[productDefinition] = shape;var representation = Add("SHAPE_REPRESENTATION", Str(definition.Name), "()", Ref(representationContext));Add("SHAPE_DEFINITION_REPRESENTATION", Ref(shape), Ref(representation));definitionRefs[definition.StableId] = (productDefinition, representation);@@ -120,6 +128,7 @@ public static class Step242AssemblyExportervar formation = Add("PRODUCT_DEFINITION_FORMATION", Str(""), Str(""), Ref(product));var definition = Add("PRODUCT_DEFINITION", Str(occurrence.StableId), Str(""), Ref(formation), Ref(definitionContext));var shape = Add("PRODUCT_DEFINITION_SHAPE", Str(""), Str(""), Ref(definition));+ productShapes[definition] = shape;var representation = Add("SHAPE_REPRESENTATION", Str(occurrence.Name), "()", Ref(representationContext));Add("SHAPE_DEFINITION_REPRESENTATION", Ref(shape), Ref(representation));assemblyRefs[occurrence.StableId] = (definition, representation);@@ -153,11 +162,20 @@ public static class Step242AssemblyExporterAdd("CONTEXT_DEPENDENT_SHAPE_REPRESENTATION", Ref(relationship), Ref(usageShape));}+ foreach (var annotation in model.Notes ?? [])+ {+ var owner = model.Occurrences.Single(item => item.StableId == annotation.OccurrenceStableId);+ var product = owner.DefinitionStableId is null ? assemblyRefs[owner.StableId] : definitionRefs[owner.DefinitionStableId];+ Step242Exporter.EmitNoteSemanticPmi((name, args) => Ref(Add(name, args)), Ref(productShapes[product.ProductDefinition]), annotation.Note);+ }++ var header = model.HeaderMetadata ?? Step242HeaderMetadata.Deterministic with+ { FileName = "aetheris_assembly.step", Description = "Aetheris AP242 assembly product structure" };var builder = new StringBuilder();Step242TextWriter.AppendCanonicalLine(builder, "ISO-10303-21;");Step242TextWriter.AppendCanonicalLine(builder, "HEADER;");- Step242TextWriter.AppendCanonicalLine(builder, "FILE_DESCRIPTION(('Aetheris AP242 assembly product structure'),'2;1');");- Step242TextWriter.AppendCanonicalLine(builder, "FILE_NAME('aetheris_assembly.step','1970-01-01T00:00:00',('Aetheris'),('Aetheris'),'Aetheris.Kernel','Aetheris.Kernel','');");+ Step242TextWriter.AppendCanonicalLine(builder, $"FILE_DESCRIPTION(({Str(header.Description)}),'2;1');");+ Step242TextWriter.AppendCanonicalLine(builder, $"FILE_NAME({Str(header.FileName)},{Str(header.CreationTimestamp)},({Str(header.Author)}),({Str(header.Organization)}),{Str(header.PreprocessorVersion)},{Str(header.OriginatingSystem)},{Str(header.Authorization)});");Step242TextWriter.AppendCanonicalLine(builder, "FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF'));");Step242TextWriter.AppendCanonicalLine(builder, "ENDSEC;");Step242TextWriter.AppendCanonicalLine(builder, "DATA;");@@ -174,6 +192,11 @@ public static class Step242AssemblyExportervar definitions = model.Definitions.Select(item => item.StableId).ToHashSet(StringComparer.Ordinal);if (!occurrences.TryGetValue(model.RootOccurrenceStableId, out var root) || root.ParentStableId is not null || root.DefinitionStableId is not null)diagnostics.Add(Diagnostic("AP242 assembly root must identify a root assembly occurrence.", "Exporter.Assembly.Root"));+ foreach (var note in model.Notes ?? [])+ if (!occurrences.ContainsKey(note.OccurrenceStableId) || string.IsNullOrWhiteSpace(note.Note.FeatureId)+ || string.IsNullOrWhiteSpace(note.Note.Target) || string.IsNullOrWhiteSpace(note.Note.Text)+ || note.Note.GeometricFaceIds.Count != 0)+ diagnostics.Add(Diagnostic("Assembly notes require a known occurrence and non-empty semantic identity, target and text; face associations are not admitted.", "Exporter.Assembly.Note"));foreach (var occurrence in model.Occurrences){if (occurrence.ParentStableId is not null && !occurrences.ContainsKey(occurrence.ParentStableId)) diagnostics.Add(Diagnostic($"Occurrence '{occurrence.StableId}' has missing parent '{occurrence.ParentStableId}'.", "Exporter.Assembly.UnresolvedParent"));diff --git a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs b/Aetheris.Kernel.Core/Step242/Step242Exporter.csindex f29308b8..134bee3f 100644--- a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs@@ -467,7 +467,7 @@ public static class Step242ExporterEmitDimensionSemanticPmi(writer, shapeId, repContextId, lengthUnitId, dimension);break;case Step242SemanticPmiNote note:- EmitNoteSemanticPmi(writer, shapeId, note);+ EmitNoteSemanticPmi(writer.AddEntity, Step242TextWriter.Ref(shapeId), note);break;case Step242SemanticPmiGeometricTolerance tolerance:EmitGeometricToleranceSemanticPmi(writer, shapeId, lengthUnitId, tolerance, datumEntities);@@ -642,10 +642,10 @@ public static class Step242ExporterEmitQuantitySemanticPmi(writer, targetAspectId, tolerance.FeatureId, tolerance.Quantity);}- private static void EmitNoteSemanticPmi(Step242TextWriter writer, string shapeId, Step242SemanticPmiNote note)+ internal static void EmitNoteSemanticPmi(Func<string, string[], string> addEntity, string shapeReference, Step242SemanticPmiNote note){- var aspectId = writer.AddEntity("SHAPE_ASPECT", Step242TextWriter.String($"firmament-note:{note.FeatureId}"), Step242TextWriter.String($"semantic note target={note.Target}"), Step242TextWriter.Ref(shapeId), Step242TextWriter.BooleanLogical(false));- writer.AddEntity("PROPERTY_DEFINITION", Step242TextWriter.String($"note:{note.FeatureId}"), Step242TextWriter.String(note.Text), Step242TextWriter.Ref(aspectId));+ var aspectId = addEntity("SHAPE_ASPECT", [Step242TextWriter.String($"firmament-note:{note.FeatureId}"), Step242TextWriter.String($"semantic note target={note.Target}"), shapeReference, Step242TextWriter.BooleanLogical(false)]);+ addEntity("PROPERTY_DEFINITION", [Step242TextWriter.String($"note:{note.FeatureId}"), Step242TextWriter.String(note.Text), Step242TextWriter.Ref(aspectId)]);}private static string BuildPlane(Step242TextWriter writer, PlaneSurface plane)diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyAppearanceTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyAppearanceTests.csnew file mode 100644index 00000000..242d612b--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyAppearanceTests.cs@@ -0,0 +1,65 @@+using Aetheris.Kernel.Firmament.Assembly;++namespace Aetheris.Kernel.Firmament.Tests.Assembly;++public sealed class AssemblyAppearanceTests+{+ private const string Source = """+ Appearance Bare { Color: [0.5,0.5,0.5]; Metallic: 1; Roughness: 0.2; }+ Material Steel { Identity: "steel"; Appearance: Bare; }+ Template<H: Length> Struct Pad {+ Rect2 R { Center: [0mm,0mm]; Size: [10mm,10mm] }+ Profile P { Loop Outer { R |> TraceLoop } }+ Extrude Body { Profile: P From: 0mm To: H }+ }+ Appearance Paint { Color: [0.9,0.8,0.6]; Metallic: 0; Roughness: 0.3; }+ Assembly Product {+ <Assembly Product>+ <Part A = Pad<H:2mm>> Material: Steel; Placement { From: Origin; To: World; } </Part>+ <Part B = Pad<H:2mm>> Material: Steel with { Appearance: Paint; }; Placement { From: Origin; To: World; TranslateLocal: [20mm,0mm,0mm]; } </Part>+ </Assembly>+ Anchor: Product;+ }+ """;++ [Fact]+ public void PhysicalIdentitySurvivesPaintOverrideAndSharedGeometry()+ {+ var result = new AssemblyM1Pipeline().Compile(Source);+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));+ var parts = result.Ir!.Instances.Where(i => i.Kind == AssemblyInstanceKind.Part).ToArray();+ Assert.All(parts, p => Assert.Equal("steel", p.Appearance!.PhysicalIdentity));+ Assert.Equal("physical-material-default", parts[0].Appearance!.Authority);+ Assert.Equal("with-appearance-override", parts[1].Appearance!.Authority);+ Assert.Single(result.Geometry!.DefinitionBodies);+ var usd = AssemblyUsdExporter.Export(result);+ Assert.Contains("userProperties:aetheris_material = \"steel\"", usd);+ Assert.Contains("bindMaterialAs = \"strongerThanDescendants\"", usd);+ Assert.Contains("userProperties:aetheris_appearance = \"Paint\"", usd);+ }++ [Fact]+ public void LookOnlyEditOfDifferentLengthReusesGeometryAndRefreshesBinding()+ {+ using var session = new FirmamentCompilationSession();+ var before = session.Compile(Source);+ var after = session.Compile(Source.Replace("Roughness: 0.3", "Roughness: 0.125"));+ Assert.True(before.IsSuccess && after.IsSuccess, string.Join("\n", after.Diagnostics));+ Assert.Equal(1, after.Reuse!.ReusedDefinitions);+ Assert.Equal(0, after.Reuse.RebuiltDefinitions);+ Assert.Equal(before.Geometry!.Artifact.DeterministicSha256, after.Geometry!.Artifact.DeterministicSha256);+ Assert.Equal(.125, after.Ir!.Instances.Single(i => i.Path.ToString() == "Product.B").Appearance!.Preview.Roughness);+ }++ [Theory]+ [InlineData("Appearance: Paint", "Appearance: Missing", "unknown-appearance")]+ [InlineData("Material: Steel;", "Material: Missing;", "unknown-material")]+ [InlineData("Metallic: 1;", "Metallic: 2;", "values-invalid")]+ [InlineData("Material: Steel;", "Material: Steel with { Color: [1,0,0]; };", "selection-invalid")]+ public void InvalidAppearanceFailsClosed(string from, string to, string code)+ {+ var result = new AssemblyM1Pipeline().Compile(Source.Replace(from, to));+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, d => d.Code.Contains(code));+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyKinematicsX0Tests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyKinematicsX0Tests.csindex deb677e0..c54e0bab 100644--- a/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyKinematicsX0Tests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyKinematicsX0Tests.cs@@ -182,7 +182,7 @@ public sealed class AssemblyKinematicsX0Testsvar schema = FirmamentSemanticSchemas.Get($"Interface<{family}>");Assert.NotNull(schema);Assert.Equal(["A", "B"], schema.Fields.Where(field => field.Required).Select(field => field.Name));- Assert.Equal(family == "Fixed" ? ["Clocking", "Gap", "Orientation"] : Array.Empty<string>(),+ Assert.Equal(family == "Fixed" ? ["Clocking", "Datum", "Gap", "Members", "Orientation"] : Array.Empty<string>(),schema.Fields.Where(field => !field.Required).Select(field => field.Name));}const string source = "Assembly A { Interface<Revolute> Joint { ";diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyPmiTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyPmiTests.csnew file mode 100644index 00000000..670c0771--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyPmiTests.cs@@ -0,0 +1,123 @@+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.Assembly;++namespace Aetheris.Kernel.Firmament.Tests.Assembly;++public sealed class AssemblyPmiTests+{+ private const string Source = """+ Record ReleaseInfo { Author: String Date: Date Version: Version Description: String Tolerance: Length }+ Static Release: ReleaseInfo {+ Author: "GPT 6.1 Sol Codex"+ Date: 2026-10-01+ Version: 0.1.0+ Description: "AI-authored presentation witness"+ Tolerance: 0.1mm+ }+ Template<H: Length> Struct Pad {+ Rect2 R { Center: [0mm,0mm]; Size: [10mm,10mm] }+ Profile P { Loop Outer { R |> TraceLoop } }+ Extrude Body { Profile: P From: 0mm To: H }+ }+ Assembly Product {+ Provenance: Release;+ Pmi {+ Note Intent { Target: Product.A; Text: "Designer's note: {not geometry} #17; https://example.test/a // literal text"; }+ }+ <Assembly Product>+ <Part A = Pad<H:2mm>> Placement { From: Origin; To: World; } </Part>+ <Part B = Pad<H:2mm>> Placement { From: Origin; To: World; TranslateLocal: [20mm,0mm,0mm]; } </Part>+ </Assembly>+ Anchor: Product;+ }+ """;++ [Fact]+ public void TypedReleaseAndOccurrenceNoteSurviveRealAp242AndUsdExport()+ {+ var result = new AssemblyM1Pipeline().Compile(Source);+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));+ Assert.Equal("GPT 6.1 Sol Codex", result.Ir!.Annotations!.Release!.Fields["Author"]);+ var export = AssemblyIrAp242Exporter.Export(result);+ Assert.True(export.IsSuccess, string.Join("\n", export.Diagnostics));+ Assert.Contains("'2026-10-01T00:00:00',('GPT 6.1 Sol Codex')", export.Value);+ var inspected = Step242SemanticPmiInspector.Inspect(export.Value);+ Assert.True(inspected.Success, string.Join("\n", inspected.Diagnostics));+ Assert.Equal(6, inspected.AnnotationCount);+ var note = Assert.Single(inspected.Items, n => n.Name == "Intent");+ Assert.Equal("Product.A", note.Target);+ Assert.Equal("Designer's note: {not geometry} #17; https://example.test/a // literal text", note.Text);+ Assert.All(inspected.Items, n => Assert.Empty(n.GeometricFaceEntityIds));+ var imported = Step242AssemblyImporter.Import(export.Value);+ Assert.True(imported.IsSuccess, string.Join("\n", imported.Diagnostics));+ Assert.Single(imported.Value.Definitions, d => d.Geometry is not null);+ Assert.Equal(2, imported.Value.Occurrences.Count(o => o.Name is "A" or "B"));+ var usd = AssemblyUsdExporter.Export(result);+ Assert.Contains("aetheris:provenance:Author = \"GPT 6.1 Sol Codex\"", usd);+ Assert.Contains("aetheris:pmi:Intent:target = \"Product.A\"", usd);+ Assert.Equal(export.Value, AssemblyIrAp242Exporter.Export(result).Value);+ }++ [Theory]+ [InlineData("Date: 2026-10-01", "Date: 2026-02-30", "provenance-record-invalid")]+ [InlineData("Version: 0.1.0", "Version: 0.1", "provenance-record-invalid")]+ [InlineData("Tolerance: 0.1mm", "Tolerance: 0.1deg", "provenance-record-invalid")]+ [InlineData("Author: String", "Author: Length", "provenance-field-invalid")]+ [InlineData("Provenance: Release;", "Provenance: Missing;", "provenance-record-unresolved")]+ [InlineData("Provenance: Release;", "Provenance: Release; Provenance: Release;", "provenance-selection-invalid")]+ [InlineData("Target: Product.A", "Target: Product.Missing", "pmi-target-unresolved")]+ [InlineData("Note Intent", "Datum Intent", "pmi-kind-unsupported")]+ [InlineData("Text:", "Unknown:", "pmi-note-invalid")]+ public void InvalidMetadataStopsCompilation(string before, string after, string diagnostic)+ {+ var result = new AssemblyM1Pipeline().Compile(Source.Replace(before, after));+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, d => d.Code == "assembly-" + diagnostic);+ }++ [Fact]+ public void NoteTextCannotDeclareRecordsOrGeometry()+ {+ var source = Source.Replace("Designer's note: {not geometry} #17; https://example.test/a // literal text",+ "Record Spoof { Value: Length } Static Trap: Spoof { Value: invalid } Box Fake { Size: [9mm,9mm,9mm] }");+ var result = new AssemblyM1Pipeline().Compile(source);+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));+ Assert.Single(result.Geometry!.DefinitionBodies);+ Assert.Equal(2, result.Geometry.InstanceBodies.Count);+ var inspection = Step242SemanticPmiInspector.Inspect(AssemblyIrAp242Exporter.Export(result).Value);+ Assert.StartsWith("Record Spoof", inspection.Items.Single(n => n.Name == "Intent").Text);+ }++ [Fact]+ public void MetadataEditRefreshesStepAndKeepsSharedGeometryCache()+ {+ using var session = new FirmamentCompilationSession();+ var before = session.Compile(Source);+ var after = session.Compile(Source.Replace("Version: 0.1.0", "Version: 0.1.1").Replace("Designer", "Reviewer"));+ Assert.True(before.IsSuccess && after.IsSuccess, string.Join("\n", after.Diagnostics));+ Assert.Equal(1, after.Reuse!.ReusedDefinitions);+ Assert.Equal(0, after.Reuse.RebuiltDefinitions);+ Assert.Equal(before.Geometry!.Artifact.DeterministicSha256, after.Geometry!.Artifact.DeterministicSha256);+ var inspected = Step242SemanticPmiInspector.Inspect(AssemblyIrAp242Exporter.Export(after).Value);+ Assert.Equal("0.1.1", inspected.Items.Single(n => n.Name == "Release.Version").Text);+ Assert.StartsWith("Reviewer's note", inspected.Items.Single(n => n.Name == "Intent").Text);+ }++ [Fact]+ public void GuitarReleaseExportsAllNotesWithoutChangingProductStructure()+ {+ var fixture = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm");+ var result = new AssemblyM1Pipeline().CompileFile(fixture);+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));+ Assert.Equal(99, result.Geometry!.InstanceBodies.Count);+ Assert.Equal(56, result.Geometry.DefinitionBodies.Count);+ Assert.Equal("0.1mm", result.Ir!.Annotations!.Release!.Fields["AuthoringTolerance"]);+ var export = AssemblyIrAp242Exporter.Export(result);+ Assert.True(export.IsSuccess, string.Join("\n", export.Diagnostics));+ var inspected = Step242SemanticPmiInspector.Inspect(export.Value);+ Assert.True(inspected.Success, string.Join("\n", inspected.Diagnostics));+ Assert.Equal(18, inspected.AnnotationCount);+ Assert.Equal("GPT 6.1 Sol Codex", inspected.Items.Single(n => n.Name == "GuitarRelease.Author").Text);+ Assert.Equal("GuitarX0.Bridge", inspected.Items.Single(n => n.Name == "BridgeHardware").Target);+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyRouteBindingTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyRouteBindingTests.csnew file mode 100644index 00000000..690e55ad--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyRouteBindingTests.cs@@ -0,0 +1,71 @@+using Aetheris.Kernel.Firmament.Assembly;++namespace Aetheris.Kernel.Firmament.Tests.Assembly;++public sealed class AssemblyRouteBindingTests+{+ private const string Source = """+ Template<H: Length> Struct Terminal {+ Expose { Semantic Entry { DatumFrame Frame = [0mm,0mm,H] x [1,0,0] y [0,1,0] z [0,0,1]; } }+ Rect2 R { Center: [0mm,0mm]; Size: [2mm,2mm] }+ Profile P { Loop Outer { R |> TraceLoop } }+ Extrude Body { Profile: P From: 0mm To: H }+ }+ Template<A: Point3,B: Point3,C: Point3> Struct Lead {+ WireRoute Route {+ Diameter: 1mm; Material: Standard.Materials.StainlessSteel.304_Annealed; MinimumBendRadius: 3mm;+ Path { Start { At: A; } Corner Turn { At: B; Radius: 3mm; } End { At: C; } }+ }+ }+ Assembly Product {+ <Assembly Product>+ <Part Start = Terminal<H:10mm>> Placement { From: Origin; To: World; } </Part>+ <Part Bend = Terminal<H:10mm>> Placement { From: Origin; To: World; TranslateLocal: [30mm,0mm,0mm]; } </Part>+ <Part End = Terminal<H:10mm>> Placement { From: Origin; To: World; TranslateLocal: [30mm,30mm,0mm]; } </Part>+ <Part Wire = Lead<>>+ Placement { From: Origin; To: World; TranslateLocal: [5mm,-5mm,1mm]; }+ Bind {+ A { At: Point3(0mm,0mm,0mm); On: Product.Start.Entry.Frame; }+ B { At: Point2(0mm,0mm); On: Product.Bend.Entry.Frame; }+ C { At: Point3(0mm,0mm,0mm); On: Product.End.Entry.Frame; }+ }+ </Part>+ </Assembly>+ Anchor: Product;+ }+ """;++ [Fact]+ public void FinalPublicFramesBindExactlyOnceIntoRouteLocalCoordinates()+ {+ var result = new AssemblyM1Pipeline().Compile(Source);+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));+ var points = result.Ir!.RouteBindings!;+ Assert.Equal(3, points.Count);+ Assert.Equal(new double[] { 0,0,10 }, points[0].WorldPoint);+ Assert.Equal(new double[] { -5,5,9 }, points[0].LocalPoint);+ Assert.Contains("A:Point3(-5mm,5mm,9mm)", points[0].SpecializedDefinition);+ Assert.Equal(2, result.Geometry!.DefinitionBodies.Count);+ }++ [Fact]+ public void EndpointPlacementEditRebuildsOnlyBoundRoute()+ {+ using var session = new FirmamentCompilationSession();+ var before = session.Compile(Source);+ var after = session.Compile(Source.Replace("[30mm,30mm,0mm]", "[30mm,40mm,0mm]"));+ Assert.True(before.IsSuccess && after.IsSuccess, string.Join("\n", after.Diagnostics));+ Assert.Equal(1, after.Reuse!.ReusedDefinitions);+ Assert.Equal(1, after.Reuse.RebuiltDefinitions);+ Assert.Equal(40, after.Ir!.RouteBindings![2].WorldPoint[1]);+ }++ [Fact]+ public void UnknownPortStopsBeforeMaterialization()+ {+ var result = new AssemblyM1Pipeline().Compile(Source.Replace("Product.End.Entry.Frame", "Product.End.Hidden.Frame"));+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, d => d.Code == "assembly-route-bind-port-unresolved");+ Assert.Null(result.Geometry);+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/CoaxialDatumTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/CoaxialDatumTests.csindex fef76427..3cf6b649 100644--- a/Aetheris.Kernel.Firmament.Tests/Assembly/CoaxialDatumTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/CoaxialDatumTests.cs@@ -7,9 +7,10 @@ namespace Aetheris.Kernel.Firmament.Tests.Assembly;public sealed class CoaxialDatumTests{private const string Fixture = "fixtures/Canonical/AssemblyInterfaces/coaxial-knob.firmasm";- private static string Source => File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/GuitarX0/hardware-definitions.firmament"))+ private static string Source => FirmamentV2.FirmamentSourceSpelling.Normalize(File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/GuitarX0/materials.firmament"))+ + File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/GuitarX0/hardware-definitions.firmament"))+ File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/GuitarX0/knob.firmament"))- + string.Join('\n', File.ReadAllLines(FirmamentCorpusHarness.ResolveFixtureFullPath(Fixture)).Where(l => !l.StartsWith("Include")));+ + string.Join('\n', File.ReadAllLines(FirmamentCorpusHarness.ResolveFixtureFullPath(Fixture)).Where(l => !l.StartsWith("Include"))));[Fact]public void CompleteKnobRotatesAsOneRigidOccurrenceWithNoGeometryRebuild()@@ -67,6 +68,7 @@ public sealed class CoaxialDatumTestspublic void CompositePublicAxisAndFrameFollowSolvedLocalChildPlacement(){var source = Source.Replace("At: 0mm; Clocking: 0deg;","At: 2mm; Clocking: 0deg;");+ Assert.NotEqual(Source, source);var result = new AssemblyM0Compiler().Compile(new AssemblyM0Parser().Parse(source).Source!);Assert.True(result.IsSuccess,Evidence(result.Diagnostics));var knob = Instance(result.Ir!.Instances,"Controls.VolumeKnob");@@ -124,6 +126,7 @@ public sealed class CoaxialDatumTests[InlineData("Interface<Fixed> CoaxialStack","Interface<Revolute> CoaxialStack","assembly-axis-internal-motion-unsupported")]public void InvalidAxisContractsFailClosed(string from,string to,string code){+ Assert.Contains(from, Source);var result = new AssemblyM0Parser().Parse(Source.Replace(from,to));Assert.False(result.IsSuccess);Assert.Contains(result.Diagnostics,d=>d.Code==code);@@ -140,8 +143,8 @@ public sealed class CoaxialDatumTestsvar definition=Assert.Single(ir.AssemblyDefinitions!,d=>d.DefinitionIdentity=="ControlKnob");Assert.Equal(new double[]{0,3,12},definition.LocalAxisSeats!.Select(e=>e.Seating.StationMm).Order());Assert.All(definition.LocalAxisSeats!,e=>Assert.True(e.Passed));- Assert.Equal(91,compiled.Geometry!.Artifact.Instances.Count);- Assert.Equal(53,compiled.Geometry.Artifact.Definitions.Count);+ Assert.Equal(99,compiled.Geometry!.Artifact.Instances.Count);+ Assert.Equal(56,compiled.Geometry.Artifact.Definitions.Count);}private static AssemblyInstanceIr Instance(IReadOnlyList<AssemblyInstanceIr> instances,string path)=>instances.Single(i=>i.Path.ToString()==path);diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/ConceptPointAuthoringTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/ConceptPointAuthoringTests.csnew file mode 100644index 00000000..1a4d1b21--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/ConceptPointAuthoringTests.cs@@ -0,0 +1,161 @@+using Aetheris.Kernel.Firmament.Assembly;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests.Assembly;++public sealed class ConceptPointAuthoringTests+{+ private static string Source => File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath(+ "fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/concept-points.firmament"));++ [Fact]+ public void CheckedLocalPointsExpandThroughOrdinaryAssemblyAndExport()+ {+ var result = new AssemblyM1Pipeline().Compile(Source);+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));+ Assert.Equal(2, result.Geometry!.DefinitionBodies.Count);+ Assert.Equal(13, result.Geometry.InstanceBodies.Count);+ var collections = result.Ir!.ConceptPoints!;+ Assert.Equal(3, collections.Count);+ var crossings = collections.Single(c => c.Name == "Nut.Crossings");+ Assert.Equal("Point2", crossings.ElementType);+ Assert.Equal(new[] { "Bass", "Middle", "Treble" }, crossings.Points.Select(p => p.Key));+ Assert.All(crossings.Points, p => Assert.Equal(2, p.Coordinates.Count));+ Assert.Contains("Linear", crossings.Recipe);+ var twelfth = collections.Single(c => c.Name == "Board.Frets").Points.Single(p => p.Key == "Fret12");+ Assert.Equal(-314, twelfth.Coordinates[1], 10);+ var fret = result.Ir.Instances.Single(i => i.Path.ToString() == "PointWitness.Frets.Fret12.Fret");+ Assert.Equal(344, fret.ResolvedTransform!.Matrix[13], 10);+ Assert.Equal(62, fret.ResolvedTransform.Matrix[14], 10);+ var bass = result.Ir.Instances.Single(i => i.Path.ToString() == "PointWitness.Bass");+ Assert.Equal(-18, bass.ResolvedTransform!.Matrix[12], 10);+ Assert.Equal(2, bass.ResolvedTransform.Matrix[14], 10);+ var pattern = Assert.Single(result.Ir.Patterns!);+ Assert.Equal("Board.Frets", pattern.Source);+ Assert.Equal(12, pattern.GeneratedCount);+ Assert.Equal("Board.Frets", pattern.Associations![11].SourceSet);+ Assert.Contains(fret.Provenance, p => p.Stage == "assembly-pattern");+ var step = AssemblyIrAp242Exporter.Export(result);+ Assert.True(step.IsSuccess, string.Join("\n", step.Diagnostics));+ var imported = Aetheris.Kernel.Core.Step242.Step242AssemblyImporter.Import(step.Value);+ Assert.True(imported.IsSuccess, string.Join("\n", imported.Diagnostics));+ var definitionIds = imported.Value.Definitions.Where(d => d.Geometry is not null).Select(d => d.StableId).ToHashSet();+ Assert.Equal(13, imported.Value.Occurrences.Count(o => definitionIds.Contains(o.DefinitionStableId!)));+ }++ [Fact]+ public void SeriesChangesMoveGeometryWithoutChangingKeyedIdentities()+ {+ AssemblyIr Compile(string source)+ {+ var parsed = new AssemblyM0Parser().Parse(source);+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));+ var result = new AssemblyM0Compiler().Compile(parsed.Source!);+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));+ return result.Ir!;+ }+ var before = Compile(Source);+ var after = Compile(Source.Replace("628mm", "630mm"));+ Assert.Equal(before.ConceptPoints!.SelectMany(c => c.Points).Select(p => p.StableId),+ after.ConceptPoints!.SelectMany(c => c.Points).Select(p => p.StableId));+ foreach (var occurrence in before.Instances)+ Assert.Equal(occurrence.StableId, after.Instances.Single(i => i.Path.ToString() == occurrence.Path.ToString()).StableId);+ Assert.NotEqual(before.Instances.Single(i => i.Path.ToString() == "PointWitness.Frets.Fret12.Fret").ResolvedTransform!.Matrix[13],+ after.Instances.Single(i => i.Path.ToString() == "PointWitness.Frets.Fret12.Fret").ResolvedTransform!.Matrix[13]);+ }++ [Theory]+ [InlineData("Count: 12", "Count: 1025")]+ [InlineData("Count: 12", "Count: 0")]+ [InlineData("First: 1", "First: -1")]+ [InlineData("First: 1", "First: 2147483647")]+ [InlineData("[Bass, Middle, Treble]", "[Bass, Bass, Treble]")]+ [InlineData("[Bass, Middle, Treble]", "Bass, Middle, Treble")]+ [InlineData("[18mm,0mm]", "[0mm,0mm]")]+ [InlineData("[18mm,0mm]", "[18deg,0mm]")]+ [InlineData("[18mm,0mm]", "[1e308mm,0mm]")]+ [InlineData("Point2(-18mm,0mm)", "Point3(-18mm,0mm,0mm)")]+ [InlineData("Nut.Crossings.Bass.X", "Nut.Crossings.Unknown.X")]+ [InlineData("Nut.Crossings.Bass.X", "Nut.Crossings.Bass.Z")]+ [InlineData("Points<Point2> Crossings", "Points<Point4> Crossings")]+ [InlineData("scale * (1.0 - Pow(2.0, -n / 12.0))", "Distance(n,scale)")]+ [InlineData("scale * (1.0 - Pow(2.0, -n / 12.0))", "Missing(n)")]+ [InlineData("scale * (1.0 - Pow(2.0, -n / 12.0))", "undefined + scale")]+ [InlineData("scale * (1.0 - Pow(2.0, -n / 12.0))", "scale + 1deg")]+ [InlineData("scale * (1.0 - Pow(2.0, -n / 12.0))", "scale / 0")]+ [InlineData("Pow(2.0, -n / 12.0)", "Pow(2mm, -n / 12.0)")]+ [InlineData("Distance(n,628mm)", "Distance(1.5,628mm)")]+ [InlineData("Distance(n,628mm)", "Distance(n,628deg)")]+ [InlineData("Distance(n,628mm)", "Distance(1e30,628mm)")]+ [InlineData("Function Distance", "Comptime Function Distance")]+ public void InvalidRecipesAndImpureOrUnboundedFunctionsFailClosed(string from, string to)+ {+ var result = new AssemblyM0Parser().Parse(Source.Replace(from, to));+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, d => d.Code == "assembly-pattern-invalid"+ && d.Message.Contains("firmament-concept-points-", StringComparison.Ordinal));+ }++ [Fact]+ public void FunctionsAreAvailableToPartAuthoringWithoutAComptimeKeyword()+ {+ var parsed = FirmamentV2Parser.Parse(File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath(+ "fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/scalar-functions-part.firmament")));+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));+ }++ [Fact]+ public void PointCollectionsAlsoRemainTypedAndErasedInPartAuthoring()+ {+ var parsed = FirmamentV2Parser.Parse(File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath(+ "fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/concept-points-part.firmament")));+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));+ var points = Assert.Single(parsed.Document!.StaticAuthoring!.ConceptPoints!);+ Assert.Equal("Point2", points.ElementType);+ Assert.Equal(2, points.Points.Count);+ }++ [Fact]+ public void TinyFunctionResultsRoundTripIntoPhysicalPlacement()+ {+ var source = "Function Tiny() -> Length = 1e-20mm;\n" + Source.Replace("Nut.Crossings.Bass.X", "Tiny()");+ var result = new AssemblyM1Pipeline().Compile(source);+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));+ var bass = result.Ir!.Instances.Single(i => i.Path.ToString() == "PointWitness.Bass");+ Assert.Equal(1e-20, bass.ResolvedTransform!.Matrix[12]);+ }++ [Fact]+ public void EvaluationBudgetsStopDeepSyntaxAndBranchingFunctionGraphs()+ {+ var nested = new string('(', 130) + "scale" + new string(')', 130);+ var deep = new AssemblyM0Parser().Parse(Source.Replace("scale * (1.0 - Pow(2.0, -n / 12.0))", nested));+ Assert.False(deep.IsSuccess);+ var graph = string.Join("\n", Enumerable.Range(0, 20).Select(n =>+ $"Function Branch{n}(x: Length) -> Length = " + (n == 19 ? "x;" : $"Branch{n+1}(x) + Branch{n+1}(x);")));+ var excessive = new AssemblyM0Parser().Parse(graph + "\n" + Source.Replace("PadHeight(1mm)", "Branch0(1mm)"));+ Assert.False(excessive.IsSuccess);+ Assert.Contains(excessive.Diagnostics, d => d.Message.Contains("function-call-invalid", StringComparison.Ordinal));+ }++ [Fact]+ public void GuitarUsesNutLocalCrossingsAndEquationDrivenFrets()+ {+ var result = new AssemblyM1Pipeline().CompileFile(FirmamentCorpusHarness.ResolveFixtureFullPath(+ "fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm"));+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));+ Assert.Equal(99, result.Geometry!.InstanceBodies.Count);+ var crossings = result.Ir!.ConceptPoints!.Single(c => c.Name == "NutLayout.Crossings");+ Assert.Equal(6, crossings.Points.Count);+ Assert.Equal(-18, crossings.Points[0].Coordinates[0], 10);+ Assert.Equal(18, crossings.Points[5].Coordinates[0], 10);+ var frets = result.Ir.ConceptPoints!.Single(c => c.Name == "FretboardLayout.Positions");+ Assert.Equal(22, frets.Points.Count);+ for (var n = 1; n <= 22; n++)+ {+ var fret = result.Ir.Instances.Single(i => i.Path.ToString() == $"GuitarX0.Neck.Frets.Fret{n}.Fret");+ Assert.Equal(658 - 628 * (1 - Math.Pow(2, -n / 12d)), fret.ResolvedTransform!.Matrix[13], 9);+ Assert.Equal(62, fret.ResolvedTransform.Matrix[14], 9);+ }+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/GuitarSurfacingWitnessTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/GuitarSurfacingWitnessTests.csindex 79a8753f..c362bc4c 100644--- a/Aetheris.Kernel.Firmament.Tests/Assembly/GuitarSurfacingWitnessTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/GuitarSurfacingWitnessTests.cs@@ -13,8 +13,8 @@ public sealed class GuitarSurfacingWitnessTests.Append(root).Select(path => new KeyValuePair<string, string>(Path.GetFileName(path), File.ReadAllText(path))).ToArray();var result = new AssemblyM1Pipeline().CompileProject(new FirmamentProjectSnapshot("guitar.firmasm", documents));Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));- Assert.Equal(53, result.Geometry!.DefinitionBodies.Count);- Assert.Equal(91, result.Geometry.InstanceBodies.Count);+ Assert.Equal(56, result.Geometry!.DefinitionBodies.Count);+ Assert.Equal(99, result.Geometry.InstanceBodies.Count);Assert.Equal(10, result.Ir!.AssemblyDefinitions!.Count);var neck = result.Ir.Instances.Single(i => i.Path.ToString() == "GuitarX0.Neck");Assert.True(neck.IsEncapsulatedDefinition);@@ -24,7 +24,9 @@ public sealed class GuitarSurfacingWitnessTestsAssert.Equal(660, nut.OriginY, 6);Assert.Equal(55, nut.OriginZ, 6);Assert.DoesNotContain("Headstock", neck.SemanticRoot.ExposedMembers.Keys);- Assert.Equal(19, result.Ir.SourceDependencies!.Count);+ Assert.Equal(22, result.Ir.SourceDependencies!.Count);+ Assert.Contains(result.Ir.SourceDependencies, d => d.Path == "neck-profile.firmament");+ Assert.Contains(result.Ir.SourceDependencies, d => d.Path == "materials.firmament");Assert.Contains(result.Ir.SourceDependencies, d => d.Path == "tuners-assembly.firmament");}[Fact]@@ -35,8 +37,15 @@ public sealed class GuitarSurfacingWitnessTestsvar compiled = new AssemblyM1Pipeline().CompileFile(path);Assert.True(compiled.IsSuccess, string.Join("\n", compiled.Diagnostics.Select(d => d.Message)));var mesh = AssemblyDisplayMeshExporter.Export(compiled);- Assert.Equal(91, mesh.Occurrences.Count(o => o.DefinitionId is not null));- Assert.Equal(4, compiled.Ir!.Patterns!.Count);+ Assert.Equal(99, mesh.Occurrences.Count(o => o.DefinitionId is not null));+ Assert.Equal(6, compiled.Ir!.Patterns!.Count);+ var inlays = compiled.Ir.Instances.Where(i => i.Path.ToString().StartsWith("GuitarX0.Neck.PearlInlays.", StringComparison.Ordinal)+ && i.Path.ToString().EndsWith(".Inlay", StringComparison.Ordinal)).ToArray();+ Assert.Equal(9, inlays.Length);+ Assert.Single(inlays.Select(i => i.DefinitionIdentity).Distinct());+ Assert.All(inlays, i => Assert.Equal(62, i.ResolvedTransform!.Matrix[14], 10));+ var inlay3 = Assert.Single(inlays, i => i.Path.ToString() == "GuitarX0.Neck.PearlInlays.Fret3.Inlay");+ Assert.Equal(573.8, inlay3.ResolvedTransform!.Matrix[13], 10);Assert.Empty(compiled.Ir.Joints!);Assert.Equal(10, compiled.Ir.AssemblyDefinitions!.Count);Assert.Single(compiled.Ir.AssemblyDefinitions.Single(d => d.DefinitionIdentity == "GuitarNeck").LocalMates,@@ -66,13 +75,38 @@ public sealed class GuitarSurfacingWitnessTestsAssert.Equal(15, dy * head.ResolvedTransform.Matrix[9] + dz * head.ResolvedTransform.Matrix[10], 7);Assert.Equal(head.ResolvedTransform.Matrix[9], m[9], 8);Assert.Equal(head.ResolvedTransform.Matrix[10], m[10], 8);+ var stem = compiled.Ir.Instances.Single(i => i.Path.ToString() == tuner.Path + ".ButtonStem");+ var local = Transform3D.FromRowMajor(stem.ResolvedTransform!.Matrix)+ * Transform3D.FromRowMajor(m).Inverse();+ var buttonEnd = local.Apply(new Point3D(0, 0, 0));+ var headEnd = local.Apply(new Point3D(0, 0, 16));+ // Stem overlaps the button's inner edge (-14.5mm) and reaches the post axis.+ Assert.InRange(buttonEnd.X, -29.5, -14.5);+ Assert.Equal(0, headEnd.X, 7);+ Assert.Equal(0, buttonEnd.Y, 7);+ Assert.Equal(-4, buttonEnd.Z, 7);+ Assert.Equal(-4, headEnd.Z, 7);}+ Assert.Single(mesh.Definitions, d => d.Identity == "Drum<R:2.5mm,H:16mm>");+ var rail = compiled.Ir.Instances.Single(i => i.Path.ToString() == "GuitarX0.Bridge.StringRail");+ var railTransform = Transform3D.FromRowMajor(rail.ResolvedTransform!.Matrix);+ // Extruded semicircle: diameter rests on the tailpiece at z=60; crown at z=65.+ Assert.Equal(60, railTransform.Apply(new Point3D(0, 0, 0)).Z, 7);+ Assert.Equal(65, railTransform.Apply(new Point3D(5, 0, 0)).Z, 7);+ var bridgeUnit = compiled.Ir.Instances.Single(i => i.Path.ToString() == "GuitarX0.Bridge");+ var crown = Assert.IsType<Aetheris.Semantics.ExactDatumFrameBinding>(AssemblyWorldQuery.Resolve(compiled.Ir,+ bridgeUnit.SemanticRoot.ExposedMembers["TailStringPlane"].StableIdentity));+ Assert.Equal(-75, crown.OriginY, 7);+ Assert.Equal(65, crown.OriginZ, 7);Assert.Equal(6, mesh.Definitions.Count(d => d.Identity.StartsWith("GuitarString<", StringComparison.Ordinal)));var surfaced = mesh.Definitions.Where(d => d.Identity.StartsWith("SectionChainFile", StringComparison.Ordinal)).ToArray();Assert.Equal(4, surfaced.Length);var strings = mesh.Definitions.Where(d => d.Identity.StartsWith("GuitarString<", StringComparison.Ordinal)).ToArray();Assert.All(strings, d => Assert.Equal("SurfaceMeshIr", d.MeshPipeline));- foreach (var definition in surfaced.Concat(strings))+ var joinDetails = mesh.Definitions.Where(d => d.Identity.StartsWith("TailpieceRail<", StringComparison.Ordinal)+ || d.Identity.StartsWith("HeadstockScarf<", StringComparison.Ordinal) || d.Identity == "Drum<R:2.5mm,H:16mm>").ToArray();+ Assert.Equal(3, joinDetails.Length);+ foreach (var definition in surfaced.Concat(strings).Concat(joinDetails)){if (definition.Identity.StartsWith("SectionChainFile", StringComparison.Ordinal))Assert.Equal("StructuredSpline", definition.MeshPipeline);@@ -110,13 +144,13 @@ public sealed class GuitarSurfacingWitnessTestsvar neck = Assert.Single(surfaced.Where(d => d.Identity.Contains("Neck.firmament", StringComparison.Ordinal)));var neckPoints = Enumerable.Range(0, neck.Positions.Length / 3).Select(i => new Point3D(neck.Positions[i * 3], neck.Positions[i * 3 + 1], neck.Positions[i * 3 + 2])).ToArray();- Assert.All(neckPoints, p => Assert.True(p.Z <= 55.000001, "Neck must stay below the flat fretboard seat."));+ Assert.All(neckPoints.Where(p => p.Y <= 630), p => Assert.True(p.Z <= 55.000001, "Main neck must stay below the flat fretboard seat."));var nutPoints = neckPoints.Where(p => System.Math.Abs(p.Y - 660) < 0.000001).ToArray();Assert.NotEmpty(nutPoints);Assert.Equal(48, nutPoints.Min(p => p.Z), 6);Assert.Equal(55, nutPoints.Max(p => p.Z), 6);Assert.True(neckPoints.Any(p => p.Y < 200 && p.Z < 20), "The rounded heel must extend into the body back.");- foreach (var p in neckPoints.Where(p => p.Y >= 240))+ foreach (var p in neckPoints.Where(p => p.Y >= 240 && p.Y <= 630)){var straightBack = 42 + (p.Y - 240) / 70;Assert.True(p.Z >= straightBack - 0.002, "The main neck must not bulge behind its straight tapered back.");@@ -125,13 +159,22 @@ public sealed class GuitarSurfacingWitnessTestsAssert.True(System.Math.Abs(p.Z - straightBack) < 0.002 || System.Math.Abs(p.Z - 55) < 0.002,"Centerline samples must lie on the straight back or flat seat.");}+ // End cap is inside the headstock's solid, rather than exposed at the nut.+ var headInverse = Transform3D.FromRowMajor(head.ResolvedTransform.Matrix).Inverse();+ var merge = neckPoints.Select(headInverse.Apply).Where(p => System.Math.Abs(p.Y - 18) < 0.000001).ToArray();+ Assert.NotEmpty(merge);+ Assert.All(merge, p => {+ Assert.InRange(p.Z, -0.000001, 14.000001);+ var halfWidth = 21.5 + 12.5 * p.Y / 40;+ Assert.True(System.Math.Abs(p.X) <= halfWidth + 0.000001, "Neck transition cap must be buried inside headstock outline.");+ });Assert.Contains("subdivisionScheme = \"none\"", AssemblyUsdExporter.Serialize(compiled.Ir!, mesh));var exported = AssemblyIrAp242Exporter.Export(compiled);Assert.True(exported.IsSuccess, string.Join("\n", exported.Diagnostics));var imported = Aetheris.Kernel.Core.Step242.Step242AssemblyImporter.Import(exported.Value);Assert.True(imported.IsSuccess, string.Join("\n", imported.Diagnostics));var geometryIds = imported.Value.Definitions.Where(d => d.Geometry is not null).Select(d => d.StableId).ToHashSet();- Assert.Equal(53, geometryIds.Count);- Assert.Equal(91, imported.Value.Occurrences.Count(o => geometryIds.Contains(o.DefinitionStableId!)));+ Assert.Equal(56, geometryIds.Count);+ Assert.Equal(99, imported.Value.Occurrences.Count(o => geometryIds.Contains(o.DefinitionStableId!)));}}diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/IncrementalCompilationTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/IncrementalCompilationTests.csindex 10da4dab..94b47dad 100644--- a/Aetheris.Kernel.Firmament.Tests/Assembly/IncrementalCompilationTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/IncrementalCompilationTests.cs@@ -136,13 +136,14 @@ public sealed class IncrementalCompilationTestsFirmamentProjectSnapshot Project() => new("guitar.firmasm", documents);var first = Good(session.CompileProject(Project()));var repeated = Good(session.CompileProject(Project()));- Assert.Equal(53, repeated.Reuse!.ReusedDefinitions);+ Assert.Equal(56, repeated.Reuse!.ReusedDefinitions);Assert.Equal(AssemblyUsdExporter.Serialize(first.Ir!, AssemblyDisplayMeshExporter.Export(first)),AssemblyUsdExporter.Serialize(repeated.Ir!, AssemblyDisplayMeshExporter.Export(repeated)));var neckFile = documents.Keys.Single(k => k == "Neck.firmament");- documents[neckFile] = documents[neckFile].Replace("-40mm", "-39.8mm");+ Assert.Contains("Depth: 40mm", documents[neckFile], StringComparison.Ordinal);+ documents[neckFile] = documents[neckFile].Replace("Depth: 40mm", "Depth: 39.8mm");var edited = Good(session.CompileProject(Project()));- Assert.Equal(52, edited.Reuse!.ReusedDefinitions);+ Assert.Equal(55, edited.Reuse!.ReusedDefinitions);Assert.Equal(1, edited.Reuse.RebuiltDefinitions);Assert.Contains(edited.Reuse.Definitions, d => !d.Reused && d.DefinitionIdentity.Contains("Neck.firmament", StringComparison.Ordinal));Assert.NotEqual(first.Geometry!.Artifact.Definitions.Single(d => d.DefinitionIdentity.Contains("Neck.firmament", StringComparison.Ordinal)).StepSha256,diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/LinearStationAuthoringTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/LinearStationAuthoringTests.csnew file mode 100644index 00000000..2aa99d30--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/LinearStationAuthoringTests.cs@@ -0,0 +1,110 @@+using Aetheris.Kernel.Firmament.Assembly;++namespace Aetheris.Kernel.Firmament.Tests.Assembly;++public sealed class LinearStationAuthoringTests+{+ private static string Source => File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath(+ "fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/linear-stations.firmament"));++ private static AssemblyIr Compile(string source)+ {+ var parsed = new AssemblyM0Parser().Parse(source);+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));+ var compiled = new AssemblyM0Compiler().Compile(parsed.Source!);+ Assert.True(compiled.IsSuccess, string.Join("\n", compiled.Diagnostics));+ return compiled.Ir!;+ }++ [Fact]+ public void StationsNormalizeDirectionAndFollowThePlacedBoardsPublishedFrame()+ {+ var result = new AssemblyM1Pipeline().Compile(Source);+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));+ Assert.Equal(2, result.Geometry!.DefinitionBodies.Count);+ Assert.Equal(4, result.Geometry.InstanceBodies.Count);+ var collection = Assert.Single(result.Ir!.ConceptPoints!);+ Assert.Equal(new[] { "First", "Second", "Third" }, collection.Points.Select(p => p.Key));+ Assert.Equal(new[] { -10d, -23.5, 4 }, collection.Points.Select(p => p.Coordinates[1]));+ Assert.Contains("Stations", collection.Recipe);+ var first = result.Ir.Instances.Single(i => i.Path.ToString() == "StationWitness.Markers.First.Inlay");+ Assert.Equal(10, first.ResolvedTransform!.Matrix[12], 10);+ Assert.Equal(18, first.ResolvedTransform.Matrix[13], 10);+ Assert.Equal(20, first.ResolvedTransform.Matrix[14], 10);+ // A board placement change propagates via its port, not station coordinates.+ var moved = new AssemblyM1Pipeline().Compile(Source.Replace("20mm,30mm", "20mm,37mm"));+ Assert.True(moved.IsSuccess, string.Join("\n", moved.Diagnostics));+ foreach (var inlay in result.Ir.Instances.Where(i => i.Path.ToString().EndsWith(".Inlay", StringComparison.Ordinal)))+ {+ var next = moved.Ir!.Instances.Single(i => i.StableId == inlay.StableId);+ Assert.Equal(inlay.ResolvedTransform!.Matrix[14] + 7, next.ResolvedTransform!.Matrix[14], 10);+ }+ var step = AssemblyIrAp242Exporter.Export(result);+ Assert.True(step.IsSuccess, string.Join("\n", step.Diagnostics));+ var imported = Aetheris.Kernel.Core.Step242.Step242AssemblyImporter.Import(step.Value);+ Assert.True(imported.IsSuccess, string.Join("\n", imported.Diagnostics));+ }++ [Fact]+ public void ReorderingAndEditingStationsPreserveKeyedIdentitiesAndMoveOnlyEditedStation()+ {+ var before = Compile(Source);+ var after = Compile(Source.Replace("First: 10mm; Second: 23.5mm; Third: -4mm;", "Third: -4mm; Second: 24mm; First: 10mm;"));+ var points = Assert.Single(after.ConceptPoints!).Points;+ Assert.Equal(new[] { "Third", "Second", "First" }, points.Select(p => p.Key));+ Assert.Equal(new[] { 0, 1, 2 }, points.Select(p => p.Ordinal));+ foreach (var point in Assert.Single(before.ConceptPoints!).Points)+ Assert.Equal(point.StableId, points.Single(p => p.Key == point.Key).StableId);+ foreach (var occurrence in before.Instances)+ {+ var next = after.Instances.Single(i => i.StableId == occurrence.StableId);+ if (occurrence.Path.ToString() == "StationWitness.Markers.Second.Inlay")+ Assert.Equal(occurrence.ResolvedTransform!.Matrix[14] - .5, next.ResolvedTransform!.Matrix[14], 10);+ else Assert.Equal(occurrence.ResolvedTransform!.Matrix, next.ResolvedTransform!.Matrix);+ }+ }++ [Fact]+ public void Point3StationsAndLargeFiniteDirectionsUseTheSameBoundedRecipe()+ {+ var result = Compile(Source.Replace("Points<Point2>", "Points<Point3>").Replace("Point2(0mm,0mm)", "Point3(1mm,2mm,3mm)")+ .Replace("[0,-2]", "[0,0,-1e308]"));+ var points = Assert.Single(result.ConceptPoints!).Points;+ Assert.Equal(new[] { 1d, 2, -7 }, points[0].Coordinates);+ Assert.Equal(new[] { 1d, 2, 7 }, points[2].Coordinates);+ }++ [Fact]+ public void NestedScalarCallsInDirectionAndStationDistancesStayDimensionChecked()+ {+ var result = Compile(Source.Replace("[0,-2]", "[0,-Pow(2,3)]").Replace("First: 10mm", "First: 5mm * Pow(2,1)"));+ Assert.Equal(-10, Assert.Single(result.ConceptPoints!).Points[0].Coordinates[1]);+ }++ [Theory]+ [InlineData("[0,-2]", "[0,0]")]+ [InlineData("[0,-2]", "[0,-2mm]")]+ [InlineData("[0,-2]", "[0,-2,0]")]+ [InlineData("First: 10mm", "First: 10deg")]+ [InlineData("First: 10mm", "First: 10")]+ [InlineData("First: 10mm", "First: 10mm; First: 11mm")]+ [InlineData("First: 10mm", "First: 1e309mm")]+ [InlineData("Direction: [0,-2];", "Direction: [0,-2]; Step: [0mm,-2mm];")]+ [InlineData("Points<Point2> Seats {", "Points<Point2> Seats { Keys: [First, Second, Third];")]+ [InlineData("First: 10mm; Second: 23.5mm; Third: -4mm;", "")]+ public void InvalidStationRecipesFailClosed(string from, string to)+ {+ var parsed = new AssemblyM0Parser().Parse(Source.Replace(from, to));+ Assert.False(parsed.IsSuccess);+ Assert.Contains(parsed.Diagnostics, d => d.Message.Contains("firmament-concept-points-"));+ }++ [Fact]+ public void TooManyStationsAndCoordinateOverflowAreRejected()+ {+ var many = string.Join(";", Enumerable.Range(0, 1025).Select(i => $"Station{i}: {i}mm")) + ";";+ Assert.False(new AssemblyM0Parser().Parse(Source.Replace("First: 10mm; Second: 23.5mm; Third: -4mm;", many)).IsSuccess);+ Assert.False(new AssemblyM0Parser().Parse(Source.Replace("Point2(0mm,0mm)", "Point2(0mm,-1e308mm)")+ .Replace("First: 10mm", "First: 1e308mm")).IsSuccess);+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/CompositionLanguageTests.cs b/Aetheris.Kernel.Firmament.Tests/CompositionLanguageTests.csnew file mode 100644index 00000000..53dd698c--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/CompositionLanguageTests.cs@@ -0,0 +1,62 @@+using Aetheris.Kernel.Firmament.Assembly;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class CompositionLanguageTests+{+ [Theory]+ [InlineData("WireRoute Lead {\n Min", "WireRoute", "MinimumBendRadius")]+ [InlineData("WireRoute Lead { Path { Follow Groove {\n Cur", "Follow", "Curve")]+ [InlineData("Section Station { Frame: Plane { Origin: [0mm,0mm,0mm]; }\n Pro", "Section", "Profile")]+ [InlineData("Concept Struct Board { Points<Point2> Frets { Series {\n Pos", "Series", "Position")]+ [InlineData("Appearance Paint {\n Rou", "Appearance", "Roughness")]+ [InlineData("Material Steel {\n App", "Material", "Appearance")]+ [InlineData("Placement {\n Fro", "Placement", "From")]+ public void CompositionDraftsOfferImplementedOwnerFields(string source, string context, string field)+ {+ var completion = FirmamentLanguageService.Complete(source, "draft.firmament", "1", source.Length);+ Assert.Equal(context, completion.Context);+ Assert.Contains(completion.Fields, f => f.Name == field);+ }++ [Fact]+ public void SnapshotNavigationFindsProfileRecipeAndMaterialInOtherFiles()+ {+ var root = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm");+ var files = Directory.GetFiles(Path.GetDirectoryName(root)!, "*.firmament").Append(root)+ .Select(p => new KeyValuePair<string, string>(Path.GetFileName(p), File.ReadAllText(p)));+ var snapshot = new FirmamentProjectSnapshot("guitar.firmasm", files);+ var neck = snapshot.Documents["Neck.firmament"];+ var profile = FirmamentLanguageAnalysisService.Definition(snapshot, "Neck.firmament", neck.IndexOf("NeckBack<", StringComparison.Ordinal));+ Assert.Equal("neck-profile.firmament", profile!.Document);+ var knob = snapshot.Documents["knob.firmament"];+ var material = FirmamentLanguageAnalysisService.Definition(snapshot, "knob.firmament", knob.IndexOf("Brass;", StringComparison.Ordinal));+ Assert.Equal("materials.firmament", material!.Document);+ var analysis = FirmamentLanguageAnalysisService.Analyze(snapshot, "Neck.firmament", "1");+ Assert.DoesNotContain(analysis.Diagnostics, d => d.Severity == "error");+ }++ [Fact]+ public void RootClassificationIgnoresCommentsStringsAndSubassemblyDefinitions()+ {+ Assert.False(FirmamentLanguageAnalysisService.HasAssemblyRoot("// <Assembly Fake>\nSubassembly Nested { <Assembly Nested> </Assembly> }"));+ Assert.False(FirmamentLanguageAnalysisService.HasAssemblyRoot("Static Text: String = \"<Assembly Fake>\";"));+ Assert.True(FirmamentLanguageAnalysisService.HasAssemblyRoot("Subassembly Nested { <Assembly Nested> </Assembly> }\n<Assembly Actual> </Assembly>"));+ Assert.True(FirmamentLanguageAnalysisService.HasAssemblyRoot("Assembly Product { <Assembly Product> </Assembly> }"));+ Assert.False(FirmamentLanguageAnalysisService.HasAssemblyRoot("/* <Assembly Fake> */ Model X { }"));+ }++ [Fact]+ public void NestedSectionFieldsAreNotOfferedAgainAndConcreteRoutesUseWireParser()+ {+ const string draft = "Section S { Frame: Plane { Origin: [0mm,0mm,0mm]; }\n ";+ var completion = FirmamentLanguageService.Complete(draft, "draft.firmament", "1", draft.Length);+ Assert.DoesNotContain(completion.Fields, f => f.Name == "Frame");+ Assert.Contains(completion.Fields, f => f.Name == "Profile");+ var route = FirmamentCorpusHarness.ReadFixtureText("fixtures/Canonical/WireForm/line-guide.firmament");+ Assert.Empty(FirmamentLanguageAnalysisService.Analyze(route, "guide.firmament", "1").Diagnostics);+ var invalid = FirmamentLanguageAnalysisService.Analyze(route.Replace("Distance: 60mm", "Distance: 100mm"), "guide.firmament", "2");+ Assert.Contains(invalid.Diagnostics, d => d.Message.Contains("guide-interval-invalid"));+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/ConceptDerivationTests.cs b/Aetheris.Kernel.Firmament.Tests/ConceptDerivationTests.csindex 06307d52..a866fcee 100644--- a/Aetheris.Kernel.Firmament.Tests/ConceptDerivationTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/ConceptDerivationTests.cs@@ -126,13 +126,18 @@ public sealed class ConceptDerivationTestsvar documents = Directory.GetFiles(Path.GetDirectoryName(path)!,"*.firmament").Append(path).ToDictionary(p => Path.GetFileName(p),File.ReadAllText);using var session = new FirmamentCompilationSession();var first = session.CompileProject(new("guitar.firmasm",documents));- Assert.True(first.IsSuccess, string.Join("\n",first.Diagnostics)); Assert.Equal(19, first.Ir!.SourceDependencies!.Count);+ Assert.True(first.IsSuccess, string.Join("\n",first.Diagnostics)); Assert.Equal(22, first.Ir!.SourceDependencies!.Count);Assert.Single(first.Ir.SourceDependencies, d => d.IsRoot);Assert.Equal(9, first.Geometry!.Artifact.Definitions.Sum(d => d.Provenance.Count(p => p.Stage == "concept-boundary-placement")));- documents["body-outline.firmament"] = documents["body-outline.firmament"].Replace("115mm,-195mm", "115.1mm,-195mm");+ var outline = documents["body-outline.firmament"];+ const string edit = @"(?<![\w-])115mm\s*,\s*-195mm\b";+ Assert.Single(System.Text.RegularExpressions.Regex.Matches(outline, edit).Cast<System.Text.RegularExpressions.Match>());+ documents["body-outline.firmament"] = System.Text.RegularExpressions.Regex.Replace(outline, edit, "115.1mm, -195mm");+ Assert.NotEqual(outline, documents["body-outline.firmament"]);var edited = session.CompileProject(new("guitar.firmasm",documents));Assert.True(edited.IsSuccess, string.Join("\n",edited.Diagnostics));- Assert.Equal(3, edited.Reuse!.RebuiltDefinitions); Assert.Equal(50, edited.Reuse.ReusedDefinitions);+ Assert.Equal(3, edited.Reuse!.RebuiltDefinitions);+ Assert.Equal(first.Geometry.Artifact.Definitions.Count - 3, edited.Reuse.ReusedDefinitions);Assert.All(edited.Geometry!.Artifact.DatumSeats!, s => Assert.True(s.Passed));foreach (var identity in new[] { "CarvedMaple", "MahoganyBack", "IvoryBinding" })Assert.NotEqual(first.Geometry!.Artifact.Definitions.Single(d => d.DefinitionIdentity.Contains(identity)).StepSha256,diff --git a/Aetheris.Kernel.Firmament.Tests/CubicBezier2ProfileTests.cs b/Aetheris.Kernel.Firmament.Tests/CubicBezier2ProfileTests.csindex 0d508a42..be78a615 100644--- a/Aetheris.Kernel.Firmament.Tests/CubicBezier2ProfileTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/CubicBezier2ProfileTests.cs@@ -5,6 +5,34 @@ namespace Aetheris.Kernel.Firmament.Tests;public sealed class CubicBezier2ProfileTests{+ [Fact]+ public void TemplateControlArithmeticKeepsExactPolynomialGeometry()+ {+ var path = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Profiles/template-control-arithmetic.firmament");+ var source = File.ReadAllText(path);+ var profile = ProfileAuthoringParser.ResolveNamedProfile(source, "P", out var diagnostics);+ Assert.Empty(diagnostics);+ Assert.NotNull(profile);+ var bottom = Assert.IsType<LineArcCubicBezier2D>(profile.Loops.Single().Segments[0].Geometry);+ Assert.Equal((-20d, -10d), bottom.Start);+ Assert.Equal((20d, -10d), bottom.End);+ var build = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(build.IsSuccess, string.Join("\n", build.Diagnostics.Select(d => d.Message)));+ Assert.DoesNotContain("RATIONAL_B_SPLINE", build.Value.StepText);+ }++ [Theory]+ [InlineData("W / H")]+ [InlineData("W / 0")]+ [InlineData("5deg")]+ public void ProfileControlArithmeticRejectsWrongUnitsAndNonfiniteValues(string expression)+ {+ var path = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Profiles/template-control-arithmetic.firmament");+ var source = File.ReadAllText(path).Replace("-W / 6", expression);+ Assert.Null(ProfileAuthoringParser.ResolveNamedProfile(source, "P", out var diagnostics));+ Assert.Contains(diagnostics, d => d.StartsWith("profile-layout-point-invalid:", StringComparison.Ordinal));+ }+[Fact]public void LampBaseUsesTwoDirectPolynomialFlanksAndExportsWithoutRationalGeometry(){diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentConventionTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentConventionTests.csnew file mode 100644index 00000000..4f517e1a--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentConventionTests.cs@@ -0,0 +1,171 @@+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Assembly;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentConventionTests+{+ [Fact]+ public void MechanicalPassPreservesAuthoredDataArgumentsMembersAndOpaqueText()+ {+ const string source = """+ include "My/Part.firmament";+ Record Spec { Width: Length; Material: String; }+ Static Stock: Spec { Width: 10mm; Material: "Steel // From: Size:"; }+ Static Points: Set<Point2> { Start => Point2(0mm,0mm) }+ Template<Width: Length> Struct Panel {+ Box Body { Size: [Width, 8mm, 4mm]; }+ Feature Extra = Make(Size: Stock.Width);+ expose { Semantic BottomSeat { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; } }+ }+ Subassembly Unit {+ <Assembly Unit>+ <Part Panel = Panel<Width:10mm>>+ Material: Steel with { Appearance: Nickel; };+ Placement { From: BottomSeat.Frame; To: World; TranslateLocal: [0mm,0mm,4mm]; }+ </Part>+ </Assembly>+ Anchor: Unit;+ }+ // From: Width: Include "leave alone";+ """;+ var once = FirmamentLanguageAnalysisService.FormatConventions(source, "module.firmament", "1");+ Assert.Contains("Record Spec { Width: Length; Material: String; }", once.Text);+ Assert.Contains("Width: 10mm; Material: \"Steel // From: Size:\"", once.Text);+ Assert.Contains("Start => Point2", once.Text);+ Assert.Contains("Template<Width: Length>", once.Text);+ Assert.Contains("Make(Size: Stock.Width)", once.Text);+ Assert.Contains("Panel<Width:10mm>", once.Text);+ Assert.Contains("size: [Width, 8mm, 4mm]", once.Text);+ Assert.Contains("material: Steel with { appearance: Nickel; }", once.Text);+ Assert.Contains("from: BottomSeat.Frame; to: World; translateLocal:", once.Text);+ Assert.Contains("// From: Width: Include \"leave alone\";", once.Text);+ Assert.Equal(once.Text, FirmamentLanguageAnalysisService.FormatConventions(once.Text, "module.firmament", "2").Text);+ Assert.Equal(FirmamentSourceSpelling.Normalize(source), FirmamentSourceSpelling.Normalize(once.Text));+ }++ [Fact]+ public void NativeFormatterAndLowercaseFieldsBindToSamePartWithoutRenaming()+ {+ const string source = "Model Witness { Units: mm; Box Body { Size: [10mm,8mm,4mm] } }";+ var formatted = FirmamentLanguageAnalysisService.Format(source, "m.firmament", "1").Text;+ Assert.Contains("units: mm", formatted);+ Assert.Contains("Box Body", formatted);+ Assert.Contains("size:", formatted);+ var before = FirmamentV2Parser.Parse(source);+ var after = FirmamentV2Parser.Parse(formatted);+ Assert.True(after.IsSuccess, string.Join("\n", after.Diagnostics));+ Assert.Equal(((FirmamentV2BoxRecord)before.Document!.Solids[0].Primitive).Size,+ ((FirmamentV2BoxRecord)after.Document!.Solids[0].Primitive).Size);+ Assert.Equal("Body", after.Document.Solids[0].Name);+ var analysis = FirmamentLanguageAnalysisService.Analyze(formatted, "m.firmament", "1");+ Assert.Contains(analysis.Tokens, t => t.Kind == "field" && formatted.Substring(t.Start, t.Length) == "size");+ }++ [Fact]+ public void LinkAliasesAreScopedAndUserReferencesRemainCaseSensitive()+ {+ const string source = """+ Concept Struct Layout On XY { Point2 Center { Position: [0mm,0mm] } }+ Profile Outline Using Layout { From: Center }+ Pattern Pins Over Layout.Points { point => <Part Pin = Drum<R:1mm>> </Part> }+ Model M { Box On { Size: [1mm,1mm,1mm] } Box B = On; }+ """;+ var text = FirmamentSourceSpelling.Prefer(source);+ Assert.Contains("Layout on XY", text);+ Assert.Contains("Outline using Layout", text);+ Assert.Contains("Pins over Layout.Points", text);+ Assert.Contains("Box On", text);+ Assert.Contains("Box B = On", text);+ Assert.DoesNotContain("Layout.points", text);+ }++ [Fact]+ public void SectionPatternsAndNamedVocabularyCollisionsKeepTheirOwners()+ {+ const string source = """+ Static Stations: Set<Point2> { Start => Point2(0mm,0mm) }+ SectionChain Body {+ Pattern Sections Over Stations {+ station => Section Station {+ Frame: Plane { Origin: [0mm,0mm,4mm]; Normal: [0,0,1]; Up: [0,1,0] }+ Profile: Outline;+ Seam: Start;+ }+ }+ }+ Point2 Start { Position: [0mm,0mm] }+ Interface<Fixed> Seat { Datum: Layout.Plane; Members: [Product.Body.Seat] }+ Mate BodyOnSeat: Seat { Member: Product.Body.Seat; At: Layout.Position; Orientation: SameDirection; }+ """;+ var preferred = FirmamentSourceSpelling.Prefer(source);+ Assert.Contains("Sections over Stations", preferred);+ Assert.Contains("frame: Plane { origin:", preferred);+ Assert.Contains("profile: Outline", preferred);+ Assert.Contains("Point2 Start { position:", preferred);+ Assert.Contains("datum: Layout.Plane; members:", preferred);+ Assert.Contains("member: Product.Body.Seat; at:", preferred);+ Assert.Equal(source, FirmamentSourceSpelling.Normalize(preferred));+ }++ [Fact]+ public void LegacyModelGrammarRemainsWithItsExistingOwner()+ {+ const string source = """+ model Legacy {+ units mm+ solid stock: Box {+ size: [10, 8, 4]+ expose {+ face(+X) => entrance+ face(-X) => exit+ }+ }+ }+ """;+ Assert.Equal(source, FirmamentSourceSpelling.Normalize(source));+ Assert.Equal(source, FirmamentSourceSpelling.Prefer(source));+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));+ }++ [Fact]+ public void UnknownOwnersAndEscapedStringsAreNeverGuessed()+ {+ const string source = "Custom Example { Width: 3mm }\n// Size: 1\nModel M { Units: mm; Note N { Text: \"A \\\" Size: \\\\\"; Target: M; } }";+ var text = FirmamentSourceSpelling.Prefer(source);+ Assert.StartsWith("Custom Example { Width: 3mm }", text);+ Assert.Contains("// Size: 1", text);+ Assert.Contains("\"A \\\" Size: \\\\\"", text);+ const string collision = "Custom Box { Size: [1mm,2mm,3mm] }\nCustom<Length> Box { Size: [1mm,2mm,3mm] }";+ Assert.Equal(collision, FirmamentSourceSpelling.Prefer(collision));+ const string afterTag = "<Assembly Unit><Part Pad = Pad<H:2mm>> Placement { from: Origin; to: World; } </Part></Assembly>";+ Assert.Contains("Placement { From: Origin; To: World; }", FirmamentSourceSpelling.Normalize(afterTag));+ }++ [Fact]+ public void AssemblyPreferredFieldsPreserveOccurrencesAndDefinitionIds()+ {+ const string source = """+ Template<H: Length> Struct Pad {+ Rect2 Outline { Center: [0mm,0mm]; Size: [4mm,2mm] }+ Profile P { Loop Outer { Outline |> TraceLoop } }+ Extrude Body { Profile: P; From: 0mm; To: H }+ }+ Assembly Product {+ <Assembly Product>+ <Part Body = Pad<H:4mm>>+ Placement { From: Origin; To: World; }+ </Part>+ </Assembly>+ Anchor: Product;+ }+ """;+ var before = new AssemblyM0Parser().Parse(source);+ var after = new AssemblyM0Parser().Parse(FirmamentSourceSpelling.Prefer(source));+ Assert.True(before.IsSuccess, string.Join("\n", before.Diagnostics));+ Assert.True(after.IsSuccess, string.Join("\n", after.Diagnostics));+ Assert.Equal(System.Text.Json.JsonSerializer.Serialize(before.Source!.Root),+ System.Text.Json.JsonSerializer.Serialize(after.Source!.Root));+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.csindex 5895c8bb..642d9108 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs@@ -8,7 +8,7 @@ public sealed class FirmamentSemanticSchemaTestspublic void GeneratedRegistry_IsStableOptInAndCoversFirstConstructs(){Assert.Equal("firmament-semantic-schema/1", FirmamentSemanticSchemas.Version);- Assert.Equal(["FrameTransform", "Placement", "Box", "Concept", "Helix", "Hole", "Interface<Fixed>", "Interface<Prismatic>", "Interface<Revolute>", "Loft", "Perforation", "Thread"], FirmamentSemanticSchemas.All.Select(s => s.Name));+ Assert.Equal(["Appearance", "FrameTransform", "Placement", "Pmi", "Note", "Provenance", "Box", "Concept", "Points", "Helix", "Hole", "Interface<Fixed>", "Interface<Prismatic>", "Interface<Revolute>", "Loft", "Perforation", "Material", "Linear", "Series", "Section", "Thread", "Follow", "WireRoute"], FirmamentSemanticSchemas.All.Select(s => s.Name));var hole = Assert.IsType<FirmamentConstructSchema>(FirmamentSemanticSchemas.Get("Hole"));var diameter = Assert.Single(hole.Fields, f => f.Name == "Diameter");Assert.Equal("Hole.Diameter", diameter.Id.Value);@@ -57,16 +57,21 @@ public sealed class FirmamentSemanticSchemaTestsvar entry = Assert.Single(completion.Entries!);Assert.Equal(name, entry.Name);Assert.Contains(requiredContext, entry.Source);- Assert.Equal(FirmamentSemanticSchemas.Get(name)!.Entry, entry.Source);+ Assert.Equal(FirmamentSourceSpelling.Prefer(FirmamentSemanticSchemas.Get(name)!.Entry!), entry.Source);}[Theory][InlineData("Helix")][InlineData("Loft")]+ [InlineData("WireRoute")]public void GeneratedEntryIsBuildable(string name){- var result = FirmamentBuildAndExport.CompileSource(FirmamentSemanticSchemas.Get(name)!.Entry!);- Assert.True(result.IsSuccess, string.Join("; ", result.Diagnostics.Select(item => item.Message)));+ var source = FirmamentSemanticSchemas.Get(name)!.Entry!;+ foreach (var spelling in new[] { source, FirmamentSourceSpelling.Prefer(source) })+ {+ var result = FirmamentBuildAndExport.CompileSource(spelling);+ Assert.True(result.IsSuccess, string.Join("; ", result.Diagnostics.Select(item => item.Message)));+ }}private static FirmamentLanguageCompletion LoftOrHelixCompletion(string source, string expected)diff --git a/Aetheris.Kernel.Firmament.Tests/SectionFamilyAuthoringTests.cs b/Aetheris.Kernel.Firmament.Tests/SectionFamilyAuthoringTests.csnew file mode 100644index 00000000..e94c5fc9--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/SectionFamilyAuthoringTests.cs@@ -0,0 +1,55 @@+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Surfacing;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class SectionFamilyAuthoringTests+{+ [Fact]+ public void GuitarNeckHasStableKeyedSectionsAndCorrespondingHeadRoot()+ {+ var path = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/GuitarX0/Neck.firmament");+ var result = SectionChainAuthoringParser.CompileFile(path);+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));+ Assert.Equal(new[] { "Sections_Heel", "Sections_HeelShoulder", "Sections_HeelBlend", "Sections_ShaftStart", "Sections_ShaftMiddle", "Sections_PreNut", "Sections_NutApproach", "Sections_Nut", "HeadBlend", "HeadMerge" }, result.Chain!.Sections.Select(s => s.SectionId));+ var pattern = Assert.Single(result.Patterns!);+ Assert.Equal(8, pattern.GeneratedCount);+ Assert.Equal("Nut", pattern.Associations![7].SourceEntry);+ foreach (var section in result.Chain.Sections)+ {+ Assert.Equal(new[] { "Edge0", "Edge1", "Edge2", "Edge3", "Edge4", "Edge5" }, section.Profile.Spans.Select(s => s.SpanId));+ if (section.SectionId == "HeadMerge")+ {+ Assert.All(section.Profile.Spans, span => Assert.IsType<SectionProfileCurve.Line>(span.Curve));+ continue;+ }+ var back = Assert.IsType<SectionProfileCurve.PolynomialBSpline>(section.Profile.Spans[0].Curve);+ Assert.InRange(back.ControlPoints[0].X, -28, -21);+ Assert.Equal(0, back.ControlPoints[0].Y);+ }+ }++ [Theory]+ [InlineData("MahoganyBack", 2)]+ [InlineData("IvoryBinding", 2)]+ [InlineData("CarvedMaple", 5)]+ public void BodyFamiliesPreserveOutlineIdentity(string name, int count)+ {+ var result = SectionChainAuthoringParser.CompileFile(FirmamentCorpusHarness.ResolveFixtureFullPath($"fixtures/Canonical/AssemblyInterfaces/GuitarX0/{name}.firmament"));+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));+ Assert.Equal(count, result.Chain!.Sections.Count);+ Assert.Equal(count, Assert.Single(result.Patterns!).GeneratedCount);+ Assert.All(result.Chain.Sections, section => Assert.Equal("LowerTreble_Span0", section.Profile.SeamSpanId));+ Assert.All(result.BoundaryEdits!, section => Assert.All(section.Edits, edit => Assert.Equal("PeriodicHermite", edit.Construction)));+ }++ [Fact]+ public void DuplicateStationKeysFailBeforeGeometry()+ {+ var source = "Model X { Units: mm Record S { Z: Length } Static Sites: Set<S> { A => S { Z: 0mm } A => S { Z: 10mm } } SectionChain X { Pattern Sections Over Sites { s => Section Site { Frame: Plane { Origin: [0mm,0mm,s.Z]; Normal: [0,0,1]; Up: [0,1,0] } Profile: Missing Seam: Edge0 } } } }";+ var result = SectionChainAuthoringParser.Compile(source);+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, d => d.Contains("set-duplicate-entry"));+ Assert.Null(result.Materialization);+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/WireLineGuideTests.cs b/Aetheris.Kernel.Firmament.Tests/WireLineGuideTests.csnew file mode 100644index 00000000..7975196c--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/WireLineGuideTests.cs@@ -0,0 +1,53 @@+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class WireLineGuideTests+{+ private static string Source => FirmamentCorpusHarness.ReadFixtureText("fixtures/Canonical/WireForm/line-guide.firmament");+ [Fact]+ public void LockedGuideSurvivesAutomaticEntryAndExactStepRoundtrip()+ {+ var parsed = WireFormAuthoring.Parse(Source);+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));+ var locked = Assert.IsType<WireStraightAir>(parsed.Value.Operations[3]);+ Assert.Equal("MainGroove", locked.Name);+ Assert.Equal(new Point3D(20,0,0), locked.Input.Position);+ Assert.Equal(new Point3D(80,0,0), locked.Output.Position);+ Assert.Equal(60, locked.LengthMm);+ var bend = Assert.IsType<WireBendAir>(parsed.Value.Operations[1]);+ Assert.Equal(10, bend.RadiusMm);+ Assert.Equal(Math.PI / 2, bend.AngleRadians, 12);+ Assert.Empty(WireFormBRepMaterializer.Validate(parsed.Value));+ var built = FirmamentBuildAndExport.CompileSource(Source);+ Assert.True(built.IsSuccess, string.Join("\n", built.Diagnostics));+ Assert.True(built.Value.WireForm!.StepReimportedManifold);+ Assert.Equal(0, built.Value.WireForm.NonRationalBSplineSurfaces);+ }+ [Theory]+ [InlineData("From: 20mm", "From: 5mm", "guide-connector-space-insufficient")]+ [InlineData("Distance: 60mm", "Distance: 100mm", "guide-interval-invalid")]+ [InlineData("Point3(120mm,0mm,0mm)", "Point3(120mm,20mm,0mm)", "guide-exit-not-qualified")]+ [InlineData("HarnessLayout.Groove", "HarnessLayout.Missing", "guide-unresolved")]+ public void UnsupportedGuideIntentHasNamedFailure(string from, string to, string diagnostic)+ {+ var result = WireFormAuthoring.Parse(Source.Replace(from, to));+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, d => d.Message.Contains(diagnostic));+ }++ [Fact]+ public void ReverseGuideKeepsTheRequestedIntervalAndTangentExit()+ {+ var source = Source.Replace("Point3(0mm,-40mm,0mm)", "Point3(100mm,-40mm,0mm)")+ .Replace("From: 20mm", "From: 80mm").Replace("Direction: Forward", "Direction: Reverse")+ .Replace("Point3(120mm,0mm,0mm)", "Point3(-20mm,0mm,0mm)");+ var parsed = WireFormAuthoring.Parse(source);+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));+ var locked = Assert.IsType<WireStraightAir>(parsed.Value.Operations[3]);+ Assert.Equal(new Point3D(80,0,0), locked.Input.Position);+ Assert.Equal(new Point3D(20,0,0), locked.Output.Position);+ Assert.Empty(WireFormBRepMaterializer.Validate(parsed.Value));+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/WirePointRouteTests.cs b/Aetheris.Kernel.Firmament.Tests/WirePointRouteTests.csnew file mode 100644index 00000000..60dc7d82--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/WirePointRouteTests.cs@@ -0,0 +1,82 @@+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class WirePointRouteTests+{+ private static string Source => File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/WireForm/point-route.firmament"));++ [Fact]+ public void ArbitraryPlaneRouteDerivesTangentFilletAndExportsExactManifold()+ {+ var parsed = WireFormAuthoring.Parse(Source);+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));+ var feature = parsed.Value;+ Assert.Equal(new Point3D(0, 0, 0), feature.StartState.Position);+ Assert.Equal(new Point3D(20, 30, 20), feature.EndState.Position);+ var bend = Assert.IsType<WireBendAir>(feature.Operations[1]);+ Assert.Equal(Math.PI / 2, bend.AngleRadians, 12);+ Assert.Equal(26, bend.Input.Position.Y, 12);+ Assert.Equal(4 / Math.Sqrt(2), bend.Output.Position.X, 12);+ Assert.Equal(bend.Output.Position.X, bend.Output.Position.Z, 12);+ Assert.Empty(WireFormBRepMaterializer.Validate(feature));+ var built = FirmamentBuildAndExport.CompileSource(Source);+ Assert.True(built.IsSuccess, string.Join("\n", built.Diagnostics));+ Assert.True(built.Value.WireForm!.StepReimportedManifold);+ Assert.Equal(0, built.Value.WireForm.NonRationalBSplineSurfaces);+ Assert.True(built.Value.WireForm.Cylinders > 0);+ Assert.True(built.Value.WireForm.Tori > 0);+ }++ [Fact]+ public void ExplicitPoint2LiftingUsesSharedFrameTranslationAndRotation()+ {+ var source = Source.Replace("At: Point3(20mm,30mm,20mm);", "At: Point2(20mm,20mm); On { From: World; TranslateLocal: [0mm,30mm,0mm]; RotateLocal: { Axis: X; Angle: 90deg } }");+ var parsed = WireFormAuthoring.Parse(source);+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));+ Assert.True((parsed.Value.EndState.Position - new Point3D(20, 30, 20)).Length < 1e-12);+ }++ [Theory]+ [InlineData("Point3(0mm,30mm,0mm)", "Point3(0mm,0mm,0mm)", "point-invalid")]+ [InlineData("Point3(20mm,30mm,20mm)", "Point3(0mm,60mm,0mm)", "corner-degenerate")]+ [InlineData("Radius: 4mm", "Radius: 40mm", "corner-does-not-fit")]+ [InlineData("; Radius: 4mm", "; Radius: 3mm", "radius-invalid")]+ [InlineData("Diameter: 1mm", "Diameter: 9mm", "radius-invalid")]+ [InlineData("Point3(0mm,0mm,0mm)", "Point3(0,0mm,0mm)", "point-invalid")]+ [InlineData("Start {", "Via {", "path-unsupported")]+ [InlineData("Diameter: 1mm;", "Diameter: 1mm; Diameter: 2mm;", "dimensions-invalid")]+ [InlineData("At: Point3(20mm,30mm,20mm);", "At: Point2(20mm,20mm);", "point-invalid")]+ public void InvalidOrUnsupportedIntentProducesNamedDiagnostic(string before, string after, string code)+ {+ var parsed = WireFormAuthoring.Parse(Source.Replace(before, after));+ Assert.False(parsed.IsSuccess);+ Assert.Contains(parsed.Diagnostics, d => d.Message.Contains("wire-route-" + code));+ }++ [Theory]+ [InlineData(0, 58, 732.589494, 64.073073, 12.805738)]+ [InlineData(1, 94, 732.509486, 100.649868, 14.372058)]+ [InlineData(2, 130, 732.474127, 137.301981, 15.022472)]+ [InlineData(5, 58, 732.589494, 64.073073, 12.805738)]+ [InlineData(4, 94, 732.509486, 100.649868, 14.372058)]+ [InlineData(3, 130, 732.474127, 137.301981, 15.022472)]+ public void GuitarPointRoutesPreserveLegacyFilletsWithinAuthoredRounding(int index, double postY, double lead, double tail, double degrees)+ {+ // Previously Python-authored values had six decimal places. Endpoints are+ // now exact inputs; these checks quantify the expected rounding correction.+ var radians = -13 * Math.PI / 180;+ var end = new Point3D(index < 3 ? -27 : 27, 660 + postY * Math.Cos(radians) - 20 * Math.Sin(radians),+ 48 + postY * Math.Sin(radians) + 20 * Math.Cos(radians));+ var result = WireRouteAuthoring.Lower(new("String", .28 + index * .08, "Standard.Materials.StainlessSteel.304_Annealed",+ new((index - 2.5) * 10.2, -75, 65), new((index - 2.5) * 7.2, 658, 65), end, 4, 4, "NutBreak"));+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));+ Assert.Equal(end, result.Value.EndState.Position);+ Assert.InRange(Math.Abs(result.Value.Operations[0].LengthMm - lead), 0, .00000051);+ Assert.InRange(Math.Abs(result.Value.Operations[2].LengthMm - tail), 0, .00000051);+ var bend = Assert.IsType<WireBendAir>(result.Value.Operations[1]);+ Assert.InRange(Math.Abs(bend.AngleRadians * 180 / Math.PI - degrees), 0, .00000051);+ Assert.Empty(WireFormBRepMaterializer.Validate(result.Value));+ }+}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyAppearanceAuthoring.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyAppearanceAuthoring.csnew file mode 100644index 00000000..8d5c120d--- /dev/null+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyAppearanceAuthoring.cs@@ -0,0 +1,108 @@+using System.Globalization;+using System.Text.RegularExpressions;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Assembly;++[FirmamentConstruct("Appearance", "Appearance", Context = "Declaration", Entry = "Appearance Name { Color: [0.5,0.5,0.5]; Metallic: 0; Roughness: 0.3; }", Description = "A finite preview look; shader realization stays downstream.")]+[FirmamentField("Color", "Color", FirmamentSchemaValueKind.Vector, Required = true)]+[FirmamentField("Metallic", "Metallic", FirmamentSchemaValueKind.Scalar, Required = true)]+[FirmamentField("Roughness", "Roughness", FirmamentSchemaValueKind.Scalar, Required = true)]+public static class AssemblyAppearanceDeclaration { }+public sealed record AssemblyAppearance(string Name, AssemblyUsdMaterial Preview);++[FirmamentConstruct("PhysicalMaterial", "Material", Context = "Declaration", Entry = "Material Steel { Identity: \"steel\"; Appearance: PolishedMetal; }", Description = "Physical identity with a default appearance; this declaration does not invent engineering properties.")]+[FirmamentField("Identity", "Identity", FirmamentSchemaValueKind.String, Required = true)]+[FirmamentField("Appearance", "Appearance", FirmamentSchemaValueKind.ConstructReference, Required = true)]+public static class AssemblyPhysicalMaterialDeclaration { }+public sealed record AssemblyPhysicalMaterial(string Name, string Identity, string Appearance);+public sealed record AssemblyAppearanceCatalog(IReadOnlyDictionary<string, AssemblyAppearance> Appearances,+ IReadOnlyDictionary<string, AssemblyPhysicalMaterial> Materials);+public sealed record AssemblyMaterialSelection(string Material, string? AppearanceOverride = null);+public sealed record AssemblyAppearanceBinding(string Material, string PhysicalIdentity, string Appearance,+ AssemblyUsdMaterial Preview, string Authority);++/// <summary>Checked physical identity/default look and occurrence finish overrides.+/// No FEA properties or geometry selectors are inferred from display color.</summary>+internal static class AssemblyAppearanceAuthoring+{+ internal static AssemblyAppearanceCatalog Parse(ref string source, List<AssemblyDiagnostic> diagnostics,+ out IReadOnlyList<(int Start, int Length)> erasedSpans)+ {+ var appearances = new Dictionary<string, AssemblyAppearance>(StringComparer.Ordinal);+ var materials = new Dictionary<string, AssemblyPhysicalMaterial>(StringComparer.Ordinal);+ var changes = new List<(int Start, int Length)>();+ foreach (Match header in Regex.Matches(source, @"\b(?<kind>Appearance|Material)\s+(?<name>[A-Za-z_]\w*)\s*\{"))+ {+ var close = source.IndexOf('}', header.Index + header.Length);+ if (close < 0) { Error("declaration-malformed", header.Value); continue; }+ var body = source[(header.Index + header.Length)..close]; var name = header.Groups["name"].Value;+ if (body.Contains('{')) { Error("declaration-fields-invalid", name); continue; }+ var fields = Fields(body);+ var allowed = header.Groups["kind"].Value == "Appearance" ? new[] { "Color", "Metallic", "Roughness" } : new[] { "Identity", "Appearance" };+ if (fields.Count != allowed.Length || !allowed.All(fields.ContainsKey)) { Error("declaration-fields-invalid", name); continue; }+ if (allowed.Length == 3)+ {+ var color = Regex.Match(fields["Color"], @"^\[(?<v>[^]]+)\]$");+ var rgb = color.Success ? color.Groups["v"].Value.Split(',').Select(Number).ToArray() : [];+ var metal = Number(fields["Metallic"]); var rough = Number(fields["Roughness"]);+ if (rgb.Length != 3 || rgb.Concat([metal, rough]).Any(v => !double.IsFinite(v) || v < 0 || v > 1)) Error("values-invalid", name);+ else if (!appearances.TryAdd(name, new(name, new(rgb[0], rgb[1], rgb[2], metal, rough)))) Error("duplicate-appearance", name);+ }+ else+ {+ var identity = Regex.Match(fields["Identity"], "^\"(?<id>[^\"\\r\\n]+)\"$");+ if (!identity.Success || !Regex.IsMatch(fields["Appearance"], @"^[A-Za-z_]\w*$")) Error("material-invalid", name);+ else if (!materials.TryAdd(name, new(name, identity.Groups["id"].Value, fields["Appearance"]))) Error("duplicate-material", name);+ }+ changes.Add((header.Index, close - header.Index + 1));+ }+ foreach (var material in materials.Values)+ if (!appearances.ContainsKey(material.Appearance)) Error("unknown-appearance", material.Name + ":" + material.Appearance);+ var chars = source.ToCharArray();+ foreach (var change in changes) Array.Fill(chars, ' ', change.Start, change.Length);+ source = new(chars);+ erasedSpans = changes;+ return new(appearances, materials);++ Dictionary<string, string> Fields(string body)+ {+ var result = new Dictionary<string, string>(StringComparer.Ordinal);+ var matches = Regex.Matches(body, @"(?<key>[A-Za-z_]\w*)\s*:\s*(?<value>\[[^]]*\]|""[^""]*""|[^;{}]+)\s*;");+ var remaining = body;+ foreach (Match match in matches)+ if (!result.TryAdd(match.Groups["key"].Value, match.Groups["value"].Value.Trim())) Error("duplicate-field", match.Groups["key"].Value);+ foreach (Match match in matches.Cast<Match>().Reverse()) remaining = remaining.Remove(match.Index, match.Length);+ if (!string.IsNullOrWhiteSpace(remaining)) Error("declaration-fields-invalid", body);+ return result;+ }+ void Error(string code, string subject) => diagnostics.Add(new("assembly-appearance-" + code, subject));+ }++ internal static AssemblyMaterialSelection? Selection(string body, List<AssemblyDiagnostic> diagnostics)+ {+ var fields = Regex.Matches(body, @"\bMaterial\s*:\s*(?<material>[A-Za-z_]\w*)(?:\s+with\s*\{\s*Appearance\s*:\s*(?<look>[A-Za-z_]\w*)\s*;\s*\})?\s*;");+ if (fields.Count > 1 || Regex.Matches(body, @"\bMaterial\s*:").Count != fields.Count)+ diagnostics.Add(new("assembly-appearance-selection-invalid", "Expected one Material identity and optional with { Appearance: Name; } override."));+ return fields.Count == 1 ? new(fields[0].Groups["material"].Value, fields[0].Groups["look"].Success ? fields[0].Groups["look"].Value : null) : null;+ }++ internal static AssemblyIr Bind(AssemblyIr ir, AssemblyAppearanceCatalog? catalog, List<AssemblyDiagnostic> diagnostics)+ {+ // Locally solved subassemblies retain selections until the root catalog binds them.+ if (catalog is null) return ir;+ return ir with { Instances = ir.Instances.Select(instance =>+ {+ if (instance.MaterialSelection is not { } selection) return instance;+ if (!catalog.Materials.TryGetValue(selection.Material, out var material))+ { diagnostics.Add(new("assembly-appearance-unknown-material", instance.Path + ":" + selection.Material)); return instance; }+ var look = selection.AppearanceOverride ?? material.Appearance;+ if (!catalog.Appearances.TryGetValue(look, out var appearance))+ { diagnostics.Add(new("assembly-appearance-unknown-appearance", instance.Path + ":" + look)); return instance; }+ return instance with { Appearance = new(material.Name, material.Identity, look, appearance.Preview,+ selection.AppearanceOverride is null ? "physical-material-default" : "with-appearance-override") };+ }).ToArray() };+ }++ private static double Number(string text) => double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) ? value : double.NaN;+}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.csindex af08de2e..77efa1ab 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs@@ -78,10 +78,12 @@ public sealed class AssemblyM0Compilerconstraint.Orientation, 6, placements.Any(placement => placement.ConstraintIds.Contains(constraint.StableId) && placement.Status == PlacementStatus.Overconstrained) ? "conflicting" : "resolved",placements.FirstOrDefault(placement => placement.ConstraintIds.Contains(constraint.StableId) && placement.Authority == PlacementAuthority.MateDerived)?.Transform))).OrderBy(solution => solution.MateStableId, StringComparer.Ordinal).ToArray();+ AssemblyPmiAuthoring.Validate(source.Annotations, instances, diagnostics);var ir = new AssemblyIr("aetheris/assembly-ir/m0", $"assembly:{source.Name}", source.Name,instances.Single(x => x.ParentStableId is null).StableId, instances, source.Interfaces, mates,- constraints, placements, relations, stackups, fits, diagnostics, assemblyDefinitions, panelMateEvidence, datums, datumSolutions, source.SourceDependencies, joints, source.Patterns);+ constraints, placements, relations, stackups, fits, diagnostics, assemblyDefinitions, panelMateEvidence, datums, datumSolutions, source.SourceDependencies, joints, source.Patterns, ConceptPoints: source.ConceptPoints, Annotations: source.Annotations);ir = ir with { AxisSeats = AssemblyDatumAuthoring.ValidateAxisSeats(source, ir, diagnostics) };+ ir = AssemblyAppearanceAuthoring.Bind(ir, source.AppearanceCatalog, diagnostics);return new(ir, diagnostics, perf);static string SemanticPath(AssemblyInstanceIr instance, SemanticValue value)@@ -132,7 +134,7 @@ public sealed class AssemblyM0Compilerdiagnostics.Add(new("assembly-instance-path-collision", "Assembly contains duplicate deterministic instance paths."));return flat.Select(x => new AssemblyInstanceIr(x.id, x.path, x.member.Kind, x.member.DefinitionIdentity, x.parent,flat.Where(c => c.parent == x.id).Select(c => c.id).Order(StringComparer.Ordinal).ToArray(), x.semantic,- x.member.ExplicitTransform, null, [.. x.member.Provenance ?? [], .. PatternProvenance(x.path)], x.member.PlacementAuthority, x.member.IsEncapsulatedDefinition, x.member.DatumSeat)).ToArray();+ x.member.ExplicitTransform, null, [.. x.member.Provenance ?? [], .. PatternProvenance(x.path)], x.member.PlacementAuthority, x.member.IsEncapsulatedDefinition, x.member.DatumSeat, x.member.MaterialSelection)).ToArray();IEnumerable<SemanticProvenance> PatternProvenance(AssemblyPath path){diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.csindex 79c259f1..90dfcff5 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.cs@@ -66,7 +66,9 @@ public sealed record AssemblyMemberSource(AssemblyDefinitionIr? SolvedAssemblyDefinition = null,SemanticValue? TypedEndpoint = null,AssemblyFramePlacementSource? FramePlacement = null,- AssemblyDatumSeat? DatumSeat = null);+ AssemblyDatumSeat? DatumSeat = null,+ AssemblyMaterialSelection? MaterialSelection = null,+ IReadOnlyList<AssemblyRouteInput>? RouteInputs = null);public sealed record AssemblyFrameTransformSource(string Name, string From, double[] Translation,string RotationAxis, double RotationDegrees, double[]? Normal = null, double[]? Up = null,@@ -110,7 +112,10 @@ public sealed record AssemblySource(IReadOnlyList<AssemblyDefinitionSource>? AssemblyDefinitions = null,IReadOnlyList<AssemblySourceDependencyIr>? SourceDependencies = null,IReadOnlyList<AssemblyFrameTransformSource>? FrameTransforms = null,- IReadOnlyList<FirmamentV2CanonicalPatternDecl>? Patterns = null);+ IReadOnlyList<FirmamentV2CanonicalPatternDecl>? Patterns = null,+ IReadOnlyList<ConceptIrKeyedPointSetValue>? ConceptPoints = null,+ AssemblyAppearanceCatalog? AppearanceCatalog = null,+ AssemblyAnnotations? Annotations = null);public sealed record AssemblySourceDependencyIr(string Path, string Sha256, bool IsRoot);@@ -126,7 +131,9 @@ public sealed record AssemblyInstanceIr(IReadOnlyList<SemanticProvenance> Provenance,PlacementAuthority PlacementAuthority = PlacementAuthority.MateDerived,bool IsEncapsulatedDefinition = false,- AssemblyDatumSeat? DatumSeat = null);+ AssemblyDatumSeat? DatumSeat = null,+ AssemblyMaterialSelection? MaterialSelection = null,+ AssemblyAppearanceBinding? Appearance = null);public sealed record MateEndpointIr(string Role, AssemblyPath ParticipantPath, string ParticipantSemanticValueId, IReadOnlyList<string> RequiredCapabilities);public sealed record InterfaceRequirementResultIr(string Name, string Expression, string Status);@@ -201,7 +208,7 @@ public sealed record AssemblyDefinitionIr(IReadOnlyList<InterfaceFitResultIr>? LocalFitResults = null,IReadOnlyList<AssemblyAxisSeatEvidence>? LocalAxisSeats = null);-public sealed record AssemblyPerformanceIr(double ParseMilliseconds, double BindMilliseconds, double MateValidationMilliseconds, double PlacementMilliseconds, double DimensionalGraphMilliseconds, double ToleranceAnalysisMilliseconds, double DefinitionMaterializationMilliseconds = 0, double GeometryExecutionMilliseconds = 0);+public sealed record AssemblyPerformanceIr(double ParseMilliseconds, double BindMilliseconds, double MateValidationMilliseconds, double PlacementMilliseconds, double DimensionalGraphMilliseconds, double ToleranceAnalysisMilliseconds, double DefinitionMaterializationMilliseconds = 0, double GeometryExecutionMilliseconds = 0, double RouteBindingMilliseconds = 0);public sealed record AssemblyGeometryMetricsIr(int Bodies, int Faces, int Edges, int Vertices, double[] Minimum, double[] Maximum);public sealed record AssemblyDefinitionArtifactIr(string StableId, string DefinitionIdentity, string SpecializationIdentity, string StepSha256, AssemblyGeometryMetricsIr Metrics, IReadOnlyList<SemanticProvenance> Provenance);public sealed record AssemblyInstanceGeometryIr(string InstanceStableId, string DefinitionArtifactStableId, AssemblyTransform WorldTransform, AssemblyGeometryMetricsIr Metrics);@@ -223,7 +230,10 @@ public sealed record AssemblyIr(IReadOnlyList<AssemblySourceDependencyIr>? SourceDependencies = null,IReadOnlyList<AssemblyJointIr>? Joints = null,IReadOnlyList<FirmamentV2CanonicalPatternDecl>? Patterns = null,- IReadOnlyList<AssemblyAxisSeatEvidence>? AxisSeats = null);+ IReadOnlyList<AssemblyAxisSeatEvidence>? AxisSeats = null,+ IReadOnlyList<ConceptIrKeyedPointSetValue>? ConceptPoints = null,+ IReadOnlyList<AssemblyRouteBindingEvidence>? RouteBindings = null,+ AssemblyAnnotations? Annotations = null);public sealed record AssemblyCompilationResult(AssemblyIr? Ir, IReadOnlyList<AssemblyDiagnostic> Diagnostics, AssemblyPerformanceIr? Performance = null){diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.csindex 22ed2943..995a748b 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs@@ -61,7 +61,7 @@ public sealed class AssemblyM0Parservar hash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(text)));dependencies.Add(new(path, hash, stack.Count == 0));var declarations = new List<string>();- foreach (Match include in Regex.Matches(text, @"^[ \t]*Include\s+""(?<path>[^""]+)""\s*;", RegexOptions.CultureInvariant | RegexOptions.Multiline))+ foreach (Match include in Regex.Matches(text, @"^[ \t]*(?:Include|include)\s+""(?<path>[^""]+)""\s*;", RegexOptions.CultureInvariant | RegexOptions.Multiline)){string childPath;try@@ -77,7 +77,7 @@ public sealed class AssemblyM0Parserif (child is null) return null;declarations.Add(child);}- declarations.Add(Regex.Replace(text, @"^[ \t]*Include\s+""[^""]+""\s*;[ \t]*(?:\r?\n)?", string.Empty, RegexOptions.CultureInvariant | RegexOptions.Multiline));+ declarations.Add(Regex.Replace(text, @"^[ \t]*(?:Include|include)\s+""[^""]+""\s*;[ \t]*(?:\r?\n)?", string.Empty, RegexOptions.CultureInvariant | RegexOptions.Multiline));return string.Join(Environment.NewLine, declarations);}@@ -99,9 +99,12 @@ public sealed class AssemblyM0Parserpublic ParseResult Parse(string input, string sourceIdentity = "<memory>", FirmamentProjectSnapshot? project = null){+ input = FirmamentSourceSpelling.Normalize(input);var watch = Stopwatch.StartNew();var diagnostics = new List<AssemblyDiagnostic>();- var source = Regex.Replace(input, @"//[^\r\n]*", m => new string(' ',m.Length));+ var source = Regex.Replace(input, "\"(?:\\\\.|[^\"\\\\])*\"|//[^\\r\\n]*", m => m.Value.StartsWith('"') ? m.Value : new string(' ',m.Length));+ var annotations = AssemblyPmiAuthoring.Parse(ref source, sourceIdentity, diagnostics);+ if (diagnostics.Count > 0) return new(null, diagnostics, watch.Elapsed.TotalMilliseconds);var patternDiagnostics = new List<string>();var expandedPatterns = CanonicalStaticAuthoring.ExpandAssemblyPatterns(source,patternDiagnostics);foreach (var error in patternDiagnostics) diagnostics.Add(new("assembly-pattern-invalid",error));@@ -111,6 +114,7 @@ public sealed class AssemblyM0Parser// lowers through the existing, locally solved definition authority.source = Regex.Replace(source, @"\bSubassembly\s+(?<name>[A-Za-z_]\w*)\s*\{","Template < __Unit: __Unit > Assembly ${name} {", RegexOptions.CultureInvariant);+ var appearanceCatalog = AssemblyAppearanceAuthoring.Parse(ref source, diagnostics, out var appearanceSpans);var gearDocument = GearAuthoring.HasGearDefinitions(source)? GearAuthoring.ParseDefinitions(source): new GearAuthoringDocument("GearModel", [], [], []);@@ -124,12 +128,14 @@ public sealed class AssemblyM0Parserif (!layout.Any(d => d.Identity == contract.DatumContract!.Datum && d.Plane == d.Identity))diagnostics.Add(new("assembly-datum-plane-unresolved", $"Interface '{contract.Name}' requires a declared Concept plane or Axis '{contract.DatumContract!.Datum}'."));var declarationChars = partDeclarations.ToCharArray();- foreach (Match header in Regex.Matches(source, @"\b(?:Template\s*<[^>]+>\s*Assembly|Assembly|Interface(?:\s*<[^>]+>)?)\s+[A-Za-z_]\w*(?:\s*:\s*[A-Za-z_]\w*)?\s*\{"))+ foreach (Match header in Regex.Matches(source, @"\b(?:Template\s*<[^>]+>\s*Assembly|Assembly|Interface(?:\s*<[^>]*>)?)\s+[A-Za-z_]\w*(?:\s*:\s*[A-Za-z_]\w*)?\s*\{")){var block = BalancedBody(source, header.Index + header.Length - 1, diagnostics, "assembly declaration");if (block is not null) Array.Fill(declarationChars, ' ', header.Index, header.Length + block.Length + 1);}- var definitionSource = new string(declarationChars).Trim();+ var definitionSource = new string(declarationChars);+ foreach (var span in appearanceSpans.OrderByDescending(s => s.Start)) definitionSource = definitionSource.Remove(span.Start, span.Length);+ definitionSource = definitionSource.Trim();var portDependencies = new List<AssemblySourceDependencyIr>();var portCache = new Dictionary<string, IReadOnlyList<SemanticValue>>(StringComparer.Ordinal);IReadOnlyList<SemanticValue> Ports(string identity)@@ -161,7 +167,7 @@ public sealed class AssemblyM0Parservar frames = ParseFrameTransforms(body, sourceIdentity, diagnostics);tree = AssemblyDatumAuthoring.Bind(body, tree, layout, interfaces, diagnostics, out var datumFrames, Ports);frames = frames.Concat(datumFrames).ToArray();- var result = new AssemblySource(assemblyHeader.Groups["name"].Value, tree, interfaces, mates, anchor, relations, asserts, sourceIdentity, definitionSource, assemblyDefinitions, SourceDependencies: portDependencies, FrameTransforms: frames, Patterns: expandedPatterns.Document?.Patterns);+ var result = new AssemblySource(assemblyHeader.Groups["name"].Value, tree, interfaces, mates, anchor, relations, asserts, sourceIdentity, definitionSource, assemblyDefinitions, SourceDependencies: portDependencies, FrameTransforms: frames, Patterns: expandedPatterns.Document?.Patterns, ConceptPoints: expandedPatterns.Document?.ConceptPoints, AppearanceCatalog: appearanceCatalog, Annotations: annotations);return Done(result);ParseResult Done(AssemblySource? value) { watch.Stop(); return new(value, diagnostics, watch.Elapsed.TotalMilliseconds); }@@ -202,7 +208,7 @@ public sealed class AssemblyM0Parserif (dependencies.Any(item => string.Equals(item.Path, fullPath, StringComparison.OrdinalIgnoreCase))) return string.Empty;dependencies.Add(new(fullPath, hash, stack.Count == 0));var declarations = new List<string>();- foreach (Match include in Regex.Matches(text, @"^[ \t]*Include\s+""(?<path>[^""]+)""\s*;", RegexOptions.CultureInvariant | RegexOptions.Multiline))+ foreach (Match include in Regex.Matches(text, @"^[ \t]*(?:Include|include)\s+""(?<path>[^""]+)""\s*;", RegexOptions.CultureInvariant | RegexOptions.Multiline)){var relative = include.Groups["path"].Value;var childPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(fullPath)!, relative));@@ -210,7 +216,7 @@ public sealed class AssemblyM0Parserif (child is null) return null;declarations.Add(child);}- var local = Regex.Replace(text, @"^[ \t]*Include\s+""[^""]+""\s*;[ \t]*(?:\r?\n)?", string.Empty, RegexOptions.CultureInvariant | RegexOptions.Multiline);+ var local = Regex.Replace(text, @"^[ \t]*(?:Include|include)\s+""[^""]+""\s*;[ \t]*(?:\r?\n)?", string.Empty, RegexOptions.CultureInvariant | RegexOptions.Multiline);declarations.Add(local);return string.Join(Environment.NewLine, declarations);}@@ -378,6 +384,8 @@ public sealed class AssemblyM0Parserpublic SemanticValue? TypedEndpoint { get; set; }public AssemblyFramePlacementSource? FramePlacement { get; set; }public AssemblyDatumSeat? DatumSeat { get; set; }+ public AssemblyMaterialSelection? MaterialSelection { get; set; }+ public IReadOnlyList<AssemblyRouteInput>? RouteInputs { get; set; }}private static IReadOnlyList<AssemblyDefinitionSource> ParseAssemblyDefinitions(string source, string sourceIdentity,@@ -481,8 +489,15 @@ public sealed class AssemblyM0Parserif (result.Any(value => value.ExposedName == alias)) { diagnostics.Add(new("assembly-expose-duplicate-name", $"Assembly Expose declares '{alias}' more than once.")); continue; }var segments = expose.Groups["path"].Value.Split('.');var child = root.Children.SingleOrDefault(item => item.Name == segments[0]);- SemanticValue? value = child is null ? null : segments.Length == 1 ? child.TypedEndpoint : child.ExposedSemantics.SingleOrDefault(item => item.ExposedName == segments[1]);- for (var i = 2; value is not null && i < segments.Length; i++) value = value.ExposedMembers.GetValueOrDefault(segments[i]);+ var memberIndex = 1;+ // Structural pattern groups are owned by this definition. Traverse+ // those groups, but stop at reusable component privacy boundaries.+ while (child is not null && !child.IsEncapsulatedDefinition && memberIndex < segments.Length+ && child.Children.SingleOrDefault(item => item.Name == segments[memberIndex]) is { } nested)+ { child = nested; memberIndex++; }+ SemanticValue? value = child is null ? null : segments.Length == memberIndex ? child.TypedEndpoint+ : child.ExposedSemantics.SingleOrDefault(item => item.ExposedName == segments[memberIndex]);+ for (var i = memberIndex + 1; value is not null && i < segments.Length; i++) value = value.ExposedMembers.GetValueOrDefault(segments[i]);if (value is null){diagnostics.Add(new("assembly-expose-unresolved-path", $"Assembly Expose '{alias}' references nonexistent internal path '{expose.Groups["path"].Value}'."));@@ -677,8 +692,8 @@ public sealed class AssemblyM0Parser{var rest = tag.Groups["rest"].Value.Trim();var nodeMatch = kind == "Assembly"- ? Regex.Match(rest, @"^(?<name>[A-Za-z_]\w*)(?:\s*=\s*(?<definition>[A-Za-z_]\w*(?:\s*<[^>]+>)?))?$")- : Regex.Match(rest, @"^(?<name>[A-Za-z_]\w*)\s*=\s*(?<definition>[A-Za-z_]\w*(?:\s*<[^>]+>)?)$");+ ? Regex.Match(rest, @"^(?<name>[A-Za-z_]\w*)(?:\s*=\s*(?<definition>[A-Za-z_]\w*(?:\s*<[^>]*>)?))?$")+ : Regex.Match(rest, @"^(?<name>[A-Za-z_]\w*)\s*=\s*(?<definition>[A-Za-z_]\w*(?:\s*<[^>]*>)?)$");if (!nodeMatch.Success) { diagnostics.Add(new("assembly-tree-invalid-tag", $"Invalid <{kind}> tree tag '{tag.Value}'.")); continue; }var node = new MutableNode(nodeMatch.Groups["name"].Value, kind == "Assembly" ? AssemblyInstanceKind.Assembly : kind == "Panel" ? AssemblyInstanceKind.Panel : AssemblyInstanceKind.Part,kind == "Assembly" ? (nodeMatch.Groups["definition"].Success ? NormalizeIdentity(nodeMatch.Groups["definition"].Value) : nodeMatch.Groups["name"].Value) : nodeMatch.Groups["definition"].Value);@@ -709,6 +724,8 @@ public sealed class AssemblyM0Parservar nodeBody = body[open.bodyStart..tag.Index];if (open.node.Kind is AssemblyInstanceKind.Part or AssemblyInstanceKind.Panel){+ open.node.MaterialSelection = AssemblyAppearanceAuthoring.Selection(nodeBody, diagnostics);+ open.node.RouteInputs = AssemblyRouteBindings.Parse(nodeBody, diagnostics);open.node.Semantics.AddRange(ParseSemantics(nodeBody, open.node.Definition, sourceIdentity, diagnostics));if (open.node.Kind == AssemblyInstanceKind.Part && publishedPorts is not null)open.node.Semantics.AddRange(publishedPorts(open.node.Definition));@@ -758,12 +775,12 @@ public sealed class AssemblyM0Parserif (root is null) diagnostics.Add(new("assembly-tree-missing", "Assembly body requires a nested <Assembly Name> product tree."));AssemblyMemberSource Freeze(MutableNode node) => new(node.Name, node.Kind, node.Definition,node.Children.Select(Freeze).ToArray(), node.Semantics, [], [new("assembly-source", node.Name, node.Definition, SemanticSourceSpan.Generated(sourceIdentity))],- node.ExplicitTransform, node.PlacementAuthority, node.IsEncapsulatedDefinition, node.SolvedAssemblyDefinition, node.TypedEndpoint, node.FramePlacement, node.DatumSeat);+ node.ExplicitTransform, node.PlacementAuthority, node.IsEncapsulatedDefinition, node.SolvedAssemblyDefinition, node.TypedEndpoint, node.FramePlacement, node.DatumSeat, node.MaterialSelection, RouteInputs: node.RouteInputs);return root is null ? null : Freeze(root);MutableNode ToMutable(AssemblyMemberSource source){- var mutable = new MutableNode(source.Name, source.Kind, source.DefinitionIdentity) { ExplicitTransform = source.ExplicitTransform, PlacementAuthority = source.PlacementAuthority, IsEncapsulatedDefinition = source.IsEncapsulatedDefinition, SolvedAssemblyDefinition = source.SolvedAssemblyDefinition, TypedEndpoint = source.TypedEndpoint, FramePlacement = source.FramePlacement, DatumSeat = source.DatumSeat };+ var mutable = new MutableNode(source.Name, source.Kind, source.DefinitionIdentity) { ExplicitTransform = source.ExplicitTransform, PlacementAuthority = source.PlacementAuthority, IsEncapsulatedDefinition = source.IsEncapsulatedDefinition, SolvedAssemblyDefinition = source.SolvedAssemblyDefinition, TypedEndpoint = source.TypedEndpoint, FramePlacement = source.FramePlacement, DatumSeat = source.DatumSeat, MaterialSelection = source.MaterialSelection, RouteInputs = source.RouteInputs };mutable.Semantics.AddRange(source.ExposedSemantics);mutable.Children.AddRange(source.Children.Select(ToMutable));return mutable;diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.csindex da3bb602..0e3da4db 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs@@ -373,6 +373,11 @@ public sealed class AssemblyM1Pipeline{if (!parsed.IsSuccess || parsed.Source is null) return new(null, null, parsed.Diagnostics);var diagnostics = parsed.Diagnostics.ToList();+ var routeWatch = Stopwatch.StartNew();+ var routeSource = AssemblyRouteBindings.Resolve(parsed.Source, diagnostics, out var routeBindings);+ if (routeSource is null) return new(null, null, diagnostics);+ parsed = parsed with { Source = routeSource };+ routeWatch.Stop();var materializationWatch = Stopwatch.StartNew();var definitions = parsed.Source.Root.Flatten().Where(member => member.Kind == AssemblyInstanceKind.Part).Select(member => member.DefinitionIdentity).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)@@ -392,9 +397,10 @@ public sealed class AssemblyM1Pipelinevar performance = compiled.Performance is null ? null : compiled.Performance with{DefinitionMaterializationMilliseconds = materializationWatch.Elapsed.TotalMilliseconds,- GeometryExecutionMilliseconds = geometryWatch.Elapsed.TotalMilliseconds+ GeometryExecutionMilliseconds = geometryWatch.Elapsed.TotalMilliseconds,+ RouteBindingMilliseconds = routeWatch.Elapsed.TotalMilliseconds};- return new(validatedIr, geometry, diagnostics, performance);+ return new(validatedIr with { RouteBindings = routeBindings }, geometry, diagnostics, performance);}private static MaterializedAssemblyDefinition? Materialize(string identity, string? declarations, string sourceIdentity,diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM2Interop.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM2Interop.csindex 75d44bcd..754f148b 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM2Interop.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM2Interop.cs@@ -146,7 +146,14 @@ public static class AssemblyIrAp242Exporterinstance.Kind == AssemblyInstanceKind.Part ? artifactByIdentity[instance.DefinitionIdentity]: instance.IsEncapsulatedDefinition ? assemblyDefinitionByIdentity[instance.DefinitionIdentity] : null, local);}).ToArray();- return Step242AssemblyExporter.Export(new(ir.Name, ir.RootInstanceStableId, definitions, occurrences));+ var notes = (ir.Annotations?.Notes ?? []).Select(note => new Step242AssemblyNote(+ ir.Instances.Single(i => i.Path.ToString() == note.Target).StableId,+ new(note.Name, note.Target, note.Text))).ToList();+ if (ir.Annotations?.Release is { } release)+ foreach (var field in release.Fields.OrderBy(p => p.Key, StringComparer.Ordinal))+ notes.Add(new(ir.RootInstanceStableId, new($"{release.Name}.{field.Key}", ir.Name, field.Value)));+ return Step242AssemblyExporter.Export(new(ir.Name, ir.RootInstanceStableId, definitions, occurrences,+ AssemblyPmiAuthoring.Header(ir.Annotations?.Release, ir.Name), notes));}private static KernelResult<string> Failure(string message) => KernelResult<string>.Failure([diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyPmiAuthoring.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyPmiAuthoring.csnew file mode 100644index 00000000..79ee5b5d--- /dev/null+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyPmiAuthoring.cs@@ -0,0 +1,148 @@+using System.Text.Json;+using System.Text.RegularExpressions;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Semantics;++namespace Aetheris.Kernel.Firmament.Assembly;++public sealed record AssemblyReleaseRecord(string Name, string Type,+ IReadOnlyDictionary<string, string> Fields, SemanticSourceSpan SourceSpan);+public sealed record AssemblyPmiNote(string Name, string Target, string Text, SemanticSourceSpan SourceSpan);+public sealed record AssemblyAnnotations(AssemblyReleaseRecord? Release, IReadOnlyList<AssemblyPmiNote> Notes);++[FirmamentConstruct("AssemblyProvenance", "Provenance", Context = "Assembly", Entry = "Provenance: Release;", Description = "Select a typed Static release Record for AP242 header metadata and inspectable semantic annotations.")]+public static class AssemblyProvenanceDeclaration { }++[FirmamentConstruct("AssemblyPmi", "Pmi", Context = "Assembly", Entry = "Pmi { Note DesignIntent { Target: Product; Text: \"Design intent\"; } }", Description = "Root-owned semantic notes associated with declared product occurrences; no face or GD&T inference.")]+public static class AssemblyPmiDeclaration { }++[FirmamentConstruct("AssemblyPmiNote", "Note", Context = "Assembly Pmi", Entry = "Note DesignIntent { Target: Product; Text: \"Design intent\"; }", Description = "An engineer-authored product annotation with an explicit occurrence target.")]+[FirmamentField("Target", "Target", FirmamentSchemaValueKind.ConstructReference, Required = true)]+[FirmamentField("Text", "Text", FirmamentSchemaValueKind.String, Required = true)]+public static class AssemblyPmiNoteDeclaration { }++/// <summary>Root-owned product annotations. Typed data stays with the ordinary Record binder;+/// this seam only selects that data and binds annotation owners, without manufacturing geometry.</summary>+internal static class AssemblyPmiAuthoring+{+ internal static AssemblyAnnotations Parse(ref string source, string identity, List<AssemblyDiagnostic> diagnostics)+ {+ var original = source;+ var mask = Mask(source);+ var changes = new List<(int Start, int Length)>();+ var notes = new List<AssemblyPmiNote>();+ AssemblyReleaseRecord? release = null;+ // Template Assembly definitions have a '>' immediately before Assembly.+ var roots = Regex.Matches(mask, @"\bAssembly\s+[A-Za-z_]\w*\s*\{").Cast<Match>()+ .Where(m => Depth(mask, m.Index) == 0 && mask[..m.Index].TrimEnd().LastOrDefault() != '>').ToArray();+ if (roots.Length != 1) return new(null, []); // The owning assembly parser diagnoses root structure.+ var root = roots[0]; var rootEnd = End(mask, root.Index + root.Length - 1);+ if (rootEnd < 0) return new(null, []);+ var bodyStart = root.Index + root.Length;+ var body = mask[bodyStart..rootEnd];+ // Note text is opaque to the Record binder, too. It must never discover+ // a fictional Record or Static declaration inside an annotation string.+ var catalogChars = original.ToCharArray();+ foreach (Match header in Regex.Matches(mask, @"\bPmi\s*\{"))+ {+ var end = End(mask, header.Index + header.Length - 1);+ if (end >= 0) Array.Fill(catalogChars, ' ', header.Index, end - header.Index + 1);+ }+ var catalog = new string(catalogChars);+ var selections = Regex.Matches(body, @"\bProvenance\s*:\s*(?<name>[A-Za-z_]\w*)\s*;");+ if (Regex.Matches(body, @"\bProvenance\s*:").Count != selections.Count || selections.Count > 1)+ Error("provenance-selection-invalid", "Expected one Provenance: StaticRecord; in the root Assembly.");+ foreach (Match selection in selections)+ {+ if (Depth(body, selection.Index) != 0) { Error("provenance-scope-invalid", "Provenance belongs to the root Assembly."); continue; }+ var name = selection.Groups["name"].Value;+ var recordDiagnostics = new List<string>();+ var value = FirmamentV2TemplateExpansion.InspectStaticRecords(catalog, recordDiagnostics).SingleOrDefault(r => r.Name == name);+ foreach (var diagnostic in recordDiagnostics) Error("provenance-record-invalid", diagnostic);+ if (value is null) Error("provenance-record-unresolved", name);+ else+ {+ var schema = FirmamentV2TemplateExpansion.InspectRecords(catalog, recordDiagnostics).Single(r => r.Name == value.TypeName);+ foreach (var required in new[] { ("Author", "String"), ("Date", "Date"), ("Version", "Version"), ("Description", "String") })+ if (schema.Fields.GetValueOrDefault(required.Item1) != required.Item2)+ Error("provenance-field-invalid", $"{name}.{required.Item1} must have type {required.Item2}.");+ if (schema.Fields.ContainsKey("Organization") && schema.Fields["Organization"] != "String")+ Error("provenance-field-invalid", $"{name}.Organization must have type String.");+ if (schema.Fields.Values.Any(t => t is not ("String" or "Date" or "Version" or "Length" or "Angle" or "Int" or "Float" or "Bool")))+ Error("provenance-field-invalid", "Release records admit flat scalar engineering data.");+ var fields = value.Fields.ToDictionary(p => p.Key, p => Unquote(p.Value), StringComparer.Ordinal);+ if (fields.Values.Any(string.IsNullOrWhiteSpace)) Error("provenance-field-invalid", "Release fields must be non-empty.");+ release = new(name, value.TypeName, fields, new(identity, bodyStart + selection.Index, selection.Length));+ // Erase only the selected data from the material-definition source so metadata edits+ // cannot invalidate the reusable geometry cache. The typed value is retained above.+ foreach (Match declaration in Regex.Matches(mask, $@"\b(?:Record\s+{Regex.Escape(value.TypeName)}|Static\s+{Regex.Escape(name)}\s*:\s*{Regex.Escape(value.TypeName)})\s*\{{"))+ {+ var end = End(mask, declaration.Index + declaration.Length - 1);+ if (end >= 0) changes.Add((declaration.Index, end - declaration.Index + 1));+ }+ }+ changes.Add((bodyStart + selection.Index, selection.Length));+ }+ foreach (Match header in Regex.Matches(body, @"\bPmi\s*\{"))+ {+ var start = bodyStart + header.Index;+ var end = End(mask, start + header.Length - 1);+ if (end < 0) { Error("pmi-malformed", "Unclosed Pmi block."); continue; }+ if (Depth(body, header.Index) != 0) Error("pmi-scope-invalid", "Assembly Pmi belongs to the root Assembly.");+ var cursor = start + header.Length;+ while (cursor < end)+ {+ while (cursor < end && char.IsWhiteSpace(mask[cursor])) cursor++;+ if (cursor == end) break;+ var note = Regex.Match(mask[cursor..end], @"^Note\s+(?<name>[A-Za-z_]\w*)\s*\{");+ if (!note.Success) { Error("pmi-kind-unsupported", "Assembly Pmi currently admits only Note Name { Target: occurrence; Text: string; }."); break; }+ var close = End(mask, cursor + note.Length - 1);+ if (close < 0 || close >= end) { Error("pmi-malformed", note.Value); break; }+ var fields = original[(cursor + note.Length)..close];+ var parsed = Regex.Match(fields, "^\\s*Target\\s*:\\s*(?<target>[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*)\\s*;\\s*Text\\s*:\\s*(?<text>\"(?:\\\\.|[^\"\\\\])*\")\\s*;\\s*$", RegexOptions.Singleline);+ if (!parsed.Success) Error("pmi-note-invalid", note.Groups["name"].Value);+ else+ {+ try+ {+ using var literal = JsonDocument.Parse(parsed.Groups["text"].Value);+ var text = literal.RootElement.GetString()!;+ var name = note.Groups["name"].Value;+ if (string.IsNullOrWhiteSpace(text) || text.Any(char.IsControl)) Error("pmi-note-invalid", name);+ else if (notes.Any(n => n.Name == name)) Error("pmi-note-duplicate", name);+ else notes.Add(new(name, parsed.Groups["target"].Value, text, new(identity, cursor, close - cursor + 1)));+ }+ catch (JsonException) { Error("pmi-note-invalid", note.Groups["name"].Value); }+ }+ cursor = close + 1;+ }+ changes.Add((start, end - start + 1));+ }+ var chars = source.ToCharArray();+ foreach (var change in changes) Array.Fill(chars, ' ', change.Start, change.Length);+ source = new(chars);+ return new(release, notes);++ void Error(string code, string message) => diagnostics.Add(new("assembly-" + code, message));+ }++ internal static void Validate(AssemblyAnnotations? annotations, IEnumerable<AssemblyInstanceIr> instances, List<AssemblyDiagnostic> diagnostics)+ {+ var paths = instances.Select(i => i.Path.ToString()).ToHashSet(StringComparer.Ordinal);+ foreach (var note in annotations?.Notes ?? [])+ if (!paths.Contains(note.Target)) diagnostics.Add(new("assembly-pmi-target-unresolved", $"Note '{note.Name}' targets unknown occurrence '{note.Target}'."));+ }++ internal static Step242HeaderMetadata? Header(AssemblyReleaseRecord? release, string assemblyName)+ => release is null ? null : new(assemblyName + ".step", release.Fields["Description"] + " v" + release.Fields["Version"],+ release.Fields["Date"] + "T00:00:00", release.Fields["Author"], release.Fields.GetValueOrDefault("Organization", "Aetheris"),+ "Aetheris.Kernel.Firmament", "Aetheris/Firmament", "");++ private static string Unquote(string value) => value.StartsWith('"') ? value[1..^1] : value;+ private static string Mask(string source) => Regex.Replace(source, "\"(?:\\\\.|[^\"\\\\])*\"|//[^\\r\\n]*", m => new string(' ', m.Length));+ private static int Depth(string text, int end)+ { var depth = 0; for (var i = 0; i < end; i++) { if (text[i] == '{') depth++; else if (text[i] == '}') depth--; } return depth; }+ private static int End(string text, int opening)+ { var depth = 0; for (var i = opening; i < text.Length; i++) { if (text[i] == '{') depth++; else if (text[i] == '}' && --depth == 0) return i; } return -1; }+}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyPublishedPorts.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyPublishedPorts.csindex 9f1c13a5..30e711db 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyPublishedPorts.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyPublishedPorts.cs@@ -46,6 +46,7 @@ internal static class AssemblyPublishedPorts.Select(d => d with { IsRoot = false }));if (!dependencies.Any(d => d.Path == path))dependencies.Add(new(path, Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(source))), false));+ source = FirmamentSourceSpelling.Normalize(source);if (!Regex.IsMatch(source, @"\bExpose\s*\{\s*Semantic\b")) return [];var chain = SectionChainAuthoringParser.Compile(Strip(source, diagnostics), materialize: false);if (!chain.IsSuccess || chain.Chain is null)@@ -78,6 +79,7 @@ internal static class AssemblyPublishedPorts}internal static string Strip(string source, List<AssemblyDiagnostic> diagnostics){+ source = FirmamentSourceSpelling.Normalize(source);var chars = source.ToCharArray();foreach (Match expose in Regex.Matches(source,@"\bExpose\s*\{")){@@ -91,6 +93,7 @@ internal static class AssemblyPublishedPortsinternal static IReadOnlyList<SemanticValue> Read(string source,string owner,string identity,string sourceIdentity,List<AssemblyDiagnostic> diagnostics,SectionChain? chain = null){+ source = FirmamentSourceSpelling.Normalize(source);var header = Regex.Match(source,$@"\b(?:Struct|Model)\s+{Regex.Escape(owner)}\s*\{{");if (!header.Success) return [];var body = AssemblyM0Parser.BalancedBody(source,header.Index+header.Length-1,diagnostics,"published part");diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyRouteBindings.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyRouteBindings.csnew file mode 100644index 00000000..dbbbf5a3--- /dev/null+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyRouteBindings.cs@@ -0,0 +1,92 @@+using System.Globalization;+using System.Text.RegularExpressions;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Semantics;++namespace Aetheris.Kernel.Firmament.Assembly;++public sealed record AssemblyRouteInput(string Parameter, double[] Point, string On);+public sealed record AssemblyRouteBindingEvidence(string Occurrence, string Parameter, string Port,+ double[] WorldPoint, double[] LocalPoint, string SpecializedDefinition);++/// <summary>Late, fixed-placement point binding. The existing M0 solver and+/// world semantic query own placement; ordinary typed Templates own specialization.</summary>+internal static class AssemblyRouteBindings+{+ internal static IReadOnlyList<AssemblyRouteInput>? Parse(string body, List<AssemblyDiagnostic> diagnostics)+ {+ var headers = Regex.Matches(body, @"\bBind\s*\{");+ if (headers.Count == 0) return null;+ if (headers.Count != 1) { Error("duplicate", "One Bind block is allowed."); return []; }+ var content = AssemblyM0Parser.BalancedBody(body, headers[0].Index + headers[0].Length - 1, diagnostics, "route Bind");+ if (content is null) return [];+ var inputs = new List<AssemblyRouteInput>(); var remaining = content;+ foreach (Match input in Regex.Matches(content, @"(?<name>[A-Za-z_]\w*)\s*\{(?<body>[^{}]*)\}"))+ {+ var fields = input.Groups["body"].Value;+ var at = Regex.Match(fields, @"\bAt\s*:\s*Point(?<dimension>[23])\((?<point>[^()]+)\)\s*;");+ var on = Regex.Match(fields, @"\bOn\s*:\s*(?<path>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)+)\s*;");+ var rest = fields;+ foreach (var field in new[] { at, on }.Where(m => m.Success).OrderByDescending(m => m.Index)) rest = rest.Remove(field.Index, field.Length);+ var point = at.Groups["point"].Value.Split(',').Select(v =>+ Materializer.WireFormAuthoring.TryLength(v.Trim(), out var value) ? value : double.NaN).ToArray();+ if (!at.Success || !on.Success || !string.IsNullOrWhiteSpace(rest)+ || point.Length != int.Parse(at.Groups["dimension"].Value) || point.Any(v => !double.IsFinite(v))+ || inputs.Any(i => i.Parameter == input.Groups["name"].Value))+ { Error("input-invalid", input.Groups["name"].Value); continue; }+ inputs.Add(new(input.Groups["name"].Value, point.Length == 2 ? [point[0], point[1], 0] : point, on.Groups["path"].Value));+ }+ foreach (Match match in Regex.Matches(content, @"[A-Za-z_]\w*\s*\{[^{}]*\}").Cast<Match>().Reverse()) remaining = remaining.Remove(match.Index, match.Length);+ if (!string.IsNullOrWhiteSpace(remaining) || inputs.Count is < 1 or > 16) Error("input-invalid", "Expected 1..16 named point bindings.");+ return inputs;+ void Error(string code, string message) => diagnostics.Add(new("assembly-route-bind-" + code, message));+ }++ internal static AssemblySource? Resolve(AssemblySource source, List<AssemblyDiagnostic> diagnostics,+ out IReadOnlyList<AssemblyRouteBindingEvidence> evidence)+ {+ var bound = new List<AssemblyRouteBindingEvidence>(); evidence = bound;+ if (!source.Root.Flatten().Any(m => m.RouteInputs is not null)) return source;+ var placed = new AssemblyM0Compiler().Compile(source);+ if (!placed.IsSuccess || placed.Ir is null) { diagnostics.AddRange(placed.Diagnostics); return null; }+ if ((placed.Ir.Joints ?? []).Any())+ { diagnostics.Add(new("assembly-route-bind-motion-not-qualified", "Bound routes require a completely fixed assembly; posed or moving routes are deferred.")); return null; }+ var declarations = source.DefinitionSource ?? "";+ AssemblyMemberSource Visit(AssemblyMemberSource member, string path)+ {+ var children = member.Children.Select(c => Visit(c, path + "." + c.Name)).ToArray();+ if (member.RouteInputs is null) return member with { Children = children };+ var templateName = member.DefinitionIdentity.Split('<')[0];+ var template = Regex.Match(declarations, $@"\b(?:Struct|Model)\s+{Regex.Escape(templateName)}\s*\{{");+ var templateBody = template.Success ? AssemblyM0Parser.BalancedBody(declarations, template.Index + template.Length - 1, diagnostics, "route template") : null;+ if (member.Kind != AssemblyInstanceKind.Part || templateBody is null || !Materializer.WireRouteAuthoring.IsSource(templateBody) || Regex.IsMatch(templateBody, @"\bExpose\b"))+ { diagnostics.Add(new("assembly-route-bind-consumer-invalid", path + ": Bind requires a point-driven WireRoute Template without route-dependent published outputs.")); return member; }+ var instance = placed.Ir.Instances.Single(i => i.Path.ToString() == path);+ if (instance.ResolvedTransform is null) { diagnostics.Add(new("assembly-route-bind-placement-unresolved", path)); return member; }+ var inverse = Transform3D.FromRowMajor(instance.ResolvedTransform.Matrix).Inverse();+ var arguments = new List<string>(); var rows = new List<(AssemblyRouteInput Input, Point3D World, Point3D Local)>();+ foreach (var input in member.RouteInputs)+ {+ if (!AssemblyM0Compiler.TryResolve(AssemblyPath.Parse(input.On), placed.Ir.Instances, out var reference)+ || !reference!.Value.TryBinding<ExactDatumFrameBinding>(out _))+ { diagnostics.Add(new("assembly-route-bind-port-unresolved", path + ":" + input.Parameter + ":" + input.On + ": a public DatumFrame is required")); continue; }+ var frame = (ExactDatumFrameBinding)AssemblyWorldQuery.Resolve(placed.Ir, reference.Value.StableIdentity);+ var p = input.Point;+ var world = new Point3D(frame.OriginX + frame.XAxisX * p[0] + frame.YAxisX * p[1] + frame.ZAxisX * p[2],+ frame.OriginY + frame.XAxisY * p[0] + frame.YAxisY * p[1] + frame.ZAxisY * p[2],+ frame.OriginZ + frame.XAxisZ * p[0] + frame.YAxisZ * p[1] + frame.ZAxisZ * p[2]);+ var local = inverse.Apply(world);+ arguments.Add(input.Parameter + ":Point3(" + string.Join(",", new[] { local.X, local.Y, local.Z }.Select(v => v.ToString("0.################", CultureInfo.InvariantCulture) + "mm")) + ")");+ rows.Add((input, world, local));+ }+ if (!member.DefinitionIdentity.EndsWith('>')) { diagnostics.Add(new("assembly-route-bind-template-required", path)); return member; }+ var prefix = member.DefinitionIdentity[..^1];+ var identity = prefix + (prefix.EndsWith('<') ? "" : ",") + string.Join(",", arguments) + ">";+ foreach (var row in rows) bound.Add(new(path, row.Input.Parameter, row.Input.On, [row.World.X, row.World.Y, row.World.Z], [row.Local.X, row.Local.Y, row.Local.Z], identity));+ return member with { Children = children, DefinitionIdentity = identity };+ }+ var root = Visit(source.Root, source.Root.Name);+ return diagnostics.Any(d => d.Severity == AssemblyDiagnosticSeverity.Error) ? null : source with { Root = root };+ }+}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyUsdExporter.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyUsdExporter.csindex daccb219..ba8c3724 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyUsdExporter.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyUsdExporter.cs@@ -36,6 +36,10 @@ public static class AssemblyUsdExporterthrow new InvalidOperationException("assembly-usd-document-mismatch");var occurrences = mesh.Occurrences.ToDictionary(o => o.Id, StringComparer.Ordinal);var definitions = mesh.Definitions.OrderBy(d => d.Id, StringComparer.Ordinal).ToArray();+ var authoredLooks = ir.Instances.Where(i => i.Appearance is not null).Select(i => i.Appearance!)+ .DistinctBy(a => a.Appearance).OrderBy(a => a.Appearance, StringComparer.Ordinal).ToArray();+ var lookPaths = authoredLooks.Select((look, index) => (look.Appearance, Path: "/Looks/Authored_" + index))+ .ToDictionary(p => p.Appearance, p => p.Path, StringComparer.Ordinal);var declaredPose = AssemblyKinematics.Evaluate(ir, evaluatedState ?? options.State ?? new Dictionary<string, double>());if (!declaredPose.IsSuccess || declaredPose.Instances.Any(instance => instance.ResolvedTransform is null|| occurrences[instance.StableId].Transform.Length != 16@@ -99,6 +103,18 @@ public static class AssemblyUsdExporterLine($" float inputs:metallic = {F(m.Metallic)}"); Line($" float inputs:roughness = {F(m.Roughness)}");Line(" token outputs:surface"); Line(" }"); Line(" }");}+ foreach (var look in authoredLooks)+ {+ var path = lookPaths[look.Appearance]; var m = look.Preview;+ ValidateMaterial(m);+ Line($" def Material {Q(path.Split('/').Last())} {{");+ Line($" custom string aetheris:appearanceIdentity = {Q(look.Appearance)}");+ Line($" token outputs:surface.connect = <{path}/Shader.outputs:surface>");+ Line(" def Shader \"Shader\" {"); Line(" uniform token info:id = \"UsdPreviewSurface\"");+ Line($" color3f inputs:diffuseColor = ({F(m.Red)}, {F(m.Green)}, {F(m.Blue)})");+ Line($" float inputs:metallic = {F(m.Metallic)}"); Line($" float inputs:roughness = {F(m.Roughness)}");+ Line(" token outputs:surface"); Line(" }"); Line(" }");+ }Line("}");var joints = ir.Joints ?? [];var bodies = joints.SelectMany(j => new[] { j.ParentOccurrenceId, j.ChildOccurrenceId }).ToHashSet();@@ -113,7 +129,18 @@ public static class AssemblyUsdExporterLine($"{indent} custom string aetheris:sourcePath = {Q(o.Path)}");Line($"{indent} custom string aetheris:definitionIdentity = {Q(ir.Instances.Single(i => i.StableId == id).DefinitionIdentity)}");if (bodies.Contains(id)) { Line($"{indent} bool physics:rigidBodyEnabled = true"); Line($"{indent} bool physics:kinematicEnabled = true"); }- if (id == ir.RootInstanceStableId) Line($"{indent} custom string aetheris:sourceName = {Q(ir.Name)}");+ if (id == ir.RootInstanceStableId)+ {+ Line($"{indent} custom string aetheris:sourceName = {Q(ir.Name)}");+ if (ir.Annotations?.Release is { } release)+ foreach (var field in release.Fields.OrderBy(p => p.Key, StringComparer.Ordinal))+ Line($"{indent} custom string aetheris:provenance:{field.Key} = {Q(field.Value)}");+ foreach (var note in ir.Annotations?.Notes ?? [])+ {+ Line($"{indent} custom string aetheris:pmi:{note.Name}:target = {Q(note.Target)}");+ Line($"{indent} custom string aetheris:pmi:{note.Name}:text = {Q(note.Text)}");+ }+ }double[] Local(double[] world, double[]? parent) => parent is null ? world :(Transform3D.FromRowMajor(world) * Transform3D.FromRowMajor(parent).Inverse()).ToRowMajor();var local = Local(o.Transform, o.ParentId is null ? null : occurrences[o.ParentId].Transform);@@ -138,7 +165,20 @@ public static class AssemblyUsdExporter}if (o.DefinitionId is not null){- Line($"{indent} def Xform \"Geometry\" (prepend references = <{definitionPaths[o.DefinitionId]}>; instanceable = true) {{}}");+ var look = ir.Instances.Single(i => i.StableId == id).Appearance;+ Line($"{indent} def Xform \"Geometry\" (prepend references = <{definitionPaths[o.DefinitionId]}>; instanceable = true" ++ (look is null ? "" : "; prepend apiSchemas = [\"MaterialBindingAPI\"]") + ") {");+ if (look is not null)+ {+ Line($"{indent} custom string userProperties:aetheris_material = {Q(look.PhysicalIdentity)}");+ Line($"{indent} custom string userProperties:aetheris_appearance = {Q(look.Appearance)}");+ Line($"{indent} rel material:binding = <{lookPaths[look.Appearance]}> (bindMaterialAs = \"strongerThanDescendants\")");+ Line($"{indent} over \"Mesh\" {{");+ Line($"{indent} custom string userProperties:aetheris_material = {Q(look.PhysicalIdentity)}");+ Line($"{indent} custom string userProperties:aetheris_appearance = {Q(look.Appearance)}");+ Line($"{indent} }}");+ }+ Line($"{indent} }}");}foreach (var child in mesh.Occurrences.Where(c => c.ParentId == id).OrderBy(c => c.Path, StringComparer.Ordinal)) WriteOccurrence(child.Id, depth + 1);Line(indent + "}");diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.csindex 37d924c1..f46d0432 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs@@ -15,12 +15,19 @@ internal static class CanonicalStaticAuthoring/// <summary>Assembly consumes the same checked Record/Set values, but yields product-tree declarations.</summary>internal static Result? ExpandAssemblyPatterns(string source, List<string> diagnostics){+ var points = ConceptPointAuthoring.Expand(source, diagnostics);+ if (points is null) return null;+ source = points.Source;var sites = AssemblySiteAuthoring.Expand(source, diagnostics);if (sites is null) return null;source = sites.Source;var headers = Regex.Matches(source,@"\bPattern\s+(?<name>[A-Za-z_]\w*)\s+Over\s+(?<set>[A-Za-z_]\w*)\s*\{").Cast<Match>().Where(h => Regex.IsMatch(source[(h.Index+h.Length)..],@"^\s*[A-Za-z_]\w*\s*=>\s*<(?:Part|Assembly)\b")).ToArray();- if (headers.Length == 0) return new(source,null);+ if (headers.Length == 0)+ {+ source = points.Math.Normalize(source, diagnostics);+ return diagnostics.Count > 0 ? null : new(source, points.Points.Count == 0 ? null : new([],[],[],[],[], ConceptPoints: points.Points));+ }var catalog = source.Select(c => c is '\r' or '\n' ? c : ' ').ToArray();foreach (Match header in Regex.Matches(source,@"\b(?:Record\s+[A-Za-z_]\w*|Static\s+[A-Za-z_]\w*\s*:\s*Set\s*<\s*[A-Za-z_]\w*\s*>)\s*\{")){@@ -59,7 +66,11 @@ internal static class CanonicalStaticAuthoringsites.Recipes.GetValueOrDefault(set.Name)));}foreach (var change in changes.OrderByDescending(c=>c.Start)) source=source.Remove(change.Start,change.Length).Insert(change.Start,change.Text);- return new(source,data.Document with { Patterns=patterns });+ source = points.Math.Normalize(source, diagnostics);+ var conceptualSets = points.Points.ToDictionary(p => ConceptPointAuthoring.SetName(p.Name), p => p);+ patterns = patterns.Select(pattern => conceptualSets.TryGetValue(pattern.Source, out var collection)+ ? pattern with { Source = collection.Name, Associations = pattern.Associations?.Select(a => a with { SourceSet = collection.Name }).ToArray() } : pattern).ToList();+ return diagnostics.Count > 0 ? null : new(source,data.Document with { Patterns=patterns, ConceptPoints=points.Points });}private static string SubstituteSetMapping(string mapping,string binder,FirmamentV2StaticSetEntry entry)@@ -67,12 +78,26 @@ internal static class CanonicalStaticAuthoringif (entry.RecordFields is not null)foreach (var field in entry.RecordFields)mapping=Regex.Replace(mapping,$@"\b{Regex.Escape(binder)}\s*\.\s*{Regex.Escape(field.Key)}\b",field.Value,RegexOptions.CultureInvariant);- else mapping=Regex.Replace(mapping,$@"\b{Regex.Escape(binder)}\b",entry.Value,RegexOptions.CultureInvariant);+ else+ {+ var point = Regex.Match(entry.Value, @"^Point(?<dim>[23])\((?<values>[^()]+)\)$");+ if (point.Success)+ {+ var coordinates = point.Groups["values"].Value.Split(',', StringSplitOptions.TrimEntries);+ for (var i = 0; i < coordinates.Length; i++)+ mapping = Regex.Replace(mapping, $@"\b{Regex.Escape(binder)}(?:\s*\.\s*Position)?\s*\.\s*{"XYZ"[i]}\b", coordinates[i]);+ mapping = Regex.Replace(mapping, $@"\b{Regex.Escape(binder)}\s*\.\s*Position\b", entry.Value);+ }+ mapping=Regex.Replace(mapping,$@"\b{Regex.Escape(binder)}\b",entry.Value,RegexOptions.CultureInvariant);+ }return mapping;}public static Result? Expand(string source, List<string> diagnostics){+ var points = ConceptPointAuthoring.Expand(source, diagnostics);+ if (points is null) return null;+ source = points.Source;var linear = LinearFeatureAuthoring.Expand(source, diagnostics);if (linear is null) return null;source = linear.Source;@@ -82,7 +107,10 @@ internal static class CanonicalStaticAuthoringvar canonicalRoot = Regex.IsMatch(source, @"^\s*Model\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant);var staticDeclaration = Regex.IsMatch(source, @"\b(?:Record|Static|Template\s*(?:<|[A-Za-z_]\w*\s*\()|Pattern\s+\w+\s+Over)\b", RegexOptions.CultureInvariant)|| symmetry.Mirrors.Count > 0 || symmetry.RadialPatterns.Count > 0 || linear.Patterns.Count > 0 || linear.Axes.Count > 0;- if (!staticDeclaration && !(canonicalRoot && Regex.IsMatch(source, @"\b(?:Require\s+[A-Za-z_]\w*\s*(?:=>|\{)|Pmi\s*\{[\s\S]*?\bFrom\s*:)", RegexOptions.CultureInvariant))) return new(source, null);+ if (!staticDeclaration && !(canonicalRoot && Regex.IsMatch(source, @"\b(?:Require\s+[A-Za-z_]\w*\s*(?:=>|\{)|Pmi\s*\{[\s\S]*?\bFrom\s*:)", RegexOptions.CultureInvariant))) {+ source = points.Math.Normalize(source, diagnostics);+ return diagnostics.Any(d => d.StartsWith(ConceptPointAuthoring.Prefix, StringComparison.Ordinal)) ? null : new(source, null);+ }var changes = new List<(int Start, int Length, string Text)>();var names = new HashSet<string>(StringComparer.Ordinal);var recordTypes = new List<FirmamentV2RecordTypeDecl>();@@ -335,7 +363,9 @@ internal static class CanonicalStaticAuthoring.Where(change => !erasures.Any(erase => erase.Start < change.Start && change.Start < erase.Start + erase.Length)).OrderByDescending(change => change.Start))source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);- return new(source, new(recordTypes, arrays, templates.Select(t => new FirmamentV2CanonicalTemplateDecl(t.Name, t.Type, t.Parameter, t.Body, t.Span)).ToArray(), patterns, requires, semanticConstraints, projections, staticRecords, tables, sets, symmetry.Mirrors, symmetry.RadialPatterns, linear.Patterns, linear.Axes));+ source = points.Math.Normalize(source, diagnostics);+ if (diagnostics.Any(d => d.StartsWith(ConceptPointAuthoring.Prefix, StringComparison.Ordinal))) return null;+ return new(source, new(recordTypes, arrays, templates.Select(t => new FirmamentV2CanonicalTemplateDecl(t.Name, t.Type, t.Parameter, t.Body, t.Span)).ToArray(), patterns, requires, semanticConstraints, projections, staticRecords, tables, sets, symmetry.Mirrors, symmetry.RadialPatterns, linear.Patterns, linear.Axes, points.Points));}private static IReadOnlyList<FirmamentV2StaticSetEntry> ParseSetEntries(string source, int start, int end, string setName, string elementType,@@ -395,6 +425,18 @@ internal static class CanonicalStaticAuthoring{declaration = mapping;declaration = SubstituteSetMapping(declaration,binder,entry);+ if (Regex.IsMatch(declaration, @"^Section\s+[A-Za-z_]\w*\s*\{"))+ {+ var sectionOpen = declaration.IndexOf('{');+ var sectionClose = MatchPair(declaration, sectionOpen, '{', '}');+ if (sectionClose != declaration.Length - 1 || Regex.Matches(declaration, @"\b(?:Pattern|Section)\s+", RegexOptions.CultureInvariant).Count != 1)+ { diagnostics.Add(Prefix + "pattern-body-invalid:" + patternName); return; }+ var sectionName = Regex.Match(declaration, @"^Section\s+(?<name>[A-Za-z_]\w*)").Groups["name"];+ declaration = declaration.Remove(sectionName.Index, sectionName.Length).Insert(sectionName.Index, materializedId);+ output.Add(declaration); generated.Add(semanticId);+ associations.Add(new(semanticId, set.Name, entry.Name, entry.Value, entry.SourceOrder, entry.Provenance));+ continue;+ }var construction = Regex.Match(declaration, @"\b(?:Hole\s*<\s*(?:Shaft|Counterbore|Countersink)\s*>|Slot\s*<\s*(?:Capsule|RoundedRectangle)\s*>|Boss|Pocket|EdgeFinish)\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);if (!construction.Success) { diagnostics.Add(Prefix + "pattern-body-invalid:" + patternName); return; }declaration = declaration.Remove(construction.Groups["name"].Index, construction.Groups["name"].Length).Insert(construction.Groups["name"].Index, materializedId);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CompositionAuthoringDeclarations.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CompositionAuthoringDeclarations.csnew file mode 100644index 00000000..e442a888--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CompositionAuthoringDeclarations.cs@@ -0,0 +1,40 @@+namespace Aetheris.Kernel.Firmament.FirmamentV2;++// Editor metadata for implemented authoring forms. Execution stays with their+// existing profile, point, section and wire binders; these are not new parsers.+[FirmamentConstruct("WireRoute", "WireRoute", Context = "Model", Entry = "WireRoute Lead { Diameter: 1mm; MinimumBendRadius: 10mm; Path { Start { At: Point3(0mm,0mm,0mm); } Corner Bend { At: Point3(40mm,0mm,0mm); Radius: 10mm; } End { At: Point3(40mm,40mm,0mm); } } }", Description = "A bounded point route lowered to exact WireForm straights and circular bends.")]+[FirmamentField("Diameter", "Diameter", FirmamentSchemaValueKind.Length, Required = true)]+[FirmamentField("MinimumBendRadius", "MinimumBendRadius", FirmamentSchemaValueKind.Length, Required = true)]+[FirmamentField("Material", "Material", FirmamentSchemaValueKind.ConstructReference)]+public static class WireRouteSemanticDeclaration { }++[FirmamentConstruct("WireFollow", "Follow", Context = "WireRoute Path", Description = "Lock a finite Concept Line3 interval; the first lane derives a circular entry and requires a tangent exit.")]+[FirmamentField("Curve", "Curve", FirmamentSchemaValueKind.ConstructReference, Required = true)]+[FirmamentField("From", "From", FirmamentSchemaValueKind.Length, Required = true)]+[FirmamentField("Distance", "Distance", FirmamentSchemaValueKind.Length, Required = true)]+[FirmamentField("Direction", "Direction", FirmamentSchemaValueKind.Choice, Choices = ["Forward", "Reverse"])]+public static class WireFollowSemanticDeclaration { }++[FirmamentConstruct("Section", "Section", Context = "SectionChain or keyed Pattern", Description = "A closed profile at a Concept frame, with stable span correspondence.")]+[FirmamentField("Frame", "Frame", FirmamentSchemaValueKind.ConstructReference, Required = true)]+[FirmamentField("Profile", "Profile", FirmamentSchemaValueKind.ConstructReference, Required = true)]+[FirmamentField("Seam", "Seam", FirmamentSchemaValueKind.ConstructReference, Description = "Optional explicit first span; omission uses the first authored span.")]+public static class SectionSemanticDeclaration { }++[FirmamentConstruct("ConceptPoints", "Points", Context = "Concept Struct", Description = "Finite keyed Point2 scaffolding from Linear, Series, or explicit Stations.")]+[FirmamentField("Keys", "Keys", FirmamentSchemaValueKind.Vector)]+public static class ConceptPointsSemanticDeclaration { }++[FirmamentConstruct("PointLinear", "Linear", Context = "Concept Points", Description = "Use Start and Step with Keys, or Start and Direction with explicit keyed Stations.")]+[FirmamentField("Start", "Start", FirmamentSchemaValueKind.Point, Required = true)]+[FirmamentField("Step", "Step", FirmamentSchemaValueKind.Vector)]+[FirmamentField("Direction", "Direction", FirmamentSchemaValueKind.Vector)]+public static class PointLinearSemanticDeclaration { }++[FirmamentConstruct("PointSeries", "Series", Context = "Concept Points", Description = "A bounded compile-time function-driven sequence; no runtime or Comptime keyword.")]+[FirmamentField("Index", "Index", FirmamentSchemaValueKind.String, Required = true)]+[FirmamentField("First", "First", FirmamentSchemaValueKind.Scalar, Required = true)]+[FirmamentField("Count", "Count", FirmamentSchemaValueKind.Scalar, Required = true)]+[FirmamentField("KeyPrefix", "KeyPrefix", FirmamentSchemaValueKind.String, Required = true)]+[FirmamentField("Position", "Position", FirmamentSchemaValueKind.Point, Required = true)]+public static class PointSeriesSemanticDeclaration { }diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.csindex 5f41d4bf..4ee44f81 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs@@ -26,6 +26,7 @@ public sealed record ConceptIrVector3(double X, double Y, double Z);[JsonDerivedType(typeof(ConceptIrRegion2Value), "Region2")][JsonDerivedType(typeof(ConceptIrPoint3Value), "Point3")][JsonDerivedType(typeof(ConceptIrPointSetValue), "PointSet")]+[JsonDerivedType(typeof(ConceptIrKeyedPointSetValue), "KeyedPointSet")][JsonDerivedType(typeof(ConceptIrLengthValue), "Length")][JsonDerivedType(typeof(ConceptIrAngleValue), "Angle")][JsonDerivedType(typeof(ConceptIrBoolValue), "Bool")]@@ -65,6 +66,13 @@ public sealed record ConceptIrPoint3Value(string StableId, ConceptIrPoint3 Pointpublic sealed record ConceptIrPointSetValue(string StableId, IReadOnlyList<ConceptIrPoint3Value> Points, string Provenance): ConceptIrValue(StableId, ConceptIrValueKind.PointSet, Provenance);+/// <summary>Finite local points; ElementType preserves dimensionality without an implicit 2D-to-3D lift.</summary>+public sealed record ConceptIrKeyedPointValue(string StableId, string Key, int Ordinal, string ElementType,+ IReadOnlyList<double> Coordinates, string Provenance);+public sealed record ConceptIrKeyedPointSetValue(string StableId, string Name, string ElementType,+ IReadOnlyList<ConceptIrKeyedPointValue> Points, string Recipe, string Provenance)+ : ConceptIrValue(StableId, ConceptIrValueKind.PointSet, Provenance);+public enum ConceptIrSemanticPhase { ConceptIr, FeatureAir }public enum ConceptIrMaterializationCategory { CompileTimeValue, MaterializedSemanticReference }diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPointAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPointAuthoring.csnew file mode 100644index 00000000..96e16b06--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPointAuthoring.cs@@ -0,0 +1,303 @@+using System.Globalization;+using System.Text.RegularExpressions;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++/// <summary>Finite Concept point recipes. Checked geometry projects to existing keyed Sets;+/// the ordinary Pattern expander remains the only occurrence expansion authority.</summary>+internal static class ConceptPointAuthoring+{+ internal const string Prefix = "firmament-concept-points-";+ internal sealed record Result(string Source, IReadOnlyList<ConceptIrKeyedPointSetValue> Points, MathCatalog Math);+ private sealed record Function(string Name, IReadOnlyList<(string Name, string Type)> Parameters, string ReturnType, string Body);++ internal sealed class MathCatalog+ {+ private int _remainingCalls;+ private readonly Dictionary<string, Function> _functions = new(StringComparer.Ordinal);+ internal string Parse(string source, List<string> diagnostics)+ {+ var changes = new List<(int Start, int Length)>();+ if (Regex.IsMatch(source, @"\bComptime\s+Function\b")) diagnostics.Add(Prefix+"function-syntax-invalid");+ foreach (Match header in Regex.Matches(source, @"\bFunction\s+(?<name>\w+)\s*\((?<args>[^()]*)\)\s*->\s*(?<type>\w+)\s*=\s*(?<body>[^;{}]+);"))+ {+ var args = header.Groups["args"].Value.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);+ var parameters = new List<(string Name,string Type)>();+ foreach (var argument in args)+ {+ var match = Regex.Match(argument,@"^(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>Int|Float|Length|Angle)$");+ if (!match.Success) diagnostics.Add(Prefix+"function-parameter-invalid");+ else parameters.Add((match.Groups["name"].Value,match.Groups["type"].Value));+ }+ var name = header.Groups["name"].Value;+ var type = header.Groups["type"].Value;+ if (!Regex.IsMatch(name, @"^[A-Za-z_]\w*$") || name == "Pow" || !Allowed(type) || parameters.Count > 16 || parameters.Select(p=>p.Name).Distinct().Count()!=parameters.Count+ || !_functions.TryAdd(name,new(name,parameters,type,header.Groups["body"].Value)))+ diagnostics.Add(Prefix+"function-definition-invalid:"+name);+ changes.Add((header.Index,header.Length));+ }+ if (_functions.Count > 128) { diagnostics.Add(Prefix+"function-limit"); return source; }+ var checkedFunctions = new HashSet<string>(StringComparer.Ordinal);+ foreach (var function in _functions.Values)+ {+ var variables=function.Parameters.ToDictionary(p=>p.Name,p=>(1d,Unit(p.Type)),StringComparer.Ordinal);+ var dependencies = Regex.Matches(function.Body,@"\b(?<name>[A-Za-z_]\w*)\s*\(").Select(m=>m.Groups["name"].Value).ToArray();+ if (!FirmamentV2FeatureExpansion.TryEvaluateScalar(function.Body,variables,(name,args)=>Call(name,args,true,[]),true,out _,out var unit)+ || unit!=Unit(function.ReturnType)) diagnostics.Add(Prefix+"function-body-invalid:"+function.Name);+ bool Cycle(string name,HashSet<string> visiting)+ {+ if (!_functions.TryGetValue(name,out var f) || checkedFunctions.Contains(name)) return false;+ if (!visiting.Add(name)) return true;+ var cycle=Regex.Matches(f.Body,@"\b(?<name>[A-Za-z_]\w*)\s*\(").Any(m=>Cycle(m.Groups["name"].Value,visiting));+ visiting.Remove(name);+ if (!cycle) checkedFunctions.Add(name);+ return cycle;+ }+ if (dependencies.Any(d=>Cycle(d,new HashSet<string>(StringComparer.Ordinal)))) diagnostics.Add(Prefix+"function-cycle:"+function.Name);+ }+ foreach (var change in changes.OrderByDescending(c=>c.Start)) source=source.Remove(change.Start,change.Length);+ if (Regex.IsMatch(source,@"\b(?:Comptime\s+)?Function\b")) diagnostics.Add(Prefix+"function-syntax-invalid");+ return source;+ }++ private (double Value,string Unit) Call(string name,IReadOnlyList<(double Value,string Unit)> args,bool typeOnly,HashSet<string> active)+ {+ if (!typeOnly && --_remainingCalls < 0) throw new FormatException();+ if (!_functions.TryGetValue(name,out var function) || args.Count!=function.Parameters.Count || active.Count>=32 || !active.Add(name)) throw new FormatException();+ try+ {+ for(var i=0;i<args.Count;i++)+ if(args[i].Unit!=Unit(function.Parameters[i].Type) || (!typeOnly && function.Parameters[i].Type=="Int" && !ValidInt(args[i].Value))) throw new FormatException();+ if(typeOnly) return (1,Unit(function.ReturnType));+ var variables=function.Parameters.Select((p,i)=>(p.Name,args[i])).ToDictionary(p=>p.Name,p=>p.Item2,StringComparer.Ordinal);+ if(!FirmamentV2FeatureExpansion.TryEvaluateScalar(function.Body,variables,(n,a)=>Call(n,a,false,active),false,out var value,out var unit)+ || unit!=Unit(function.ReturnType) || (function.ReturnType=="Int" && !ValidInt(value))) throw new FormatException();+ return (value,unit);+ }+ finally { active.Remove(name); }+ }++ internal bool Evaluate(string expression,IReadOnlyDictionary<string,(double Value,string Unit)> variables,out double value,out string unit)+ {+ _remainingCalls = 10000;+ return FirmamentV2FeatureExpansion.TryEvaluateScalar(expression,variables,(n,a)=>Call(n,a,false,[]),false,out value,out unit);+ }++ // Only scalar consumer fields are normalized. No source code is executed.+ internal string Normalize(string source,List<string> diagnostics)+ {+ foreach(var name in _functions.Keys)+ {+ var offset=0;+ while(offset<source.Length)+ {+ var match=Regex.Match(source[offset..],$@"\b{Regex.Escape(name)}\s*\(");+ if(!match.Success) break;+ var start=offset+match.Index; var open=source.IndexOf('(',start); var close=Matching(source,open,'(',')');+ if(close<0) { diagnostics.Add(Prefix+"function-call-invalid:"+name); break; }+ var expression=source[start..(close+1)];+ if(!Evaluate(expression,new Dictionary<string,(double,string)>(),out var value,out var unit))+ { diagnostics.Add(Prefix+"function-call-invalid:"+expression); offset=close+1; continue; }+ var literal=Literal(value,unit);+ source=source.Remove(start,close-start+1).Insert(start,literal); offset=start+literal.Length;+ }+ }+ return source;+ }+ private static bool ValidInt(double value) => Math.Abs(value) <= 9007199254740991d && value == Math.Truncate(value);+ private static bool Allowed(string type)=>type is "Int" or "Float" or "Length" or "Angle";+ private static string Unit(string type)=>type switch { "Length"=>"mm","Angle"=>"deg",_=>"" };+ }++ internal static Result? Expand(string source,List<string> diagnostics)+ {+ var math=new MathCatalog(); source=math.Parse(source,diagnostics);+ var collections=new List<ConceptIrKeyedPointSetValue>();+ var changes=new List<(int Start,int Length,string Text)>();+ var sets=new Dictionary<string,string>(StringComparer.Ordinal);+ var totalPoints = 0;+ foreach(Match owner in Regex.Matches(source,@"\bConcept\s+Struct\s+(?<name>[A-Za-z_]\w*)\s*\{"))+ {+ var open=source.IndexOf('{',owner.Index); var close=Matching(source,open,'{','}');+ if(close<0) { diagnostics.Add(Prefix+"unclosed"); continue; }+ var body=source[(open+1)..close];+ if(!Regex.IsMatch(body,@"\bPoints\s*<")) continue;+ var generated=new List<string>(); var remaining=body;+ foreach(Match header in Regex.Matches(body,@"\bPoints\s*<\s*(?<type>Point2|Point3)\s*>\s+(?<name>[A-Za-z_]\w*)\s*\{"))+ {+ var end=Matching(body,body.IndexOf('{',header.Index),'{','}');+ if(end<0) { diagnostics.Add(Prefix+"unclosed"); continue; }+ if (totalPoints > 4096) return null;+ var fields=body[(header.Index+header.Length)..end];+ var identity=owner.Groups["name"].Value+"."+header.Groups["name"].Value;+ var setName=SetName(identity);+ if(!sets.TryAdd(identity,setName)) { diagnostics.Add(Prefix+"duplicate:"+identity); continue; }+ var type=header.Groups["type"].Value; var count=type=="Point2"?2:3;+ var points=new List<ConceptIrKeyedPointValue>();+ void Error(string reason)=>diagnostics.Add(Prefix+reason+":"+identity);+ var recipe=Regex.Match(fields,@"\b(?<kind>Linear|Series)\s*\{");+ if(recipe.Success)+ {+ var finish=Matching(fields,fields.IndexOf('{',recipe.Index),'{','}');+ if(finish<0) { Error("recipe-unclosed"); continue; }+ var recipeBody=fields[(recipe.Index+recipe.Length)..finish];+ string? stationsBody = null;+ var stationHeaders = Regex.Matches(recipeBody, @"\bStations\s*\{");+ if (stationHeaders.Count > 0)+ {+ if (stationHeaders.Count != 1 || recipe.Groups["kind"].Value != "Linear") { Error("stations-fields-invalid"); continue; }+ var stationHeader = stationHeaders[0];+ var stationEnd = Matching(recipeBody, stationHeader.Index + stationHeader.Length - 1, '{', '}');+ if (stationEnd < 0) { Error("stations-unclosed"); continue; }+ stationsBody = recipeBody[(stationHeader.Index + stationHeader.Length)..stationEnd];+ recipeBody = recipeBody.Remove(stationHeader.Index, stationEnd - stationHeader.Index + 1);+ }+ var entries=Fields(recipeBody,Error);+ var outer=fields.Remove(recipe.Index,finish-recipe.Index+1);+ if(recipe.Groups["kind"].Value=="Linear")+ {+ var outerFields=Fields(outer,Error);+ if (stationsBody is not null)+ {+ if (outerFields.Count != 0 || entries.Count != 2 || !entries.ContainsKey("Start") || !entries.ContainsKey("Direction"))+ { Error("stations-fields-invalid"); continue; }+ var start = Point(entries["Start"], type, math, new Dictionary<string,(double,string)>(), Error);+ var directionText = entries["Direction"].Trim();+ if (start is null || !Regex.IsMatch(directionText, @"^\[[^\[\]]*\]$")) { Error("stations-direction-invalid"); continue; }+ var components = Components(directionText[1..^1]);+ var direction = new double[count];+ if (components.Count != count) { Error("stations-direction-invalid"); continue; }+ var validDirection = true;+ for (var i = 0; i < count; i++)+ if (!math.Evaluate(components[i], new Dictionary<string,(double,string)>(), out direction[i], out var unit)+ || unit != "" || !double.IsFinite(direction[i])) validDirection = false;+ var scale = direction.Max(v => Math.Abs(v));+ if (!validDirection || scale == 0) { Error("stations-direction-invalid"); continue; }+ // Scale first so even finite very large/small vectors normalize safely.+ var norm = Math.Sqrt(direction.Sum(v => (v / scale) * (v / scale)));+ direction = direction.Select(v => (v / scale) / norm).ToArray();+ var stations = Fields(stationsBody, Error);+ if (stations.Count is < 1 or > 1024) { Error("point-limit"); continue; }+ foreach (var station in stations)+ {+ if (!math.Evaluate(station.Value, new Dictionary<string,(double,string)>(), out var distance, out var unit)+ || unit != "mm" || !double.IsFinite(distance)) { Error("station-distance-invalid"); continue; }+ Add(station.Key, points.Count, start.Zip(direction, (s, d) => s + d * distance).ToArray());+ }+ // Explicit station form is mutually exclusive with Keys/Step.+ // The same keyed point IR and Pattern executor own both forms.+ }+ else+ {+ if(outerFields.Count!=1 || !outerFields.TryGetValue("Keys",out var keysText) || entries.Count!=2 || !entries.ContainsKey("Start") || !entries.ContainsKey("Step"))+ { Error("linear-fields-invalid"); continue; }+ if (!Regex.IsMatch(keysText, @"^\s*\[[^\[\]]*\]\s*$")) { Error("keys-invalid"); continue; }+ var keys=keysText.Trim().Trim('[',']').Split(',',StringSplitOptions.TrimEntries|StringSplitOptions.RemoveEmptyEntries);+ var start=Point(entries["Start"],type,math,new Dictionary<string,(double,string)>(),Error); var step=Point(entries["Step"],type,math,new Dictionary<string,(double,string)>(),Error);+ if(start is null || step is null || keys.Length is <1 or >1024 || keys.Distinct().Count()!=keys.Length || keys.Any(k=>!Regex.IsMatch(k,@"^[A-Za-z_]\w*$")) || step.All(v=>v==0))+ { Error("linear-invalid"); continue; }+ for(var i=0;i<keys.Length;i++) Add(keys[i],i,start.Zip(step,(s,d)=>s+i*d).ToArray());+ }+ }+ else+ {+ if(!string.IsNullOrWhiteSpace(outer.Replace(";","")) || entries.Count!=5 || new[]{"Index","First","Count","KeyPrefix","Position"}.Any(k=>!entries.ContainsKey(k)))+ { Error("series-fields-invalid"); continue; }+ if(!Regex.IsMatch(entries["Index"],@"^[A-Za-z_]\w*$") || !Regex.IsMatch(entries["KeyPrefix"],@"^[A-Za-z_]\w*$")+ || !int.TryParse(entries["First"],out var first) || !int.TryParse(entries["Count"],out var amount) || first<0 || amount is <1 or >1024 || (long)first+amount>int.MaxValue)+ { Error("series-bounds-invalid"); continue; }+ for(var i=0;i<amount;i++)+ {+ var n=first+i;+ var point=Point(entries["Position"],type,math,new Dictionary<string,(double,string)>{{entries["Index"],(n,"")}},Error);+ if(point is not null) Add(entries["KeyPrefix"]+n.ToString(CultureInfo.InvariantCulture),i,point);+ }+ }+ }+ else+ {+ var manual=Fields(fields,Error);+ if(manual.Count is <1 or >1024) Error("point-limit");+ foreach(var entry in manual)+ { var point=Point(entry.Value,type,math,new Dictionary<string,(double,string)>(),Error); if(point is not null) Add(entry.Key,points.Count,point); }+ }+ void Add(string key,int ordinal,double[] point)+ {+ if (++totalPoints > 4096) { if (totalPoints == 4097) Error("total-limit"); return; }+ if(point.Length!=count || point.Any(v=>!double.IsFinite(v))) { Error("nonfinite"); return; }+ points.Add(new("concept:"+identity+"."+key,key,ordinal,type,point,identity+"."+key));+ }+ collections.Add(new("concept:"+identity,identity,type,points,body[header.Index..(end+1)],identity));+ generated.Add($"Static {setName}: Set<{type}> {{\n"+string.Join("\n",points.Select(p=>$"{p.Key} => {type}({string.Join(",",p.Coordinates.Select(v=>Literal(v,"mm")))})"))+"\n}");+ remaining=remaining.Replace(body[header.Index..(end+1)],"",StringComparison.Ordinal);+ }+ if (Regex.IsMatch(remaining, @"\bPoints\s*<")) diagnostics.Add(Prefix+"collection-syntax-invalid");+ // Preserve other Concept members for their existing owner; erase an empty container.+ var retained=string.IsNullOrWhiteSpace(remaining.Replace(";",""))?"":$"Concept Struct {owner.Groups["name"].Value} {{ {remaining} }}";+ changes.Add((owner.Index,close-owner.Index+1,retained+"\n"+string.Join("\n",generated)));+ }+ if(collections.Sum(c=>c.Points.Count)>4096) diagnostics.Add(Prefix+"total-limit");+ foreach(var change in changes.OrderByDescending(c=>c.Start)) source=source.Remove(change.Start,change.Length).Insert(change.Start,change.Text);+ foreach(var collection in collections)+ {+ foreach(var point in collection.Points)+ {+ var path=collection.Name+"."+point.Key;+ if (point.ElementType == "Point2" && Regex.IsMatch(source,$@"\b{Regex.Escape(path)}(?:\.Position)?\.Z\b")) diagnostics.Add(Prefix+"point-dimension-invalid:"+path);+ for(var i=0;i<point.Coordinates.Count;i++) source=Regex.Replace(source,$@"\b{Regex.Escape(path)}(?:\.Position)?\.{"XYZ"[i]}\b",Literal(point.Coordinates[i],"mm"));+ source=Regex.Replace(source,$@"\b{Regex.Escape(path)}(?:\.Position)?\b",$"{point.ElementType}({string.Join(",",point.Coordinates.Select(v=>Literal(v,"mm")))})");+ }+ source=Regex.Replace(source,$@"\bOver\s+{Regex.Escape(collection.Name)}\b","Over "+sets[collection.Name]);+ if (Regex.IsMatch(source,$@"\b{Regex.Escape(collection.Name)}\.")) diagnostics.Add(Prefix+"point-member-unresolved:"+collection.Name);+ }+ return diagnostics.Any(d => d.StartsWith(Prefix, StringComparison.Ordinal)) ? null : new(source,collections,math);+ }++ private static Dictionary<string,string> Fields(string body,Action<string> error)+ {+ var result=new Dictionary<string,string>(StringComparer.Ordinal);+ foreach(var field in body.Split(';',StringSplitOptions.TrimEntries|StringSplitOptions.RemoveEmptyEntries))+ { var split=field.Split(':',2,StringSplitOptions.TrimEntries); if(split.Length!=2 || !Regex.IsMatch(split[0],@"^[A-Za-z_]\w*$") || !result.TryAdd(split[0],split[1])) error("field-invalid"); }+ return result;+ }+ private static double[]? Point(string text,string type,MathCatalog math,IReadOnlyDictionary<string,(double Value,string Unit)> variables,Action<string> error)+ {+ text=text.Trim();+ if(text.StartsWith(type+"(",StringComparison.Ordinal) && text.EndsWith(')')) text=text[(type.Length+1)..^1];+ else if(text.StartsWith('[') && text.EndsWith(']')) text=text[1..^1];+ else { error("point-type-invalid"); return null; }+ var parts=Components(text); var expected=type=="Point2"?2:3;+ if(parts.Count!=expected) { error("point-arity-invalid"); return null; }+ var result=new double[expected];+ for(var i=0;i<expected;i++) if(!math.Evaluate(parts[i],variables,out result[i],out var unit) || unit!="mm") { error("point-expression-invalid");return null; }+ return result;+ }+ internal static IReadOnlyList<string> Components(string text)+ {+ var parts=new List<string>(); var start=0; var depth=0;+ for(var i=0;i<text.Length;i++) { if(text[i]=='(') depth++; if(text[i]==')') depth--; if(text[i]==',' && depth==0) { parts.Add(text[start..i]);start=i+1; } }+ parts.Add(text[start..]); return parts;+ }+ internal static string SetName(string identity) => "__ConceptPoints_" + identity.Split('.').Aggregate("", (name, part) => name + part.Length.ToString(CultureInfo.InvariantCulture) + "_" + part);+ internal static string Literal(double value, string unit)+ {+ // Existing point grammars consume plain decimals. Expand round-trip exponent+ // spelling without rounding: a tiny Float may later be multiplied by a large Length.+ var text = value.ToString("R", CultureInfo.InvariantCulture);+ var exponentAt = text.IndexOf('E');+ if (exponentAt < 0) return text + unit;+ var mantissa = text[..exponentAt];+ var sign = mantissa.StartsWith('-') ? "-" : "";+ mantissa = mantissa.TrimStart('-');+ var decimalAt = mantissa.IndexOf('.');+ if (decimalAt < 0) decimalAt = mantissa.Length;+ decimalAt += int.Parse(text[(exponentAt + 1)..], CultureInfo.InvariantCulture);+ var digits = mantissa.Replace(".", "", StringComparison.Ordinal);+ var plain = decimalAt <= 0 ? "0." + new string('0', -decimalAt) + digits+ : decimalAt >= digits.Length ? digits + new string('0', decimalAt - digits.Length)+ : digits.Insert(decimalAt, ".");+ return sign + plain + unit;+ }+ private static int Matching(string text,int open,char first,char last)+ { var depth=0; for(var i=open;i<text.Length;i++) { if(text[i]==first) depth++;else if(text[i]==last && --depth==0) return i; }return -1; }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.csindex 334b3f67..4955731e 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs@@ -1,4 +1,5 @@using System.Text;+using Aetheris.Kernel.Firmament.Assembly;namespace Aetheris.Kernel.Firmament.FirmamentV2;@@ -17,8 +18,9 @@ public sealed record FirmamentLanguageFormat(string Document, string Revision, s/// </summary>public static class FirmamentLanguageAnalysisService{- private sealed record Lexeme(int Start, int Length, string Text, string Shape);- private static readonly HashSet<string> Keywords = ["Model", "Units", "Modify", "WireForm", "Construction", "Use", "schema", "Let", "Static", "With", "Expose"];+ internal sealed record Lexeme(int Start, int Length, string Text, string Shape);+ private static readonly HashSet<string> Keywords = ["Model", "Units", "Modify", "WireForm", "Construction", "Use", "schema", "Let", "Static", "With", "with", "Expose", "Include", "Subassembly", "Assembly", "Part", "Template", "Function", "Record", "Pattern", "Over", "Using", "Output"];+ private static readonly HashSet<string> DeclarationKinds = ["Model", "Struct", "Subassembly", "Assembly", "Template", "Profile", "Static", "Record", "Function", "Pattern", "Section", "SectionChain", "FrameTransform", "Points"];private static readonly HashSet<string> Types = ["Length", "Angle", "Float", "Int", "Bool", "Box3", "Plane", "Point2", "Point3"];private static readonly HashSet<string> Choices = FirmamentSemanticSchemas.All.SelectMany(construct => construct.Fields).SelectMany(field => field.Choices).ToHashSet(StringComparer.Ordinal);@@ -26,9 +28,30 @@ public static class FirmamentLanguageAnalysisServicepublic static FirmamentLanguageAnalysis Analyze(string source, string document, string revision){ArgumentNullException.ThrowIfNull(source);- var lexemes = Lex(source);+ var lexemes = Lex(FirmamentSourceSpelling.Normalize(source));var tokens = lexemes.Select((lexeme, index) => new FirmamentLanguageToken(lexeme.Start, lexeme.Length, Classify(lexemes, index))).ToArray();+ // Imported authoring modules need project context. Do not feed them into+ // the unrelated concrete-part parser and manufacture syntax errors.+ if (lexemes.Any(t => t.Text == "Include" && t.Shape == "identifier"))+ return new(document, revision, tokens, [new("information", "firmament-language-project-context-required", "Imported declarations require project-aware analysis.", 0, 0)]);+ if (HasAssemblyRoot(source))+ {+ var assembly = new AssemblyM0Parser().Parse(source, document);+ return new(document, revision, tokens, assembly.Diagnostics.Select(d => new FirmamentLanguageDiagnostic(d.Severity == AssemblyDiagnosticSeverity.Error ? "error" : "information", d.Code, d.Message, 0, 0)).ToArray());+ }+ if (SectionChainAuthoringParser.IsSectionChainSource(source))+ {+ var section = SectionChainAuthoringParser.Compile(source, materialize: false);+ return new(document, revision, tokens, section.Diagnostics.Select(d => LocateDiagnostic(source, lexemes, d)).ToArray());+ }+ if (Materializer.WireRouteAuthoring.IsSource(source) && !lexemes.Any(t => t.Shape == "identifier" && t.Text == "Template"))+ {+ var route = Materializer.WireFormAuthoring.Parse(source);+ return new(document, revision, tokens, route.Diagnostics.Select(d => new FirmamentLanguageDiagnostic("error", d.Source, d.Message, 0, 0)).ToArray());+ }+ if (lexemes.Any(t => t.Shape == "identifier" && t.Text is "Template" or "Subassembly" or "Appearance" or "Material"))+ return new(document, revision, tokens, [new("information", "firmament-language-project-context-required", "Declaration modules are validated in their consuming project.", 0, 0)]);var parse = FirmamentV2Parser.Parse(source);var failures = parse.Diagnostics.Where(item => FirmamentV2Parser.IsFatalDiagnosticCode(item) ||item == "firmament-v2-parse-failed").Distinct(StringComparer.Ordinal).ToArray();@@ -39,7 +62,7 @@ public static class FirmamentLanguageAnalysisServicepublic static FirmamentLanguageHover? Hover(string source, string document, string revision, int offset){- var lexemes = Lex(source);+ var lexemes = Lex(FirmamentSourceSpelling.Normalize(source));var index = lexemes.FindIndex(item => item.Start <= offset && offset <= item.Start + item.Length && item.Shape == "identifier");if (index < 0) return null;var token = lexemes[index];@@ -55,29 +78,87 @@ public static class FirmamentLanguageAnalysisServicepublic static FirmamentLanguageLocation? Definition(string source, string document, int offset){- var tokens = Lex(source);+ var tokens = Lex(FirmamentSourceSpelling.Normalize(source));var selected = tokens.FirstOrDefault(item => item.Shape == "identifier" && item.Start <= offset && offset <= item.Start + item.Length);if (selected is null) return null;- var declarations = tokens.Select((token, index) => (token, index))- .Where(pair => pair.index > 0 && pair.token.Text == selected.Text && pair.token.Shape == "identifier" &&- FirmamentSemanticSchemas.All.Any(schema => schema.Name == tokens[pair.index - 1].Text) &&- pair.index + 1 < tokens.Count && tokens[pair.index + 1].Text == "{")- .Select(pair => pair.token).ToArray();+ var declarations = Declarations(tokens, selected.Text, ReferenceKind(tokens, selected)).ToArray();return declarations.Length == 1 ? new(document, declarations[0].Start, declarations[0].Length) : null;}+ /// <summary>Lexical source navigation only; never grants access to a private placement port.</summary>+ public static FirmamentLanguageLocation? Definition(FirmamentProjectSnapshot project, string document, int offset)+ {+ if (!project.TryResolve(document, out var source)) return null;+ var local = Definition(source, document, offset);+ if (local is not null) return local;+ var tokens = Lex(FirmamentSourceSpelling.Normalize(source));+ var selected = tokens.FirstOrDefault(t => t.Shape == "identifier" && t.Start <= offset && offset < t.Start + t.Length);+ if (selected is null) return null;+ var matches = project.Documents.SelectMany(d => Declarations(Lex(d.Value), selected.Text, ReferenceKind(tokens, selected))+ .Select(t => new FirmamentLanguageLocation(d.Key, t.Start, t.Length))).ToArray();+ return matches.Length == 1 ? matches[0] : null;+ }++ public static FirmamentLanguageAnalysis Analyze(FirmamentProjectSnapshot project, string document, string revision)+ {+ if (!project.TryResolve(document, out var source)) throw new ArgumentException("Document is absent from the snapshot.", nameof(document));+ var tokens = Lex(FirmamentSourceSpelling.Normalize(source));+ var parsed = new AssemblyM0Parser().ParseProject(project);+ return new(document, revision, tokens.Select((t, i) => new FirmamentLanguageToken(t.Start, t.Length, Classify(tokens, i))).ToArray(),+ parsed.Diagnostics.Select(d => new FirmamentLanguageDiagnostic(d.Severity == AssemblyDiagnosticSeverity.Error ? "error" : "information", d.Code, d.Message, 0, 0)).ToArray());+ }++ public static bool HasAssemblyRoot(string source)+ {+ var tokens = Lex(source).Where(t => t.Shape != "comment").ToArray();+ var depth = 0;+ for (var i = 0; i + 1 < tokens.Length; i++)+ {+ if (tokens[i].Text == "{") depth++;+ else if (tokens[i].Text == "}") depth--;+ if (depth == 0 && tokens[i].Text == "<" && tokens[i + 1].Text == "Assembly") return true;+ if (depth == 0 && tokens[i].Text == "Assembly" && tokens[i + 1].Shape == "identifier" && (i == 0 || tokens[i - 1].Text != "/")) return true;+ }+ return false;+ }++ private static string? ReferenceKind(IReadOnlyList<Lexeme> tokens, Lexeme selected)+ {+ var at = tokens.ToList().FindIndex(t => t.Start == selected.Start);+ return at >= 2 && tokens[at - 1].Text == ":" && tokens[at - 2].Text is "Material" or "Appearance" or "Profile"+ ? tokens[at - 2].Text : null;+ }++ private static IEnumerable<Lexeme> Declarations(IReadOnlyList<Lexeme> tokens, string name, string? kind = null)+ {+ for (var i = 1; i + 1 < tokens.Count; i++)+ {+ if (tokens[i].Shape != "identifier" || tokens[i].Text != name) continue;+ var previous = i - 1;+ if (tokens[previous].Text == ">")+ {+ while (previous >= 0 && tokens[previous].Text != "<") previous--;+ previous--;+ }+ if (previous < 0 || !(DeclarationKinds.Contains(tokens[previous].Text) || FirmamentSemanticSchemas.All.Any(s => s.Name == tokens[previous].Text))) continue;+ if (kind is not null && tokens[previous].Text != kind) continue;+ if (tokens[i + 1].Text is "{" or "=" or ":" or "(" or "<") yield return tokens[i];+ }+ }+public static FirmamentLanguageFormat Format(string source, string document, string revision){if (!FirmamentV2Parser.Parse(source).IsSuccess)throw new InvalidOperationException("Format Document requires valid Firmament source. Fix syntax errors first.");- var lexemes = Lex(source);+ var preferred = FirmamentSourceSpelling.Prefer(source);+ var lexemes = Lex(preferred);var output = new StringBuilder(source.Length + 64);var indent = 0;var lineStart = true;Lexeme? previous = null;foreach (var token in lexemes){- var gap = previous is null ? string.Empty : source[(previous.Start + previous.Length)..token.Start];+ var gap = previous is null ? string.Empty : preferred[(previous.Start + previous.Length)..token.Start];if (token.Text == "}"){indent = Math.Max(0, indent - 1);@@ -96,6 +177,9 @@ public static class FirmamentLanguageAnalysisServiceprevious = token;}var formatted = output.ToString().TrimEnd() + "\n";+ if (!Lex(FirmamentSourceSpelling.Normalize(source)).Select(t => (t.Text, t.Shape))+ .SequenceEqual(Lex(FirmamentSourceSpelling.Normalize(formatted)).Select(t => (t.Text, t.Shape))))+ throw new InvalidOperationException("Canonical layout was refused because it changed source tokens.");if (!FirmamentV2Parser.Parse(formatted).IsSuccess)throw new InvalidOperationException("Canonical layout was refused because it changed parser admission.");return new(document, revision, formatted, formatted != source);@@ -106,6 +190,19 @@ public static class FirmamentLanguageAnalysisService}}+ /// <summary>+ /// Conservative project/module pass: only admitted vocabulary spellings change.+ /// Layout, literals, comments, and authored identities remain byte-for-byte intact.+ /// This is not standalone or project validation; use the consuming compiler for that.+ /// </summary>+ public static FirmamentLanguageFormat FormatConventions(string source, string document, string revision)+ {+ var text = FirmamentSourceSpelling.Prefer(source);+ if (FirmamentSourceSpelling.Normalize(text) != FirmamentSourceSpelling.Normalize(source))+ throw new InvalidOperationException("Convention formatting changed canonical source.");+ return new(document, revision, text, text != source);+ }+private static bool NeedsSpace(string? previous, string current){if (previous is null || previous is "(" or "[" or "<" or "." or "+" or "-") return false;@@ -139,7 +236,7 @@ public static class FirmamentLanguageAnalysisServicereturn new("error", code, diagnostic.Replace('-', ' '), start, length);}- private static List<Lexeme> Lex(string source)+ internal static List<Lexeme> Lex(string source){var result = new List<Lexeme>();for (var at = 0; at < source.Length;)@@ -153,13 +250,19 @@ public static class FirmamentLanguageAnalysisServicewhile (at < source.Length && source[at] != '\n') at++;shape = "comment";}+ else if (at + 1 < source.Length && source[at] == '/' && source[at + 1] == '*')+ {+ var end = source.IndexOf("*/", at + 2, StringComparison.Ordinal);+ at = end < 0 ? source.Length : end + 2;+ shape = "comment";+ }else if (source[at] == '"'){at++;while (at < source.Length){+ if (source[at] == '\\' && at + 1 < source.Length) { at += 2; continue; }if (source[at++] != '"') continue;- if (at >= 2 && source[at - 2] == '\\') continue;break;}shape = "string";diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.csindex b2dd0f45..11277fd9 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs@@ -18,6 +18,7 @@ public static class FirmamentLanguageService{ArgumentNullException.ThrowIfNull(source);if (offset < 0 || offset > source.Length) throw new ArgumentOutOfRangeException(nameof(offset));+ source = FirmamentSourceSpelling.Normalize(source);var prefixStart = offset;while (prefixStart > 0 && (char.IsLetterOrDigit(source[prefixStart - 1]) || source[prefixStart - 1] == '_')) prefixStart--;var prefix = source[prefixStart..offset];@@ -26,7 +27,13 @@ public static class FirmamentLanguageServiceIReadOnlyList<FirmamentAuthoringField> fields;string context;var interfaceFamily = ActiveFrameInterface(source, offset);- if (interfaceFamily is not null)+ var composition = ActiveCompositionConstruct(source, offset);+ if (composition is not null)+ {+ fields = FirmamentSchemaAuthoringFields.For(composition.Value.Name);+ context = composition.Value.Name;+ }+ else if (interfaceFamily is not null){fields = FirmamentSchemaAuthoringFields.For($"Interface<{interfaceFamily}>");context = $"Interface<{interfaceFamily}>";@@ -59,7 +66,7 @@ public static class FirmamentLanguageService|| beforePrefix.EndsWith("Interface<", StringComparison.Ordinal)&& item.Name.StartsWith("Interface<" + prefix, StringComparison.OrdinalIgnoreCase)) &&(!inModify || item.Context?.StartsWith("Modify", StringComparison.Ordinal) == true))- .Select(item => new FirmamentLanguageEntry(item.Id.Value, item.Name, item.Context ?? string.Empty, item.Entry!)).ToArray();+ .Select(item => new FirmamentLanguageEntry(item.Id.Value, item.Name, item.Context ?? string.Empty, FirmamentSourceSpelling.Prefer(item.Entry!))).ToArray();return new(document, revision, entries.Length > 0 ? "ConstructEntry" : "Unsupported",prefixStart, prefix.Length, [], [], entries);}@@ -73,12 +80,18 @@ public static class FirmamentLanguageService}if (beforePrefix.Contains(':')) return new(document, revision, "Value", prefixStart, prefix.Length, [], []);- var open = source.LastIndexOf('{', Math.Max(0, offset - 1));+ var open = composition?.Open ?? source.LastIndexOf('{', Math.Max(0, offset - 1));var body = open >= 0 ? source[(open + 1)..offset] : string.Empty;var present = fields.Where(field => Regex.IsMatch(body, $@"\b{Regex.Escape(field.Name)}\s*:", RegexOptions.CultureInvariant)).Select(field => field.Name).ToHashSet(StringComparer.Ordinal);- var candidates = fields.Where(field => !present.Contains(field.Name) && field.Name.StartsWith(prefix, StringComparison.Ordinal)).ToArray();+ var candidates = fields.Where(field => !present.Contains(field.Name) && field.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToArray();var missing = fields.Where(field => field.Required && !present.Contains(field.Name)).Select(field => field.Name).ToList();+ if (context == "Interface<Fixed>" && present.Contains("Datum"))+ {+ candidates = candidates.Where(f => f.Name is not ("A" or "B")).ToArray();+ missing.RemoveAll(name => name is "A" or "B");+ if (!present.Contains("Members")) missing.Add("Members");+ }if (context == "Helix" && !present.Contains("Pitch") && !present.Contains("Height")) missing.Add("Pitch or Height");return new(document, revision, context, prefixStart, prefix.Length, candidates, missing);}@@ -113,4 +126,24 @@ public static class FirmamentLanguageService.Cast<Match>().LastOrDefault();return header is not null && !prefix[(header.Index + header.Length)..].Contains('}');}++ private static (string Name, int Open)? ActiveCompositionConstruct(string source, int offset)+ {+ // Ignore comments/strings and balance nested blocks in incomplete drafts.+ var prefix = Regex.Replace(source[..offset], @"//[^\r\n]*|/\*[\s\S]*?\*/|""(?:\\.|[^""\\])*""", m => new string(' ', m.Length));+ var names = "WireRoute|Follow|Section|Points|Linear|Series|Appearance|Material|Placement|FrameTransform";+ var matches = Regex.Matches(prefix, $@"\b(?<kind>{names})(?:\s*<[^>]+>)?(?:\s+[A-Za-z_]\w*)?\s*\{{");+ foreach (Match header in matches.Cast<Match>().Reverse())+ {+ var depth = 1;+ foreach (var c in prefix[(header.Index + header.Length)..])+ {+ if (c == '{') depth++;+ else if (c == '}') depth--;+ if (depth == 0) break;+ }+ if (depth > 0) return (header.Groups["kind"].Value, header.Index + header.Length - 1);+ }+ return null;+ }}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.csnew file mode 100644index 00000000..1b01fcba--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs@@ -0,0 +1,214 @@+using System.Text;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++/// <summary>+/// Bounded, case-only aliases at vocabulary positions. Schema identities and+/// authored symbols remain case-sensitive. Unknown scopes are left alone.+/// </summary>+public static class FirmamentSourceSpelling+{+ private sealed record Scope(string Owner, bool AuthoredData, int Parentheses, int Angles);+ private static readonly Dictionary<string, HashSet<string>> Fields = CreateFields();+ private static readonly Dictionary<string, string> Links = new(StringComparer.Ordinal)+ {+ ["Using"] = "using", ["On"] = "on", ["Over"] = "over",+ ["Include"] = "include", ["Expose"] = "expose", ["Bind"] = "bind"+ };++ public static string PreferredField(string name) => name.Length == 0 ? name : char.ToLowerInvariant(name[0]) + name[1..];+ public static string Normalize(string source) => Rewrite(source, preferred: false);+ public static string Prefer(string source) => Rewrite(source, preferred: true);++ private static string Rewrite(string source, bool preferred)+ {+ ArgumentNullException.ThrowIfNull(source);+ var tokens = FirmamentLanguageAnalysisService.Lex(source).Where(t => t.Shape != "comment").ToArray();+ var output = new StringBuilder(source);+ var scopes = new Stack<Scope>();+ var parentheses = 0;+ var angles = 0;+ for (var i = 0; i < tokens.Length; i++)+ {+ var t = tokens[i];+ // Assembly's XML-shaped occurrence scopes are independent of braces.+ if (t.Text == "<" && i + 1 < tokens.Length && tokens[i + 1].Text is "Part" or "Assembly")+ {+ var kind = tokens[i + 1].Text;+ var depth = 1;+ var tagEnd = i + 1;+ while (++tagEnd < tokens.Length && depth > 0)+ {+ if (tokens[tagEnd].Text == "<") depth++;+ else if (tokens[tagEnd].Text == ">") depth--;+ }+ tagEnd--;+ // Do not rewrite named generic arguments inside the tag.+ i = tagEnd;+ scopes.Push(new(kind, false, parentheses, angles));+ continue;+ }+ if (t.Text == "<" && i + 2 < tokens.Length && tokens[i + 1].Text == "/" && tokens[i + 2].Text is "Part" or "Assembly")+ {+ if (scopes.Count > 0) scopes.Pop();+ while (i < tokens.Length && tokens[i].Text != ">") i++;+ continue;+ }+ if (t.Text == "(") parentheses++;+ else if (t.Text == ")") parentheses--;+ else if (t.Text == "<") angles++;+ else if (t.Text == ">" && angles > 0) angles--;+ if (t.Text == "{")+ {+ var owner = BlockOwner(tokens, i);+ var authored = (scopes.TryPeek(out var parent) && parent.AuthoredData) || owner is "Record" or "Static" or "Table" or "Stations" or "Legacy";+ // Appearance overrides inherit the material owner's admitted fields.+ if (owner == "with" && scopes.TryPeek(out parent) && parent.Owner is "Part" or "Assembly") owner = "Material";+ // A bound route parameter name is authored; its site fields belong to Bind.+ if (!Fields.ContainsKey(owner) && scopes.TryPeek(out parent) && parent.Owner == "Bind") owner = "RouteSite";+ scopes.Push(new(owner, authored, parentheses, angles));+ continue;+ }+ if (t.Text == "}") { if (scopes.Count > 0) scopes.Pop(); continue; }+ if (t.Shape != "identifier" || scopes.Any(s => s.AuthoredData)) continue;+ var fieldPosition = i + 1 < tokens.Length && tokens[i + 1].Text == ":";+ string? canonical = null;+ if (fieldPosition && scopes.TryPeek(out var scope) && parentheses == scope.Parentheses && angles == scope.Angles+ && Fields.TryGetValue(scope.Owner, out var fields))+ canonical = fields.FirstOrDefault(f => t.Text == f || t.Text == PreferredField(f));+ else if (!fieldPosition && (i == 0 || tokens[i - 1].Text != "."))+ {+ // Positive linking positions only; never convert a value/reference.+ canonical = Links.FirstOrDefault(pair => (t.Text == pair.Key || t.Text == pair.Value) &&+ IsLink(tokens, i, pair.Key)).Key;+ }+ if (canonical is null) continue;+ var spelling = preferred ? Links.GetValueOrDefault(canonical) ?? PreferredField(canonical) : canonical;+ // All supported spelling aliases retain spans (important for diagnostics).+ if (spelling.Length != t.Length) throw new InvalidOperationException("Vocabulary alias changed a source span.");+ for (var c = 0; c < t.Length; c++) output[t.Start + c] = spelling[c];+ }+ return output.ToString();+ }++ private static bool IsLink(FirmamentLanguageAnalysisService.Lexeme[] tokens, int i, string word)+ {+ var next = i + 1 < tokens.Length ? tokens[i + 1] : null;+ if (word == "Include") return next?.Shape == "string";+ if (word is "Expose" or "Bind") return next?.Text == "{";+ if (next?.Shape != "identifier") return false;+ var start = i - 1;+ while (start >= 0 && tokens[start].Text is not ("{" or "}" or ";")) start--;+ var header = tokens[(start + 1)..i].Select(t => t.Text).ToArray();+ return word switch+ {+ "Using" => header.Contains("Profile"),+ "On" => header.Length >= 3 && header[^3] == "Concept" && header[^2] == "Struct",+ "Over" => header.Length >= 2 && header[^2] == "Pattern",+ _ => false+ };+ }++ private static string BlockOwner(FirmamentLanguageAnalysisService.Lexeme[] tokens, int open)+ {+ if (open == 0) return "";+ var boundary = open - 1;+ while (boundary >= 0 && tokens[boundary].Text is not ("{" or "}" or ";")) boundary--;+ var header = tokens[(boundary + 1)..open];+ // Historical lowercase documents have a distinct grammar (not merely+ // different casing). Keep their complete scopes with that owner.+ if (header.Any(t => t.Text is "model" or "solid" or "modify" or "feature")) return "Legacy";+ if (header.Any(t => t.Text == "Static")) return "Static";+ if (header.Any(t => t.Text == "Record")) return "Record";+ if (header.Any(t => t.Text is "Over" or "over") && header.Any(t => t.Text == "Pattern")) return "Pattern";+ if (header.Any(t => t.Text == "Mate")) return "Mate";+ if (tokens[open - 1].Text == ":") return open >= 2 ? CanonicalOwner(tokens[open - 2].Text) : "";+ var end = open - 1;+ if (end > 0 && tokens[end].Shape == "identifier" && tokens[end - 1].Text == ">")+ {+ var generic = end - 1;+ var depth = 1;+ while (generic > 0 && depth > 0)+ {+ generic--;+ if (tokens[generic].Text == ">") depth++;+ else if (tokens[generic].Text == "<") depth--;+ }+ if (depth == 0 && generic > 0 && tokens[generic - 1].Shape == "identifier")+ return CanonicalOwner(tokens[generic - 1].Text);+ // A bare Placement after an XML occurrence tag is not a generic declaration.+ }+ if (end > 0 && tokens[end].Shape == "identifier" && Fields.ContainsKey(tokens[end - 1].Text))+ return tokens[end - 1].Text; // named construct, even if its name resembles vocabulary+ var last = CanonicalOwner(tokens[end].Text);+ if (Fields.ContainsKey(last) && end > 0 && tokens[end - 1].Shape == "identifier" && tokens[end - 1].Text != "return")+ return tokens[end - 1].Text; // unknown owner with a vocabulary-shaped authored name+ if (Fields.ContainsKey(last) || last is "Record" or "Static" or "Table" or "Stations" or "with") return last;+ if (tokens[end].Shape == "identifier") end--; // authored name+ if (end >= 0 && tokens[end].Text == ">")+ {+ var depth = 1;+ while (end > 0 && depth > 0)+ {+ end--;+ if (tokens[end].Text == ">") depth++;+ else if (tokens[end].Text == "<") depth--;+ }+ end--;+ }+ var owner = end >= 0 ? CanonicalOwner(tokens[end].Text) : "";+ if (owner == "Pattern" && end > 0 && tokens[end - 1].Text == "Linear") return "Linear";+ if (owner == "Sites" && end > 0 && tokens[end - 1].Text == "Linear") return "Linear";+ // Static name: Type { ... } and Profile name using Layout { ... }.+ if (end >= 1 && tokens[end].Text == ":" && end >= 2 && tokens[end - 2].Text == "Static") return "Static";+ if (end >= 2 && tokens[end].Text is "Using" or "using" && tokens[end - 2].Text == "Profile") return "Profile";+ return owner;+ }++ private static string CanonicalOwner(string text) => Links.FirstOrDefault(p => p.Value == text).Key ??+ (text == "rotateLocal" ? "RotateLocal" : text);++ private static Dictionary<string, HashSet<string>> CreateFields()+ {+ var result = FirmamentSemanticSchemas.All.GroupBy(s => s.Name.Split('<')[0], StringComparer.Ordinal)+ .ToDictionary(g => g.Key, g => g.SelectMany(s => s.Fields).Select(f => f.Name).ToHashSet(StringComparer.Ordinal), StringComparer.Ordinal);+ void Add(string owners, string names)+ {+ foreach (var owner in owners.Split(' '))+ {+ if (!result.TryGetValue(owner, out var fields)) result[owner] = fields = new(StringComparer.Ordinal);+ fields.UnionWith(names.Split(' '));+ }+ }+ // Bounded owner vocabularies not yet projected through generated schema.+ Add("Model", "Units Material");+ Add("Assembly Subassembly", "Anchor Provenance");+ Add("Part Occurrence", "Material Appearance");+ Add("Plane DatumPlane", "Origin Normal Up From Offset RotateLocal Clocking");+ Add("DatumFrame", "On At X");+ Add("Point2 Point3", "Position");+ Add("Axis Axis2 Line3", "Origin Direction Start End Reference");+ Add("Circle2", "Center Radius");+ Add("Rect2 RoundedRect2 Oval2", "Center Size Radius");+ Add("Polygon2", "Vertices");+ Add("Curve2", "From On Scale Pivot Translate Rotate");+ Add("CubicBezier2", "From Control1 Control2 To");+ Add("Profile", "From");+ Add("Replace", "On Through Derivatives");+ Add("Path", "Start Heading");+ Add("Line", "Length To");+ Add("Extrude Base", "Profile From To Role");+ Add("Boss Pocket", "On Profile Height Depth");+ Add("Linear", "Source Direction Count Spacing Keys Start Step");+ Add("RotateLocal", "Axis Angle");+ Add("Mate", "Interface Member At Gap Clocking Orientation Support");+ Add("Note", "Target Text");+ Add("Appearance", "Color Metallic Roughness Opacity");+ Add("Material", "Identity Appearance");+ Add("Start End Corner RouteSite", "At On Radius");+ Add("SectionChain", "Continuity Start End");+ Add("Loft", "Sections Solid");+ Add("Continuity", "Order");+ return result;+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.csindex 461b05c1..ea5b4312 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs@@ -276,7 +276,7 @@ public sealed record FirmamentV2BossDecl(string Name, string Host, string On, stpublic sealed record FirmamentV2PocketDecl(string Name, string Host, string On, string Profile, double Depth, double HostThickness, double RemainingFloor, double MinimumFloorThickness, string MinimumFloorPolicySource, string StableId, FirmamentV2SourceSpan SourceSpan);public sealed record FirmamentV2SelectionDecl(string Name, string Target, string Source, string Requirement, FirmamentV2SourceSpan SourceSpan);/// <summary>Normalized, erased-before-materialization evidence for canonical static authoring.</summary>-public sealed record FirmamentV2StaticAuthoringDocument(IReadOnlyList<FirmamentV2RecordTypeDecl> RecordTypes, IReadOnlyList<FirmamentV2StaticArrayDecl> Arrays, IReadOnlyList<FirmamentV2CanonicalTemplateDecl> Templates, IReadOnlyList<FirmamentV2CanonicalPatternDecl> Patterns, IReadOnlyList<FirmamentV2RequireDecl> Requires, IReadOnlyList<FirmamentV2SemanticConstraint>? SemanticConstraints = null, IReadOnlyDictionary<string, FirmamentV2PmiProjection>? PmiProjections = null, IReadOnlyList<FirmamentV2StaticRecordDecl>? StaticRecords = null, IReadOnlyList<FirmamentV2StaticTableDecl>? Tables = null, IReadOnlyList<FirmamentV2StaticSetDecl>? Sets = null, IReadOnlyList<FirmamentV2MirrorDerivation>? Mirrors = null, IReadOnlyList<FirmamentV2RadialPatternDecl>? RadialPatterns = null, IReadOnlyList<FirmamentV2LinearPatternDecl>? LinearPatterns = null, IReadOnlyList<FirmamentV2Axis2Decl>? PlanarAxes = null);+public sealed record FirmamentV2StaticAuthoringDocument(IReadOnlyList<FirmamentV2RecordTypeDecl> RecordTypes, IReadOnlyList<FirmamentV2StaticArrayDecl> Arrays, IReadOnlyList<FirmamentV2CanonicalTemplateDecl> Templates, IReadOnlyList<FirmamentV2CanonicalPatternDecl> Patterns, IReadOnlyList<FirmamentV2RequireDecl> Requires, IReadOnlyList<FirmamentV2SemanticConstraint>? SemanticConstraints = null, IReadOnlyDictionary<string, FirmamentV2PmiProjection>? PmiProjections = null, IReadOnlyList<FirmamentV2StaticRecordDecl>? StaticRecords = null, IReadOnlyList<FirmamentV2StaticTableDecl>? Tables = null, IReadOnlyList<FirmamentV2StaticSetDecl>? Sets = null, IReadOnlyList<FirmamentV2MirrorDerivation>? Mirrors = null, IReadOnlyList<FirmamentV2RadialPatternDecl>? RadialPatterns = null, IReadOnlyList<FirmamentV2LinearPatternDecl>? LinearPatterns = null, IReadOnlyList<FirmamentV2Axis2Decl>? PlanarAxes = null, IReadOnlyList<ConceptIrKeyedPointSetValue>? ConceptPoints = null);public sealed record FirmamentV2RecordTypeDecl(string Name, IReadOnlyDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan);public sealed record FirmamentV2StaticArrayDecl(string Name, string ElementType, IReadOnlyList<IReadOnlyDictionary<string, string>> Elements, FirmamentV2SourceSpan SourceSpan);/// <summary>A finite immutable source-ordered collection whose entry names are semantic identity.</summary>diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.csindex d9c84d57..5f8f6aaf 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs@@ -378,12 +378,21 @@ internal static class FirmamentV2FeatureExpansionvar parser = new ScalarParser(expression); return parser.TryParse(out value, out unit);}- private sealed class ScalarParser(string text)+ internal static bool TryEvaluateScalar(string expression, IReadOnlyDictionary<string, (double Value, string Unit)> variables,+ Func<string, IReadOnlyList<(double Value, string Unit)>, (double Value, string Unit)> functions,+ bool typeOnly, out double value, out string unit)+ => new ScalarParser(expression, variables, functions, typeOnly).TryParse(out value, out unit);++ private sealed class ScalarParser(string text,+ IReadOnlyDictionary<string, (double Value, string Unit)>? variables = null,+ Func<string, IReadOnlyList<(double Value, string Unit)>, (double Value, string Unit)>? functions = null,+ bool typeOnly = false){private int _at;+ private int _depth;public bool TryParse(out double value, out string unit){- try { var result = Add(); White(); if (_at != text.Length || !double.IsFinite(result.Value)) throw new FormatException(); value = result.Value; unit = result.Unit; return true; }+ try { if (text.Length > 8192) throw new FormatException(); var result = Add(); White(); if (_at != text.Length || (!typeOnly && !double.IsFinite(result.Value))) throw new FormatException(); value = result.Value; unit = result.Unit; return true; }catch { value = 0; unit = string.Empty; return false; }}private (double Value, string Unit) Add()@@ -398,14 +407,39 @@ internal static class FirmamentV2FeatureExpansion{White(); if (!Take('*') && !Take('/')) return left; var op = text[_at - 1]; var right = Atom();if (op == '*') { if (left.Unit.Length > 0 && right.Unit.Length > 0) throw new FormatException(); left = (left.Value * right.Value, left.Unit.Length > 0 ? left.Unit : right.Unit); }- else { if (right.Value == 0 || right.Unit.Length > 0) throw new FormatException(); left = (left.Value / right.Value, left.Unit); }+ else { if ((!typeOnly && right.Value == 0) || (right.Unit.Length > 0 && right.Unit != left.Unit)) throw new FormatException(); left = (typeOnly ? 1 : left.Value / right.Value, right.Unit.Length > 0 ? string.Empty : left.Unit); }}}private (double Value, string Unit) Atom(){- White(); if (Take('(')) { var value = Add(); White(); if (!Take(')')) throw new FormatException(); return value; }- var start = _at; if (_at < text.Length && (text[_at] == '+' || text[_at] == '-')) _at++;+ if (++_depth > 128) throw new FormatException();+ try { return AtomCore(); }+ finally { _depth--; }+ }+ private (double Value, string Unit) AtomCore()+ {+ White(); if (Take('+')) return Atom(); if (Take('-')) { var negative = Atom(); return (-negative.Value, negative.Unit); }+ if (Take('(')) { var value = Add(); White(); if (!Take(')')) throw new FormatException(); return value; }+ if (_at < text.Length && (char.IsLetter(text[_at]) || text[_at] == '_'))+ {+ var begin = _at++;+ while (_at < text.Length && (char.IsLetterOrDigit(text[_at]) || text[_at] == '_')) _at++;+ var name = text[begin.._at]; White();+ if (!Take('(')) return variables is not null && variables.TryGetValue(name, out var variable) ? variable : throw new FormatException();+ var arguments = new List<(double Value, string Unit)>(); White();+ if (!Take(')'))+ {+ do { arguments.Add(Add()); White(); } while (Take(','));+ if (!Take(')')) throw new FormatException();+ }+ if (name == "Pow" && arguments.Count == 2 && arguments.All(a => a.Unit.Length == 0))+ return (typeOnly ? 1 : Math.Pow(arguments[0].Value, arguments[1].Value), string.Empty);+ return functions?.Invoke(name, arguments) ?? throw new FormatException();+ }+ var start = _at;while (_at < text.Length && (char.IsDigit(text[_at]) || text[_at] == '.')) _at++;+ if (_at < text.Length && text[_at] is 'e' or 'E')+ { _at++; if (_at < text.Length && text[_at] is '+' or '-') _at++; while (_at < text.Length && char.IsDigit(text[_at])) _at++; }if (start == _at || !double.TryParse(text[start.._at], NumberStyles.Float, CultureInfo.InvariantCulture, out var number)) throw new FormatException();var unit = text.AsSpan(_at).StartsWith("mm") ? "mm" : text.AsSpan(_at).StartsWith("deg") ? "deg" : string.Empty; _at += unit.Length; return (number, unit);}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csindex a5e078c4..257de2c0 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -307,6 +307,7 @@ public static class FirmamentV2ParserFirmamentV2ForgeConceptCatalog? conceptCatalog){ArgumentNullException.ThrowIfNull(sourceText);+ sourceText = FirmamentSourceSpelling.Normalize(sourceText);sourceText = ProfileModificationTemplateLibrary.ResolveImports(sourceText);var diagnostics = new List<string> { "firmament-v2-parser-invoked" };var source = StripLineComments(sourceText);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.csindex 5ee8bcf6..55b9efbc 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs@@ -264,7 +264,7 @@ internal static class FirmamentV2TemplateExpansionStart: declaration.SourceSpan.Start,Length: declaration.SourceSpan.Length,Text: string.Equals(declaration.Name, template.Name, StringComparison.Ordinal)- ? $"{template.TargetKind} {instanceName}{template.HeaderTail} {{{body}}}{liftedPmi}"+ ? RenderOutput(template.TargetKind, instanceName, template.HeaderTail, body) + liftedPmi: string.Empty)).OrderByDescending(change => change.Start).ToArray();@@ -340,7 +340,7 @@ internal static class FirmamentV2TemplateExpansionbody = ExpandNestedApplications(body, byName, source, enums, recordTypes, staticRecords,diagnostics, instantiations, [template.Name]);var liftedPmi = LiftPmi(body, out body);- changes.Add((application.SourceSpan.Start, application.SourceSpan.Length, $"{template.TargetKind} {application.InstanceName}{template.HeaderTail} {{{body}}}{liftedPmi}"));+ changes.Add((application.SourceSpan.Start, application.SourceSpan.Length, RenderOutput(template.TargetKind, application.InstanceName, template.HeaderTail, body) + liftedPmi));}if (HasErrors(diagnostics)) return null;foreach (var change in changes.OrderByDescending(c => c.Start)) source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);@@ -356,7 +356,7 @@ internal static class FirmamentV2TemplateExpansionforeach (Match start in Regex.Matches(source, @"\bTemplate\s*<", RegexOptions.CultureInvariant)){var open = source.IndexOf('<', start.Index); var close = Matching(source, open, '<', '>');- var header = close < 0 ? Match.Empty : Regex.Match(source[(close + 1)..], @"^\s*(?<kind>Concept\s+Struct|Struct|Model|Panel|SheetMetal|ProfileDelta)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)(?<tail>\s*:\s*[A-Za-z_][A-Za-z0-9_]*)?\s*\{", RegexOptions.CultureInvariant);+ var header = close < 0 ? Match.Empty : Regex.Match(source[(close + 1)..], @"^\s*(?<kind>Concept\s+Struct|Struct|Model|Panel|SheetMetal|ProfileDelta|Profile)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)(?<tail>\s*:\s*[A-Za-z_][A-Za-z0-9_]*)?\s*\{", RegexOptions.CultureInvariant);if (close >= 0 && !header.Success&& Regex.IsMatch(source[(close + 1)..], @"^\s*[A-Za-z_][A-Za-z0-9_]*\s*\{", RegexOptions.CultureInvariant))continue; // finite feature Template; CanonicalStaticAuthoring owns this bounded form.@@ -371,6 +371,32 @@ internal static class FirmamentV2TemplateExpansionreturn result.ToImmutable();}+ private static string RenderOutput(string kind, string instance, string tail, string body)+ {+ // Profile guides belong to each specialization; span identities stay shared.+ if (kind == "Profile")+ {+ var names = Regex.Matches(body, @"\b(?:Concept\s+Struct|Curve2|Point2|Line2|CubicBezier2|Circle2|Arc2|Rect2|RoundedRect2|Ellipse2|Path2)\s+(?<name>[A-Za-z_]\w*)\s*\{")+ .Select(m => m.Groups["name"].Value).Distinct(StringComparer.Ordinal).ToArray();+ foreach (var name in names)+ body = Regex.Replace(body, $@"\b{Regex.Escape(name)}\b", instance + "_" + name);+ }+ var prelude = "";+ if (kind == "Profile")+ {+ for (var offset = 0; offset < body.Length;)+ {+ var match = Regex.Match(body[offset..], @"\b(?:Concept\s+Struct|Point2|Line2|CubicBezier2|Circle2|Arc2|Rect2|RoundedRect2|Ellipse2|Path2)\s+[A-Za-z_]\w*\s*\{");+ if (!match.Success) break;+ var start = offset + match.Index; var open = body.IndexOf('{', start); var close = Matching(body, open, '{', '}');+ if (close < 0) break;+ prelude += body[start..(close + 1)] + "\n";+ body = body.Remove(start, close - start + 1); offset = start;+ }+ }+ return prelude + $"{kind} {instance}{tail} {{{body}}}";+ }+private static ImmutableArray<TemplateParameterIr> ParseParameters(string text, int offset, List<string> diagnostics){var result = ImmutableArray.CreateBuilder<TemplateParameterIr>(); var names = new HashSet<string>(StringComparer.Ordinal);@@ -391,13 +417,13 @@ internal static class FirmamentV2TemplateExpansionprivate static ImmutableArray<TemplateApplicationIr> ParseApplications(string source, IReadOnlyDictionary<string, TemplateDeclarationIr> templates, List<string> diagnostics){var result = ImmutableArray.CreateBuilder<TemplateApplicationIr>();- foreach (Match start in Regex.Matches(source, @"\b(?<kind>Concept\s+Struct|Struct|Model|Panel|SheetMetal|ProfileDelta)\s+(?<instance>[A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?<template>[A-Za-z_][A-Za-z0-9_]*)\s*<", RegexOptions.CultureInvariant))+ foreach (Match start in Regex.Matches(source, @"\b(?<kind>Concept\s+Struct|Struct|Model|Panel|SheetMetal|ProfileDelta|Profile)\s+(?<instance>[A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?<template>[A-Za-z_][A-Za-z0-9_]*)\s*<", RegexOptions.CultureInvariant)){if (!templates.ContainsKey(start.Groups["template"].Value)) continue;var open = source.IndexOf('<', start.Index); var close = Matching(source, open, '<', '>');if (close < 0) { diagnostics.Add(MissingArgument); continue; }var args = ImmutableArray.CreateBuilder<TemplateArgumentIr>(); var seen = new HashSet<string>(StringComparer.Ordinal);- foreach (var raw in source[(open + 1)..close].Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))+ foreach (var raw in ConceptPointAuthoring.Components(source[(open + 1)..close]).Select(value => value.Trim()).Where(value => value.Length > 0)){var parsed = Regex.Match(raw, @"^(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<value>.+)$", RegexOptions.CultureInvariant);if (!parsed.Success) { diagnostics.Add(UnknownArgument + ":" + raw); continue; }@@ -500,6 +526,7 @@ internal static class FirmamentV2TemplateExpansionprivate static bool TypeMatches(string value, string type, IReadOnlyDictionary<string, ImmutableHashSet<string>> enums,IReadOnlyDictionary<string, TemplateRecordTypeIr>? recordTypes = null, IReadOnlyDictionary<string, TemplateStaticRecordIr>? staticRecords = null) => type switch{+ "Point3" => Regex.IsMatch(value, @"^Point3\(\s*[-+]?\d+(?:\.\d+)?mm\s*,\s*[-+]?\d+(?:\.\d+)?mm\s*,\s*[-+]?\d+(?:\.\d+)?mm\s*\)$"),"Length" => Regex.IsMatch(value, @"^[-+]?[0-9]+(?:\.[0-9]+)?mm$", RegexOptions.CultureInvariant),"Angle" => Regex.IsMatch(value, @"^[-+]?[0-9]+(?:\.[0-9]+)?deg$", RegexOptions.CultureInvariant),"String" => Regex.IsMatch(value, "^\"[^\"]*\"$", RegexOptions.CultureInvariant),@@ -515,7 +542,7 @@ internal static class FirmamentV2TemplateExpansion_ => false};private static bool IsBuiltInValueType(string type, IReadOnlyDictionary<string, ImmutableHashSet<string>> enums) =>- type is "Length" or "Angle" or "String" or "Version" or "Date" or "ImportedStep" or "ProfilePath" or "Int" or "Float" or "Bool" or "int" or "float" or "bool" || enums.ContainsKey(type);+ type is "Point3" or "Length" or "Angle" or "String" or "Version" or "Date" or "ImportedStep" or "ProfilePath" or "Int" or "Float" or "Bool" or "int" or "float" or "bool" || enums.ContainsKey(type);private static IReadOnlyDictionary<string, TemplateRecordTypeIr> ParseRecordTypes(string source, List<string> diagnostics){@@ -864,7 +891,7 @@ internal static class FirmamentV2TemplateExpansion// Feature AIR. The instantiation record above preserves the semantic boundary;// material grammar receives concrete declarations without unsupported nested Structs.changes.Add((application.SourceSpan.Start, application.SourceSpan.Length,- specializedBody + liftedPmi));+ (template.TargetKind == "Profile" ? RenderOutput("Profile", application.InstanceName, template.HeaderTail, specializedBody) : specializedBody) + liftedPmi));}foreach (var change in changes.OrderByDescending(change => change.Start))body = body.Remove(change.Start, change.Length).Insert(change.Start, change.Text);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/LoftAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/LoftAuthoringParser.csindex 9f334a6c..f1bbd116 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/LoftAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/LoftAuthoringParser.cs@@ -42,6 +42,7 @@ public static class LoftAuthoringParserpublic static SectionChainAuthoringResult Compile(string source, bool materialize = true){ArgumentNullException.ThrowIfNull(source);+ source = FirmamentSourceSpelling.Normalize(source);var diagnostics = new List<string>();if (!Regex.IsMatch(source, @"\bUnits\s*:\s*mm\b", RegexOptions.CultureInvariant))diagnostics.Add("loft-units-invalid:millimetres-required");diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.csindex 347200fa..7d47b8bb 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs@@ -13,7 +13,7 @@ public static class ProfileAuthoringParser{public const string SegmentEndpointMustReferenceNamedPoint = "ProfileSegmentEndpointMustReferenceNamedPoint";private const double Tolerance = 1e-9;- private static readonly Regex Point = new(@"\bPoint2\s+(?<n>[A-Za-z_]\w*)\s*\{\s*Position\s*:\s*(?:\[|Point2\s*\()\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm\s*(?:\]|\))", RegexOptions.Singleline | RegexOptions.CultureInvariant);+ private static readonly Regex Point = new(@"\bPoint2\s+(?<n>[A-Za-z_]\w*)\s*\{\s*Position\s*:\s*(?:\[(?<xy>[^\[\]\r\n]+)\]|Point2\s*\((?<xy>[^()\r\n]+)\))", RegexOptions.Singleline | RegexOptions.CultureInvariant);private static readonly Regex Line = new(@"\bLine2\s+(?<n>[A-Za-z_]\w*)\s*\{\s*From\s*:\s*(?<a>[\w.]+)\s*;?\s*To\s*:\s*(?<b>[\w.]+)", RegexOptions.Singleline | RegexOptions.CultureInvariant);private static readonly Regex CubicBezier = new(@"\bCubicBezier2\s+(?<n>[A-Za-z_]\w*)\s*\{\s*From\s*:\s*(?<a>[\w.]+)\s*;?\s*Control1\s*:\s*(?<c1>[\w.]+)\s*;?\s*Control2\s*:\s*(?<c2>[\w.]+)\s*;?\s*To\s*:\s*(?<b>[\w.]+)", RegexOptions.Singleline | RegexOptions.CultureInvariant);private static readonly Regex Circle = new(@"(?:\bConcept\s+)?\bCircle2\s+(?<n>[A-Za-z_]\w*)\s*\{\s*Center\s*:\s*(?<c>[\w.]+)\s*;?\s*Radius\s*:\s*(?<r>[-+.\deE]+)mm", RegexOptions.Singleline | RegexOptions.CultureInvariant);@@ -247,8 +247,15 @@ public static class ProfileAuthoringParserprivate static void AddOrdinaryGuides(string source, Dictionary<string, (double X, double Y)> points, Dictionary<string, LineArcProfileCurve2D> guides, List<string> diagnostics, bool applySpans = true){foreach (Match match in Point.Matches(source))- if (TryNumber(match.Groups["x"].Value, out var x) && TryNumber(match.Groups["y"].Value, out var y))+ {+ // Profile Templates substitute dimensions before this binder. Reuse the+ // bounded, unit-checked scalar evaluator for authored control arithmetic.+ var xy = match.Groups["xy"].Value.Split(',');+ if (xy.Length == 2 && FirmamentV2FeatureExpansion.TryEvaluateScalar(xy[0], out var x, out var xu) && xu == "mm"+ && FirmamentV2FeatureExpansion.TryEvaluateScalar(xy[1], out var y, out var yu) && yu == "mm")points[match.Groups["n"].Value] = (x, y);+ else diagnostics.Add($"profile-layout-point-invalid:{match.Groups["n"].Value}:expected-two-finite-lengths");+ }foreach (Match match in Rect.Matches(source)){var name = match.Groups["n"].Value;diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileBoundaryAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileBoundaryAuthoring.csindex 4d8168a5..185881e0 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileBoundaryAuthoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileBoundaryAuthoring.cs@@ -68,6 +68,31 @@ internal static class ProfileBoundaryAuthoringif (seed is null) return true;if (seed.Loops.Count != 1) { diagnostics.Add($"profile-edit-loop-count-invalid:{name}"); return true; }var segments = seed.Loops[0].Segments;+ var periodic = new Dictionary<int, IReadOnlyList<(double X, double Y)>>();+ if (replacements.Any(b => Regex.IsMatch(b.Body, @"\bDerivatives\s*:\s*Periodic\b")))+ {+ var knots = new List<(double X, double Y)>(); var starts = new List<int>();+ for (var i = 0; i < segments.Count; i++)+ {+ if (segments[i].Geometry is not LineArcLineSegment2D carrier)+ { diagnostics.Add($"profile-edit-periodic-carrier-invalid:{name}"); return true; }+ starts.Add(knots.Count); knots.Add(carrier.Start);+ foreach (var replacement in replacements)+ {+ var replacementFields = Fields(replacement.Body, ["On", "Range", "Through", "Derivatives", "Join", "StartTangent", "EndTangent"], diagnostics, replacement.Name);+ if (!replacementFields.TryGetValue("On", out var target) || FindMember(segments, target, owner, localFrom) != i) continue;+ if (replacementFields.ContainsKey("Range")) diagnostics.Add($"profile-edit-periodic-range-not-qualified:{replacement.Name}");+ if (replacementFields.TryGetValue("Through", out var value)) knots.AddRange(Vectors(value, "mm", diagnostics, replacement.Name));+ }+ }+ if (knots.Count > 1024) { diagnostics.Add($"profile-edit-boundary-limit:{name}:maximum=1024"); return true; }+ for (var i = 0; i < segments.Count; i++)+ {+ var finish = i + 1 < starts.Count ? starts[i + 1] : knots.Count;+ periodic[i] = Enumerable.Range(starts[i], finish - starts[i] + 1).Select(index =>+ Scale(Subtract(knots[(index + 1) % knots.Count], knots[(index + knots.Count - 1) % knots.Count]), .5)).ToArray();+ }+ }var edits = new List<Edit>();var ids = new HashSet<string>(StringComparer.Ordinal);foreach (var block in replacements)@@ -84,7 +109,8 @@ internal static class ProfileBoundaryAuthoringif (!ValidRange(range, length)) { diagnostics.Add($"profile-edit-range-invalid:{block.Name}"); continue; }if (!fields.TryGetValue("Through", out var through)) { diagnostics.Add($"profile-edit-construction-required:{block.Name}:Through"); continue; }var points = Vectors(through, "mm", diagnostics, block.Name);- var derivatives = fields.TryGetValue("Derivatives", out var derivativeText) ? Vectors(derivativeText, "mm", diagnostics, block.Name) : null;+ var derivatives = fields.TryGetValue("Derivatives", out var derivativeText)+ ? derivativeText == "Periodic" ? periodic.GetValueOrDefault(index) : Vectors(derivativeText, "mm", diagnostics, block.Name) : null;var join = fields.GetValueOrDefault("Join", "Position");if (join is not ("Position" or "Tangent")) diagnostics.Add($"profile-edit-join-invalid:{block.Name}:{join}");(double X, double Y)? startTangent = fields.TryGetValue("StartTangent", out var startText) ? Vector(startText, "", diagnostics, block.Name) : null;@@ -95,7 +121,7 @@ internal static class ProfileBoundaryAuthoringvar curves = Construct(line, range, construction, diagnostics, block.Name);edits.Add(new(block.Name, index, range.Item1 / length, range.Item2 / length,curves.Select((c, i) => ($"{block.Name}_Span{i}", (LineArcProfileCurve2D)c)).ToArray(),- derivatives is null ? "ChordHermite" : "ExplicitHermite", $"profile:{name}/Replace:{block.Name}", construction.MatchTangent));+ derivatives is null ? "ChordHermite" : derivativeText == "Periodic" ? "PeriodicHermite" : "ExplicitHermite", $"profile:{name}/Replace:{block.Name}", construction.MatchTangent));}foreach (var apply in applies){diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.csindex 84467ed9..9999d82b 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs@@ -11,7 +11,8 @@ public sealed record SectionChainAuthoringResult(IReadOnlyList<string> Diagnostics,LoftAuthoredBinding? LoftBinding = null,IReadOnlyList<SectionChainProfileDerivation>? ProfileDerivations = null,- IReadOnlyList<SectionChainBoundaryEditInspection>? BoundaryEdits = null);+ IReadOnlyList<SectionChainBoundaryEditInspection>? BoundaryEdits = null,+ IReadOnlyList<FirmamentV2CanonicalPatternDecl>? Patterns = null);public sealed record SectionChainBoundaryEditInspection(string Section, string Profile,IReadOnlyList<ProfileBoundaryEditEvidence> Edits);@@ -44,9 +45,19 @@ public static class SectionChainAuthoringParserpublic static SectionChainAuthoringResult Compile(string source, bool materialize = true){ArgumentNullException.ThrowIfNull(source);+ source = FirmamentSourceSpelling.Normalize(source);if (LoftAuthoringParser.IsLoftSource(source))return LoftAuthoringParser.Compile(source, materialize);var diagnostics = new List<string>();+ var boundaries = ClosedBoundary2Authoring.Expand(source, diagnostics);+ if (boundaries is null || diagnostics.Count > 0) return new(false, null, null, diagnostics);+ source = boundaries.Source;+ var staticSource = CanonicalStaticAuthoring.Expand(source, diagnostics);+ if (staticSource is null || diagnostics.Count > 0) return new(false, null, null, diagnostics);+ source = ExpandSectionValues(staticSource.Source, diagnostics);+ var templates = FirmamentV2TemplateExpansion.Expand(source, diagnostics);+ if (templates is null || diagnostics.Count > 0) return new(false, null, null, diagnostics);+ source = templates.Source;if (!Regex.IsMatch(source, @"\bUnits\s*:\s*mm\b", RegexOptions.CultureInvariant))diagnostics.Add("section-chain-units-invalid:millimetres-required");var declarations = Blocks(source, "SectionChain").ToArray();@@ -121,15 +132,46 @@ public static class SectionChainAuthoringParserdiagnostics.Add("section-chain-normalization-tolerance-invalid:positive-length-required");if (diagnostics.Count != 0) return Fail(diagnostics);var chain = new SectionChain(declaration.Name, sections, correspondence, transition, start, end, continuity, ProfileApproximationTolerance: tolerance);- if (!materialize) return new(true, chain, null, [], ProfileDerivations: derivations, BoundaryEdits: boundaryEdits);+ if (!materialize) return new(true, chain, null, [], ProfileDerivations: derivations, BoundaryEdits: boundaryEdits, Patterns: staticSource.Document?.Patterns);var result = SectionChainMaterializer.Materialize(chain);if (!result.IsSuccess)diagnostics.AddRange(result.Diagnostics.Select(item => $"{item.Code}:{item.Message}"));- return new(result.IsSuccess, chain, result, diagnostics, ProfileDerivations: derivations, BoundaryEdits: boundaryEdits);+ return new(result.IsSuccess, chain, result, diagnostics, ProfileDerivations: derivations, BoundaryEdits: boundaryEdits, Patterns: staticSource.Document?.Patterns);SectionChainAuthoringResult Fail(IEnumerable<string> items) => new(false, null, null, items.Distinct(StringComparer.Ordinal).ToArray());}+ private static string ExpandSectionValues(string source, List<string> diagnostics)+ {+ var changes = new List<(int Start, int Length, string Text)>();+ foreach (Match header in Regex.Matches(source, @"\bSection\s+(?<name>[A-Za-z_]\w*)\s*\{"))+ {+ var open = source.IndexOf('{', header.Index); var close = MatchingBrace(source, open);+ if (close < 0) { diagnostics.Add("section-chain-section-malformed"); continue; }+ var body = source[(open + 1)..close]; var name = header.Groups["name"].Value;+ var prelude = "";+ var frame = Regex.Match(body, @"\bFrame\s*:\s*Plane\s*\{");+ if (frame.Success)+ {+ var frameOpen = body.IndexOf('{', frame.Index); var frameClose = MatchingBrace(body, frameOpen);+ if (frameClose < 0) { diagnostics.Add("section-chain-inline-frame-invalid:" + name); continue; }+ var concept = "__SectionDatum_" + name; var construction = "__SectionFrame_" + name;+ prelude += $"Concept Struct {concept} {{ Support: Plane {{{body[(frameOpen + 1)..frameClose]}}} }}\nConstruction Plane {construction} {{ Trace: {concept}.Support }}\n";+ body = body.Remove(frame.Index, frameClose - frame.Index + 1).Insert(frame.Index, "Frame: " + construction + "\n");+ }+ var profile = Regex.Match(body, @"\bProfile\s*:\s*(?<call>[A-Za-z_]\w*\s*<[^<>]+>)");+ if (profile.Success)+ {+ var profileName = "__SectionProfile_" + name;+ prelude += $"Profile {profileName} = {profile.Groups["call"].Value}\n";+ body = body.Remove(profile.Index, profile.Length).Insert(profile.Index, "Profile: " + profileName + "\n");+ }+ if (prelude.Length > 0) changes.Add((header.Index, close - header.Index + 1, prelude + $"Section {name} {{{body}}}"));+ }+ foreach (var change in changes.OrderByDescending(c => c.Start)) source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);+ return source;+ }+private static SectionProfileSpan? Convert(ResolvedProfileSegment2D segment, List<string> diagnostics, string section) => segment.Geometry switch{LineArcCubicBezier2D cubic => new(segment.Name, new SectionProfileCurve.PolynomialBSpline(3, [new(cubic.Start.X, cubic.Start.Y), new(cubic.Control1.X, cubic.Control1.Y), new(cubic.Control2.X, cubic.Control2.Y), new(cubic.End.X, cubic.End.Y)], [4, 4], [0, 1])),diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.csindex 609ec2c5..317ce47d 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.cs@@ -72,12 +72,14 @@ public static class LoftSemanticDeclaration { }[FirmamentConstruct("Concept", "Concept", Context = "Document", Entry = "Concept MountingFrame { Bounds: Box3; TopPlane: Plane }", Description = "Named semantic requirements; member names and types are authored per Concept.")]public static class ConceptSemanticDeclaration { }-[FirmamentConstruct("InterfaceFixed", "Interface<Fixed>", Context = "Assembly", Entry = "Interface<Fixed> Mount { A: Assembly.Base.Mount; B: Assembly.Link.Socket; }", Description = "Two semantic datum frames define one zero-DOF rigid relationship.")]+[FirmamentConstruct("InterfaceFixed", "Interface<Fixed>", Context = "Assembly", Entry = "Interface<Fixed> Mount { A: Assembly.Base.Mount; B: Assembly.Link.Socket; }", Description = "Two semantic frames, or members seated on a shared Concept datum, define a rigid relationship.")][FirmamentField("A", "A", FirmamentSchemaValueKind.ConstructReference, Required = true, Description = "Parent occurrence's source-addressable DatumFrame-capable semantic port.")][FirmamentField("B", "B", FirmamentSchemaValueKind.ConstructReference, Required = true, Description = "Child occurrence's source-addressable DatumFrame-capable semantic port.")][FirmamentField("Gap", "Gap", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Default = "0mm", Description = "Seat translation along A's positive Z.")][FirmamentField("Clocking", "Clocking", FirmamentSchemaValueKind.Angle, Unit = FirmamentUnitKind.Angle, Default = "0deg", Description = "Right-handed rotation about A's positive Z.")][FirmamentField("Orientation", "Orientation", FirmamentSchemaValueKind.Choice, Default = "SameDirection", Choices = ["SameDirection", "OpposedDirection"])]+[FirmamentField("Datum", "Datum", FirmamentSchemaValueKind.ConstructReference, Description = "Shared Concept plane or axis instead of A/B.")]+[FirmamentField("Members", "Members", FirmamentSchemaValueKind.Vector, Description = "Checked published member seats on the common Datum.")]public static class FixedInterfaceSemanticDeclaration { }[FirmamentConstruct("AssemblyPlacement", "Placement", Context = "Assembly", Entry = "Placement { From: Origin; To: World; TranslateLocal: [0mm,0mm,0mm]; }", Description = "One authored rigid layout authority; lowered through the existing frame solver.")]diff --git a/Aetheris.Kernel.Firmament/Materializer/WireForm.cs b/Aetheris.Kernel.Firmament/Materializer/WireForm.csindex a4e02dd3..77466fc3 100644--- a/Aetheris.Kernel.Firmament/Materializer/WireForm.cs+++ b/Aetheris.Kernel.Firmament/Materializer/WireForm.cs@@ -135,11 +135,13 @@ public static class WireFormAuthoringreturn false;}- public static bool IsWireFormSource(string source) => Declaration.IsMatch(source);+ public static bool IsWireFormSource(string source) => Declaration.IsMatch(source) || WireRouteAuthoring.IsSource(source);public static KernelResult<WireFormFeatureAir> Parse(string source){ArgumentNullException.ThrowIfNull(source);+ source = FirmamentV2.FirmamentSourceSpelling.Normalize(source);+ if (WireRouteAuthoring.IsSource(source)) return WireRouteAuthoring.Parse(source);var declaration = Declaration.Match(source);if (!declaration.Success) return Fail("wireform-declaration-missing", "No WireForm declaration was found.");var open = source.IndexOf('{', declaration.Index);@@ -282,7 +284,7 @@ public static class WireFormAuthoringtry { direction = Direction3D.Create(vector); return true; }catch (ArgumentException) { direction = default; return false; }}- private static int MatchingBrace(string source, int open) { var depth = 0; for (var i = open; i >= 0 && i < source.Length; i++) { if (source[i] == '{') depth++; else if (source[i] == '}' && --depth == 0) return i; } return -1; }+ internal static int MatchingBrace(string source, int open) { var depth = 0; for (var i = open; i >= 0 && i < source.Length; i++) { if (source[i] == '{') depth++; else if (source[i] == '}' && --depth == 0) return i; } return -1; }private static Vector3D Rotate(Vector3D vector, Vector3D axis, double angle) => vector * Math.Cos(angle) + Cross(axis, vector) * Math.Sin(angle) + axis * (Dot(axis, vector) * (1d - Math.Cos(angle)));internal static Vector3D Cross(Vector3D a, Vector3D b) => new(a.Y * b.Z - a.Z * b.Y, a.Z * b.X - a.X * b.Z, a.X * b.Y - a.Y * b.X);internal static double Dot(Vector3D a, Vector3D b) => a.X * b.X + a.Y * b.Y + a.Z * b.Z;diff --git a/Aetheris.Kernel.Firmament/Materializer/WireRoute.cs b/Aetheris.Kernel.Firmament/Materializer/WireRoute.csnew file mode 100644index 00000000..412c3cde--- /dev/null+++ b/Aetheris.Kernel.Firmament/Materializer/WireRoute.cs@@ -0,0 +1,210 @@+using System.Text.RegularExpressions;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Numerics;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Firmament.Assembly;+using Aetheris.Kernel.StandardLibrary.Materials;++namespace Aetheris.Kernel.Firmament.Materializer;++/// <summary>Finite three-point route. Corner is a virtual intersection, not an exact-through point.</summary>+public sealed record WirePointRouteAir(string Name, double DiameterMm, string MaterialReference,+ Point3D Start, Point3D Corner, Point3D End, double MinimumBendRadiusMm, double RadiusMm, string CornerName = "Corner");++/// <summary>Deterministic fillet lowering to the existing exact WireForm sweep authority.</summary>+public static class WireRouteAuthoring+{+ private static readonly Regex Declaration = new(@"\bWireRoute\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);+ public static bool IsSource(string source) => Declaration.IsMatch(source);++ public static KernelResult<WireFormFeatureAir> Parse(string source)+ {+ source = FirmamentV2.FirmamentSourceSpelling.Normalize(source);+ // Comments cannot contribute operations or fields.+ source = Regex.Replace(source, @"//[^\r\n]*", "");+ var declarations = Declaration.Matches(source);+ if (declarations.Count != 1) return Fail("declaration-invalid", "Exactly one concrete WireRoute is required.");+ if (Regex.IsMatch(source, @"\bWireForm\s+[A-Za-z_]\w*\s*\{"))+ return Fail("declaration-invalid", "WireRoute and WireForm cannot share a concrete materialization unit.");+ var declaration = declarations[0];+ var open = declaration.Index + declaration.Length - 1;+ var close = WireFormAuthoring.MatchingBrace(source, open);+ if (close < 0) return Fail("declaration-invalid", "Unclosed WireRoute.");+ var body = source[(open + 1)..close];+ var path = Block(ref body, @"Path");+ if (path is null) return Fail("path-invalid", "Path is required.");+ var fields = Fields(body, ["Diameter", "Material", "MinimumBendRadius"]);+ if (fields is null || !WireFormAuthoring.TryLength(fields.GetValueOrDefault("Diameter"), out var diameter) || diameter <= 0+ || !WireFormAuthoring.TryLength(fields.GetValueOrDefault("MinimumBendRadius"), out var minimum) || minimum <= 0)+ return Fail("dimensions-invalid", "Diameter and MinimumBendRadius require finite positive lengths; unknown/duplicate fields are rejected.");+ var steps = new List<(string Kind, string Name, string Body)>();+ while (!string.IsNullOrWhiteSpace(path))+ {+ var match = Regex.Match(path, @"^\s*(?<kind>Start|Corner|Follow|End)(?:\s+(?<name>[A-Za-z_]\w*))?\s*\{");+ if (!match.Success) return Fail("path-unsupported", "Expected Start/Corner/End or Start/Follow/End; Via and multi-corner routes are deferred.");+ var stepClose = WireFormAuthoring.MatchingBrace(path, match.Length - 1);+ if (stepClose < 0) return Fail("path-invalid", "Unclosed route step.");+ steps.Add((match.Groups["kind"].Value, match.Groups["name"].Value, path[match.Length..stepClose]));+ path = path[(stepClose + 1)..];+ }+ if (steps.Count == 3 && steps[0].Kind == "Start" && steps[1].Kind == "Follow" && steps[2].Kind == "End")+ return FollowLine(source, declaration.Groups["name"].Value, diameter, minimum,+ fields.GetValueOrDefault("Material") ?? "Standard.Materials.StainlessSteel.304_Annealed", steps);+ if (steps.Count != 3 || steps[0].Kind != "Start" || steps[1].Kind != "Corner" || steps[2].Kind != "End")+ return Fail("path-unsupported", "Exactly Start, Corner, End are supported.");+ var points = new Point3D[3]; double radius = 0;+ for (var i = 0; i < steps.Count; i++)+ {+ var step = steps[i].Body;+ var on = Block(ref step, "On");+ var values = Fields(step, i == 1 ? ["At", "Radius"] : ["At"]);+ if (values is null || !TryPoint(values.GetValueOrDefault("At"), on is not null, out var point))+ return Fail("point-invalid", "At requires Point3 of finite lengths, or Point2 with an explicit On frame.");+ if (on is not null)+ {+ // Share the checked placement parser and composition math; no second frame engine.+ var diagnostics = new List<AssemblyDiagnostic>();+ var frame = AssemblyFrameAuthoring.Parse("WireRoute.On", on, "From", "<wire-route>", diagnostics);+ if (frame is null || frame.From != "World") return Fail("frame-invalid", "On requires From: World; placed port references need a later assembly binding phase.");+ var transform = AssemblyFrameAuthoring.Compose(Transform3D.Identity, frame, diagnostics);+ if (diagnostics.Count != 0) return Fail("frame-invalid", string.Join("; ", diagnostics.Select(d => d.Message)));+ point = transform.Apply(point);+ }+ points[i] = point;+ if (i == 1 && (!WireFormAuthoring.TryLength(values!.GetValueOrDefault("Radius"), out radius) || radius < minimum))+ return Fail("radius-invalid", "Corner Radius must be finite and at least MinimumBendRadius.");+ }+ return Lower(new(declaration.Groups["name"].Value, diameter,+ fields.GetValueOrDefault("Material") ?? "Standard.Materials.StainlessSteel.304_Annealed", points[0], points[1], points[2], minimum, radius,+ string.IsNullOrEmpty(steps[1].Name) ? "Corner" : steps[1].Name));+ }++ private static KernelResult<WireFormFeatureAir> FollowLine(string source, string name, double diameter, double radius,+ string material, IReadOnlyList<(string Kind, string Name, string Body)> steps)+ {+ var startFields = Fields(steps[0].Body, ["At"]); var endFields = Fields(steps[2].Body, ["At"]);+ var follow = Fields(steps[1].Body, ["Curve", "From", "Distance", "Direction"]);+ if (startFields is null || endFields is null || follow is null+ || !TryPoint(startFields.GetValueOrDefault("At"), false, out var start)+ || !TryPoint(endFields.GetValueOrDefault("At"), false, out var end)+ || !WireFormAuthoring.TryLength(follow.GetValueOrDefault("From"), out var from)+ || !WireFormAuthoring.TryLength(follow.GetValueOrDefault("Distance"), out var distance) || distance <= 0)+ return Fail("guide-fields-invalid", "Follow requires Point3 endpoints and finite From/positive Distance lengths.");+ var reference = follow.GetValueOrDefault("Curve")?.Split('.');+ if (reference is not { Length: 2 } || reference.Any(p => !Regex.IsMatch(p, @"^[A-Za-z_]\w*$")))+ return Fail("guide-unresolved", "Curve requires a named Concept Struct Line3.");+ var owner = Regex.Matches(source, $@"\bConcept\s+Struct\s+{Regex.Escape(reference[0])}\s*\{{");+ if (owner.Count != 1) return Fail("guide-unresolved", "Concept guide owner is missing or ambiguous.");+ var close = WireFormAuthoring.MatchingBrace(source, owner[0].Index + owner[0].Length - 1);+ if (close < 0) return Fail("guide-unresolved", "Concept guide owner is unclosed.");+ var ownerBody = source[(owner[0].Index + owner[0].Length)..close];+ var guideBody = Block(ref ownerBody, "Line3\\s+" + Regex.Escape(reference[1]));+ var guide = guideBody is null ? null : Fields(guideBody, ["From", "To"]);+ if (guide is null || !TryPoint(guide.GetValueOrDefault("From"), false, out var a) || !TryPoint(guide.GetValueOrDefault("To"), false, out var b))+ return Fail("guide-unresolved", "Line3 requires finite Point3 From and To.");+ var axis = b - a;+ if (!double.IsFinite(axis.Length) || !axis.TryNormalize(out var direction)) return Fail("guide-degenerate", "Guide endpoints must be distinct.");+ var sense = follow.GetValueOrDefault("Direction", "Forward");+ if (sense is not ("Forward" or "Reverse")) return Fail("guide-direction-invalid", sense);+ var last = from + (sense == "Reverse" ? -distance : distance);+ if (from < 0 || from > axis.Length || last < 0 || last > axis.Length) return Fail("guide-interval-invalid", "The locked interval must lie entirely on the declared guide; no wrapping/clamping.");+ var entry = a + direction * from; var exit = a + direction * last;+ if (sense == "Reverse") direction = -direction;+ var tolerance = ToleranceContext.Default.Linear;+ var endOffset = end - exit;+ if (endOffset.Cross(direction).Length > tolerance || endOffset.Dot(direction) <= tolerance)+ return Fail("guide-exit-not-qualified", "The first guide lane requires an End beyond the interval along its outgoing tangent.");+ // A unique orthogonal projection determines the approach; no strategy search.+ var corner = entry + direction * (start - entry).Dot(direction);+ var approach = corner - start;+ if (approach.Length <= tolerance)+ return Fail("guide-approach-not-qualified", "The first lane requires a non-collinear approach; a wholly straight wire can use WireForm Straight.");+ if ((entry - corner).Dot(direction) < radius + tolerance)+ return Fail("guide-connector-space-insufficient", "The entry fillet must finish before the locked interval starts.");+ var route = Lower(new(name, diameter, material, start, corner, end, radius, radius, "GuideEntry"));+ if (!route.IsSuccess || route.Value is null) return route;+ var tail = (WireStraightAir)route.Value.Operations[^1];+ var firstLength = (entry - tail.Input.Position).Length;+ var enter = tail.Input with { Position = entry, AccumulatedLengthMm = tail.Input.AccumulatedLengthMm + firstLength };+ var leave = enter with { Position = exit, AccumulatedLengthMm = enter.AccumulatedLengthMm + distance };+ var finish = leave with { Position = end, AccumulatedLengthMm = leave.AccumulatedLengthMm + endOffset.Length };+ return KernelResult<WireFormFeatureAir>.Success(route.Value with { Operations =+ [route.Value.Operations[0], route.Value.Operations[1],+ new WireStraightAir("GuideApproach", 3, firstLength, tail.Input, enter),+ new WireStraightAir(string.IsNullOrEmpty(steps[1].Name) ? "Follow" : steps[1].Name, 4, distance, enter, leave),+ new WireStraightAir("GuideExit", 5, endOffset.Length, leave, finish)] });+ }++ public static KernelResult<WireFormFeatureAir> Lower(WirePointRouteAir route)+ {+ var tolerance = ToleranceContext.Default;+ if (!double.IsFinite(route.DiameterMm) || route.DiameterMm <= 0 || !double.IsFinite(route.MinimumBendRadiusMm)+ || route.MinimumBendRadiusMm <= 0 || !double.IsFinite(route.RadiusMm) || route.RadiusMm < route.MinimumBendRadiusMm+ || route.RadiusMm <= route.DiameterMm / 2 + tolerance.Linear)+ return Fail("radius-invalid", "Positive dimensions and centerline radius greater than wire radius are required.");+ if (new[] { route.Start, route.Corner, route.End }.Any(p => !double.IsFinite(p.X) || !double.IsFinite(p.Y) || !double.IsFinite(p.Z)))+ return Fail("point-invalid", "Route coordinates must be finite.");+ var lead = route.Corner - route.Start; var tail = route.End - route.Corner;+ if (!double.IsFinite(lead.Length) || !double.IsFinite(tail.Length)+ || !lead.TryNormalize(out var incoming) || !tail.TryNormalize(out var outgoing))+ return Fail("point-invalid", "Route legs must have distinct finite endpoints.");+ var cross = incoming.Cross(outgoing);+ if (!cross.TryNormalize(out var normal)) return Fail("corner-degenerate", "Collinear/reversing corners are unsupported; use WireForm Straight for a straight wire.");+ var angle = Math.Atan2(cross.Length, Math.Clamp(incoming.Dot(outgoing), -1, 1));+ var setback = route.RadiusMm * Math.Tan(angle / 2);+ if (!double.IsFinite(setback) || angle <= tolerance.Angular || Math.PI - angle <= tolerance.Angular+ || lead.Length - setback <= tolerance.Linear || tail.Length - setback <= tolerance.Linear)+ return Fail("corner-does-not-fit", "Bend tangent setbacks must fit both route legs with positive remaining straight lengths.");+ var material = new MaterialResolver().Resolve(route.MaterialReference.Trim('"'));+ if (!material.IsSuccess || material.Material is null) return Fail("material-unresolved", material.Message ?? "Unresolved material.");+ var tangent = Direction3D.Create(incoming); var up = Direction3D.Create(normal);+ var start = new WireState(route.Start, tangent, up, 0);+ var bendStart = start with { Position = route.Corner - incoming * setback, AccumulatedLengthMm = lead.Length - setback };+ var radial = Direction3D.Create(incoming.Cross(normal));+ var center = bendStart.Position - radial.ToVector() * route.RadiusMm;+ var bendEnd = new WireState(route.Corner + outgoing * setback, Direction3D.Create(outgoing), up,+ bendStart.AccumulatedLengthMm + route.RadiusMm * angle);+ var end = bendEnd with { Position = route.End, AccumulatedLengthMm = bendEnd.AccumulatedLengthMm + tail.Length - setback };+ return KernelResult<WireFormFeatureAir>.Success(new(route.Name, route.DiameterMm, route.MaterialReference, material.Material, start,+ [new WireStraightAir("Lead", 1, lead.Length - setback, start, bendStart),+ new WireBendAir(route.CornerName, 2, route.RadiusMm, angle, "Up", up, center, radial, bendStart, bendEnd),+ new WireStraightAir("Tail", 3, tail.Length - setback, bendEnd, end)], WireFormAuthoring.FrameTransportPolicy));+ }++ private static bool TryPoint(string? text, bool on, out Point3D point)+ {+ point = default;+ if (text is null) return false;+ var match = Regex.Match(text, @"^Point(?<dimension>2|3)\((?<values>[^()]*)\)$");+ if (!match.Success) return false;+ var dimension = int.Parse(match.Groups["dimension"].Value);+ if (dimension == 2 && !on) return false;+ var parts = match.Groups["values"].Value.Split(',');+ if (parts.Length != dimension) return false;+ var values = new double[3];+ for (var i = 0; i < dimension; i++) if (!WireFormAuthoring.TryLength(parts[i].Trim(), out values[i])) return false;+ point = new(values[0], values[1], values[2]); return true;+ }+ private static string? Block(ref string source, string header)+ {+ var matches = Regex.Matches(source, $@"\b{header}\s*\{{");+ if (matches.Count != 1) return null;+ var match = matches[0]; var close = WireFormAuthoring.MatchingBrace(source, match.Index + match.Length - 1);+ if (close < 0) return null;+ var body = source[(match.Index + match.Length)..close];+ source = source.Remove(match.Index, close - match.Index + 1); return body;+ }+ private static Dictionary<string, string>? Fields(string source, string[] allowed)+ {+ var result = new Dictionary<string, string>(StringComparer.Ordinal);+ foreach (var field in source.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))+ {+ var colon = field.IndexOf(':');+ if (colon < 0 || !allowed.Contains(field[..colon].Trim()) || !result.TryAdd(field[..colon].Trim(), field[(colon + 1)..].Trim())) return null;+ }+ return result;+ }+ private static KernelResult<WireFormFeatureAir> Fail(string code, string message) => KernelResult<WireFormFeatureAir>.Failure([new(+ Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Core.Diagnostics.KernelDiagnosticSeverity.Error,+ $"wire-route-{code}: {message}", "FirmamentV2.WireRoute")]);+}diff --git a/docs/public/demos/guitar-surfacing-x0.md b/docs/public/demos/guitar-surfacing-x0.mdindex f41bd351..06e5c350 100644--- a/docs/public/demos/guitar-surfacing-x0.md+++ b/docs/public/demos/guitar-surfacing-x0.md@@ -19,7 +19,13 @@ pwsh -File scripts/qualify-guitar-x0.ps1 -Render -Viewport`-Render` requires Blender with Cycles; `-Blender` supplies another executable. `-Viewport` uses the locally installed OpenUSD 25.08 SDK from the existing USD qualification workflow; `-UsdRoot` supplies its directory. Neither dependency is installed by this script. Without those flags, it builds, benchmarks, exports geometry and checks display mesh closure. Output defaults to ignored `artifacts/local/guitar-x0/`.-The fixtures are ordinary authored Firmament. `python scripts/create-guitar-x0.py` reproducibly regenerates them from a small original silhouette and a finite part layout. SectionChain source is built with `aetheris section-chain build`, while the assembly uses `aetheris asm export-ap242` and `aetheris asm export-usd`.+The fixtures are ordinary authored Firmament. `python scripts/create-guitar-x0.py`+is now a read-only CLI reproduction harness: it exports artifacts and verifies+that source hashes did not change. Body/neck Profile recipes, keyed sections,+endpoint bindings and physical-material appearance defaults are source-owned.+Root-aware `aetheris build` and `inspect` delegate to the existing geometry and+assembly owners; `asm export-usd` remains the presentation export command. See+[the qualified owl authoring slice](../firmament/source-owned-guitar-authoring.md).For source changes, run both test lanes after the solution build:@@ -95,3 +101,128 @@ Stabilization validation: Release solution build passed with zero errors; the foThe follow-up side review requested a flatter lengthwise back. Shaft stations now lie on one straight taper from back z=42 mm at y=240 mm to z=48 mm at the nut (y=660 mm). An extra station before the shaft isolates the heel fairing from the shaft tangent; the rounded D cross-section remains. This removes the visible longitudinal belly without changing the fretboard, headstock or other product parts. A regression checks that shaft samples never protrude behind the straight taper and that centerline samples remain on the back or flat seat. The rear studio light is enabled only for neck inspection views, preserving the front studio lighting.Straight shaft validation: Release solution build and focused geometry regression passed; Core fast lane passed 1,005 tests; serial full solution lane passed 4,012 tests with zero failures or skips. STEP reimport, OpenUSD validation, closed outward-oriented meshes and unchanged viewport geometry pass. Logs use the `straight-neck-` prefix under local output; `straight-neck-test-summary.json` records the totals.++## Source-authoring owl closeout, 2026-10-01++The [updated checklist](../firmament/authoring-composition-proposal.md) and+[implemented syntax](../firmament/source-owned-guitar-authoring.md) record this slice.+Profile/section recipes are source-owned; fixed public endpoints drive strings;+physical Material supplies Appearance defaults with explicit with overrides.+Rendering consumes authored identities instead of matching occurrence names.++Release solution build passed. Focused qualification passed 95 Firmament and 27+CLI tests; fast Core passed 1,004. The full serial gate passed 4,225 tests with+zero failures and seven existing skips across 21 projects. Cold compilation was+11.105s, warm uncached 5.108s, and retained-session 0.887s with all 53 definitions+reused. Display preparation was 0.218–0.398s; these local measurements include+first-use JIT in cold, exclude process startup/build, and are not a Zoo speed ratio.+Current cached/uncached USD serializations match.++Fresh outputs are under ignored artifacts/local/owl: guitar.step, guitar.usda,+report.md/report.json, inspect.json, timings.json, display.json and render/.+Six full-resolution Cycles images and guitar-studio.blend use the final USD hash,+with 91 imported meshes, nine pearl assignments and two pickup treatments;+shading/camera changes preserve product topology. Blender import took 0.198s;+hero took 42.79s and shaded isometric 41.72s at 1800x2200, GPU/OptiX, 64 samples.+Earlier native Storm orbit measurements above remain historical; this slice+qualifies the compiled Cycles scene and does not claim a refreshed native orbit run.++## Connection-detail polish, 2026-10-01++The reusable tuner now includes one lateral steel stem joining its button to the+headstock, automatically shared by all six patterned occurrences. An exact+semicircular rail sits on the tailpiece's top face. Its crown supplies the public+string datum at z=65mm, replacing the previous 5mm free offset above the flat+tailpiece. The six existing string routes retain their actual geometry.++The neck uses ten G1 sections, with the existing straight shaft taper isolated+from the short headstock transition. Its D-shaped cross-section is split exactly+into six corresponding spans, then blends into the rectangular headstock root.+The slab begins 16mm behind its original base datum; the transition's terminal cap+is buried inside it at 18mm. A small solid scarf under the veneer closes the front+of the angled join. This is a presentation assembly of separate exact solids;+it does not claim fused joinery, a continuous G2 interface to the slab, tuner+internals, string holes or mechanically functional string retention.++The control arithmetic needed for splitting the cubic profile exposed a narrow+authoring omission: Point2 controls accepted only literals after Template+substitution. The profile binder now delegates finite Length arithmetic to the+existing bounded scalar evaluator. The regression fixture checks real exact+extrusion and rejects wrong units and nonfinite coordinates. No new compiler or+geometry engine was introduced.++Compared with the preceding owl export, all 91 existing part placements remain+unchanged and 89 keep identical display geometry within 1e-9. Only the neck and+headstock solid change; eight added occurrences provide six stems, the rail and+the scarf. The result has 99 visible parts and 56 shared geometry definitions.+Reproduction, comparison, mesh checks and fresh presentation outputs live under+ignored `artifacts/local/guitar-polish/`. The renderer adds front, rear and side+headstock close-ups so the three repairs can be inspected directly.++The standalone neck CLI build and STEP reimport pass: one closed shell, 56 exact+faces (54 polynomial spline faces and two planar caps), zero rational product+surfaces and zero faceted fallback. Pcurve reconstruction deviation is below+0.000000007mm; loop closure and orientation checks pass. The admitted triangle+proxy self-intersection check passes; it is validation evidence, not a global+analytic intersection proof.++Fresh local benchmark: cold compile 12.848s, warm uncached compile 6.324s,+retained-session compile 0.993s with all 56 definitions reused. Mesh preparation+takes 0.224–0.437s and USD serialization 0.075–0.109s. All three serialized scenes+match. As before, cold includes first-use JIT, process startup/build are excluded,+and the measurements do not establish a numerical speedup over Zoo.++Polish validation: Release solution build passes with zero errors and four+existing WASM interop warnings. Core fast lane passes 1,004 tests. Final full serial+gate passes 4,229 tests with zero failures and seven existing local-data skips+across 21 projects. The first full run caught three stale fixture assertions for+the section/span layout and shared-definition reuse count; their updated checks+pass in the final run. Both logs and all TRX results remain in local output.++Nine full-resolution Cycles views and the saved studio scene use the final USD+hash. The 1800x2200 hero takes 11.81s and isometric 11.21s at 64 GPU/OptiX samples;+USD import takes 0.142s. All 99 product meshes survive shading and camera changes+without topology edits or compiler invocation. Closed-edge/outward-normal checks+pass for the four surfaced parts, six strings, pickup and three new shared detail+definitions. `report.md`/`report.json` link source, STEP, USD, Blender scene,+images, timings, comparisons and test evidence. **This is ready as a presentation+witness**; hardware internals and fused manufacturing joinery remain simplified.++## Authored provenance and PMI, 2026-10-01++The composition root now declares a typed `GuitarReleaseInfo` Record and immutable+`GuitarRelease` value, selected by `Provenance: GuitarRelease;`. Version **0.1.0**+credits **GPT 6.1 Sol Codex**, explicitly identifies the creator as an AI agent+working under human direction, and records the release date, milestone, nominal+units, authoring tolerance, and presentation-only status.++Eight named product notes cover design intent, the 0.1 mm authoring convention,+carved body, neck/head joint, electronics, bridge, strings/tuners, and finish.+Together with ten release fields they export as **18 semantic AP242 annotations**.+The STEP header also carries the author, date, description, and version. These+notes are design information; they do not claim measured acceptance, newly+qualified GD&T, or a manufactured instrument. The authored release date becomes+a fixed midnight timestamp, independent of when the exporter runs.++Reinspect with the assembly-aware route:++```powershell+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll build fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm --output artifacts/local/guitar-provenance/guitar.step --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll analyze assembly artifacts/local/guitar-provenance/guitar.step --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll asm export-usd fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm artifacts/local/guitar-provenance/guitar.usda --evidence artifacts/local/guitar-provenance/display.json --json+```++The real STEP reinspection recovers all 18 annotations with their intended+occurrence targets. All existing STEP geometry/product/placement entities are+byte-identical to the connection-polish baseline; only the header and 36 note+entities are added. The 99 body occurrences and 56 shared geometry definitions+are preserved. USD carries the same release fields and notes as custom+attributes, with unchanged meshes and transforms; the existing beauty images+continue to represent the current geometry. Metadata edits reuse geometry, as+qualified through a retained compilation session regression.++Current outputs and detailed evidence live in `artifacts/local/guitar-provenance/`.+Provenance closeout: Release build and repository layout/diff checks pass; the+Core fast lane passes 1,004 tests and the full serial gate passes **4,243 tests**+with zero failures and seven existing local-data skips across 21 projects.+See [assembly PMI syntax and limits](../firmament/pmi.md#assembly-release-records-and-design-notes).diff --git a/docs/public/firmament/assembly-authoring-foundation.md b/docs/public/firmament/assembly-authoring-foundation.mdindex 8a4aafa5..65b74201 100644--- a/docs/public/firmament/assembly-authoring-foundation.md+++ b/docs/public/firmament/assembly-authoring-foundation.md@@ -130,16 +130,20 @@ nonfinite values, duplicate fields and invalid orientation fail diagnostically.The fixture has zero authored LegacyExplicit matrices. Neck NutMount/HeelMountpublish section ports; NutWorld/HeadTilt place the headstock; VeneerSeat seats the-veneer. Seven keyed patterns cover pickup seats/coils/poles, saddles and tuner-posts/washers/buttons. Hardware positions preserve the previous witness, with-107 visible parts, 55 shared definitions, six WireForms and four SectionChains.--Python still generates spline controls/sections, computes fret spacing, and-derives WireForm lengths, bend angles and bases from endpoints. Decorative-hardware still uses absolute coordinates where mounting ports are unauthored.-Profile-valued templates, section patterns and point-driven routes are the next-useful authoring slice, deferred pending review. No surfacing-kernel change is-needed to take that step. Appearance remains downstream Cycles shading.+veneer. Six keyed assembly patterns now cover saddles, tuner rows, controls,+frets and inlays; the two pickups share a functional part definition with feature patterns.+The current witness has 91 visible parts, 53 shared definitions, six WireForms+and four SectionChains.++Python now only reproduces CLI artifacts without changing authored source. Body and neck profiles and section recipes live in Firmament. Fret spacing and widths live in pure+`Function` declarations and a bounded Concept point series, with placement local+to the nut's published frame. See [Concept points and Functions](concept-points-and-functions.md).+The six strings now use [point-driven routes](wire-point-routes.md); Firmament+derives their lengths, angles and forming frames. Pearl inlays use explicit linear+stations seated on the board's published MarkerOrigin. Physical Material selects+its default Appearance, with explicit with finish overrides; procedural Cycles+shading remains downstream. See [source-owned guitar authoring](source-owned-guitar-authoring.md)+and the [updated checkpoint](authoring-composition-proposal.md).Ground truth:@@ -153,8 +157,9 @@ Generated reports, STEP/USD and Cycles artifacts go under ignored artifacts/loca## Qualification on 2026-09-30Verdict: **success for this bounded foundation slice**. The motivating guitar-now uses the implemented constructs through M1, exact STEP export, shared USD-prototypes and downstream rendering. Authoring D has not been started.+used the implemented constructs through M1, exact STEP export, shared USD+prototypes and downstream rendering. This is the original foundation qualification;+subsequent authoring slices are recorded in the session checkpoint above.- Release solution build: passed (existing WebAssembly interop warnings).- Core fast lane: 1005 passed; serial full solution gate: 4034 passed.diff --git a/docs/public/firmament/assembly-components-and-sites.md b/docs/public/firmament/assembly-components-and-sites.mdindex db7c2335..1ca88b10 100644--- a/docs/public/firmament/assembly-components-and-sites.md+++ b/docs/public/firmament/assembly-components-and-sites.md@@ -121,8 +121,9 @@ carved body remain visible engineering data. They share `ControlKnob`; theselector is one `PickupSelector` occurrence. Internal component offsets occuronly in their defining modules.-The guitar generator preserves these directly authored modules. It still computes-fret spacing and WireForm routes; string endpoints follow the corrected tuner+The guitar generator preserves these directly authored modules. The neck now authors fret spacing with `Function` and a bounded Concept point+series (see [Concept points and Functions](concept-points-and-functions.md)).+The generator still computes WireForm routes; string endpoints follow the corrected tunerpost seats. The nut bend radius is 4mm, with matching tangent setbacks, so therevised leads pass the existing WireForm clearance checks at every string gauge.Those route calculations are not an assembly placement authority.@@ -132,3 +133,7 @@ Ground truth:```powershelldotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll asm inspect fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm --json --profile```++## Owl authoring update++Expose forwarding may traverse definition-owned structural pattern groups to a public component port. Encapsulated component privacy remains enforced; this does not grant arbitrary descendant access. The guitar tuners forward six StringEntry ports for fixed route binding.diff --git a/docs/public/firmament/authoring-composition-proposal.md b/docs/public/firmament/authoring-composition-proposal.mdindex e082b58f..034cb0d2 100644--- a/docs/public/firmament/authoring-composition-proposal.md+++ b/docs/public/firmament/authoring-composition-proposal.md@@ -1,19 +1,121 @@# Firmament authoring and composition: proposals from GUITAR-SURFACING-X0-Status: **roadmap; Foundations A–C now have a bounded implementation.**-See [the implemented assembly authoring foundation](assembly-authoring-foundation.md)-for supported syntax, limits, and the guitar reassessment. Remaining sketches-below retain their proposed status; Authoring D is deferred for review.+Status: **bounded owl implemented on 2026-10-01; advanced contracts remain explicit follow-ons.**+The checklist below distinguishes shipped bounded capabilities from remaining+contracts. The original numbered proposals remain for traceability; their sketches+are superseded wherever a linked implementation guide specifies different syntax.The guitar demonstrated that the existing exact geometry and display paths can produce a convincing designed object. It also required a Python source generator to assemble 107 occurrences, calculate transforms, expand repeated hardware, generate spline controls, calculate fret spacing, and construct string routes. That generator emits ordinary Firmament; it does not replace the kernel. Nevertheless, too much design intent lives outside the language.The objective is to move those responsibilities into typed, finite Firmament authoring and existing compiler owners. This is a proposal for several bounded milestones, not a request for a general scripting language, universal constraint solver, or new surfacing kernel.-All code blocks below are **proposed syntax**, including blocks that reuse existing constructs. They are design sketches, not compile-ready fixtures. Names such as `Body.Top`, `Neck.Nut` and `Pickup.Seat` denote proposed published ports; they are not currently emitted by the guitar fixtures. Implementations must publish those ports before the examples can resolve.+Code blocks in the original numbered proposals are historical **design sketches**,+not compile-ready fixtures. Use the linked implementation guides and current+guitar modules for supported syntax and published port names.++## Session checkpoint: original friction checklist++**Addressed** means the first bounded slice works through the real compiler and+guitar witness. It does not mean every extension described in the original+proposal is implemented. **Partial** means useful functionality shipped but a+named part of the original contract remains. **Open** means the proposed+source-level capability has not shipped.++| Original item | Status | What works now | Remaining friction / boundary |+| --- | --- | --- | --- |+| 1. Assembly Patterns | **Addressed, bounded** | Keyed finite occurrence families, shared definitions, stable identities and expanded provenance. Six guitar patterns cover saddle, tuner, control, fret and inlay families. | No nested assembly patterns, arbitrary relationship-pattern bodies or patterned Expose collections. Pickup poles correctly use feature repetition inside one part instead. |+| 2. Readable frames and placement | **Addressed, bounded** | FrameTransform, local translation/rotation, published-frame alignment and single placement authority. Headstock/tuners and point-route forming no longer require Python transform math; fixed placed endpoints use public-frame Bind. | General frame-valued expressions and dynamic endpoint scopes remain follow-ons. |+| 3. Definition-owned semantic ports | **Addressed, bounded** | Ordinary part and SectionChain publications; nested forwarding/privacy; body deck, neck terminals, component mounts and board MarkerOrigin. | No general stable face/curve selector or arbitrary surface port publication. Not every geometric face is source-addressable. |+| 4. Interface depth | **Partial; core seating shipped** | Fixed Gap/Clocking, role/member checks, Concept-plane-directed seating with material evidence, Concept-axis Fixed stacks and complete-component Revolute placement. | Rich reusable dimension/fit predicates and arbitrary cross-scope datum targeting remain limited. Generalized user-defined Lower is superseded, not unfinished work to implement. |+| 5. Profile/section families | **Addressed for the guitar** | Generic Profile outputs with local-guide hygiene, keyed Section Patterns, inline Concept frames, periodic boundary derivatives. Body and flat neck recipes are now source-owned. | Higher-order Profile arguments and general InterpolatingLoop2 remain outside this slice. |+| 6. Straight/fair surfacing intent | **Partial: witness fixed, language contract open** | Approved flat-ish neck, isolated heel stations, existing G1 SectionChain path and side-profile regression checks. | No explicit per-transition Law/endpoint tangent authoring or declarative StraightBack envelope contract. The present fix is an authored station recipe, not a new global straightness proof. |+| 7. Non-planar attachment | **Partial; datum-first model clarified** | Concept planes derive from published physical construction frames with offset/clocking; consumers seat on that scaffold. The guitar deck no longer needs an independent bridge-height guess. | Tangent-frame evaluation on analytic/SectionChain surfaces, explicit location/trim/seam rules and curved-base footprint support are not implemented by frame derivation alone. |+| 8. Engineering expressions and finite sites | **Addressed, bounded** | Pure scalar Function arithmetic and Pow, equation-driven 22-fret series, keyed nut crossings, explicit linear inlay stations, ordinary Linear/Mirrored component sites. | Angle trigonometry, typed vector/frame operations, geometry-valued arguments/results and equation-defined curves remain bounded follow-ons. Functions already run during compilation; no Comptime keyword is needed. |+| 9. Point-driven WireForm | **Addressed, bounded** | Six strings bind final public tailpiece/nut/tuner frames; typed Point3 specialization and placement-aware cache inputs. First finite Concept Line3 Follow guide lowers to exact WireForm. | Fixed assemblies only; tangent exits. Exact Via, multiple corners, circular/spline guides, route outputs and obstacle search remain deferred. |+| 10. Semantic appearance binding | **Addressed, bounded** | Physical Material owns its default Appearance; occurrence with overrides the finish. USD and Cycles consume authored identities. Look-only edits reuse exact geometry. | Physical aliases do not certify engineering properties; procedural sunburst/pearl and pickup shading remain downstream. |+| 11. Unified compilation and diagnostics | **Addressed front door; deeper tooling partial** | Root-aware build/inspect delegates to existing owners; repeat inspection exposes cache reasons/timings. Section keys, bound endpoint provenance, new schema fields and snapshot cross-file navigation are covered. | Aggregate project diagnostic locations, full generated-span mapping, every draft grammar and client integration remain follow-ons. |++Implementation references: [assembly foundation](assembly-authoring-foundation.md),+[published-frame and boundary derivation](concept-derivation.md),+[datum seating](datum-seating.md), [coaxial mating](concept-axis-mating-proposal.md),+[profile boundary edits](profile-boundary-edits.md),+[Functions and point collections](concept-points-and-functions.md), and+[point wire routes](wire-point-routes.md).++### Additional wins beyond the original eleven items++- [x] **Component-oriented containment:** guitar.firmasm composes multiple modules;+ knobs, selectors and tuners are complete reusable components, rather than+ assemblies collecting unrelated categories of features.+- [x] **Functional part construction:** two pickups instantiate one feature-built+ Humbucker definition. Housing, coils and repeated poles are part features.+ [Functional pickup construction](functional-pickup.md) records the qualified subset.+- [x] **Basic incremental compilation:** a retained+ [FirmamentCompilationSession](incremental-compilation.md) reuses successful exact+ definition materializations with source/dependency-aware invalidation. Placement,+ validation, tessellation and export still run. Ordinary declaration edits may+ invalidate many parts conservatively; this is not a minimal dependency graph or+ a cross-process CLI cache.+- [x] **Human-authored station convention:** pearl distances are written at 0.1mm+ resolution; the largest migration shift is 0.044mm, inside the stated 0.1mm+ physical tolerance. Compiler intermediates and kernel tolerances stay precise.++### Bounded owl delivered++- [x] **Source-owned profile/section families:** shared generic body and neck+ recipes, keyed section rows, stable spans, periodic derivatives, approved flat+ shaft retained. Python is now a read-only reproduction harness.+- [x] **Authoring front door:** root-aware build/inspect, retained-session timing+ and cache reasons, section associations and route endpoint provenance; schema+ help and snapshot navigation for the added syntax.+- [x] **Placed endpoints and first guide:** fixed public-frame Bind inputs and one+ finite Concept Line3 Follow interval with exact entry fillet and tangent exit.+- [x] **Semantic appearance:** Material default plus with finish override; authored+ identities replace renderer name matching and leave geometry buffers unchanged.+- [x] **Reassess further surface/Interface work against a real case:** guitar deck+ seating already has physical evidence. No new arbitrary curved-attachment case+ was needed; tangent/trim/seam/footprint and richer dimension predicates remain+ named follow-ons, rather than speculative scope added to this milestone.++[Implemented syntax and limits](source-owned-guitar-authoring.md) supersede the+historical sketches below. Procedural rendering remains downstream; no geometry+recipes are generated in Python. Editor coverage is bounded, not a claim of full+source-map or all-client completion support.++### Owl closeout evidence++Release solution build passed; 95 focused Firmament and 27 CLI tests passed.+Fast Core passed 1,004; the full serial solution gate passed **4,225**, with zero+failures and seven existing skips across 21 projects. Fresh STEP/USD and six+full-resolution Cycles views are in ignored artifacts/local/owl, with a short+report, inspection/provenance, timing, mesh checks and input-hash evidence.+Cached/uncached USD is identical. Cold/warm/cached compile times were 11.105s,+5.108s and 0.887s; all 53 definitions reused in the cached lane. Camera changes+in the compiled Cycles scene preserve product topology and invoke no Firmament+build; no refreshed native Storm orbit or measured Zoo ratio is claimed.++### Prior checkpoint evidence++The current root is [guitar.firmasm](../../../fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm).+Prior checkpoint code qualification (before the owl slice): Release solution build, 47 focused tests,+1,004 fast core tests, and 4,192 full serial solution tests passed, with 7 existing+skips. The current witness has 91 visible parts, 53 geometry definitions, 10+reusable assembly definitions and six assembly patterns. USD has 163 occurrence+nodes including its root; STEP has 162 occurrences and 63 definitions.++The prior inlay migration preserves every definition's geometry buffers and all+non-inlay transforms. Cycles verifies nine pearl assignments, two pickup treatments+and unchanged imported product topology. These are current model/export/render+checks, not a new camera-orbit or Zoo timing comparison. Earlier build/performance+numbers in linked milestone guides are explicitly historical snapshots.++Reproducible local evidence is under ignored `artifacts/local/linear-stations/`:+report.md/json, inspection, comparison, STEP/USD, full-gate TRX and the Cycles+preview/scene. This checkpoint also refreshes CLI inspection of the current root.## Evidence and current baseline-The motivating source is [the guitar generator](../../../scripts/create-guitar-x0.py), its [authored fixtures](../../../fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar-x0.firmament), and the [witness report](../demos/guitar-surfacing-x0.md).+The motivating source is [the guitar generator](../../../scripts/create-guitar-x0.py), its [current composition root](../../../fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm), and the [witness report](../demos/guitar-surfacing-x0.md).Current capabilities should be extended, not accidentally proposed a second time:@@ -34,13 +136,13 @@ During this audit, `aetheris asm inspect fixtures/Canonical/AssemblyInterfaces/t| 2. Frame composition and placement | P0 | Rigid local offsets/rotations and named frame alignment | Existing datum-frame and placement IR || 3. Definition-owned semantic ports | P0 | Authored frames and SectionChain terminal frames | Existing semantic values and Expose || 4. Deeper Interface contracts | P0 | Frame member requirements, seating gap and clocking | 2–3 |-| 5. Section/profile family authoring | P1 | Parameterized profiles and finite section sets | Existing Templates, Patterns and SectionChain |+| 5. Profile/section families | **Addressed for the guitar** | Generic Profile outputs with local-guide hygiene, keyed Section Patterns, inline Concept frames, periodic boundary derivatives. Body and flat neck recipes are now source-owned. | Higher-order Profile arguments and general InterpolatingLoop2 remain outside this slice. || 6. Explicit straight/fair transition intent | P1 | Endpoint tangent constraints and named transition laws | Existing SectionChain tangent/materializer path || 7. Placement on curved supports | P1 | Named analytic support, explicit location and clocking | 2–4; surface evaluator || 8. Dimensioned engineering expressions | P1 | Pure scalar arithmetic, small math set and finite sampling | Existing compile-time value evaluator |-| 9. Point-driven WireForm routes | P1 | Three points, one explicit bend radius | 2–3, existing WireForm |-| 10. Semantic appearance binding | P2 | Named simple looks bound to definitions/occurrences | Existing USD appearance path |-| 11. Unified build and source diagnostics | P0 alongside each slice | Dispatch, generated-source provenance and dependency reports | Existing CLI, schema and language analysis |+| 9. Point-driven WireForm | **Addressed, bounded** | Six strings bind final public tailpiece/nut/tuner frames; typed Point3 specialization and placement-aware cache inputs. First finite Concept Line3 Follow guide lowers to exact WireForm. | Fixed assemblies only; tangent exits. Exact Via, multiple corners, circular/spline guides, route outputs and obstacle search remain deferred. |+| 10. Semantic appearance binding | **Addressed, bounded** | Physical Material owns its default Appearance; occurrence with overrides the finish. USD and Cycles consume authored identities. Look-only edits reuse exact geometry. | Physical aliases do not certify engineering properties; procedural sunburst/pearl and pickup shading remain downstream. |+| 11. Unified compilation and diagnostics | **Addressed front door; deeper tooling partial** | Root-aware build/inspect delegates to existing owners; repeat inspection exposes cache reasons/timings. Section keys, bound endpoint provenance, new schema fields and snapshot cross-file navigation are covered. | Aggregate project diagnostic locations, full generated-span mapping, every draft grammar and client integration remain follow-ons. |Ship 2–3 first as a small foundation, then 1 and the first part of 4. Do not require curved-support placement or a material language before making ordinary assemblies pleasant to author.@@ -157,33 +259,42 @@ Interface<Fixed> VeneerSeat {Define `Gap` along A's outward local Z, and `Clocking` about that axis. `OpposedDirection` must have a documented right-handed mapping, including its X reference; flipping only Z is invalid. The result is a fixed offset, not a hidden translational/rotational DOF. Absence of these new fields preserves current zero-coincident behavior.-Then deepen reusable named Interfaces without inventing a new compiler-owned generic family for every product:+**Review correction: the general Lower-language sketch is superseded.**+The chosen model declares Concept layout geometry first, then realizes published+material ports relative to that scaffold. It does not ask Firmament to reconcile+multiple material-to-material constraints or introduce a user-defined constraint+lowering language.++The implemented [Concept-directed seating](datum-seating.md) form separates a+shared datum contract from per-member realization:```firmament-Interface MountedHardware {- Parameter Gap: Length = 0mm- Role Support requires {- Frame: DatumFrame- AvailableWidth: Length- }- Role Hardware requires {- Frame: DatumFrame- RequiredWidth: Length- }- Lower FrameCoincident Support.Frame Hardware.Frame OpposedDirection- Lower OffsetAlongAxis Support.Frame.Z Hardware.Frame.Origin Gap- Require WidthFits => Hardware.RequiredWidth <= Support.AvailableWidth+Concept Struct Layout {+ Plane Deck { Origin: [0mm,0mm,53mm]; Normal: [0,0,1]; Up: [0,1,0] }+ DatumFrame BridgeSeat { On: Deck; At: [0mm,-35mm]; X: [1,0] }}--Mate BridgeSeat: MountedHardware<Gap: 2mm> {- Support: Guitar.Body.BridgeSeat- Hardware: Guitar.Bridge.Mount+Interface<Fixed> DeckSeat {+ Datum: Layout.Deck+ Members: [Hardware.Bridge.BottomSeat]+}+Mate BridgeOnDeck: DeckSeat {+ Member: Hardware.Bridge.BottomSeat+ At: Layout.BridgeSeat+ Orientation: SameDirection}```-The two `Lower` lines illustrate intent. The implementation must normalize them into **one seated-frame relation** before solving, rather than demand zero frame coincidence and a nonzero offset simultaneously. Prefer exposing that normalized relation directly if the combined spelling is misleading during syntax review.+The same design extends to [Concept axes](concept-axis-mating-proposal.md), with+station and clocking. Shared scaffolding is erased; existing placement and+kinematic machinery own the resulting physical realization. Published-frame+[derivation](concept-derivation.md) supplies explicit offsets/clocking when the+scaffold should follow a physical construction reference.-Role member requirements are checked before lowering, with exact member/type diagnostics. Parameters are finite typed values. `Require` reads resolved semantic dimensions, not arbitrary mesh measurements. A `WidthFits` check is a width contract, not proof that a curved mounting footprint is collision-free.+Role/member capability checks, membership, privacy and placement authority are+implemented. Rich reusable dimension predicates remain separate work: a width+comparison may eventually read published dimensions, but it is not yet the+complete WidthFits contract in the original sketch and never proves curved+footprint contact. No new generic Lower language is needed to add such checks.Reuse current fits, tolerance and capability semantics. Inspection should distinguish fully located, deliberately movable, unresolved and contradictory relationships, name the owning driver, and report meaningful residuals. Do not add generic loop closure, nonlinear contact solving or arbitrary equation solving in this milestone.@@ -307,6 +418,11 @@ This locates a point/frame. It does **not** prove that a wide flat hardware base## 8. Pure engineering expressions and finite sample sets+Implemented bounded slice: [`Function` and `Points<Point2|Point3>`](concept-points-and-functions.md).+The guitar uses a keyed `Series` for its 22 frets. The `SampleSet` spelling below+is the original proposal, superseded by the implemented Concept geometry syntax.+Angle trigonometry and vector intrinsics remain deferred.+**Friction:** fret positions require `ScaleLength * (1 - 2^(-n/12))`; the Python generator also handles taper interpolation and geometry-vector calculations. A finite value calculation should not force source generation.```firmament@@ -329,7 +445,12 @@ Extend the existing typed value evaluator rather than inventing an assembly-only## 9. Point-driven WireForm routes-**Friction:** each guitar string currently needs Python to calculate directions, bend angle, tangent setbacks and its placement basis. WireForm already owns the exact straight/bend construction.+Extended design: [Wire routing and Concept guides](wire-routing-and-guides-proposal.md)+adds hard Via points, locked arc-length guide intervals and bounded connector+planning. The [three-point guitar migration](wire-point-routes.md) is implemented; guided+routing now has a bounded Line3 guide and placed-port binding; obstacle search remains deferred.++**Original friction (three-point slice resolved):** each guitar string needed Python to calculate directions, bend angle, tangent setbacks and its placement basis. WireForm already owns the exact straight/bend construction.```firmamentWireRoute LowE {@@ -393,9 +514,26 @@ Generate schema/completion/hover data with each new construct, and maintain brow## Review decisions and boundaries-The highest-value initial decision is the composition model: should direct frame placement be an explicit layout authority alongside Interfaces, or syntax that lowers to a fixed Interface? This draft prefers the former, with one driver per occurrence and a common transform owner. Mechanical contracts remain visible when the author declares them.--Review the seated-frame syntax before implementation. A combined relation is clearer than contradictory primitive relations with a hidden precedence rule. Also settle named pattern identity, the coordinate space of frame references, and definition-level port publication before introducing surface attachment syntax.+The composition model is settled for the implemented lane:++- Concept geometry supplies the design scaffold; physical ports realize a declared+ relationship to it. Direct readable Placement remains an explicit layout option.+- Each occurrence has one placement authority. Fixed seating and coaxial mating+ delegate to existing frame/kinematic owners rather than introducing general+ simultaneous constraint solving.+- Definition-owned semantic publication and explicit subassembly forwarding+ preserve privacy and local/world coordinate meaning.+- A part owns its features; an assembly contains complete reusable components.+ Keyed Pattern expansion preserves identity independently of specialization.+- Functions evaluate during compilation. Finite point recipes, profile edits and+ routing lower to existing typed IR and materializers; no runtime language is added.+- Explicit scalar placements use conventional 0.1mm authoring resolution unless+ a more specific physical tolerance is stated. Numeric computation stays precise.++Future proposals should extend these decisions. The old Lower language,+material-to-material constraint network and a mandatory universal SurfaceAttachment+constructor are not prerequisites. Surface-driven placement should derive an+explicit Concept frame under a qualified support/location contract.Each milestone should include one valid guitar-sized fixture, targeted invalid cases, CLI inspection, schema/language-analysis coverage, and the full existing solution test lane. Geometry changes require exact topology/pcurve/STEP qualification; appearance-only changes require binding and unchanged-geometry evidence. Generated artifacts stay under ignored `artifacts/local/`; durable examples belong under `fixtures/`.diff --git a/docs/public/firmament/casing-and-layout-proposal.md b/docs/public/firmament/casing-and-layout-proposal.mdnew file mode 100644index 00000000..2345d1ed--- /dev/null+++ b/docs/public/firmament/casing-and-layout-proposal.md@@ -0,0 +1,237 @@+# Firmament casing and layout proposal++Status: accepted convention; bounded formatter and guitar sweep implemented,+2026-10-01. The current contract is [language style](language-style.md).+The audit below records the pre-change behavior. This is not an exhaustive+syntax migration: authored ports and template arguments require paired manual+edits; unknown scopes and legacy spellings may remain. The guitar STEP, USD and+display geometry are unchanged by the implemented sweep.++Keep the artifact vocabulary prominent, and let its descriptions read quietly.+Firmament should still read as a specification of objects, scaffolding, and+construction recipes. PascalCase on every property and reference currently makes+all those different roles compete for attention.++## Pre-change audit++- `language-style.md` prescribes PascalCase for both constructs and built-in+ fields. Authored names remain stylistically free.+- `FirmamentV2Parser` mixes case-sensitive canonical construct patterns with+ selected case-insensitive compatibility paths. Lowercasing a file is not a+ supported general conversion.+- `AssemblyM0Parser`, `AssemblyFrameAuthoring`, Concept point expansion, and+ Template/Feature binding also match specific spellings. For example,+ `TranslateLocal`, `Over`, `On XY`, and named Record members do not all share+ one spelling policy.+- The actual V2 editor formatter is+ `FirmamentLanguageAnalysisService.Format`. It preserves token text, changes+ spacing/layout, and reparses with `FirmamentV2Parser`. It does not currently+ perform semantic renaming or select all the assembly/project authoring paths.+ The older `FirmamentFormatter` and `FirmamentCanonicalFormatter` belong to+ the compatibility frontend and are not the V2 migration seam.+- Generated semantic schemas already separate stable construct/field IDs from+ their displayed names. That is a useful existing seam for preferred spelling,+ completions, hover, and formatting; it is not yet a universal grammar registry.+- Symbol and published-port lookups use case-sensitive identities. Names also+ feed generated pattern identities, STEP product names, and provenance.++The current standalone functional pickup still validates through Aetheris.CLI.+The proposed spellings have not been compiled. Existing source remains the+compatibility baseline.++## Recommended convention++| Semantic role | Convention | Examples |+| --- | --- | --- |+| Artifact/declaration and construction kinds | PascalCase | `Model`, `Assembly`, `Part`, `Concept Struct`, `Profile`, `Compose`, `Feature`, `WireRoute`, `FrameTransform` |+| Reusable definition/type names | PascalCase | `Humbucker`, `ControlKnob`, `PickupSpec`, `Length`, `Point2` |+| Concrete values, local geometry, occurrences, patterns, public ports | camelCase | `standardPickup`, `layout`, `outline`, `neckPickup`, `poles`, `bottomSeat` |+| Property labels and value parameters | camelCase | `width`, `polePitch`, `from`, `translateLocal`, `minimumBendRadius`, `spec` |+| Linking words and scope directives | lowercase | `using`, `on`, `over`, `with`, `return`, `include`, `expose`, `bind` |+| Scalar math functions and their parameters | camelCase | `fretDistance(n, scale)`, `pow(...)` |+| Built-in variants, domain symbols, and external identities | Preserve domain spelling | `Fixed`, `Revolute`, `Periodic`, `Stock`, `XY`, `+Z`, `mm`, `304_Annealed` |++This is a recommendation for authored style, not a rule that infers a symbol's+type from its capital letter. Definitions and occurrences are distinguished by+their declaration/binding context. A root product may retain its definition's+name, such as `Assembly GuitarX0` and `<Assembly GuitarX0>`; nested occurrences+then read as `body`, `neck`, and `electronics`.++Keep `Static`, `Template`, `Record`, and `Function` as explicit declaration+kinds. Keep geometry and engineering forms such as `Placement`, `Interface`,+`Mate`, `Linear`, `Series`, `Require`, and `Assert` prominent too. An anonymous+`Placement` is still a domain construct; it does not become lowercase simply+because it has no authored name. `expose` and `bind` introduce publication and+input scopes rather than a new physical object.++Reusable Feature constructors remain PascalCase, e.g. `Coil(...) -> Boss`.+Their returned construction and named invocation results read as ordinary+values. Scalar Functions use camelCase, e.g. `fretDistance(...) -> Length`.+Both remain bounded compile-time evaluation; this adds no runtime execution,+`Comptime` keyword, inheritance, or general statement language.++## Pickup: quieter fields, visible construction++Current excerpt:++```firmament+Feature Coil(Center: Point2, Width: Length, Depth: Length,+ Height: Length, Support: Plane) -> Boss {+ RoundedRect2 Outline { Center: Center; Size: [Width,Depth]; Radius: 3mm }+ Profile Section { Loop Outer { Outline |> TraceLoop } }+ return Boss { On: Support; Profile: Section; Height: Height }+}+```++Proposed spelling and layout:++```firmament+Feature Coil(center: Point2, width: Length, depth: Length,+ height: Length, support: Plane) -> Boss {+ RoundedRect2 outline {+ center: center;+ size: [width, depth];+ radius: 3mm;+ }++ Profile section {+ Loop outer { outline |> TraceLoop }+ }++ return Boss {+ on: support;+ profile: section;+ height: height;+ }+}+```++The same distinction helps the specification and its instances:++```firmament+Record PickupSpec {+ width: Length;+ depth: Length;+ polePitch: Length;+}++Static standardPickup: PickupSpec {+ width: 88mm;+ depth: 46mm;+ polePitch: 10.2mm;+}++Static bridgePickupSpec = standardPickup with { polePitch: 10.4mm }++// Inside the full Humbucker recipe's Compose body:+Feature poleSeed = Pole(center: layout.firstPole, support: coilTop)+Linear Pattern poles {+ source: poleSeed;+ direction: layout.longitudinal.direction;+ count: 6;+ spacing: spec.polePitch;+}+```++These are excerpts, not standalone complete pickup definitions. `width` in the+Record is an authored member; `size` in `RoundedRect2` is a compiler-owned field.+They look consistent but require different migration mechanisms.++## Assembly: preserve the product tree++```firmament+Subassembly ControlKnob {+ <Assembly ControlKnob>+ <Part skirt = Drum<R: 12mm, H: 3mm>>+ material: Brass;+ </Part>+ <Part grip = Drum<R: 9mm, H: 9mm>>+ material: AmberPolymer;+ </Part>+ </Assembly>++ Interface<Fixed> coaxialStack {+ datum: knobLayout.spindle;+ members: [ControlKnob.skirt.spindleSeat, ControlKnob.grip.spindleSeat];+ }++ Mate gripOnSpindle: coaxialStack {+ member: ControlKnob.grip.spindleSeat;+ at: 3mm;+ clocking: 0deg;+ }+}+```++This excerpt assumes the referenced scaffolding and ports exist. The XML-like+containment still makes the assembly explicit. The lowercase properties explain+how its objects relate. Existing `Drum` parameter names `R` and `H` are preserved+here deliberately: replacing them with `radius` and `height` requires changing+the definition and its bound call sites, rather than formatting a use site.++Likewise, keep current published `.Frame`, `.BottomSeat`, and other authored+members until a definition-aware rename changes their declarations and every+reference. New definitions should prefer `frame` and `bottomSeat`. Intrinsic+point projections such as `point.Position.X` can gain preferred+`point.position.x` spelling only through their owning point binder; a formatter+must not lowercase arbitrary dotted references.++## Layout rules++Use two-space indentation, preserving the current V2 convention. Give substantial+objects and multi-field interfaces one field per line, and separate scaffolding,+material construction, and publication with blank lines. Keep tiny single-field+blocks compact where they remain legible. Keep closing XML tags on their own+lines for multi-line occurrences.++Use spaces after commas and around assignments, arrows, and arithmetic. Keep+unit suffixes attached (`0.1mm`, `13deg`) and dotted references uninterrupted.+Prefer descriptive new parameters to abbreviated `L/W/H/R`, with explicit+refactoring for existing definitions. Use a soft 100-column wrapping target;+never reorder profile spans, route events, section stations, keyed Sets, or+assembly children to satisfy layout.++Preserve semicolons required by the owning grammar. A formatter may standardize+optional field terminators only in grammars that admit them; this is not a reason+to redesign delimiters in the casing milestone. Preserve comments, quoted text,+numeric literals, engineering units, and material/standard identifiers. In+particular, do not round derived surface controls while formatting. The guitar's+0.1 mm authoring convention does not authorize changing exact geometry values.++## Implementation boundary++1. **Compiler-owned spelling aliases.** Give constructs, fields, and admitted+ linking words preferred source spellings and explicit legacy aliases, with+ stable semantic IDs unchanged. Resolve a field under its owning construct;+ reject duplicate aliases such as `From` plus `from` in the same block. Keep+ user names and external identities case-sensitive. Do not make every regex+ case-insensitive or globally lowercase the source.+2. **Safe formatting.** Extend the existing V2 formatting service using bound+ token roles and source spans, not string replacement or BRep reconstruction.+ Apply preferred spelling only to positively identified compiler-owned tokens.+ Use the appropriate existing frontend/project context for admission before+ and after formatting. Preserve unknown/ambiguous tokens or leave that document+ unformatted with a specific diagnostic. No second grammar in the editor.+3. **Separate authored-name refactoring.** Offer an explicit, previewable rename+ for Record fields, parameters, concrete geometry, ports, and occurrences.+ Include imported definitions and references; refuse incomplete project+ context and collisions. Ordinary Format Document must not change public+ identities, generated pattern keys, STEP product names, or exported provenance.+ A reviewed migration may intentionally change those names; compare geometry+ and report the identity changes rather than calling them byte-equivalent.+4. **Dogfood and qualify.** First apply supported spelling/layout to the guitar's+ pickup, knob, and composition root. Qualify each newly admitted construct or+ frontend before advertising its spelling. Generate completions/help from the+ same authority and then update canonical documentation and fixtures. Keep+ accepted legacy source working during migration; do not repoint the current+ style guide at unsupported snippets.++Verification should check legacy/preferred semantic equivalence, unchanged+geometry and transforms, unchanged identities for formatting alone, idempotence,+comments/strings, alias collisions, and binding-sensitive renames. Include the+guitar, profile editing, section chains, WireForm routes, and PMI release records,+then run the repository's Release build, fast lane, and full serial gate.++The first bounded implementation should be preferred field labels and linking+words plus layout, with authored-name migrations kept explicit. It should not+rename the language's artifact constructs or redesign its authoring grammar.diff --git a/docs/public/firmament/concept-points-and-functions.md b/docs/public/firmament/concept-points-and-functions.mdnew file mode 100644index 00000000..999db339--- /dev/null+++ b/docs/public/firmament/concept-points-and-functions.md@@ -0,0 +1,225 @@+# Concept points and Functions++Implemented: keyed local `Points<Point2>` / `Points<Point3>` collections and pure,+expression-bodied scalar `Function` declarations. Functions always evaluate+during compilation. There is no `Comptime` keyword or runtime execution.++## Nut crossings++```firmament+Concept Struct NutLayout {+ Points<Point2> Crossings {+ Keys: [String0, String1, String2, String3, String4, String5];+ Linear {+ Start: Point2(-18mm, 0mm);+ Step: [7.2mm, 0mm];+ }+ }+}+```++The six points are local millimeter coordinates. Named references such as+`NutLayout.Crossings.String0.X` and `.Y` resolve to checked scalar values.+`NutLayout.Crossings.String0` resolves to `Point2(-18mm,0mm)`; `.Position` is+an equivalent explicit point projection. A Point2 has no Z coordinate.+Moving the nut does not change this scaffold. A physical placement must name+the frame that gives these local coordinates their spatial meaning.++Function expressions and point-recipe fields use explicit semicolon terminators+in this bounded grammar.++Manual collections use `Key: Point2(...);` or `Key: Point3(...);` members:++```firmament+Concept Struct Supports {+ Points<Point3> Seats {+ Bass: Point3(-18mm,0mm,2mm);+ Treble: Point3(18mm,0mm,2mm);+ }+}+```++## Explicit stations along a line++An alternative Linear recipe declares independent, keyed distances rather than+equal pitch. It produces the same Point2/Point3 collection:++```firmament+Concept Struct FretboardLayout {+ Points<Point2> InlayPositions {+ Linear {+ Start: Point2(0mm,0mm);+ Direction: [0,-1];+ Stations {+ Fret3: 84.2mm;+ Fret5: 143.5mm;+ Fret7: 196.4mm;+ Fret9: 243.5mm;+ Fret12: 304.7mm;+ Fret15: 356.1mm;+ Fret17: 385.8mm;+ Fret19: 412.2mm;+ Fret21: 435.7mm;+ }+ }+ }+}+```++Each station computes `Start + normalized(Direction) * Distance`. Direction is+a nonzero dimensionless vector with the same dimensionality as the collection.+Distances are finite Length expressions; negative distances and explicitly+coincident stations are permitted. Keys are unique identifiers. Declaration+order supplies ordinals; stable identities depend on keys, so reordering does+not reassign positions. Keys/Step and Direction/Stations are mutually exclusive.+The existing 1024-point per-collection and 4096-point total bounds apply.++Guitar station distances are authored at **0.1mm resolution**, following the+default physical authoring convention when no tighter tolerance is stated.+Rounding to a tenth moves an old station by at most 0.05mm. This convention+does not round compiler intermediates or change kernel numerical tolerances.++The Board template publishes its top-surface marker frame:++```firmament+Expose {+ Semantic MarkerOrigin {+ DatumFrame Frame = [0mm,658mm,H] x [1,0,0] y [0,1,0] z [0,0,1];+ }+}+```++Inside GuitarNeck, consume stations using the existing Pattern and Placement:++```firmament+FrameTransform InlayDatum { From: GuitarNeck.Rosewood.MarkerOrigin.Frame; }++Pattern PearlInlays Over FretboardLayout.InlayPositions {+ point => <Part Inlay = Panel<L:25mm,W:12mm,H:0.3mm,R:1mm>>+ Placement {+ From: BottomSeat.Frame; To: InlayDatum.Frame;+ TranslateLocal: [point.Position.X,point.Position.Y,0mm];+ }+ </Part>+}+```++Collinearity follows from the recipe, and seating/orientation follows from the+board-owned frame. Moving or rotating that board carries its inlays. This is+datum seating; footprint containment and recessed pearl pockets are separate+geometry concerns. The current inlays remain decorative panels on the board.+Inspection preserves the authored Stations recipe and keyed point coordinates;+ordinary pattern inspection supplies occurrence associations and provenance.++## Equation-driven frets++```firmament+Function FretDistance(n: Int, scale: Length) -> Length =+ scale * (1.0 - Pow(2.0, -n / 12.0));+Function FretWidth(distance: Length) -> Length =+ 42mm + 13mm * ((distance + 2mm) / 540mm);++Concept Struct FretboardLayout {+ Points<Point2> Positions {+ Series {+ Index: n;+ First: 1;+ Count: 22;+ KeyPrefix: Fret;+ Position: Point2(0mm, -FretDistance(n,628mm));+ }+ }+}+```++`First` and `Count` are literal integer bounds. This produces Fret1 through+Fret22, in ascending index order; Fret12 is exactly `[0mm,-314mm]`.+The authored recipe and each point's key, ordinal, dimensionality, coordinates+and stable identity remain in inspection evidence.++The guitar consumes the series with the existing assembly Pattern syntax:++```firmament+Pattern Frets Over FretboardLayout.Positions {+ point => <Part Fret = Panel<L:FretWidth(-point.Position.Y),W:1.2mm,H:1mm,R:0.5mm>>+ Placement {+ From: BottomSeat.Frame;+ To: FretboardDatum.Frame;+ TranslateLocal: [point.Position.X, point.Position.Y, 0mm];+ }+ </Part>+}+```++In `GuitarNeck`, the placement frame is explicitly derived from the nut:++```firmament+FrameTransform FretboardDatum { From: GuitarNeck.Nut.BottomSeat.Frame; }+```++Occurrences have paths such as `GuitarX0.Neck.Frets.Fret12.Fret`. Changing+scale length moves the keyed occurrences without changing their occurrence+identities. Definition identities still reflect their actual geometry arguments.+Patterns preserve the logical collection name in expanded associations.++## Compilation contract++- Functions have unique names in the compiled source catalog, at most 16+ parameters each, and `Int`, `Float`, `Length` or `Angle` arguments/results.+ Forward calls are permitted; recursive dependency cycles are rejected.+- Expressions admit literals, parameters, parentheses, unary signs, arithmetic,+ other declared Functions, and dimensionless `Pow(base,exponent)`.+ Division is real division, including when both operands are integral.+- Lengths use `mm`, angles use `deg`. Addition/subtraction require matching+ dimensions. Multiplication admits at most one dimensional operand. Dividing+ matching dimensions produces a dimensionless result. `Pow` requires both+ arguments to be dimensionless. Int arguments/results must be integral and+ exactly representable within the checked range ±(2^53 − 1).+- Each collection has 1–1024 points; total expansion is limited to 4096 points.+ Linear keys are unique identifiers, and the step must be nonzero. Series+ indices are nonnegative with checked integer bounds.+- Function catalogs have at most 128 declarations. Evaluation limits are+ 32 active Function calls, 10000 calls per scalar evaluation, 8192 characters+ per scalar expression and 128 nested scalar atoms. Non-finite results fail.+- There are no loops, mutation, recursion, I/O, reflection, host C# callbacks+ or arbitrary source evaluation. New errors use `firmament-concept-points-*`;+ assembly parsing wraps them in `assembly-pattern-invalid` diagnostics.++The shared scalar evaluator owns arithmetic and units. Checked Concept point+recipes project to the existing finite keyed Set frontend; the existing Pattern+expander remains the occurrence expansion authority. Concept collections retain+typed `ConceptIrKeyedPointSetValue` inspection data, are erased before geometry+construction, and contribute no bodies to STEP or display meshes. Point2 is+never silently promoted to Point3.++## Guitar dogfood and evidence++The directly authored `fixtures/Canonical/AssemblyInterfaces/GuitarX0/neck-assembly.firmament`+replaces 22 explicit fret tags and world positions with the declarations above.+The Python witness generator now preserves that module rather than overwriting+its fret authoring. The inlays now use the explicit station recipe and board-owned+marker datum above. Nut crossings feed the implemented [point wire routes](wire-point-routes.md).++CLI inspection, AP242 export and USD export succeed with 91 visible parts and+53 shared geometry definitions. The original fret-series milestone added 23 assembly nodes+(130 → 153 total occurrences); it adds no visible geometry. Comparison against+the previous witness preserves all mesh index arrays. Only fret coordinates+and widths change, by less than 0.000001mm, because the compiler evaluates the+formula at full precision rather than reading six-decimal Python output. These+counts/comparisons describe that earlier milestone. The inlay pattern additionally+adds 10 containment nodes (163 total display occurrences), retains nine visible+inlays and their shared geometry, and moves them only by the authored 0.1mm rounding.++Generated evidence lives under ignored `artifacts/local/concept-points/`:+`inspect.json`, `comparison.json`, `guitar.step`, `guitar.usda`, `display.json`,+focused test TRX/logs and full-suite logs. The reusable qualification fixture is+`fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/concept-points.firmament`.++Equation-driven profile curves, point-driven WireForm routing, scalar record+parameters, closures and a general collection programming language are deferred.++Final qualification: Release solution build passed; 32 focused authoring/guitar+tests passed; the fast kernel lane passed 1004 tests; the serial full solution+gate passed 4160 tests across 20 projects with tests, with 7 existing skips.+The Python generator was syntax-checked without regenerating the authored+witness. The final CLI exports and comparison use the same qualified build.diff --git a/docs/public/firmament/functional-pickup.md b/docs/public/firmament/functional-pickup.mdindex f556b1ba..9127d8b0 100644--- a/docs/public/firmament/functional-pickup.md+++ b/docs/public/firmament/functional-pickup.md@@ -130,3 +130,7 @@ Generated evidence is under ignored `artifacts/local/pickup-features/`:- `guitar/step-analysis.json`, `guitar/mesh-check.json`, `guitar/timings.json`,`guitar/render.json`: hierarchy, mesh, timing and shading evidence.- `solution-build.log`, `fast.log`, `closeout-full.log`: build and test validation logs.++## Owl authoring update++The create-guitar-x0.py command is now a read-only CLI reproduction harness. It no longer generates or rewrites pickup, body, neck or assembly source. Appearance is assigned semantically through Material and with, while pickup axial feature shading remains an honest downstream placeholder.diff --git a/docs/public/firmament/incremental-compilation.md b/docs/public/firmament/incremental-compilation.mdindex 81842ddb..7ffba7eb 100644--- a/docs/public/firmament/incremental-compilation.md+++ b/docs/public/firmament/incremental-compilation.md@@ -90,3 +90,7 @@ Recorded evidence is under ignored `artifacts/local/pickup-features/`:`incremental-final-timings.json`, `incremental-final-focused.log`,`incremental-final-build.log`, `incremental-final-fast.log` and`incremental-final-full.log`.++## Owl authoring update++Canonical assembly inspect --repeat 2 retains a session and reports per-build elapsed time and reuse/rebuild reasons. Appearance catalogs are excluded from geometry definition inputs; length-changing look-only edits reuse geometry. Placed route Point3 bindings are part of specialization identity, so endpoint placement changes invalidate the affected route. See [source-owned guitar authoring](source-owned-guitar-authoring.md).diff --git a/docs/public/firmament/language-style.md b/docs/public/firmament/language-style.mdindex 5badb30d..d7c568d9 100644--- a/docs/public/firmament/language-style.md+++ b/docs/public/firmament/language-style.md@@ -1,14 +1,90 @@# Firmament V2 language style-Firmament-owned vocabulary is canonically PascalCase. This includes document and declaration constructs, semantic features, built-in primitive and value names, and built-in fields. Canonical source therefore uses `Model`, `Units`, `Sphere`, `Modify`, `Analysis`, `Body`, `Region`, and `ThroughAll`.+Firmament uses mixed casing to make artifact definitions stand out from their+descriptions. This is a naming convention, not a rule enforced by the compiler.+The [design proposal](casing-and-layout-proposal.md) records the reasoning.-User-defined identifiers are case-preserving and stylistically free. `beam`, `Beam`, `mainDeck`, and `MAIN_DECK` may all be names when the owning construct admits an identifier. External identifiers preserve their engineering or source spelling, including material designations, standards, imported identities, and part numbers such as `5052_H32`.+| Role | Convention | Examples |+| --- | --- | --- |+| Artifact, declaration, construction form | PascalCase | `Model`, `Assembly`, `Concept Struct`, `Profile`, `Feature`, `Placement`, `Mate` |+| Type and reusable recipe | PascalCase | `Length`, `PickupSpec`, `Humbucker`, `ControlKnob` |+| Concrete value, local geometry, occurrence, parameter, port | camelCase | `layout`, `outline`, `neckPickup`, `bottomSeat`, `width` |+| Built-in property label | camelCase | `units`, `size`, `from`, `translateLocal`, `minimumBendRadius` |+| Linking and scope word | lowercase | `using`, `on`, `over`, `with`, `return`, `include`, `expose`, `bind` |+| Scalar function | camelCase | `fretDistance`, `halfWidth` |+| Engineering symbol, enum, external identity | Preserve domain spelling | `XY`, `+Z`, `Fixed`, `Periodic`, `Stock`, `mm`, `304_Annealed` |-Lowercase and historical aliases may remain accepted for compatibility when unambiguous. They receive no style warning and must not select different semantics. Documentation, snippets, generated examples, and `fixtures/Canonical/` use the canonical spelling.+The root product may keep its definition name: `Assembly GuitarX0` and+`<Assembly GuitarX0>`. Feature constructors such as `Coil` remain PascalCase.+Use two-space indentation, spaces after list commas, blank lines between major+definitions, and separate closing tags for multiline occurrences. Preserve+numbers and units; formatting must not round derived surface controls.-Semicolons are optional wherever newline/block structure already delimits a field. Use them when they improve readability in dense one-line Records, Tables, or `ProfileDelta` members; their presence must not select a different language path.+User-defined identifiers and published members remain case-sensitive.+`beam`, `Beam`, `mainDeck`, and `MAIN_DECK` remain valid wherever an identifier+is admitted. Case alone does not assign a semantic type. Material designations,+standards, imported identities and part numbers retain their source spelling.+Existing PascalCase properties and supported historical aliases remain accepted,+without style warnings. Older examples need not be rewritten wholesale.-Casing is not a type-system distinction unless a domain explicitly says otherwise. A field uses `Name: Value`; braces delimit declarations, brackets delimit lists, and semicolons are optional where the owning grammar is unambiguous.+```firmament+Feature Coil(center: Point2, width: Length, depth: Length,+ height: Length, support: Plane) -> Boss {+ RoundedRect2 outline { center: center; size: [width, depth]; radius: 3mm }+ Profile section { Loop Outer { outline |> TraceLoop } }+ return Boss { on: support; profile: section; height: height }+}+```++## Safe formatting and bounded compatibility++`aetheris format <file.firmament|file.firmasm>...` prints preferred vocabulary+spellings; add `--write` to update the explicitly named files, or `--json` for a+change summary. This conservative pass preserves layout, comments, strings,+numeric literals, user names and occurrence identities. It prepares every input+before writing and refuses a rewrite that changes normalized source text.+It is **not validation**: validate/build the consuming assembly after a sweep.++The same pass is available as+`FirmamentLanguageAnalysisService.FormatConventions`. The existing standalone+V2 `Format` API also prefers these spellings while arranging layout, and checks+both token equivalence and parser admission. Imported modules use the conservative+pass and their consuming project's compiler; they are not standalone parts.++Compatibility is scoped to schema-owned properties plus the bounded profile,+frame, assembly, point and wire vocabularies used by the guitar. The parser maps+these aliases back to existing semantic identities. Unknown blocks, Record and+Static data, explicit station keys, named template/Feature arguments and dotted+members are not guessed or renamed by the formatter. Property completion accepts+either prefix spelling; generated entry snippets prefer the new spelling, while+schema/field identities in inspection APIs remain stable.++Historical lowercase `model`/`solid` scopes retain their existing grammar and+are left untouched by the spelling pass; they are not migrated to native V2.++Authored names require a manual, binding-aware edit. For example, `.Frame`,+`.BottomSeat`, `Spec`, `R` and `H` can be authored public contracts; their casing+must change together with every declaration and use. The guitar sweep deliberately+retains its established public ports, template argument names, occurrence paths+and generated span keys. Its private pickup geometry, record fields and scalar+functions demonstrate the quieter convention. Remaining casing stragglers are+acceptable. An exhaustive migration or symbol rename service is outside this pass.++Current assembly definition identities can retain whitespace in specialization+arguments. Preserve those argument spellings when preserving identities; this+formatter does so. General whitespace canonicalization of definition keys is a+separate compiler concern.++Semicolons are optional wherever the owning grammar already admits newline/block structure as a field delimiter.+The bounded `Function` expressions and `Points` recipes currently require explicit+semicolon terminators; see [Concept points and Functions](concept-points-and-functions.md).+Root assembly `provenance` selections and `Pmi Note` fields also require explicit+semicolons; see [PMI](pmi.md). Use semicolons when they improve readability in dense one-line Records, Tables, or `ProfileDelta` members; their presence must not select a different language path where optional.++Built-in aliases exist only where the owning grammar admits them.+A field uses `name: value`; braces delimit+declarations, brackets delimit lists, and semicolons are optional where the+owning grammar is unambiguous.Different target grammars are intentional. Native Model geometry uses axis faces and semantic selectors; Sheet Metal uses named planar regions and paths; native and imported Analysis use body-qualified faces; Assembly uses typed roles, ports, interfaces, and DatumFrame references. Similar engineering ideas do not make these value types interchangeable.@@ -16,4 +92,6 @@ Firmament V1 is compatibility history, not canonical V2 authoring. Speculative o## Preview 3 migration note-Preview 3 documents one visual dialect. Existing supported lowercase and `solid name: Primitive` inputs remain accepted where documented, without casing warnings. New source should use PascalCase Firmament vocabulary, direct named primitive declarations, and `Units: mm`.+Preview 3 originally documented PascalCase vocabulary and fields. Its supported+lowercase and `solid name: Primitive` inputs remain accepted where documented.+New examples prefer mixed casing and direct named primitives with `units: mm`.diff --git a/docs/public/firmament/pmi.md b/docs/public/firmament/pmi.mdindex a448cd24..4d3f0b5a 100644--- a/docs/public/firmament/pmi.md+++ b/docs/public/firmament/pmi.md@@ -28,3 +28,72 @@ aetheris analyze artifacts/pmi.step --jsonThe build's `pmiExportEvidence` and the analyzer's `semanticPmi` are independent public evidence surfaces. Supported validate records and inspected AP242 records must agree at the semantic-record level; one record may lower to several STEP entities.Pattern-generated geometry may coexist with PMI, but Preview 3 does not publish a stable selector for individual generated pattern instances or quantity/repeated-feature PMI authoring.++## Assembly release records and design notes++The assembly lane supports root-owned product annotations and a selected typed+release Record. These lower through the existing semantic PMI note emitter to+AP242 `SHAPE_ASPECT` and `PROPERTY_DEFINITION` entities, and are recovered by+`aetheris analyze assembly guitar.step --json` under `semanticPmi`. They are semantic notes, not rendered+dimension labels or newly qualified manufacturing requirements.++```firmament+Record ReleaseInfo {+ Author: String+ Date: Date+ Version: Version+ Description: String+ AuthoringTolerance: Length+}+Static Release: ReleaseInfo {+ Author: "GPT 6.1 Sol Codex"+ Date: 2026-10-01+ Version: 0.1.0+ Description: "Carved-top guitar presentation witness"+ AuthoringTolerance: 0.1mm+}+Assembly GuitarX0 {+ Provenance: Release;+ Pmi {+ Note DesignIntent {+ Target: GuitarX0;+ Text: "Presentation demonstrator; not released for manufacture.";+ }+ }+ // Ordinary XML-like occurrence tree and placement declarations follow.+}+```++`Provenance` selects one ordinary `Static` Record. The common Record binder checks+its fields, including real calendar dates, three-component semantic versions, and+dimensioned lengths. `Author: String`, `Date: Date`, `Version: Version`, and+`Description: String` are required. Optional fields are flat `String`, `Date`,+`Version`, `Length`, `Angle`, `Int`, `Float`, or `Bool` data; `Organization: String`+sets the STEP organization when present. Field values are exported as annotations+named `Release.Field`, in stable field-name order. The selected date supplies a+deterministic midnight STEP header timestamp; it is the authored release date,+not the time of export. There is no implicit wall-clock mutation.++`Pmi` and `Provenance` belong directly to the root Assembly. `Note` takes+`Target` then `Text`, with explicit semicolon terminators. A target must resolve+to a complete occurrence path, including the root, such as `GuitarX0.Bridge`;+unknown targets, duplicate note names, malformed text, and unsupported PMI kinds+stop compilation. Text supports JSON string escapes and preserves apostrophes,+braces, semicolons, and literal `//` without interpreting them as geometry or+comments. Control characters are rejected.++Notes are associated with the target's AP242 product-definition shape. For a+shared definition the explicit occurrence path remains in the semantic target;+this does not invent an occurrence-specific BRep face association. Face-targeted+assembly tolerances, assembly GD&T, nested reusable-definition annotation+authoring, and graphical PMI presentation remain outside this bounded lane.+Existing Model PMI contracts above retain their separate selector rules.+Assembly package reconstruction does not yet reauthor these annotations; inspect+the original STEP directly rather than assuming package import/re-export+preserves release metadata.++The assembly IR preserves the release data and note source spans. USD also+carries them as root `aetheris:provenance:*` and `aetheris:pmi:*` custom attributes.+Editing metadata refreshes these outputs while reusing unchanged geometry.+The complete guitar example is+[`guitar.firmasm`](../../../fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm).diff --git a/docs/public/firmament/profile-boundary-edits.md b/docs/public/firmament/profile-boundary-edits.mdindex c505b7e0..72f64f3d 100644--- a/docs/public/firmament/profile-boundary-edits.md+++ b/docs/public/firmament/profile-boundary-edits.md@@ -207,3 +207,7 @@ an approximant must not be reported as an exact representation of the equation.After equation binding, the ordinary boundary-edit validity checks still apply.See the [larger design proposal](programmable-profile-loops-proposal.md) fordeferred periodic intervals, Curve2 payloads, inner loops and Profile-valued Features.++## Owl authoring update++The body witness now uses Derivatives: Periodic to derive cyclic Hermite tangents from ordered replacement knots. Straight seed carriers and full replacements only; ranges and non-straight carriers are rejected. Existing exact loop validation remains authoritative. See [source-owned guitar authoring](source-owned-guitar-authoring.md).diff --git a/docs/public/firmament/section-chains.md b/docs/public/firmament/section-chains.mdindex 767aa68b..c987d161 100644--- a/docs/public/firmament/section-chains.md+++ b/docs/public/firmament/section-chains.md@@ -131,3 +131,7 @@ The positional bound is `sqrt(2) * radius * abs(segmentSweep)^6 / (720 * 64)`, p`G2WithinSampledTolerance` is an inspection result at the reported samples, not a new G2 construction guarantee. The samples include endpoints, 33 regular parameters, and applicable spline knots. The rounded-section fixture measures zero position/normal mismatch but a 0.125/mm curvature jump at its R8 line/arc seams. Those joins are G1. Arc normalization does not smooth away source curvature jumps. `Continuity: G2` remains rejected for SectionChain.Editing a section normally retains the existing bounded G1 derivative neighborhood. If an edit changes the common normalization segment count, all transitions on that chain must be regenerated; the edit delta truthfully reports this wider dependency and does not claim the terminations are preserved. Source semantic span identities remain stable. See the [SURF-G2-X1 progression report](../../release/SURF-G2-X1.md) for the remaining G2 boundary-condition work.++## Owl authoring update++Generic Profile recipes and keyed Section Patterns now lower inline Concept frame/Profile values through this same binder. Generated section keys and associations appear in root-aware inspection. See [source-owned guitar authoring](source-owned-guitar-authoring.md).diff --git a/docs/public/firmament/source-owned-guitar-authoring.md b/docs/public/firmament/source-owned-guitar-authoring.mdnew file mode 100644index 00000000..23cacd68--- /dev/null+++ b/docs/public/firmament/source-owned-guitar-authoring.md@@ -0,0 +1,178 @@+# Source-owned guitar authoring++The remaining guitar recipes now live in reviewed Firmament files. Python is a+read-only CLI reproduction harness; Blender remains a downstream presentation+step. Neither authors or replaces the guitar BRep.++The guitar now demonstrates the [mixed-case naming convention](language-style.md):+artifact/type vocabulary remains prominent, built-in properties and scope words+read quietly, and private pickup locals and fret functions use camelCase. A safe+formatter pass followed by a bounded manual pass retained published ports,+occurrence paths, template specialization identities and exact export bytes.+Older snippets below remain accepted compatibility spellings.++## Profiles and finite sections++Generic Templates may output `Profile`. Local Point2/Curve2 guides are namespaced+per specialization; Loop span names remain stable for section correspondence.+Profiles are output values here, not higher-order Template arguments.++```firmament+Include "neck-profile.firmament";+Record NeckStation { Y: Length; Depth: Length }+Static Stations: Set<NeckStation> {+ Shaft => NeckStation { Y: 440mm; Depth: 10.1mm }+ Nut => NeckStation { Y: 660mm; Depth: 7mm }+}+SectionChain Neck {+ Pattern Sections Over Stations {+ s => Section Station {+ Frame: Plane { Origin: [0mm,s.Y,55mm]; Normal: [0,1,0]; Up: [0,0,1] }+ Profile: NeckBack<HalfWidth: 21mm, WidthHandle: 11.6mm,+ Depth: s.Depth, DepthHandle: 4mm, SeatHandle: 14mm>+ Seam: Edge0+ }+ }+ // Supply transition and termination intent as in the actual Neck fixture.+}+```++The actual guitar keeps its approved straight shaft taper, adds two isolation+stations before the nut, and uses two more sections for the headstock transition.+`Sections_Nut` is the generated section identity; inspection retains its `Nut`+source key. Inline frame/profile values lower to existing Concept planes and+ordinary Profiles before the SectionChain binder runs.++`Point2` profile controls accept finite, dimension-checked scalar arithmetic after+Template substitution, such as `Position: [-Width / 2, -Depth * 0.55228475]`.+This reuses the existing bounded scalar evaluator. Wrong units, division by zero+and unresolved values produce `profile-layout-point-invalid`; no host source is+executed. The neck's original cubic D-profile is split exactly at its midpoints+so six spans can correspond to the rectangular headstock root. This changes the+span layout without approximating the original cross-section.++The short scarf beneath the veneer is an ordinary exact extrusion seated on the+headstock's published Base frame. The neck, scarf, slab and veneer remain separate+witness solids; their construction is not a certified fused manufacturing joint.+The tuner stem lives inside `GuitarTuner`, so the two three-instance patterns also+reuse it. The tailpiece's exact semicircular rail publishes `StringCrown`; the+bridge forwards that frame as `TailStringPlane`, and string bindings use zero+height offset there.++Body boundary replacements may request `Derivatives: Periodic`. A centered cyclic+Hermite derivative is derived from the ordered replacement knots on straight seed+carriers, with a 1,024-knot limit. Exact closure, cusp and self-intersection checks+still apply. Partial ranges and non-straight seed carriers are rejected. This is a+bounded interpolation recipe, not a general equation-curve or fairness solver.++## Physical material and finish++```firmament+Appearance BareSteel { Color: [0.55,0.57,0.60]; Metallic: 1; Roughness: 0.2; }+Appearance PaintedRed { Color: [0.45,0.02,0.01]; Metallic: 0; Roughness: 0.25; }+Material Steel { Identity: "steel"; Appearance: BareSteel; }++// Inside an ordinary Part occurrence:+Material: Steel;+// Or, for a finish that retains the same physical identity.+Material: Steel with { Appearance: PaintedRed; };+```++Color channels, Metallic and Roughness must be finite and within 0..1. The `with`+override selects only appearance. Material identities are nominal physical+designations, not certified engineering properties; existing material/FEA+qualification remains separate. A decorative pickup compound is explicitly a+presentation placeholder.++Precedence is occurrence `with` override, then physical material default. Authored+occurrence bindings are stronger than legacy exporter definition-material JSON.+Unassigned legacy occurrences retain that compatibility path. USD carries both+physical material and appearance identities as custom properties; Cycles consumes+these identities rather than occurrence-name or specialization-string matches.+Sunburst, lacquer, pearl and pickup feature shading are downstream shader choices.+They do not alter the exported geometry. Look-only edits preserve exact definition+buffers and reuse successful materializations, including length-changing look edits.++## Placed public route endpoints++```firmament+// Lead is a Struct Template with A/B/C: Point3 inputs and one WireRoute.+<Part Wire = Lead<>>+ Placement { From: Origin; To: World; }+ Bind {+ A { At: Point3(0mm,0mm,0mm); On: Product.Start.Entry.Frame; }+ B { At: Point2(0mm,0mm); On: Product.Nut.Top.Frame; }+ C { At: Point3(0mm,0mm,0mm); On: Product.Tuner.StringEntry; }+ }+</Part>+```++Fixed assembly placement resolves first. Each public datum lifts a local Point2/3+to world space and converts it into the consuming route occurrence's coordinates+exactly once. Those resolved Point3 arguments become ordinary specialization/cache+inputs. Inspection reports the port, world point, local point and bound definition.+Changing a terminal placement rebuilds its affected route while unchanged terminal+definitions reuse their materializations.++The first lane requires a fully fixed assembly, ordinary route Templates without+published outputs, and 1..16 named bindings. Dynamic joints, private ports and+route-dependent published frames fail explicitly. Reusable subassembly definitions+remain local prototypes; final occurrence route bindings are recorded separately.+The guitar's tailpiece string rail retains an explicit 5mm decorative stand-off+above its published top plane; this is not a claim of a modeled string hole.++## First locked guide++```firmament+Concept Struct HarnessLayout {+ Line3 Groove { From: Point3(0mm,0mm,0mm); To: Point3(100mm,0mm,0mm); }+}+WireRoute Signal {+ Diameter: 2mm; MinimumBendRadius: 10mm;+ Path {+ Start { At: Point3(0mm,-40mm,0mm); }+ Follow MainGroove { Curve: HarnessLayout.Groove;+ From: 20mm; Distance: 60mm; Direction: Forward; }+ End { At: Point3(120mm,0mm,0mm); }+ }+}+```++This lane follows a finite literal Concept Line3 interval, derives an entry fillet+at the requested minimum bend radius, and requires the end to extend along the+outgoing tangent. It lowers through the existing exact WireForm cylinder/torus+authority. Invalid intervals, insufficient approach room and non-tangent exits+fail. Reverse traversal is supported. Arbitrary/circular/spline guides, exact Via,+multiple corners and obstacle search remain separate qualification work.++## CLI and editor++`aetheris build <root.firmasm> --output artifacts/local/guitar.step` delegates to+the existing native assembly exporter. Root-aware `inspect` delegates to assembly,+SectionChain or ordinary part inspection. For a canonical ordinary M1 assembly:++```powershell+aetheris inspect fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm --json --profile --repeat 2 --out artifacts/local/guitar/inspect.json+python scripts/create-guitar-x0.py --out artifacts/local/guitar+```++`--repeat` retains one explicit compilation session for 1..16 builds. JSON includes+per-build elapsed time, reuse/rebuild reasons and optional phase timings. It is not+a disk cache: placement, validation, tessellation and export still run each build.+The reproduction harness hashes its inputs and never rewrites fixtures.++Compiler-owned editor metadata covers route/Follow, keyed Sections, point recipes,+appearance/material and placement fields. Project-snapshot analysis and lexical+cross-file definition navigation support profile recipes and material aliases.+Single imported modules report that project context is needed instead of running+an unrelated part parser. Navigation does not grant private-port placement access.+Whole-project diagnostics currently retain aggregate locations; full generated-span+mapping, every draft grammar and editor-client integration are not claimed here.++## Deliberate remaining boundaries++The guitar already has physical planar seating evidence at its deck datum. No new+guitar case requires arbitrary tangent-frame evaluation, trim/seam attachment rules+or full curved-base footprint proofs. Those contracts, richer fit predicates, G2/+explicit surface laws, equation curves and higher-order geometry remain follow-ons.+The bounded source-authoring milestone does not add a general constraint solver.diff --git a/docs/public/firmament/templates.md b/docs/public/firmament/templates.mdindex 7690c264..b03f71d6 100644--- a/docs/public/firmament/templates.md+++ b/docs/public/firmament/templates.md@@ -20,7 +20,7 @@ Struct StandardPlate = MountingPlate<Width: 80mm, Height: 50mm, Thickness: 8mm>The complete build-qualified version is [`generic-mounting-plate.firmament`](../../../fixtures/Canonical/Templates/generic-mounting-plate.firmament).-The explicit output keyword is significant: current Templates specialize `Struct`, `Model`, `Concept Struct`, `Panel`, `SheetMetal`, or `ProfileDelta` declarations. It is not inferred from the body.+The explicit output keyword is significant: current Templates specialize `Struct`, `Model`, `Concept Struct`, `Panel`, `SheetMetal`, `Profile`, or `ProfileDelta` declarations. It is not inferred from the body.A finite feature Template used by `Pattern ... Over` has the same generic visual form:@@ -134,7 +134,7 @@ Firmament has no `Select`, `Where`, `GroupBy`, joins, query comprehensions, SQL## Output boundary-The modern generic specializer admits `Struct`, `Model`, `Concept Struct`, `Panel`, `SheetMetal`, and `ProfileDelta` output declarations. Finite feature Templates admit the currently documented `Hole<Shaft>`, capsule/rounded-rectangle `Slot`, `Profile`, and `StandardPart` outputs. Templates can thereby influence existing geometry, Sheet Metal, semantic PMI inputs, and an Analysis contained in an admitted concrete model, but Preview 3 has no separate generic FEA or Drawing output contract and no new PMI feature kinds.+The modern generic specializer admits `Struct`, `Model`, `Concept Struct`, `Panel`, `SheetMetal`, `Profile`, and `ProfileDelta` output declarations. Finite feature Templates admit the currently documented `Hole<Shaft>`, capsule/rounded-rectangle `Slot`, `Profile`, and `StandardPart` outputs. Templates can thereby influence existing geometry, Sheet Metal, semantic PMI inputs, and an Analysis contained in an admitted concrete model, but Preview 3 has no separate generic FEA or Drawing output contract and no new PMI feature kinds.`Struct`, `Compose`, and `Modify` keep their ordinary meanings after specialization: `Struct` owns construction intent, `Compose` creates an admitted profile-based body, and `Modify` applies admitted post-construction semantic features. Template is not a geometry subsystem.@@ -143,3 +143,5 @@ The modern generic specializer admits `Struct`, `Model`, `Concept Struct`, `PaneProtocol v1 keeps stable IDs such as `Standard.SheetMetal.ElectronicsEnclosure` separate from display signatures such as `ElectronicsEnclosure<Spec: EnclosureSpec>`. `ListTemplates` discovers stable IDs. `DescribeTemplate` exposes the signature, output kind, parameter category, units/dimensions, required/default state, enum cases, nested Record fields, named `Require` constraints, documentation, and artifacts. `InvokeTemplate` binds language-neutral values and returns deterministic artifacts and specialization identity; it never exposes compiler AST nodes.Syntax cleanup therefore does not rename a public Template. See [Template engineering examples](template-examples.md) and the [Forge Host guide](../forge/interop.md).++Generic Profile output and bounded Point3 parameters are demonstrated in [source-owned guitar authoring](source-owned-guitar-authoring.md). Local guide names are specialization-owned; semantic Loop spans are preserved. Profiles are not higher-order Template arguments.diff --git a/docs/public/firmament/wire-point-routes.md b/docs/public/firmament/wire-point-routes.mdnew file mode 100644index 00000000..55dd34b9--- /dev/null+++ b/docs/public/firmament/wire-point-routes.md@@ -0,0 +1,44 @@+# Point wire routes++`WireRoute` now lowers a finite `Start` → `Corner` → `End` path to the existing WireForm exact cylinder/torus sweep. This first slice removes the guitar's Python-computed lengths, angles, and placement bases. Functions remain ordinary compile-time Firmament Functions; no `Comptime` keyword is needed.++```firmament+schema WireForm+Model Lead {+ WireRoute Signal {+ Diameter: 1mm;+ MinimumBendRadius: 4mm;+ Path {+ Start { At: Point3(0mm,0mm,0mm); }+ Corner Bend { At: Point3(0mm,30mm,0mm); Radius: 4mm; }+ End {+ At: Point2(20mm,20mm);+ On {+ From: World;+ TranslateLocal: [0mm,30mm,0mm];+ RotateLocal: { Axis: X; Angle: 90deg }+ }+ }+ }+ }+}+```++`At` accepts a checked Point3, or Point2 with an explicit `On` frame. Point coordinates are lengths. `On` shares the existing FrameTransform parser and transform composition, including Normal/Up and RotateLocal; this slice requires `From: World`. Within a reusable definition, World means the definition's coordinate system; ordinary assembly Placement remains the sole occurrence placement authority. Keyed Concept point coordinates can be supplied through existing scalar template arguments.++The Corner is the virtual intersection of the two route legs. The fillet does **not** pass through that intersection. For turning angle θ and centerline radius R, each leg loses `R * tan(θ/2)` at the corner. Firmament computes the tangent frame, bend plane, circle center, arc, and remaining straight lengths. Radius must meet MinimumBendRadius and exceed the wire's radius. Both remaining straight lengths must be positive. Collinear/reversing corners, duplicate/unknown fields, missing units, malformed frames, and non-finite dimensions fail with named `wire-route-*` diagnostics. Straight-only wires retain WireForm Straight.++The existing WireForm materializer still owns sweep validity, self-clearance, STEP export/reimport and manifold checks. MinimumBendRadius is an authored geometric constraint, not a material strain qualification. Inspection reports the derived Lead, named Corner, and Tail operations through the existing WireForm engineering feature path.++The guitar's six routes now use Point3 Template inputs bound to final public+nut, tuner and tailpiece frames after fixed placement. The standalone low-E file+retains explicit local frames as an independent route witness. See+[source-owned guitar authoring](source-owned-guitar-authoring.md) for Bind ordering,+cache dependencies, public-port restrictions and the first Line3 Follow guide.++Implemented witnesses: fixtures/Canonical/WireForm/point-route.firmament,+line-guide.firmament, and the guitar strings-assembly.firmament. Python only runs+CLI reproduction and verifies that authored source was not changed.++Exact-through Via, multiple corners, circular/spline guides and obstacle routing+remain in the [routing proposal](wire-routing-and-guides-proposal.md).diff --git a/docs/public/firmament/wire-routing-and-guides-proposal.md b/docs/public/firmament/wire-routing-and-guides-proposal.mdnew file mode 100644index 00000000..561e4760--- /dev/null+++ b/docs/public/firmament/wire-routing-and-guides-proposal.md@@ -0,0 +1,205 @@+# Wire routing and Concept guides++Status: [Start/Corner/End point routes](wire-point-routes.md), fixed public endpoint+bindings and a finite Concept Line3 Follow lane are implemented. See the+[qualified syntax and limits](source-owned-guitar-authoring.md). The broader+auto-routing, multi-step and arbitrary-guide contracts below remain proposals.++The intent is an ordered centerline contract: start here, visit these points,+follow this Concept curve interval, and terminate here. The compiler constructs+the connecting spans, checks their admissibility and lowers the accepted path+to ordinary WireForm geometry. Concepts remain erased design scaffolding.++## Suggested syntax++```firmament+Concept Struct HarnessLayout {+ Points<Point3> Anchors {+ Source: Point3(0mm,0mm,0mm);+ CableTie: Point3(30mm,0mm,0mm);+ Terminal: Point3(180mm,20mm,0mm);+ }+ Line3 Groove {+ From: Point3(60mm,20mm,0mm);+ To: Point3(160mm,20mm,0mm);+ }+}++WireRoute SignalLead {+ Diameter: 2mm;+ Material: Standard.Materials.StainlessSteel.304_Annealed;+ MinimumBendRadius: 10mm;+ Routing: Auto;++ Path {+ Start { At: HarnessLayout.Anchors.Source; }+ Via Tie { At: HarnessLayout.Anchors.CableTie; }+ Follow MainGroove {+ Curve: HarnessLayout.Groove;+ From: 0mm;+ Distance: 80mm;+ Direction: Forward;+ }+ End { At: HarnessLayout.Anchors.Terminal; }+ }+}+```++This illustrates the proposed contract, not a qualified route artifact. A Concept+line itself is sufficient as a guide; there is no separate Guide object to create.+`Follow` also accepts admitted Concept Curve2/Curve3 values. A Curve2 must have+an explicit construction plane/frame, using the existing `On` convention; its+local coordinates are lifted through that frame once. The current Concept Curve2+lane derives closed Profile boundaries; open guide curves need a deliberate+extension of that resolver, not an assumption that they already exist.++`From` is arc length from the curve's declared start, in its forward orientation.+`Distance` is positive traced arc length. Forward advances from `From`; Reverse+decreases it and reverses the tangent. For this line, the locked interval runs+from `[60mm,20mm,0mm]` to `[140mm,20mm,0mm]`. Both endpoint tangents are +X.+Omitting Direction means Forward. `Distance: Remaining` may be admitted as an+explicit extent alternative. Out-of-range intervals fail; closed-curve wrapping+is deferred rather than silently clamping or moving the seam.++Start/End may optionally specify Tangent. It always means travel direction along+the wire, including at End; adapters from terminal outward normals must make+that sign conversion explicit. Tangents at Via points are free unless authored.+The declared command order is preserved.++## Three different constraints++| Construct | Meaning |+| --- | --- |+| `Via Tie { At: P; }` | The realized centerline passes through P with a tangent-continuous join. A cable-tie center can be a hard point. |+| `Corner NutBreak { At: P; Radius: 4mm; }` | P is the virtual intersection of untrimmed legs. A circular fillet replaces it; the centerline generally does not pass through P. |+| `Follow Groove { Curve: C; From: S; Distance: L; }` | The whole oriented curve interval is locked, including its endpoint positions and tangents. Only the free spans may change. |++MinimumBendRadius is a centerline radius bound, not a command that every bend use+that exact radius. An authored Corner Radius must meet the minimum. Guide arcs+must also meet it. Lines have infinite curvature radius. A kink or cusp in a+locked guide is invalid; the compiler cannot fillet away part of that guide.+Authors can modify the Concept curve explicitly when smoothing is intended.++For the guitar, preserve the existing 4mm virtual NutBreak first. Its present+WireForm rounds a corner; replacing it with hard `Via` would change the shape.+The new Point2 crossings must be explicitly lifted using an actual nut string+plane published by the neck definition, rather than assuming NutMount denotes+the string height. Example proposed route input:++```firmament+Corner NutBreak {+ At: NutLayout.Crossings.String0;+ On: Guitar.Neck.StringPlane;+ Radius: 4mm;+}+```++`On` here is the proposed Point2-to-spatial route binding. Missing On is a+dimensional error. `StringPlane` is a proposed publication, not an existing port.+Tailpiece starts and tuner string-entry endpoints likewise need definition-owned+publications; routing should not reach into private component geometry.++## What is reusable today++- `Piping/OrthogonalAutoRouter.cs` provides deterministic bounded A*, conservative+ KeepOut inflation, endpoint directions, hard waypoints and local rerouting.+ It currently requires axis-aligned directions and produces 90-degree elbows.+ Its clearance checker and 1000mm elbow penalty are specifically piping policy.+- `Materializer/WireForm.cs` owns forming state, arbitrary-plane circular bends,+ exact cylinder/torus sweeps and conservative self-clearance validation.+- `WireEvaluablePathAir` already provides evaluated centerlines, tangents and+ approximation evidence for coil/knot paths. General guide paths need new+ dispatch and qualification, not just a new subtype with an assumed working+ materializer.+- Keyed Concept points, checked scalar Functions, assembly published frames,+ fixed placement and incremental definition caching provide the input scaffolding.++Extract the existing orthogonal search into a small, geometry-only centerline+search seam when wires need obstacle avoidance. Keep the piping facade and its+fixtures unchanged. Supply actual wire radius and wire cost policy; do not fake+a pipe specification or adopt piping fittings as wire geometry. Reuse suitable+collision bounds, while retaining family-specific realized-curve verification.++## Compiler path++1. Bind an ordered `WireRouteRequestIr`: wire section/material, minimum radius,+ named point/corner constraints, locked guide intervals, optional endpoint+ tangents, route policy and any explicit KeepOut references. Keep stable authored+ command keys and source provenance. Reuse scalar Function evaluation for lengths.+2. Resolve published inputs through the existing assembly placement authority.+ Convert them into the route occurrence's local frame exactly once. Ordinary+ occurrence placement then applies that frame once at display/export. Route+ geometry must not also carry a second world-placement transform.+3. Resolve each guide to a bounded curve value with position, tangent, arc-length+ mapping, regularity and curvature evidence. Derive entry/exit tangent states.+ Retain the immutable guide interval in the planned centerline.+4. Construct a bounded set of free-span candidates: straight, line/arc connectors,+ qualified biarcs and, for admitted axis-aligned cases, the shared orthogonal+ search. Check complete candidate chains, not independently greedy spans:+ a Via tangent and nonlocal collisions can couple neighboring connectors.+ Cap candidates/search and diagnose budget exhaustion separately from having+ no admitted candidate. This is bounded geometric construction and search,+ not a general constraint solver.+5. Use JudgmentEngine to select among competing admitted strategies. Hard point,+ guide, tangent, radius and clearance constraints determine admissibility;+ route length and optional bend cost determine preference, with stable ties.+ Deterministic curve binding and copying a locked guide need no utility scoring.+6. Lower accepted straight/circular spans directly to `WireStraightAir` and+ `WireBendAir`, preserving transported forming frames. General guide curves+ require a qualified `WireGuidePathAir` on the existing evaluable-path seam.+ Extend materializer/inspection dispatch explicitly and reuse tube construction.+7. Validate the realized sweep, including guide joins and nonlocal self-clearance.+ Publish start/end frames, physical centerline length and constraint-to-operation+ associations. Geometry, STEP, USD and camera interaction use the compiled result.++Fixed endpoint placements and projected scaffolds are read dependencies. Reject+cycles where the route helps place a part that supplies its own endpoint, and+defer dynamic-joint endpoints. Incremental cache keys must include bound endpoint+frames, guide geometry/intervals, policy and KeepOut inputs; unchanged routes reuse+their bodies. Moving a camera is never a routing input.++## Exactness and physical meaning++Line/circle guides have analytic length and curvature and can retain exact native+sweeps. For splines, retain the authored curve as the semantic authority, but+arc-length inversion and tube realization may need distinct numerical and shape+tolerances. Report those bounds. Curvature and clearance admission need conservative+evidence; a few favorable samples do not prove the minimum bend radius everywhere.+If the current kernel cannot qualify a curve, stop with a named unsupported-guide+diagnostic rather than silently treating its samples as exact geometry.++A guide denotes the wire centerline. If it comes from a groove floor or support+surface, explicitly derive the centerline at the required wire-radius/clearance+offset first. Surface-normal offsets and spatial curve offsets are different+operations. Following a guide proves no groove width, cable-tie fit or physical+support contact. Guides do not create solids or grant automatic KeepOut exemptions.+X0 obstacles remain conservative declared bounds; a whole-body box cannot prove+that a wire fits inside a groove. Electrical topology, insulation layers, bundle+packing, slack/gravity and string tension remain separate concerns.++## Recommended implementation slices++1. **Point routes:** Start/Corner/End with arbitrary-plane circular bends. Dogfood+ all six guitar strings; remove Python lengths, angles and raw placement bases.+ Compare endpoints, swept lengths, exact cylinder/torus geometry and STEP round-trip.+2. **Guide routes:** Line3 and qualified planar/spatial circular intervals first,+ with tangent entry/exit connectors. Qualify hard Via behavior explicitly; do+ not implement it as a renamed rounded Corner. Add cable-tie/groove witnesses,+ reverse intervals, insufficient transition room and too-tight guide failures.+3. **Obstacle routing:** share the orthogonal search, preserving all piping tests.+ Validate the realized rounded wire envelope against original KeepOut bounds.+4. **General curves:** open Concept Curve2/Curve3 binding, arc-length tolerances,+ curvature qualification and existing evaluable-path tube realization. Admit+ each curve family on evidence; do not make arbitrary splines an X0 prerequisite.++This ships the guitar improvement first while leaving one coherent syntax for+guided harness routing. The guide is an authored geometric constraint, and the+compiler owns the finite transitions around it.+## Implemented first slice++Start/Corner/End point routes are implemented through the existing exact WireForm backend. See [point wire routes](wire-point-routes.md) for the current syntax and explicit frame-binding boundary. The broader guide and auto-routing syntax below remains proposed.+++## Owl authoring update++Implemented first guide: Start/Follow/End on one finite literal Concept Line3 interval, automatic minimum-radius entry fillet, forward tangent exit. Placed public endpoint binding is also shipped for fully fixed assemblies. Remaining guide/planning sketches below are proposals. See [source-owned guitar authoring](source-owned-guitar-authoring.md).diff --git a/fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/concept-points-part.firmament b/fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/concept-points-part.firmamentnew file mode 100644index 00000000..07bc8103--- /dev/null+++ b/fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/concept-points-part.firmament@@ -0,0 +1,7 @@+Model PointsPart {+ Units: mm+ Concept Struct Layout {+ Points<Point2> Sizes { Small: Point2(2mm,3mm); Large: Point2(4mm,6mm); }+ }+ Box Body { Size: [Layout.Sizes.Large.X,Layout.Sizes.Small.Y,1mm] }+}diff --git a/fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/concept-points.firmament b/fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/concept-points.firmamentnew file mode 100644index 00000000..dc9324b8--- /dev/null+++ b/fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/concept-points.firmament@@ -0,0 +1,40 @@+Function Distance(n: Int, scale: Length) -> Length = scale * (1.0 - Pow(2.0, -n / 12.0));+Function PadHeight(h: Length) -> Length = h + 1mm;+Concept Struct Nut {+ Points<Point2> Crossings {+ Keys: [Bass, Middle, Treble];+ Linear { Start: Point2(-18mm,0mm); Step: [18mm,0mm]; }+ }+ Points<Point3> Supports {+ Left: Point3(-18mm,0mm,2mm);+ Right: Point3(18mm,0mm,2mm);+ }+}+Concept Struct Board {+ Points<Point2> Frets {+ Series { Index: n; First: 1; Count: 12; KeyPrefix: Fret;+ Position: Point2(0mm, -Distance(n,628mm)); }+ }+}+Template<H: Length> Struct Pad {+ Rect2 Outline { Center: [0mm,0mm]; Size: [4mm,2mm] }+ Profile P { Loop Outer { Outline |> TraceLoop } }+ Extrude Body { Profile: P; From: 0mm; To: H }+ Expose { Semantic Bottom { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; } }+}+Assembly PointWitness {+ <Assembly PointWitness>+ Pattern Frets Over Board.Frets {+ point => <Part Fret = Pad<H:PadHeight(1mm)>>+ Placement { From: Bottom.Frame; To: BoardSeat.Frame;+ TranslateLocal: [point.Position.X,point.Position.Y,0mm]; }+ </Part>+ }+ <Part Bass = Pad<H:1mm>>+ Placement { From: Bottom.Frame; To: World;+ TranslateLocal: [Nut.Crossings.Bass.X,Nut.Crossings.Bass.Y,Nut.Supports.Left.Z]; }+ </Part>+ </Assembly>+ FrameTransform BoardSeat { From: World; TranslateLocal: [0mm,658mm,62mm]; }+ Anchor: PointWitness;+}diff --git a/fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/linear-stations.firmament b/fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/linear-stations.firmamentnew file mode 100644index 00000000..c5434a87--- /dev/null+++ b/fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/linear-stations.firmament@@ -0,0 +1,32 @@+Concept Struct Markers {+ Points<Point2> Seats {+ Linear {+ Start: Point2(0mm,0mm);+ Direction: [0,-2];+ Stations { First: 10mm; Second: 23.5mm; Third: -4mm; }+ }+ }+}+Template<H: Length> Struct Pad {+ Rect2 Outline { Center: [0mm,0mm]; Size: [4mm,2mm] }+ Profile P { Loop Outer { Outline |> TraceLoop } }+ Extrude Body { Profile: P; From: 0mm; To: H }+ Expose {+ Semantic Bottom { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; }+ Semantic MarkerOrigin { DatumFrame Frame = [0mm,0mm,H] x [1,0,0] y [0,1,0] z [0,0,1]; }+ }+}+Assembly StationWitness {+ <Assembly StationWitness>+ <Part Board = Pad<H:2mm>>+ Placement { From: Bottom.Frame; To: World; TranslateLocal: [10mm,20mm,30mm]; RotateLocal: { Axis: X; Angle: 90deg } }+ </Part>+ Pattern Markers Over Markers.Seats {+ point => <Part Inlay = Pad<H:0.3mm>>+ Placement { From: Bottom.Frame; To: MarkerDatum.Frame; TranslateLocal: [point.Position.X,point.Position.Y,0mm]; }+ </Part>+ }+ </Assembly>+ FrameTransform MarkerDatum { From: StationWitness.Board.MarkerOrigin.Frame; }+ Anchor: StationWitness;+}diff --git a/fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/product-notes.firmasm b/fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/product-notes.firmasmnew file mode 100644index 00000000..23e8cdb3--- /dev/null+++ b/fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/product-notes.firmasm@@ -0,0 +1,25 @@+Record ReleaseInfo { Author: String Date: Date Version: Version Description: String AuthoringTolerance: Length }+Static Release: ReleaseInfo {+ Author: "GPT 6.1 Sol Codex"+ Date: 2026-10-01+ Version: 0.1.0+ Description: "AI-authored assembly annotation witness"+ AuthoringTolerance: 0.1mm+}+Template<H: Length> Struct Pad {+ Rect2 R { Center: [0mm,0mm]; Size: [10mm,10mm] }+ Profile P { Loop Outer { R |> TraceLoop } }+ Extrude Body { Profile: P From: 0mm To: H }+}+Assembly Product {+ Provenance: Release;+ Pmi {+ Note DesignIntent { Target: Product; Text: "Presentation geometry; authoring convention 0.1 mm, not a certified manufacturing tolerance."; }+ Note Finish { Target: Product.A; Text: "Designer's note: {illustrative} #17; https://example.test/a // literal text"; }+ }+ <Assembly Product>+ <Part A = Pad<H:2mm>> Placement { From: Origin; To: World; } </Part>+ <Part B = Pad<H:2mm>> Placement { From: Origin; To: World; TranslateLocal: [20mm,0mm,0mm]; } </Part>+ </Assembly>+ Anchor: Product;+}diff --git a/fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/scalar-functions-part.firmament b/fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/scalar-functions-part.firmamentnew file mode 100644index 00000000..6dd96159--- /dev/null+++ b/fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/scalar-functions-part.firmament@@ -0,0 +1,5 @@+Model ScalarPart {+ Units: mm+ Function Height(n: Int) -> Length = 2mm * n;+ Box Body { Size: [2mm,3mm,Height(4)] }+}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/CarvedMaple.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/CarvedMaple.firmamentindex bfcfe53a..3bcaf344 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/CarvedMaple.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/CarvedMaple.firmament@@ -1,48 +1,25 @@-Include "body-outline.firmament";+include "body-profile.firmament";Model CarvedMaple {- Units: mm- Concept Struct Frames {- S0: Plane { Origin: [0mm,0mm,40mm]; Normal: [0,0,1]; Up: [0,1,0] }- S1: Plane { Origin: [0mm,0mm,43mm]; Normal: [0,0,1]; Up: [0,1,0] }- S2: Plane { Origin: [0mm,0mm,48mm]; Normal: [0,0,1]; Up: [0,1,0] }- S3: Plane { Origin: [0mm,0mm,52mm]; Normal: [0,0,1]; Up: [0,1,0] }- S4: Plane { Origin: [0mm,0mm,53mm]; Normal: [0,0,1]; Up: [0,1,0] }+ units: mm+ Record BodyStation { Height: Length; Scale: Float }+ Static Stations: Set<BodyStation> {+ S0 => BodyStation { Height: 40mm; Scale: 0.992 }+ S1 => BodyStation { Height: 43mm; Scale: 0.955 }+ S2 => BodyStation { Height: 48mm; Scale: 0.84 }+ S3 => BodyStation { Height: 52mm; Scale: 0.76 }+ S4 => BodyStation { Height: 53mm; Scale: 0.72 }}- Concept Struct SectionLayout {- Curve2 Outline0 { From: BodyOutline; On: XY; Scale: 0.992; Pivot: [0mm,-25mm]; Translate: [0mm,0mm]; Rotate: 0deg }- Curve2 Outline1 { From: BodyOutline; On: XY; Scale: 0.955; Pivot: [0mm,-25mm]; Translate: [0mm,0mm]; Rotate: 0deg }- Curve2 Outline2 { From: BodyOutline; On: XY; Scale: 0.84; Pivot: [0mm,-25mm]; Translate: [0mm,0mm]; Rotate: 0deg }- Curve2 Outline3 { From: BodyOutline; On: XY; Scale: 0.76; Pivot: [0mm,-25mm]; Translate: [0mm,0mm]; Rotate: 0deg }- Curve2 Outline4 { From: BodyOutline; On: XY; Scale: 0.72; Pivot: [0mm,-25mm]; Translate: [0mm,0mm]; Rotate: 0deg }+ SectionChain CarvedMaple {+ continuity: G1+ Pattern Sections over Stations {+ s => Section Station {+ frame: Plane { origin: [0mm,0mm,s.Height]; normal: [0,0,1]; up: [0,1,0] }+ profile: BodySection<Ratio: s.Scale>+ seam: LowerTreble_Span0+ }+ }+ start: Cap+ end: Cap}- Construction Plane F0 { Trace: Frames.S0 }- Profile P0 Using SectionLayout { Loop Outer { Outline0 |> TraceLoop } }- Construction Plane F1 { Trace: Frames.S1 }- Profile P1 Using SectionLayout { Loop Outer { Outline1 |> TraceLoop } }- Construction Plane F2 { Trace: Frames.S2 }- Profile P2 Using SectionLayout { Loop Outer { Outline2 |> TraceLoop } }- Construction Plane F3 { Trace: Frames.S3 }- Profile P3 Using SectionLayout { Loop Outer { Outline3 |> TraceLoop } }- Construction Plane F4 { Trace: Frames.S4 }- Profile P4 Using SectionLayout { Loop Outer { Outline4 |> TraceLoop } }- SectionChain CarvedMaple { Continuity: G1- Section S0 { Frame: F0- Profile: P0- Seam: LowerTreble_Span0 }- Section S1 { Frame: F1- Profile: P1- Seam: LowerTreble_Span0 }- Section S2 { Frame: F2- Profile: P2- Seam: LowerTreble_Span0 }- Section S3 { Frame: F3- Profile: P3- Seam: LowerTreble_Span0 }- Section S4 { Frame: F4- Profile: P4- Seam: LowerTreble_Span0 }- Start: Cap- End: Cap- }- Expose { Semantic TopSeat { DatumFrame Frame = CarvedMaple.Section.S4.Frame; } }+ expose { Semantic TopSeat { DatumFrame Frame = CarvedMaple.Section.Sections_S4.Frame; } }}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/IvoryBinding.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/IvoryBinding.firmamentindex 0cee403b..756b4598 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/IvoryBinding.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/IvoryBinding.firmament@@ -1,26 +1,21 @@-Include "body-outline.firmament";+include "body-profile.firmament";Model IvoryBinding {- Units: mm- Concept Struct Frames {- S0: Plane { Origin: [0mm,0mm,38mm]; Normal: [0,0,1]; Up: [0,1,0] }- S1: Plane { Origin: [0mm,0mm,40mm]; Normal: [0,0,1]; Up: [0,1,0] }+ units: mm+ Record BodyStation { Height: Length; Scale: Float }+ Static Stations: Set<BodyStation> {+ S0 => BodyStation { Height: 38mm; Scale: 1 }+ S1 => BodyStation { Height: 40mm; Scale: 1 }}- Concept Struct SectionLayout {- Curve2 Outline0 { From: BodyOutline; On: XY; Scale: 1; Pivot: [0mm,-25mm]; Translate: [0mm,0mm]; Rotate: 0deg }- Curve2 Outline1 { From: BodyOutline; On: XY; Scale: 1; Pivot: [0mm,-25mm]; Translate: [0mm,0mm]; Rotate: 0deg }- }- Construction Plane F0 { Trace: Frames.S0 }- Profile P0 Using SectionLayout { Loop Outer { Outline0 |> TraceLoop } }- Construction Plane F1 { Trace: Frames.S1 }- Profile P1 Using SectionLayout { Loop Outer { Outline1 |> TraceLoop } }- SectionChain IvoryBinding { Continuity: G0- Section S0 { Frame: F0- Profile: P0- Seam: LowerTreble_Span0 }- Section S1 { Frame: F1- Profile: P1- Seam: LowerTreble_Span0 }- Start: Cap- End: Cap+ SectionChain IvoryBinding {+ continuity: G0+ Pattern Sections over Stations {+ s => Section Station {+ frame: Plane { origin: [0mm,0mm,s.Height]; normal: [0,0,1]; up: [0,1,0] }+ profile: BodySection<Ratio: s.Scale>+ seam: LowerTreble_Span0+ }+ }+ start: Cap+ end: Cap}}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/MahoganyBack.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/MahoganyBack.firmamentindex 915ece1b..eb0ebd52 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/MahoganyBack.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/MahoganyBack.firmament@@ -1,26 +1,21 @@-Include "body-outline.firmament";+include "body-profile.firmament";Model MahoganyBack {- Units: mm- Concept Struct Frames {- S0: Plane { Origin: [0mm,0mm,0mm]; Normal: [0,0,1]; Up: [0,1,0] }- S1: Plane { Origin: [0mm,0mm,38mm]; Normal: [0,0,1]; Up: [0,1,0] }+ units: mm+ Record BodyStation { Height: Length; Scale: Float }+ Static Stations: Set<BodyStation> {+ S0 => BodyStation { Height: 0mm; Scale: 1 }+ S1 => BodyStation { Height: 38mm; Scale: 1 }}- Concept Struct SectionLayout {- Curve2 Outline0 { From: BodyOutline; On: XY; Scale: 1; Pivot: [0mm,-25mm]; Translate: [0mm,0mm]; Rotate: 0deg }- Curve2 Outline1 { From: BodyOutline; On: XY; Scale: 1; Pivot: [0mm,-25mm]; Translate: [0mm,0mm]; Rotate: 0deg }- }- Construction Plane F0 { Trace: Frames.S0 }- Profile P0 Using SectionLayout { Loop Outer { Outline0 |> TraceLoop } }- Construction Plane F1 { Trace: Frames.S1 }- Profile P1 Using SectionLayout { Loop Outer { Outline1 |> TraceLoop } }- SectionChain MahoganyBack { Continuity: G0- Section S0 { Frame: F0- Profile: P0- Seam: LowerTreble_Span0 }- Section S1 { Frame: F1- Profile: P1- Seam: LowerTreble_Span0 }- Start: Cap- End: Cap+ SectionChain MahoganyBack {+ continuity: G0+ Pattern Sections over Stations {+ s => Section Station {+ frame: Plane { origin: [0mm,0mm,s.Height]; normal: [0,0,1]; up: [0,1,0] }+ profile: BodySection<Ratio: s.Scale>+ seam: LowerTreble_Span0+ }+ }+ start: Cap+ end: Cap}}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/Neck.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/Neck.firmamentindex 80dbdc96..9f8c0ec3 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/Neck.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/Neck.firmament@@ -1,161 +1,51 @@+include "neck-profile.firmament";Model Neck {- Units: mm- Concept Struct Frames {- S0: Plane { Origin: [0mm,145mm,55mm]; Normal: [0,1,0]; Up: [0,0,1] }- S1: Plane { Origin: [0mm,195mm,55mm]; Normal: [0,1,0]; Up: [0,0,1] }- S2: Plane { Origin: [0mm,220mm,55mm]; Normal: [0,1,0]; Up: [0,0,1] }- S3: Plane { Origin: [0mm,240mm,55mm]; Normal: [0,1,0]; Up: [0,0,1] }- S4: Plane { Origin: [0mm,440mm,55mm]; Normal: [0,1,0]; Up: [0,0,1] }- S5: Plane { Origin: [0mm,660mm,55mm]; Normal: [0,1,0]; Up: [0,0,1] }+ units: mm+ Function halfWidth(y: Length) -> Length = (56mm - 13 * (y - 120mm) / 540) / 2;+ Function ellipseHandle(v: Length) -> Length = v * 0.55228475;+ Function seatHandle(v: Length) -> Length = v / 3;+ // Direction cosines retain the frame's 13deg orientation, not extra part precision.+ Function headSeatY(s: Length) -> Length = 660mm + s * 0.9743700647852352 + 14mm * 0.224951054343865;+ Function headSeatZ(s: Length) -> Length = 48mm - s * 0.224951054343865 + 14mm * 0.9743700647852352;+ Record NeckStation { Y: Length; Depth: Length }+ // PreNut preserves the shaft's straight taper before the short head transition.+ Static Stations: Set<NeckStation> {+ Heel => NeckStation { Y: 145mm; Depth: 40mm }+ HeelShoulder => NeckStation { Y: 195mm; Depth: 36mm }+ HeelBlend => NeckStation { Y: 220mm; Depth: 13.285714mm }+ ShaftStart => NeckStation { Y: 240mm; Depth: 13mm }+ ShaftMiddle => NeckStation { Y: 440mm; Depth: 10.142857mm }+ PreNut => NeckStation { Y: 630mm; Depth: 7.428571mm }+ NutApproach => NeckStation { Y: 650mm; Depth: 7.142857mm }+ Nut => NeckStation { Y: 660mm; Depth: 7mm }}- Construction Plane F0 { Trace: Frames.S0 }- Point2 P0C0P0 { Position: [-27.699074mm,0mm] }- Point2 P0C0P1 { Position: [-27.699074mm,-22.09139mm] }- Point2 P0C0P2 { Position: [-15.297776mm,-40mm] }- Point2 P0C0P3 { Position: [0mm,-40mm] }- CubicBezier2 P0C0 { From: P0C0P0; Control1: P0C0P1; Control2: P0C0P2; To: P0C0P3 }- Point2 P0C1P0 { Position: [0mm,-40mm] }- Point2 P0C1P1 { Position: [15.297776mm,-40mm] }- Point2 P0C1P2 { Position: [27.699074mm,-22.09139mm] }- Point2 P0C1P3 { Position: [27.699074mm,0mm] }- CubicBezier2 P0C1 { From: P0C1P0; Control1: P0C1P1; Control2: P0C1P2; To: P0C1P3 }- Point2 P0C2P0 { Position: [27.699074mm,0mm] }- Point2 P0C2P1 { Position: [9.233025mm,0mm] }- Point2 P0C2P2 { Position: [-9.233025mm,0mm] }- Point2 P0C2P3 { Position: [-27.699074mm,0mm] }- CubicBezier2 P0C2 { From: P0C2P0; Control1: P0C2P1; Control2: P0C2P2; To: P0C2P3 }- Profile P0 { Loop Outer {- Segment Edge0 { Trace: P0C0; From: P0C0P0; To: P0C0P3 }- Segment Edge1 { Trace: P0C1; From: P0C1P0; To: P0C1P3 }- Segment Edge2 { Trace: P0C2; From: P0C2P0; To: P0C2P3 }- } }- Construction Plane F1 { Trace: Frames.S1 }- Point2 P1C0P0 { Position: [-27.097222mm,0mm] }- Point2 P1C0P1 { Position: [-27.097222mm,-19.882251mm] }- Point2 P1C0P2 { Position: [-14.965383mm,-36mm] }- Point2 P1C0P3 { Position: [0mm,-36mm] }- CubicBezier2 P1C0 { From: P1C0P0; Control1: P1C0P1; Control2: P1C0P2; To: P1C0P3 }- Point2 P1C1P0 { Position: [0mm,-36mm] }- Point2 P1C1P1 { Position: [14.965383mm,-36mm] }- Point2 P1C1P2 { Position: [27.097222mm,-19.882251mm] }- Point2 P1C1P3 { Position: [27.097222mm,0mm] }- CubicBezier2 P1C1 { From: P1C1P0; Control1: P1C1P1; Control2: P1C1P2; To: P1C1P3 }- Point2 P1C2P0 { Position: [27.097222mm,0mm] }- Point2 P1C2P1 { Position: [9.032407mm,0mm] }- Point2 P1C2P2 { Position: [-9.032407mm,0mm] }- Point2 P1C2P3 { Position: [-27.097222mm,0mm] }- CubicBezier2 P1C2 { From: P1C2P0; Control1: P1C2P1; Control2: P1C2P2; To: P1C2P3 }- Profile P1 { Loop Outer {- Segment Edge0 { Trace: P1C0; From: P1C0P0; To: P1C0P3 }- Segment Edge1 { Trace: P1C1; From: P1C1P0; To: P1C1P3 }- Segment Edge2 { Trace: P1C2; From: P1C2P0; To: P1C2P3 }- } }- Construction Plane F2 { Trace: Frames.S2 }- Point2 P2C0P0 { Position: [-26.796296mm,0mm] }- Point2 P2C0P1 { Position: [-26.796296mm,-7.337497mm] }- Point2 P2C0P2 { Position: [-14.799186mm,-13.285714mm] }- Point2 P2C0P3 { Position: [0mm,-13.285714mm] }- CubicBezier2 P2C0 { From: P2C0P0; Control1: P2C0P1; Control2: P2C0P2; To: P2C0P3 }- Point2 P2C1P0 { Position: [0mm,-13.285714mm] }- Point2 P2C1P1 { Position: [14.799186mm,-13.285714mm] }- Point2 P2C1P2 { Position: [26.796296mm,-7.337497mm] }- Point2 P2C1P3 { Position: [26.796296mm,0mm] }- CubicBezier2 P2C1 { From: P2C1P0; Control1: P2C1P1; Control2: P2C1P2; To: P2C1P3 }- Point2 P2C2P0 { Position: [26.796296mm,0mm] }- Point2 P2C2P1 { Position: [8.932099mm,0mm] }- Point2 P2C2P2 { Position: [-8.932099mm,0mm] }- Point2 P2C2P3 { Position: [-26.796296mm,0mm] }- CubicBezier2 P2C2 { From: P2C2P0; Control1: P2C2P1; Control2: P2C2P2; To: P2C2P3 }- Profile P2 { Loop Outer {- Segment Edge0 { Trace: P2C0; From: P2C0P0; To: P2C0P3 }- Segment Edge1 { Trace: P2C1; From: P2C1P0; To: P2C1P3 }- Segment Edge2 { Trace: P2C2; From: P2C2P0; To: P2C2P3 }- } }- Construction Plane F3 { Trace: Frames.S3 }- Point2 P3C0P0 { Position: [-26.555556mm,0mm] }- Point2 P3C0P1 { Position: [-26.555556mm,-7.179702mm] }- Point2 P3C0P2 { Position: [-14.666228mm,-13mm] }- Point2 P3C0P3 { Position: [0mm,-13mm] }- CubicBezier2 P3C0 { From: P3C0P0; Control1: P3C0P1; Control2: P3C0P2; To: P3C0P3 }- Point2 P3C1P0 { Position: [0mm,-13mm] }- Point2 P3C1P1 { Position: [14.666228mm,-13mm] }- Point2 P3C1P2 { Position: [26.555556mm,-7.179702mm] }- Point2 P3C1P3 { Position: [26.555556mm,0mm] }- CubicBezier2 P3C1 { From: P3C1P0; Control1: P3C1P1; Control2: P3C1P2; To: P3C1P3 }- Point2 P3C2P0 { Position: [26.555556mm,0mm] }- Point2 P3C2P1 { Position: [8.851852mm,0mm] }- Point2 P3C2P2 { Position: [-8.851852mm,0mm] }- Point2 P3C2P3 { Position: [-26.555556mm,0mm] }- CubicBezier2 P3C2 { From: P3C2P0; Control1: P3C2P1; Control2: P3C2P2; To: P3C2P3 }- Profile P3 { Loop Outer {- Segment Edge0 { Trace: P3C0; From: P3C0P0; To: P3C0P3 }- Segment Edge1 { Trace: P3C1; From: P3C1P0; To: P3C1P3 }- Segment Edge2 { Trace: P3C2; From: P3C2P0; To: P3C2P3 }- } }- Construction Plane F4 { Trace: Frames.S4 }- Point2 P4C0P0 { Position: [-24.148148mm,0mm] }- Point2 P4C0P1 { Position: [-24.148148mm,-5.601745mm] }- Point2 P4C0P2 { Position: [-13.336654mm,-10.142857mm] }- Point2 P4C0P3 { Position: [0mm,-10.142857mm] }- CubicBezier2 P4C0 { From: P4C0P0; Control1: P4C0P1; Control2: P4C0P2; To: P4C0P3 }- Point2 P4C1P0 { Position: [0mm,-10.142857mm] }- Point2 P4C1P1 { Position: [13.336654mm,-10.142857mm] }- Point2 P4C1P2 { Position: [24.148148mm,-5.601745mm] }- Point2 P4C1P3 { Position: [24.148148mm,0mm] }- CubicBezier2 P4C1 { From: P4C1P0; Control1: P4C1P1; Control2: P4C1P2; To: P4C1P3 }- Point2 P4C2P0 { Position: [24.148148mm,0mm] }- Point2 P4C2P1 { Position: [8.049383mm,0mm] }- Point2 P4C2P2 { Position: [-8.049383mm,0mm] }- Point2 P4C2P3 { Position: [-24.148148mm,0mm] }- CubicBezier2 P4C2 { From: P4C2P0; Control1: P4C2P1; Control2: P4C2P2; To: P4C2P3 }- Profile P4 { Loop Outer {- Segment Edge0 { Trace: P4C0; From: P4C0P0; To: P4C0P3 }- Segment Edge1 { Trace: P4C1; From: P4C1P0; To: P4C1P3 }- Segment Edge2 { Trace: P4C2; From: P4C2P0; To: P4C2P3 }- } }- Construction Plane F5 { Trace: Frames.S5 }- Point2 P5C0P0 { Position: [-21.5mm,0mm] }- Point2 P5C0P1 { Position: [-21.5mm,-3.865993mm] }- Point2 P5C0P2 { Position: [-11.874122mm,-7mm] }- Point2 P5C0P3 { Position: [0mm,-7mm] }- CubicBezier2 P5C0 { From: P5C0P0; Control1: P5C0P1; Control2: P5C0P2; To: P5C0P3 }- Point2 P5C1P0 { Position: [0mm,-7mm] }- Point2 P5C1P1 { Position: [11.874122mm,-7mm] }- Point2 P5C1P2 { Position: [21.5mm,-3.865993mm] }- Point2 P5C1P3 { Position: [21.5mm,0mm] }- CubicBezier2 P5C1 { From: P5C1P0; Control1: P5C1P1; Control2: P5C1P2; To: P5C1P3 }- Point2 P5C2P0 { Position: [21.5mm,0mm] }- Point2 P5C2P1 { Position: [7.166667mm,0mm] }- Point2 P5C2P2 { Position: [-7.166667mm,0mm] }- Point2 P5C2P3 { Position: [-21.5mm,0mm] }- CubicBezier2 P5C2 { From: P5C2P0; Control1: P5C2P1; Control2: P5C2P2; To: P5C2P3 }- Profile P5 { Loop Outer {- Segment Edge0 { Trace: P5C0; From: P5C0P0; To: P5C0P3 }- Segment Edge1 { Trace: P5C1; From: P5C1P0; To: P5C1P3 }- Segment Edge2 { Trace: P5C2; From: P5C2P0; To: P5C2P3 }- } }- SectionChain Neck { Continuity: G1- Section S0 { Frame: F0- Profile: P0- Seam: Edge0 }- Section S1 { Frame: F1- Profile: P1- Seam: Edge0 }- Section S2 { Frame: F2- Profile: P2- Seam: Edge0 }- Section S3 { Frame: F3- Profile: P3- Seam: Edge0 }- Section S4 { Frame: F4- Profile: P4- Seam: Edge0 }- Section S5 { Frame: F5- Profile: P5- Seam: Edge0 }- Start: Cap- End: Cap+ SectionChain Neck {+ continuity: G1+ Pattern Sections over Stations {+ s => Section Station {+ frame: Plane { origin: [0mm,s.Y,55mm]; normal: [0,1,0]; up: [0,0,1] }+ profile: NeckBack<HalfWidth: halfWidth(s.Y), WidthHandle: ellipseHandle(halfWidth(s.Y)), Depth: s.Depth, DepthHandle: ellipseHandle(s.Depth), SeatHandle: seatHandle(halfWidth(s.Y))>+ seam: Edge0+ }+ }+ // The headstock begins at the nut and tips back 13deg. Two short D-sections+ // carry the D-section into its rectangular root; the cap is buried in the slab.+ // NutMount remains the same interior section, so board/tuner placement stays put.+ Section HeadBlend {+ frame: Plane { origin: [0mm,headSeatY(8mm),headSeatZ(8mm)]; normal: [0,0.9743700647852352,-0.224951054343865]; up: [0,0.224951054343865,0.9743700647852352] }+ profile: NeckBack<HalfWidth:24mm, WidthHandle:ellipseHandle(24mm), Depth:14mm, DepthHandle:ellipseHandle(14mm), SeatHandle:seatHandle(24mm)>+ seam: Edge0+ }+ Section HeadMerge {+ frame: Plane { origin: [0mm,headSeatY(18mm),headSeatZ(18mm)]; normal: [0,0.9743700647852352,-0.224951054343865]; up: [0,0.224951054343865,0.9743700647852352] }+ profile: HeadRoot<HalfWidth:27.125mm, Depth:14mm>+ seam: Edge0+ }+ start: Cap+ end: Cap+ }+ expose {+ Semantic NutMount { DatumFrame Frame = Neck.Section.Sections_Nut.Frame; }+ Semantic HeelMount { DatumFrame Frame = Neck.Section.Sections_Heel.Frame; }}- Expose { Semantic NutMount { DatumFrame Frame = Neck.Section.S5.Frame; }- Semantic HeelMount { DatumFrame Frame = Neck.Section.S0.Frame; } }}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/body-assembly.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/body-assembly.firmamentindex 207e6a8e..073f1ff1 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/body-assembly.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/body-assembly.firmament@@ -1,19 +1,22 @@-Include "hardware-layout.firmament";+include "hardware-layout.firmament";Subassembly GuitarBody {<Assembly GuitarBody><Part MahoganyBack = SectionChainFile<"MahoganyBack.firmament">>- Placement { From: Origin; To: World; TranslateLocal: [0mm,0mm,0mm]; }+ material: Mahogany;+ Placement { from: Origin; to: World; translateLocal: [0mm,0mm,0mm]; }</Part><Part IvoryBinding = SectionChainFile<"IvoryBinding.firmament">>- Placement { From: Origin; To: World; TranslateLocal: [0mm,0mm,0mm]; }+ material: IvoryPolymer;+ Placement { from: Origin; to: World; translateLocal: [0mm,0mm,0mm]; }</Part><Part CarvedMaple = SectionChainFile<"CarvedMaple.firmament">>+ material: Maple with { appearance: Sunburst; };</Part></Assembly>- Interface<Fixed> BodyDeckSeat { Datum: GuitarLayout.HardwareDeck; Members: [GuitarBody.CarvedMaple.TopSeat] }- Mate BodyOnDeck: BodyDeckSeat { Member: GuitarBody.CarvedMaple.TopSeat; At: GuitarLayout.BodySeat; Orientation: SameDirection; Support: true; }+ Interface<Fixed> BodyDeckSeat { datum: GuitarLayout.HardwareDeck; members: [GuitarBody.CarvedMaple.TopSeat] }+ Mate BodyOnDeck: BodyDeckSeat { member: GuitarBody.CarvedMaple.TopSeat; at: GuitarLayout.BodySeat; orientation: SameDirection; support: true; }- Anchor: GuitarBody;+ anchor: GuitarBody;}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/body-outline.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/body-outline.firmamentindex 178a358d..4cb2fbdf 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/body-outline.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/body-outline.firmament@@ -1,45 +1,45 @@// Shared named body boundary; no authored spline control cage.-Static Landmarks: Set<Point2> {- Tail => Point2(0mm,-220mm)- TrebleWaist => Point2(105mm,28mm)- Horn => Point2(113mm,160mm)- NeckSeat => Point2(28mm,204mm)- BassShoulder => Point2(-111mm,174mm)- BassWaist => Point2(-95mm,40mm)+Static landmarks: Set<Point2> {+ Tail => Point2(0mm, -220mm)+ TrebleWaist => Point2(105mm, 28mm)+ Horn => Point2(113mm, 160mm)+ NeckSeat => Point2(28mm, 204mm)+ BassShoulder => Point2(-111mm, 174mm)+ BassWaist => Point2(-95mm, 40mm)}-Concept Struct BodyLayout {- Polygon2<Explicit> Scaffold { Vertices: Landmarks }+Concept Struct bodyLayout {+ Polygon2<Explicit> scaffold { vertices: landmarks }}-Profile BodyOutline Using BodyLayout {- From: Scaffold- Replace LowerTreble {- On: Scaffold.Tail_TrebleWaist- Through: [[115mm,-195mm], [168mm,-115mm], [148mm,-35mm]]- Derivatives: [[115mm,0mm], [84mm,52.5mm], [16.5mm,80mm], [-31.5mm,71.5mm], [-15mm,65mm]]- }- Replace HornRise {- On: Scaffold.TrebleWaist_Horn- Through: [[118mm,95mm], [124mm,140mm]]- Derivatives: [[-15mm,65mm], [9.5mm,56mm], [-2.5mm,32.5mm], [-16.5mm,1mm]]- }- Replace Cutaway {- On: Scaffold.Horn_NeckSeat- Through: [[91mm,142mm], [48mm,137mm]]- Derivatives: [[-16.5mm,1mm], [-32.5mm,-11.5mm], [-31.5mm,31mm], [-45mm,34mm]]- }- Replace Shoulder {- On: Scaffold.NeckSeat_BassShoulder- Through: [[-42mm,205mm]]- Derivatives: [[-45mm,34mm], [-69.5mm,-15mm], [-38.5mm,-45mm]]- }- Replace UpperBass {- On: Scaffold.BassShoulder_BassWaist- Through: [[-119mm,115mm]]- Derivatives: [[-38.5mm,-45mm], [8mm,-67mm], [-9mm,-73.5mm]]- }- Replace LowerBass {- On: Scaffold.BassWaist_Tail- Through: [[-137mm,-32mm], [-168mm,-115mm], [-115mm,-195mm]]- Derivatives: [[-9mm,-73.5mm], [-36.5mm,-77.5mm], [11mm,-81.5mm], [84mm,-52.5mm], [115mm,0mm]]- }+Profile BodyOutline using bodyLayout {+ from: scaffold+ Replace LowerTreble {+ on: scaffold.Tail_TrebleWaist+ through: [[115mm, -195mm], [168mm, -115mm], [148mm, -35mm]]+ derivatives: Periodic+ }+ Replace HornRise {+ on: scaffold.TrebleWaist_Horn+ through: [[118mm, 95mm], [124mm, 140mm]]+ derivatives: Periodic+ }+ Replace Cutaway {+ on: scaffold.Horn_NeckSeat+ through: [[91mm, 142mm], [48mm, 137mm]]+ derivatives: Periodic+ }+ Replace Shoulder {+ on: scaffold.NeckSeat_BassShoulder+ through: [[-42mm, 205mm]]+ derivatives: Periodic+ }+ Replace UpperBass {+ on: scaffold.BassShoulder_BassWaist+ through: [[-119mm, 115mm]]+ derivatives: Periodic+ }+ Replace LowerBass {+ on: scaffold.BassWaist_Tail+ through: [[-137mm, -32mm], [-168mm, -115mm], [-115mm, -195mm]]+ derivatives: Periodic+ }}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/body-profile.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/body-profile.firmamentnew file mode 100644index 00000000..02adcf94--- /dev/null+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/body-profile.firmament@@ -0,0 +1,7 @@+include "body-outline.firmament";+Template<Ratio: Float> Profile BodySection {+ Concept Struct Local {+ Curve2 Outline { from: BodyOutline; on: XY; scale: Ratio; pivot: [0mm,-25mm]; translate: [0mm,0mm]; rotate: 0deg }+ }+ Loop Outer { Local.Outline |> TraceLoop }+}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/bridge-assembly.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/bridge-assembly.firmamentindex 5f5b6af1..8578eb43 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/bridge-assembly.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/bridge-assembly.firmament@@ -1,4 +1,19 @@-Include "hardware-layout.firmament";+include "hardware-layout.firmament";+// Exact semicircular extrusion. The published seat is its flat diameter face;+// the crown datum keeps string endpoints on the rail instead of a free offset.+Template<L: Length,R: Length> Struct TailpieceRail {+ Concept Path Section {+ start: Point2(0mm,-R); heading: 0deg+ Arc Crown { Radius: R; Turn: 180deg }+ Close Diameter+ }+ Profile RailSection From Section+ Extrude Body { profile: RailSection; from: -L / 2; to: L / 2 }+ expose {+ Semantic BottomSeat { DatumFrame Frame = [0mm,0mm,0mm] x [0,0,-1] y [0,1,0] z [1,0,0]; }+ Semantic StringCrown { DatumFrame Frame = [R,0mm,0mm] x [0,0,-1] y [0,1,0] z [1,0,0]; }+ }+}Static SaddlesSites: Set<HardwareSite> {Saddle0 => HardwareSite { X: -25.5mm; Y: -35mm; Z: 63mm }Saddle1 => HardwareSite { X: -15.3mm; Y: -35mm; Z: 63mm }@@ -10,19 +25,27 @@ Static SaddlesSites: Set<HardwareSite> {Subassembly GuitarBridge {<Assembly GuitarBridge><Part Bridge = Panel<L:82mm,W:12mm,H:10mm,R:5mm>>+ material: Steel with { appearance: PolishedNickel; };</Part><Part Tailpiece = Panel<L:88mm,W:15mm,H:7mm,R:6mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,-75mm,53mm]; }+ material: Steel with { appearance: PolishedNickel; };+ Placement { from: Origin; to: World; translateLocal: [0mm,-75mm,53mm]; }+ </Part>+ <Part StringRail = TailpieceRail<L:76mm,R:5mm>>+ material: Steel with { appearance: PolishedNickel; };+ Placement { from: BottomSeat.Frame; to: GuitarBridge.Tailpiece.TopSeat.Frame; }</Part>- Pattern Saddles Over SaddlesSites {+ Pattern Saddles over SaddlesSites {site => <Part Saddle = Panel<L:7mm,W:9mm,H:2mm,R:1mm>>- Placement { From: Origin; To: World; TranslateLocal: [site.X,site.Y,site.Z]; }+ material: Steel;+ Placement { from: Origin; to: World; translateLocal: [site.X,site.Y,site.Z]; }</Part>}</Assembly>- Interface<Fixed> BridgeDeckSeat { Datum: GuitarLayout.HardwareDeck; Members: [GuitarBridge.Bridge.BottomSeat] }- Mate BridgeOnDeck: BridgeDeckSeat { Member: GuitarBridge.Bridge.BottomSeat; At: GuitarLayout.BridgeSeat; Orientation: SameDirection; }+ Interface<Fixed> BridgeDeckSeat { datum: GuitarLayout.HardwareDeck; members: [GuitarBridge.Bridge.BottomSeat] }+ Mate BridgeOnDeck: BridgeDeckSeat { member: GuitarBridge.Bridge.BottomSeat; at: GuitarLayout.BridgeSeat; orientation: SameDirection; }- Anchor: GuitarBridge;+ anchor: GuitarBridge;+ expose { DatumFrame TailStringPlane = StringRail.StringCrown.Frame; }}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/electronics-assembly.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/electronics-assembly.firmamentindex f768380a..94f7b6e7 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/electronics-assembly.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/electronics-assembly.firmament@@ -1,6 +1,6 @@-Include "pickups-assembly.firmament";-Include "knob.firmament";-Include "selector.firmament";+include "pickups-assembly.firmament";+include "knob.firmament";+include "selector.firmament";// Named controls retain explicit seat heights on the carved body.Static KnobSeats: Set<HardwareSite> {@@ -11,23 +11,25 @@ Static KnobSeats: Set<HardwareSite> {}Subassembly GuitarElectronics {<Assembly GuitarElectronics>- Pattern Controls Over KnobSeats {+ Pattern Controls over KnobSeats {seat => <Assembly Knob = ControlKnob>- Placement { From: Mount; To: World; TranslateLocal: [seat.X,seat.Y,seat.Z]; }+ Placement { from: Mount; to: World; translateLocal: [seat.X,seat.Y,seat.Z]; }</Assembly>}<Assembly Selector = PickupSelector>- Placement { From: Mount; To: World; TranslateLocal: [-73mm,137mm,43mm]; }+ Placement { from: Mount; to: World; translateLocal: [-73mm,137mm,43mm]; }</Assembly><Part ControlCover = Panel<L:63mm,W:93mm,H:1mm,R:15mm>>- Placement { From: Origin; To: World; TranslateLocal: [85mm,-115mm,-1mm]; }+ material: BlackPolymer;+ Placement { from: Origin; to: World; translateLocal: [85mm,-115mm,-1mm]; }</Part><Part SelectorCover = Drum<R:24mm,H:1mm>>- Placement { From: Origin; To: World; TranslateLocal: [-73mm,137mm,-1mm]; }+ material: BlackPolymer;+ Placement { from: Origin; to: World; translateLocal: [-73mm,137mm,-1mm]; }</Part><Assembly Pickups = GuitarPickups>- Placement { From: Origin; To: World; }+ Placement { from: Origin; to: World; }</Assembly></Assembly>- Anchor: GuitarElectronics;+ anchor: GuitarElectronics;}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar-x0.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar-x0.firmamentindex 21b958fd..eb6a8cfe 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar-x0.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar-x0.firmament@@ -1,28 +1,29 @@+include "materials.firmament";// Compatibility entry; prefer guitar.firmasm.// GUITAR-SURFACING-X0: composition root. Geometry and local layout live in modules.-Include "hardware-definitions.firmament";-Include "body-assembly.firmament";-Include "neck-assembly.firmament";-Include "electronics-assembly.firmament";-Include "bridge-assembly.firmament";-Include "strings-assembly.firmament";+include "hardware-definitions.firmament";+include "body-assembly.firmament";+include "neck-assembly.firmament";+include "electronics-assembly.firmament";+include "bridge-assembly.firmament";+include "strings-assembly.firmament";Assembly GuitarX0 {<Assembly GuitarX0><Assembly Body = GuitarBody>- Placement { From: Origin; To: World; }+ Placement { from: Origin; to: World; }</Assembly><Assembly Neck = GuitarNeck>- Placement { From: Origin; To: World; }+ Placement { from: Origin; to: World; }</Assembly><Assembly Electronics = GuitarElectronics>- Placement { From: Origin; To: World; }+ Placement { from: Origin; to: World; }</Assembly><Assembly Bridge = GuitarBridge>- Placement { From: Origin; To: World; }+ Placement { from: Origin; to: World; }</Assembly><Assembly Strings = GuitarStrings>- Placement { From: Origin; To: World; }+ Placement { from: Origin; to: World; }</Assembly></Assembly>- Anchor: GuitarX0;+ anchor: GuitarX0;}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasmindex 8b580b2a..5d088d83 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm@@ -1,27 +1,88 @@+include "materials.firmament";// GUITAR-SURFACING-X0: composition root. Geometry and local layout live in modules.-Include "hardware-definitions.firmament";-Include "body-assembly.firmament";-Include "neck-assembly.firmament";-Include "electronics-assembly.firmament";-Include "bridge-assembly.firmament";-Include "strings-assembly.firmament";+include "hardware-definitions.firmament";+include "body-assembly.firmament";+include "neck-assembly.firmament";+include "electronics-assembly.firmament";+include "bridge-assembly.firmament";+include "strings-assembly.firmament";++Record GuitarReleaseInfo {+ Author: String+ CreatorKind: String+ Date: Date+ Version: Version+ Milestone: String+ Description: String+ Organization: String+ Units: String+ AuthoringTolerance: Length+ Status: String+}+Static GuitarRelease: GuitarReleaseInfo {+ Author: "GPT 6.1 Sol Codex"+ CreatorKind: "AI agent; human-directed design and review"+ Date: 2026-10-01+ Version: 0.1.0+ Milestone: "GUITAR-SURFACING-X0"+ Description: "Aetheris single-cut carved-top electric guitar presentation witness"+ Organization: "Aetheris"+ Units: "mm"+ AuthoringTolerance: 0.1mm+ Status: "Presentation demonstrator; not released for manufacture"+}Assembly GuitarX0 {- <Assembly GuitarX0>- <Assembly Body = GuitarBody>- Placement { From: Origin; To: World; }- </Assembly>- <Assembly Neck = GuitarNeck>- Placement { From: Origin; To: World; }- </Assembly>- <Assembly Electronics = GuitarElectronics>- Placement { From: Origin; To: World; }- </Assembly>- <Assembly Bridge = GuitarBridge>- Placement { From: Origin; To: World; }- </Assembly>- <Assembly Strings = GuitarStrings>- Placement { From: Origin; To: World; }+ provenance: GuitarRelease;+ Pmi {+ Note DesignIntent {+ target: GuitarX0;+ text: "Single-cut carved-top electric guitar inspired by the Les Paul silhouette; original demo proportions, no trademark-faithful reproduction or branding.";+ }+ Note AuthoringTolerance {+ target: GuitarX0;+ text: "Nominal authoring tolerance: 0.1 mm. Round authored engineering locations to this resolution where practical; preserve derived surface controls and mathematical evaluations. This convention is not a manufacturing acceptance limit, kernel tolerance, or tessellation setting.";+ }+ Note CarvedBody {+ target: GuitarX0.Body;+ text: "Carved maple top and mahogany back use source-owned profiles and exact admitted section-chain surfaces. The top is not globally planar; hardware seats on explicit Concept datums. Binding is decorative.";+ }+ Note NeckJoint {+ target: GuitarX0.Neck;+ text: "The neck has a nearly straight shaft back and an exact section-chain transition into a tilted headstock. Neck, scarf, and headstock are separate solids with intentional contact/overlap; globally fused G2 joinery and manufacturing fit are not qualified.";+ }+ Note Electronics {+ target: GuitarX0.Electronics;+ text: "Pickups, poles, knobs, and selector are presentation geometry with reusable definitions and datum-based placement. Coil winding, wiring, switches, and electrical function are not modeled.";+ }+ Note BridgeHardware {+ target: GuitarX0.Bridge;+ text: "Bridge, six saddles, and a semicircular stop-tailpiece rail support the visible string route. Anchor holes, adjustment mechanisms, and structural or intonation qualification are omitted.";+ }+ Note StringsAndTuners {+ target: GuitarX0.Strings;+ text: "Six point-driven WireForm strings follow nut, bridge, tailpiece, and tuner entry datums. Tension, vibration, winding, and tuner internals are decorative simplifications; tuner buttons have physical connector stems.";+ }+ Note Finish {+ target: GuitarX0;+ text: "Firmament assigns nominal physical materials and semantic appearance overrides. USD carries preview appearances; the glossy amber-to-dark-edge sunburst and studio lighting are realized downstream in Blender Cycles, not encoded as STEP texture or extra geometry.";+ }+ }+ <Assembly GuitarX0>+ <Assembly Body = GuitarBody>+ Placement { from: Origin; to: World; }+ </Assembly>+ <Assembly Neck = GuitarNeck>+ Placement { from: Origin; to: World; }+ </Assembly>+ <Assembly Electronics = GuitarElectronics>+ Placement { from: Origin; to: World; }+ </Assembly>+ <Assembly Bridge = GuitarBridge>+ Placement { from: Origin; to: World; }+ </Assembly>+ <Assembly Strings = GuitarStrings>+ Placement { from: Origin; to: World; }+ </Assembly></Assembly>- </Assembly>- Anchor: GuitarX0;+ anchor: GuitarX0;}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/hardware-definitions.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/hardware-definitions.firmamentindex 308621f0..99aad0f5 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/hardware-definitions.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/hardware-definitions.firmament@@ -1,56 +1,76 @@Template<L: Length, W: Length, H: Length, R: Length> Struct Panel {- Expose { Semantic BottomSeat { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; } }- RoundedRect2 Outline { Center: [0mm,0mm] Size: [L,W] Radius: R }+ expose { Semantic BottomSeat { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; } Semantic TopSeat { DatumFrame Frame = [0mm,0mm,H] x [1,0,0] y [0,1,0] z [0,0,1]; } }+ RoundedRect2 Outline { center: [0mm,0mm] size: [L,W] radius: R }Profile P { Loop Outer { Outline |> TraceLoop } }- Extrude Body { Profile: P From: 0mm To: H }+ Extrude Body { profile: P from: 0mm to: H }}-Template<R: Length,H: Length> Struct Drum {- Expose { Semantic BottomSeat { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; }+Template<R: Length,H: Length,EntryHeight: Length = 0mm> Struct Drum {+ expose { Semantic BottomSeat { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; }+ Semantic StringEntry { DatumFrame Frame = [0mm,0mm,EntryHeight] x [1,0,0] y [0,1,0] z [0,0,1]; }Semantic SpindleSeat { Axis Axis = [0mm,0mm,0mm] -> [0,0,1];DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; } }- Circle2 Outline { Center: [0mm,0mm] Radius: R }+ Circle2 Outline { center: [0mm,0mm] radius: R }Profile P { Loop Outer { Outline |> TraceLoop } }- Extrude Body { Profile: P From: 0mm To: H }+ Extrude Body { profile: P from: 0mm to: H }}Template<L: Length,W: Length,H: Length> Struct Surround {- RoundedRect2 Outer { Center: [0mm,0mm] Size: [L,W] Radius: 4mm }+ RoundedRect2 Outer { center: [0mm,0mm] size: [L,W] radius: 4mm }// Solid decorative seat; the black bobbins sit on it. No routed opening claim.Profile P { Loop Outer { Outer |> TraceLoop } }- Extrude Body { Profile: P From: 0mm To: H }+ Extrude Body { profile: P from: 0mm to: H }}Template<H: Length> Struct Board {- Point2 RightNut { Position: [21.5mm,660mm] }- Point2 LeftNut { Position: [-21.5mm,660mm] }- Concept Path Outline { Start: Point2(-28mm,120mm) Heading: 0deg- Line End { Length: 56mm }- Line Right { To: RightNut }- Line Nut { To: LeftNut }+ expose { Semantic MarkerOrigin { DatumFrame Frame = [0mm,658mm,H] x [1,0,0] y [0,1,0] z [0,0,1]; } }+ Point2 RightNut { position: [21.5mm,660mm] }+ Point2 LeftNut { position: [-21.5mm,660mm] }+ Concept Path Outline { start: Point2(-28mm,120mm) heading: 0deg+ Line End { length: 56mm }+ Line Right { to: RightNut }+ Line Nut { to: LeftNut }Close Left}Profile P From Outline- Extrude Body { Profile: P From: 0mm To: H }+ Extrude Body { profile: P from: 0mm to: H }}-Template<H: Length> Struct Head {- Expose { Semantic Base { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }+// Short solid scarf under the veneer, behind the nut. The rounded back is+// supplied by Neck's section chain; this closes the front of the angled join.+Template<L: Length> Struct HeadstockScarf {+ Concept Path Side {+ start: Point2(-1.5mm,6.8mm); heading: 0deg+ Line Back { to: BackEnd }+ Line Shoulder { to: FrontEnd }+ Line Front { to: NutCorner }+ Close NutBack+ }+ Point2 NutCorner { position: [-3.1mm,14mm] }+ Point2 FrontEnd { position: [8mm,14mm] }+ Point2 BackEnd { position: [8mm,7mm] }+ Profile P From Side+ Extrude Body { profile: P; from: -L / 2; to: L / 2 }+ expose { Semantic Mount { DatumFrame Frame = [0mm,0mm,0mm] x [0,0,1] y [1,0,0] z [0,1,0]; } }+}++Template<H: Length, RootStart: Length = 0mm, RootHalfWidth: Length = 21.5mm, RootWidth: Length = 43mm> Struct Head {+ expose { Semantic Base { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }Semantic Front { DatumFrame Frame = [0mm,0mm,H] x [1,0,0] y [0,1,0] z [0,0,1]; } }- Point2 RFlare { Position: [34mm,40mm] }- Point2 RSide { Position: [39mm,154mm] }- Point2 RCrown { Position: [12mm,160mm] }- Point2 LCrown { Position: [-12mm,160mm] }- Point2 LSide { Position: [-39mm,154mm] }- Point2 LFlare { Position: [-34mm,40mm] }- Concept Path Outline { Start: Point2(-21.5mm,0mm) Heading: 0deg- Line Base { Length: 43mm }- Line FlareR { To: RFlare }- Line SideR { To: RSide }- Line CrownR { To: RCrown }- Line Crown { To: LCrown }- Line CrownL { To: LSide }- Line SideL { To: LFlare }+ Point2 RFlare { position: [34mm,40mm] }+ Point2 RSide { position: [39mm,154mm] }+ Point2 RCrown { position: [12mm,160mm] }+ Point2 LCrown { position: [-12mm,160mm] }+ Point2 LSide { position: [-39mm,154mm] }+ Point2 LFlare { position: [-34mm,40mm] }+ Concept Path Outline { start: Point2(-RootHalfWidth,RootStart) heading: 0deg+ Line Base { length: RootWidth }+ Line FlareR { to: RFlare }+ Line SideR { to: RSide }+ Line CrownR { to: RCrown }+ Line Crown { to: LCrown }+ Line CrownL { to: LSide }+ Line SideL { to: LFlare }Close FlareL}Profile P From Outline- Extrude Body { Profile: P From: 0mm To: H }+ Extrude Body { profile: P from: 0mm to: H }}Record HardwareSite { X: Length; Y: Length; Z: Length }diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/hardware-layout.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/hardware-layout.firmamentindex 4a3f56db..4a1cb8ee 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/hardware-layout.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/hardware-layout.firmament@@ -1,7 +1,7 @@Concept Struct GuitarLayout {- Plane HardwareDeck { From: SectionChainFile<"CarvedMaple.firmament">.TopSeat.Frame; Offset: 0mm; Clocking: 0deg }- DatumFrame BodySeat { On: HardwareDeck; At: [0mm,0mm]; X: [1,0] }- DatumFrame NeckPickupSeat { On: HardwareDeck; At: [0mm,98mm]; X: [1,0] }- DatumFrame BridgePickupSeat { On: HardwareDeck; At: [0mm,0mm]; X: [1,0] }- DatumFrame BridgeSeat { On: HardwareDeck; At: [0mm,-35mm]; X: [1,0] }+ Plane HardwareDeck { from: SectionChainFile<"CarvedMaple.firmament">.TopSeat.Frame; offset: 0mm; clocking: 0deg }+ DatumFrame BodySeat { on: HardwareDeck; at: [0mm,0mm]; x: [1,0] }+ DatumFrame NeckPickupSeat { on: HardwareDeck; at: [0mm,98mm]; x: [1,0] }+ DatumFrame BridgePickupSeat { on: HardwareDeck; at: [0mm,0mm]; x: [1,0] }+ DatumFrame BridgeSeat { on: HardwareDeck; at: [0mm,-35mm]; x: [1,0] }}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/knob.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/knob.firmamentindex 2c045357..e9629f9e 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/knob.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/knob.firmament@@ -1,23 +1,29 @@// A rigid knob stack seated by station on one Concept spindle.Concept Struct KnobLayout {- Axis Spindle { Origin: [0mm,0mm,0mm]; Direction: [0,0,1]; Reference: [1,0,0]; }+ Axis Spindle { origin: [0mm, 0mm, 0mm]; direction: [0, 0, 1]; reference: [1, 0, 0]; }}Subassembly ControlKnob {- <Assembly ControlKnob>- <Part KnobSkirt = Drum<R:12mm,H:3mm>></Part>- <Part AmberKnob = Drum<R:9mm,H:9mm>></Part>- <Part KnobCap = Drum<R:5mm,H:1mm>></Part>- </Assembly>- Interface<Fixed> CoaxialStack {- Datum: KnobLayout.Spindle;- Members: [ControlKnob.KnobSkirt.SpindleSeat,ControlKnob.AmberKnob.SpindleSeat,ControlKnob.KnobCap.SpindleSeat];- }- Mate SkirtOnSpindle: CoaxialStack { Member: ControlKnob.KnobSkirt.SpindleSeat; At: 0mm; Clocking: 0deg; }- Mate GripOnSpindle: CoaxialStack { Member: ControlKnob.AmberKnob.SpindleSeat; At: 3mm; Clocking: 0deg; }- Mate CapOnSpindle: CoaxialStack { Member: ControlKnob.KnobCap.SpindleSeat; At: 12mm; Clocking: 0deg; }- Anchor: ControlKnob;- Expose {- DatumFrame Mount = KnobSkirt.SpindleSeat.Frame;- Semantic Spindle = KnobSkirt.SpindleSeat;- }+ <Assembly ControlKnob>+ <Part KnobSkirt = Drum<R:12mm,H:3mm>>+ material: Brass;+ </Part>+ <Part AmberKnob = Drum<R:9mm,H:9mm>>+ material: AmberPolymer;+ </Part>+ <Part KnobCap = Drum<R:5mm,H:1mm>>+ material: Brass;+ </Part>+ </Assembly>+ Interface<Fixed> CoaxialStack {+ datum: KnobLayout.Spindle;+ members: [ControlKnob.KnobSkirt.SpindleSeat, ControlKnob.AmberKnob.SpindleSeat, ControlKnob.KnobCap.SpindleSeat];+ }+ Mate SkirtOnSpindle: CoaxialStack { member: ControlKnob.KnobSkirt.SpindleSeat; at: 0mm; clocking: 0deg; }+ Mate GripOnSpindle: CoaxialStack { member: ControlKnob.AmberKnob.SpindleSeat; at: 3mm; clocking: 0deg; }+ Mate CapOnSpindle: CoaxialStack { member: ControlKnob.KnobCap.SpindleSeat; at: 12mm; clocking: 0deg; }+ anchor: ControlKnob;+ expose {+ DatumFrame Mount = KnobSkirt.SpindleSeat.Frame;+ Semantic Spindle = KnobSkirt.SpindleSeat;+ }}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/materials.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/materials.firmamentnew file mode 100644index 00000000..64c9e5c2--- /dev/null+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/materials.firmament@@ -0,0 +1,26 @@+// Nominal physical identities, not certified material grades or analysis properties.+// Appearance changes do not alter physical identity or exact geometry.+Appearance PolishedSteel { color: [0.65,0.69,0.73]; metallic: 1; roughness: 0.16; }+Appearance WarmIvory { color: [0.72,0.59,0.36]; metallic: 0; roughness: 0.23; }+Appearance BlackPolymer { color: [0.009,0.007,0.006]; metallic: 0; roughness: 0.21; }+Appearance EbonyLacquer { color: [0.008,0.01,0.013]; metallic: 0; roughness: 0.18; }+Appearance Pearl { color: [0.74,0.73,0.62]; metallic: 0.2; roughness: 0.22; }+Appearance Amber { color: [0.38,0.13,0.013]; metallic: 0.25; roughness: 0.21; }+Appearance Brass { color: [0.48,0.27,0.06]; metallic: 0.7; roughness: 0.24; }+Appearance CherryMahogany { color: [0.1,0.017,0.007]; metallic: 0; roughness: 0.24; }+Appearance Rosewood { color: [0.035,0.012,0.006]; metallic: 0; roughness: 0.36; }+Appearance GoldenMaple { color: [0.85,0.48,0.065]; metallic: 0; roughness: 0.24; }+Appearance Sunburst { color: [0.85,0.48,0.065]; metallic: 0; roughness: 0.24; }+Appearance PickupComposite { color: [0.009,0.007,0.006]; metallic: 0; roughness: 0.21; }+Appearance PolishedNickel { color: [0.65,0.69,0.73]; metallic: 1; roughness: 0.16; }+Material Steel { identity: "steel"; appearance: PolishedSteel; }+Material IvoryPolymer { identity: "ivory-colored polymer"; appearance: WarmIvory; }+Material BlackPolymer { identity: "black polymer"; appearance: BlackPolymer; }+Material Ebony { identity: "ebony veneer"; appearance: EbonyLacquer; }+Material MotherOfPearl { identity: "mother of pearl"; appearance: Pearl; }+Material AmberPolymer { identity: "amber polymer"; appearance: Amber; }+Material Brass { identity: "brass"; appearance: Brass; }+Material Mahogany { identity: "mahogany"; appearance: CherryMahogany; }+Material Rosewood { identity: "rosewood"; appearance: Rosewood; }+Material Maple { identity: "maple"; appearance: GoldenMaple; }+Material PickupComposite { identity: "decorative pickup composite"; appearance: PickupComposite; }diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/neck-assembly.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/neck-assembly.firmamentindex 171dbb32..59446431 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/neck-assembly.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/neck-assembly.firmament@@ -1,125 +1,103 @@-Include "tuners-assembly.firmament";+include "tuners-assembly.firmament";++// All Functions evaluate during compilation; lengths remain dimension checked.+Function fretDistance(n: Int, scale: Length) -> Length =+ scale * (1.0 - Pow(2.0, -n / 12.0));+Function fretWidth(distance: Length) -> Length =+ 42mm + 13mm * ((distance + 2mm) / 540mm);++Concept Struct NutLayout {+ Points<Point2> Crossings {+ keys: [String0, String1, String2, String3, String4, String5];+ Linear { start: Point2(-18mm, 0mm); step: [7.2mm, 0mm]; }+ }+}+Concept Struct FretboardLayout {+ Points<Point2> Positions {+ Series {+ index: n; first: 1; count: 22; keyPrefix: Fret;+ position: Point2(0mm, -fretDistance(n, 628mm));+ }+ }+ // Authored marker stations use 0.1mm resolution; compiler math stays precise.+ Points<Point2> InlayPositions {+ Linear {+ start: Point2(0mm,0mm);+ direction: [0,-1];+ Stations {+ Fret3: 84.2mm;+ Fret5: 143.5mm;+ Fret7: 196.4mm;+ Fret9: 243.5mm;+ Fret12: 304.7mm;+ Fret15: 356.1mm;+ Fret17: 385.8mm;+ Fret19: 412.2mm;+ Fret21: 435.7mm;+ }+ }+ }++}Subassembly GuitarNeck {<Assembly GuitarNeck><Part Neck = SectionChainFile<"Neck.firmament">>- Placement { From: Origin; To: World; TranslateLocal: [0mm,0mm,0mm]; }+ material: Mahogany;+ Placement { from: Origin; to: World; translateLocal: [0mm,0mm,0mm]; }</Part><Part BoardBinding = Board<H:5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,0mm,55mm]; }+ material: IvoryPolymer;+ Placement { from: Origin; to: World; translateLocal: [0mm,0mm,55mm]; }</Part><Part Rosewood = Board<H:2mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,0mm,60mm]; }+ material: Rosewood;+ Placement { from: Origin; to: World; translateLocal: [0mm,0mm,60mm]; }</Part>- <Part Headstock = Head<H:14mm>>- Placement { From: Base.Frame; To: HeadTilt.Frame; }+ // Neck's section chain fills the first 16mm; the slab starts inside that loft.+ <Part Headstock = Head<H:14mm,RootStart:16mm,RootHalfWidth:26.5mm,RootWidth:53mm>>+ material: Mahogany;+ Placement { from: Base.Frame; to: HeadTilt.Frame; }</Part><Part HeadVeneer = Head<H:1mm>>+ material: Ebony;</Part>- <Part Nut = Panel<L:44mm,W:4mm,H:3mm,R:1mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,658mm,62mm]; }- </Part>- <Part Fret1 = Panel<L:42.896685mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,622.753068mm,62mm]; }- </Part>- <Part Fret2 = Panel<L:43.697598mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,589.484395mm,62mm]; }- </Part>- <Part Fret3 = Panel<L:44.453559mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,558.082949mm,62mm]; }- </Part>- <Part PearlInlay3 = Panel<L:25mm,W:12mm,H:0.3mm,R:1mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,573.783672mm,62mm]; }- </Part>- <Part Fret4 = Panel<L:45.167091mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,528.44393mm,62mm]; }- </Part>- <Part Fret5 = Panel<L:45.840575mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,500.468422mm,62mm]; }- </Part>- <Part PearlInlay5 = Panel<L:25mm,W:12mm,H:0.3mm,R:1mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,514.456176mm,62mm]; }- </Part>- <Part Fret6 = Panel<L:46.47626mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,474.063059mm,62mm]; }- </Part>- <Part Fret7 = Panel<L:47.076266mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,449.139714mm,62mm]; }- </Part>- <Part PearlInlay7 = Panel<L:25mm,W:12mm,H:0.3mm,R:1mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,461.601386mm,62mm]; }- </Part>- <Part Fret8 = Panel<L:47.642597mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,425.61521mm,62mm]; }- </Part>- <Part Fret9 = Panel<L:48.177142mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,403.411034mm,62mm]; }- </Part>- <Part PearlInlay9 = Panel<L:25mm,W:12mm,H:0.3mm,R:1mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,414.513122mm,62mm]; }- </Part>- <Part Fret10 = Panel<L:48.681685mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,382.453083mm,62mm]; }- </Part>- <Part Fret11 = Panel<L:49.15791mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,362.671412mm,62mm]; }- </Part>- <Part Fret12 = Panel<L:49.607407mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,344mm,62mm]; }- </Part>- <Part PearlInlay12 = Panel<L:25mm,W:12mm,H:0.3mm,R:1mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,353.335706mm,62mm]; }- </Part>- <Part Fret13 = Panel<L:50.031676mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,326.376534mm,62mm]; }- </Part>- <Part Fret14 = Panel<L:50.432132mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,309.742197mm,62mm]; }- </Part>- <Part Fret15 = Panel<L:50.810113mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,294.041474mm,62mm]; }- </Part>- <Part PearlInlay15 = Panel<L:25mm,W:12mm,H:0.3mm,R:1mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,301.891836mm,62mm]; }- </Part>- <Part Fret16 = Panel<L:51.166879mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,279.221965mm,62mm]; }- </Part>- <Part Fret17 = Panel<L:51.503621mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,265.234211mm,62mm]; }- </Part>- <Part PearlInlay17 = Panel<L:25mm,W:12mm,H:0.3mm,R:1mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,272.228088mm,62mm]; }- </Part>- <Part Fret18 = Panel<L:51.821463mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,252.031529mm,62mm]; }- </Part>- <Part Fret19 = Panel<L:52.121466mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,239.569857mm,62mm]; }- </Part>- <Part PearlInlay19 = Panel<L:25mm,W:12mm,H:0.3mm,R:1mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,245.800693mm,62mm]; }- </Part>- <Part Fret20 = Panel<L:52.404632mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,227.807605mm,62mm]; }- </Part>- <Part Fret21 = Panel<L:52.671904mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,216.705517mm,62mm]; }- </Part>- <Part PearlInlay21 = Panel<L:25mm,W:12mm,H:0.3mm,R:1mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,222.256561mm,62mm]; }- </Part>- <Part Fret22 = Panel<L:52.924176mm,W:1.2mm,H:1mm,R:0.5mm>>- Placement { From: Origin; To: World; TranslateLocal: [0mm,206.226542mm,62mm]; }+ <Part NutScarf = HeadstockScarf<L:43mm>>+ material: Mahogany;+ Placement { from: Mount.Frame; to: GuitarNeck.Headstock.Base.Frame; }</Part>+ <Part Nut = Panel<L:44mm,W:4mm,H:3mm,R:1mm>>+ material: IvoryPolymer;+ Placement { from: Origin; to: World; translateLocal: [0mm,658mm,62mm]; }+ </Part>+ Pattern Frets over FretboardLayout.Positions {+ point => <Part Fret = Panel<L:fretWidth(-point.Position.Y),W:1.2mm,H:1mm,R:0.5mm>>+ material: Steel with { appearance: PolishedNickel; };+ Placement {+ from: BottomSeat.Frame; to: FretboardDatum.Frame;+ translateLocal: [point.Position.X, point.Position.Y, 0mm];+ }+ </Part>+ }+ Pattern PearlInlays over FretboardLayout.InlayPositions {+ point => <Part Inlay = Panel<L:25mm,W:12mm,H:0.3mm,R:1mm>>+ material: MotherOfPearl;+ Placement {+ from: BottomSeat.Frame; to: InlayDatum.Frame;+ translateLocal: [point.Position.X, point.Position.Y, 0mm];+ }+ </Part>+ }<Assembly Tuners = GuitarTuners>// Front includes the 14mm headstock; 1mm seats on its veneer.- Placement { From: Origin; To: GuitarNeck.Headstock.Front.Frame; TranslateLocal: [0mm,0mm,1mm]; }+ Placement { from: Origin; to: GuitarNeck.Headstock.Front.Frame; translateLocal: [0mm,0mm,1mm]; }</Assembly></Assembly>- FrameTransform NutWorld { From: GuitarNeck.Neck.NutMount.Frame; Normal: [0,1,0]; Up: [0,0,1]; TranslateLocal: [0mm,-7mm,0mm]; }- FrameTransform HeadTilt { From: NutWorld.Frame; RotateLocal: { Axis: X; Angle: -13deg } }- Interface<Fixed> VeneerSeat { A: GuitarNeck.Headstock.Front.Frame; B: GuitarNeck.HeadVeneer.Base.Frame; Gap: 0mm; Clocking: 0deg; }- Anchor: GuitarNeck;- Expose { DatumFrame NutMount = Neck.NutMount.Frame; DatumFrame HeelMount = Neck.HeelMount.Frame; DatumFrame HeadFront = Headstock.Front.Frame; }+ FrameTransform InlayDatum { from: GuitarNeck.Rosewood.MarkerOrigin.Frame; }+ FrameTransform FretboardDatum { from: GuitarNeck.Nut.BottomSeat.Frame; }+ FrameTransform NutWorld { from: GuitarNeck.Neck.NutMount.Frame; normal: [0,1,0]; up: [0,0,1]; translateLocal: [0mm,-7mm,0mm]; }+ FrameTransform HeadTilt { from: NutWorld.Frame; rotateLocal: { axis: X; angle: -13deg } }+ Interface<Fixed> VeneerSeat { a: GuitarNeck.Headstock.Front.Frame; b: GuitarNeck.HeadVeneer.Base.Frame; gap: 0mm; clocking: 0deg; }+ anchor: GuitarNeck;+ expose { DatumFrame NutMount = Neck.NutMount.Frame; DatumFrame HeelMount = Neck.HeelMount.Frame; DatumFrame HeadFront = Headstock.Front.Frame; DatumFrame StringPlane = Nut.TopSeat.Frame; DatumFrame StringLowE = Tuners.StringLowE; DatumFrame StringA = Tuners.StringA; DatumFrame StringD = Tuners.StringD; DatumFrame StringG = Tuners.StringG; DatumFrame StringB = Tuners.StringB; DatumFrame StringHighE = Tuners.StringHighE; }}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/neck-profile.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/neck-profile.firmamentnew file mode 100644index 00000000..18d50073--- /dev/null+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/neck-profile.firmament@@ -0,0 +1,60 @@+// D-section split at the cubic midpoints (de Casteljau, no shape change).+// Six named spans also correspond to the rectangular headstock root.+Template<HalfWidth: Length, WidthHandle: Length, Depth: Length, DepthHandle: Length, SeatHandle: Length>+Profile NeckBack {+ Point2 Left { position: [-HalfWidth,0mm] }+ Point2 LeftA { position: [-HalfWidth,-DepthHandle / 2] }+ Point2 LeftB { position: [-0.75 * HalfWidth - 0.25 * WidthHandle,-0.5 * DepthHandle - 0.25 * Depth] }+ Point2 LeftMid { position: [-0.5 * HalfWidth - 0.375 * WidthHandle,-0.375 * DepthHandle - 0.5 * Depth] }+ Point2 LeftC { position: [-0.25 * HalfWidth - 0.5 * WidthHandle,-0.25 * DepthHandle - 0.75 * Depth] }+ Point2 LeftD { position: [-WidthHandle / 2,-Depth] }+ Point2 Back { position: [0mm,-Depth] }+ Point2 RightD { position: [WidthHandle / 2,-Depth] }+ Point2 RightC { position: [0.25 * HalfWidth + 0.5 * WidthHandle,-0.25 * DepthHandle - 0.75 * Depth] }+ Point2 RightMid { position: [0.5 * HalfWidth + 0.375 * WidthHandle,-0.375 * DepthHandle - 0.5 * Depth] }+ Point2 RightB { position: [0.75 * HalfWidth + 0.25 * WidthHandle,-0.5 * DepthHandle - 0.25 * Depth] }+ Point2 RightA { position: [HalfWidth,-DepthHandle / 2] }+ Point2 Right { position: [HalfWidth,0mm] }+ Point2 SeatA { position: [SeatHandle,0mm] }+ Point2 SeatB { position: [-SeatHandle,0mm] }+ Point2 SeatRight { position: [2 * SeatHandle,0mm] }+ Point2 SeatLeft { position: [-2 * SeatHandle,0mm] }+ Point2 SeatMiddle { position: [0mm,0mm] }+ CubicBezier2 BassShoulder { from: Left; control1: LeftA; control2: LeftB; to: LeftMid }+ CubicBezier2 BassBack { from: LeftMid; control1: LeftC; control2: LeftD; to: Back }+ CubicBezier2 TrebleBack { from: Back; control1: RightD; control2: RightC; to: RightMid }+ CubicBezier2 TrebleShoulder { from: RightMid; control1: RightB; control2: RightA; to: Right }+ CubicBezier2 SeatTreble { from: Right; control1: SeatRight; control2: SeatA; to: SeatMiddle }+ CubicBezier2 SeatBass { from: SeatMiddle; control1: SeatB; control2: SeatLeft; to: Left }+ Loop Outer {+ Segment Edge0 { Trace: BassShoulder; From: Left; To: LeftMid }+ Segment Edge1 { Trace: BassBack; From: LeftMid; To: Back }+ Segment Edge2 { Trace: TrebleBack; From: Back; To: RightMid }+ Segment Edge3 { Trace: TrebleShoulder; From: RightMid; To: Right }+ Segment Edge4 { Trace: SeatTreble; From: Right; To: SeatMiddle }+ Segment Edge5 { Trace: SeatBass; From: SeatMiddle; To: Left }+ }+}++Template<HalfWidth: Length, Depth: Length> Profile HeadRoot {+ Point2 LeftTop { position: [-HalfWidth,0mm] }+ Point2 LeftBottom { position: [-HalfWidth,-Depth] }+ Point2 Back { position: [0mm,-Depth] }+ Point2 RightBottom { position: [HalfWidth,-Depth] }+ Point2 RightTop { position: [HalfWidth,0mm] }+ Point2 Seat { position: [0mm,0mm] }+ Line2 Left { From: LeftTop; To: LeftBottom }+ Line2 BassBack { From: LeftBottom; To: Back }+ Line2 TrebleBack { From: Back; To: RightBottom }+ Line2 Right { From: RightBottom; To: RightTop }+ Line2 TrebleSeat { From: RightTop; To: Seat }+ Line2 BassSeat { From: Seat; To: LeftTop }+ Loop Outer {+ Segment Edge0 { Trace: Left; From: LeftTop; To: LeftBottom }+ Segment Edge1 { Trace: BassBack; From: LeftBottom; To: Back }+ Segment Edge2 { Trace: TrebleBack; From: Back; To: RightBottom }+ Segment Edge3 { Trace: Right; From: RightBottom; To: RightTop }+ Segment Edge4 { Trace: TrebleSeat; From: RightTop; To: Seat }+ Segment Edge5 { Trace: BassSeat; From: Seat; To: LeftTop }+ }+}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/pickup.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/pickup.firmamentindex 0b16608c..c0560b4c 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/pickup.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/pickup.firmament@@ -1,50 +1,50 @@// One exact pickup part; all construction coordinates are local to its Mount.Record PickupSpec {- Width: Length; Depth: Length; BaseHeight: Length- CoilWidth: Length; CoilDepth: Length; CoilHeight: Length- CoilOffset: Length; PolePitch: Length+ width: Length; depth: Length; baseHeight: Length+ coilWidth: Length; coilDepth: Length; coilHeight: Length+ coilOffset: Length; polePitch: Length}Static StandardPickup: PickupSpec {- Width: 88mm; Depth: 46mm; BaseHeight: 4mm- CoilWidth: 70mm; CoilDepth: 17mm; CoilHeight: 5mm- CoilOffset: 10mm; PolePitch: 10.2mm+ width: 88mm; depth: 46mm; baseHeight: 4mm+ coilWidth: 70mm; coilDepth: 17mm; coilHeight: 5mm+ coilOffset: 10mm; polePitch: 10.2mm}-Static BridgePickupSpec = StandardPickup with { PolePitch: 10.2mm }+Static BridgePickupSpec = StandardPickup with { polePitch: 10.2mm }-Feature Coil(Center: Point2, Width: Length, Depth: Length, Height: Length, Support: Plane) -> Boss {- RoundedRect2 Outline { Center: Center; Size: [Width,Depth]; Radius: 3mm }- Profile Section { Loop Outer { Outline |> TraceLoop } }- return Boss { On: Support; Profile: Section; Height: Height }+Feature Coil(center: Point2, width: Length, depth: Length, height: Length, support: Plane) -> Boss {+ RoundedRect2 outline { center: center; size: [width, depth]; radius: 3mm }+ Profile section { Loop Outer { outline |> TraceLoop } }+ return Boss { on: support; profile: section; height: height }}-Feature Pole(Center: Point2, Support: Plane) -> Boss {- Circle2 Outline { Center: Center; Radius: 2.2mm }- Profile Section { Loop Outer { Outline |> TraceLoop } }- return Boss { On: Support; Profile: Section; Height: 1mm }+Feature Pole(center: Point2, support: Plane) -> Boss {+ Circle2 outline { center: center; radius: 2.2mm }+ Profile section { Loop Outer { outline |> TraceLoop } }+ return Boss { on: support; profile: section; height: 1mm }}Template<Spec: PickupSpec> Struct Humbucker {- Concept Struct Layout On XY {- Point2 UpperCenter { Position: [0mm,Spec.CoilOffset] }- Point2 LowerCenter { Position: [0mm,-Spec.CoilOffset] }- Axis2 Longitudinal { Origin: [0mm,0mm]; Direction: [1,0] }- Axis2 Transverse { Origin: [0mm,0mm]; Direction: [0,1] }- Point2 FirstPole { Position: [-2.5 * Spec.PolePitch,Spec.CoilOffset] }- RoundedRect2 BaseOutline { Center: [0mm,0mm]; Size: [Spec.Width,Spec.Depth]; Radius: 4mm }- }- Profile BaseProfile Using Layout { Loop Outer { BaseOutline |> TraceLoop } }- Plane BaseTop { Origin: [0mm,0mm,Spec.BaseHeight]; Normal: [0,0,1]; Up: [0,1,0] }- Plane CoilTop { Origin: [0mm,0mm,Spec.BaseHeight + Spec.CoilHeight]; Normal: [0,0,1]; Up: [0,1,0] }- Compose Body {- Base Housing { Profile: BaseProfile; From: 0mm; To: Spec.BaseHeight; Role: Stock }- Feature UpperCoil = Coil(Center: Layout.UpperCenter, Width: Spec.CoilWidth, Depth: Spec.CoilDepth, Height: Spec.CoilHeight, Support: BaseTop)- Feature LowerCoil = Coil(Center: Layout.LowerCenter, Width: Spec.CoilWidth, Depth: Spec.CoilDepth, Height: Spec.CoilHeight, Support: BaseTop)- Feature PoleSeed = Pole(Center: Layout.FirstPole, Support: CoilTop)- Linear Pattern Poles {- Source: PoleSeed- Direction: Layout.Longitudinal.Direction- Count: 6- Spacing: Spec.PolePitch+ Concept Struct layout on XY {+ Point2 upperCenter { position: [0mm, Spec.coilOffset] }+ Point2 lowerCenter { position: [0mm, -Spec.coilOffset] }+ Axis2 longitudinal { origin: [0mm, 0mm]; direction: [1, 0] }+ Axis2 transverse { origin: [0mm, 0mm]; direction: [0, 1] }+ Point2 firstPole { position: [-2.5 * Spec.polePitch, Spec.coilOffset] }+ RoundedRect2 baseOutline { center: [0mm, 0mm]; size: [Spec.width, Spec.depth]; radius: 4mm }}- }- Expose { Semantic Mount { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; } }+ Profile baseProfile using layout { Loop Outer { baseOutline |> TraceLoop } }+ Plane baseTop { origin: [0mm, 0mm, Spec.baseHeight]; normal: [0, 0, 1]; up: [0, 1, 0] }+ Plane coilTop { origin: [0mm, 0mm, Spec.baseHeight + Spec.coilHeight]; normal: [0, 0, 1]; up: [0, 1, 0] }+ Compose Body {+ Base housing { profile: baseProfile; from: 0mm; to: Spec.baseHeight; role: Stock }+ Feature upperCoil = Coil(center: layout.upperCenter, width: Spec.coilWidth, depth: Spec.coilDepth, height: Spec.coilHeight, support: baseTop)+ Feature lowerCoil = Coil(center: layout.lowerCenter, width: Spec.coilWidth, depth: Spec.coilDepth, height: Spec.coilHeight, support: baseTop)+ Feature poleSeed = Pole(center: layout.firstPole, support: coilTop)+ Linear Pattern poles {+ source: poleSeed+ direction: layout.longitudinal.Direction+ count: 6+ spacing: Spec.polePitch+ }+ }+ expose { Semantic Mount { DatumFrame Frame = [0mm, 0mm, 0mm] x [1, 0, 0] y [0, 1, 0] z [0, 0, 1]; } }}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/pickups-assembly.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/pickups-assembly.firmamentindex 38cca0e6..78ed418d 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/pickups-assembly.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/pickups-assembly.firmament@@ -1,15 +1,17 @@-Include "pickup.firmament";-Include "hardware-layout.firmament";+include "pickup.firmament";+include "hardware-layout.firmament";Subassembly GuitarPickups {<Assembly GuitarPickups>- <Part NeckPickup = Humbucker<Spec: StandardPickup>></Part>- <Part BridgePickup = Humbucker<Spec: StandardPickup>></Part>+ <Part NeckPickup = Humbucker<Spec: StandardPickup>>+ material: PickupComposite;</Part>+ <Part BridgePickup = Humbucker<Spec: StandardPickup>>+ material: PickupComposite;</Part></Assembly>- Interface<Fixed> PickupsDeckSeat { Datum: GuitarLayout.HardwareDeck; Members: [GuitarPickups.NeckPickup.Mount,GuitarPickups.BridgePickup.Mount] }- Mate NeckPickupOnDeck: PickupsDeckSeat { Member: GuitarPickups.NeckPickup.Mount; At: GuitarLayout.NeckPickupSeat; Orientation: SameDirection; }- Mate BridgePickupOnDeck: PickupsDeckSeat { Member: GuitarPickups.BridgePickup.Mount; At: GuitarLayout.BridgePickupSeat; Orientation: SameDirection; }+ Interface<Fixed> PickupsDeckSeat { datum: GuitarLayout.HardwareDeck; members: [GuitarPickups.NeckPickup.Mount,GuitarPickups.BridgePickup.Mount] }+ Mate NeckPickupOnDeck: PickupsDeckSeat { member: GuitarPickups.NeckPickup.Mount; at: GuitarLayout.NeckPickupSeat; orientation: SameDirection; }+ Mate BridgePickupOnDeck: PickupsDeckSeat { member: GuitarPickups.BridgePickup.Mount; at: GuitarLayout.BridgePickupSeat; orientation: SameDirection; }- Anchor: GuitarPickups;+ anchor: GuitarPickups;}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/selector.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/selector.firmamentindex 4eb90dd0..eb1eb8df 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/selector.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/selector.firmament@@ -1,16 +1,19 @@// A complete decorative pickup selector, seated at the underside of its ring.Subassembly PickupSelector {- <Assembly PickupSelector>- <Part SelectorRing = Drum<R:16mm,H:1.5mm>>- Placement { From: BottomSeat.Frame; To: World; }- </Part>- <Part SelectorStem = Drum<R:2.5mm,H:12mm>>- Placement { From: BottomSeat.Frame; To: World; TranslateLocal: [0mm,0mm,1.5mm]; }- </Part>- <Part SelectorTip = Drum<R:4mm,H:7mm>>- Placement { From: BottomSeat.Frame; To: World; TranslateLocal: [0mm,0mm,11mm]; }- </Part>- </Assembly>- Anchor: PickupSelector;- Expose { DatumFrame Mount = SelectorRing.BottomSeat.Frame; }+ <Assembly PickupSelector>+ <Part SelectorRing = Drum<R:16mm,H:1.5mm>>+ material: IvoryPolymer;+ Placement { from: BottomSeat.Frame; to: World; }+ </Part>+ <Part SelectorStem = Drum<R:2.5mm,H:12mm>>+ material: Steel;+ Placement { from: BottomSeat.Frame; to: World; translateLocal: [0mm, 0mm, 1.5mm]; }+ </Part>+ <Part SelectorTip = Drum<R:4mm,H:7mm>>+ material: IvoryPolymer;+ Placement { from: BottomSeat.Frame; to: World; translateLocal: [0mm, 0mm, 11mm]; }+ </Part>+ </Assembly>+ anchor: PickupSelector;+ expose { DatumFrame Mount = SelectorRing.BottomSeat.Frame; }}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/string-low-e.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/string-low-e.firmamentindex f62fa35e..74cd2e6c 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/string-low-e.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/string-low-e.firmament@@ -1,12 +1,16 @@schema WireFormModel GuitarLowE {- Units: mm- WireForm String {- Diameter: 0.68mm- Material: Standard.Materials.StainlessSteel.304_Annealed- StartFrame { Origin: [25.5mm,-75mm,65mm]; Tangent: [-0.0102313880420824,0.999947657979523,0]; Up: [-0.738352332641793,-0.00755476465868138,-0.674372863046382] }- Straight SpeakingLength { Length: 732.589494mm }- Bend NutBreak { Radius: 4mm; Angle: 12.805738deg; Plane: Up }- Straight TunerLead { Length: 64.073073mm }+ WireRoute String {+ diameter: 0.68mm;+ material: Standard.Materials.StainlessSteel.304_Annealed;+ minimumBendRadius: 4mm;+ Path {+ Start { at: Point3(25.5mm,-75mm,65mm); }+ Corner NutBreak { at: Point3(18mm,658mm,65mm); radius: 4mm; }+ End {+ at: Point3(27mm,58mm,20mm);+ On { From: World; TranslateLocal: [0mm,660mm,48mm]; RotateLocal: { axis: X; angle: -13deg } }+ }+ }}}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/strings-assembly.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/strings-assembly.firmamentindex 5fe280a7..00dffad5 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/strings-assembly.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/strings-assembly.firmament@@ -1,37 +1,72 @@-// GUITAR-SURFACING-X0. Original design inspired by the single-cut family.-// Every visible product part is compiled Firmament geometry. Finish is downstream.-Template<D: Length, Lead: Length, Tail: Length, Deflection: Angle> Struct GuitarString {- WireForm String {- Diameter: D- Material: Standard.Materials.StainlessSteel.304_Annealed- StartFrame { Origin: [0mm,0mm,0mm]; Tangent: [0,0,1]; Up: [1,0,0] }- Straight SpeakingLength { Length: Lead }- Bend NutBreak { Radius: 4mm; Angle: Deflection; Plane: Up }- Straight TunerLead { Length: Tail }+// Definition-local points are bound after the fixed assembly has been placed.+Template<D: Length,Tail: Point3,Nut: Point3,Post: Point3> Struct GuitarString {+ WireRoute String {+ diameter: D;+ material: Standard.Materials.StainlessSteel.304_Annealed;+ minimumBendRadius: 4mm;+ Path {+ Start { at: Tail; }+ Corner NutBreak { at: Nut; radius: 4mm; }+ End { at: Post; }+ }}}-Subassembly GuitarStrings {<Assembly GuitarStrings>- <Part String0 = GuitarString<D:0.28mm,Lead:732.589494mm,Tail:64.073073mm,Deflection:12.805738deg>>- Placement { From: Origin; To: World; TranslateLocal: [-25.5mm,-75mm,65mm]; Normal: [0.0102313880420824,0.999947657979523,0]; Up: [0.674337565008175,-0.00689977044687765,0.738390981517668]; }+ <Part String0 = GuitarString<D:0.28mm>>+ material: Steel;+ Placement { from: Origin; to: World; }+ bind {+ Tail { At: Point3(-25.5mm,0mm,0mm); On: GuitarX0.Bridge.TailStringPlane; }+ Nut { At: Point2(NutLayout.Crossings.String0.X,0mm); On: GuitarX0.Neck.StringPlane; }+ Post { At: Point3(0mm,0mm,0mm); On: GuitarX0.Neck.StringLowE; }+ }</Part>- <Part String1 = GuitarString<D:0.36mm,Lead:732.509486mm,Tail:100.649868mm,Deflection:14.372058deg>>- Placement { From: Origin; To: World; TranslateLocal: [-15.3mm,-75mm,65mm]; Normal: [0.00613903847430546,0.999981155925756,0]; Up: [0.669164958053743,-0.00410810683661916,0.743102538261814]; }+ <Part String1 = GuitarString<D:0.36mm>>+ material: Steel;+ Placement { from: Origin; to: World; }+ bind {+ Tail { At: Point3(-15.3mm,0mm,0mm); On: GuitarX0.Bridge.TailStringPlane; }+ Nut { At: Point2(NutLayout.Crossings.String1.X,0mm); On: GuitarX0.Neck.StringPlane; }+ Post { At: Point3(0mm,0mm,0mm); On: GuitarX0.Neck.StringA; }+ }</Part>- <Part String2 = GuitarString<D:0.44mm,Lead:732.474127mm,Tail:137.301981mm,Deflection:15.022472deg>>- Placement { From: Origin; To: World; TranslateLocal: [-5.1mm,-75mm,65mm]; Normal: [0.00204638043552803,0.999997906161364,0]; Up: [0.662627199851135,-0.00135599017704871,0.748948165968837]; }+ <Part String2 = GuitarString<D:0.44mm>>+ material: Steel;+ Placement { from: Origin; to: World; }+ bind {+ Tail { At: Point3(-5.1mm,0mm,0mm); On: GuitarX0.Bridge.TailStringPlane; }+ Nut { At: Point2(NutLayout.Crossings.String2.X,0mm); On: GuitarX0.Neck.StringPlane; }+ Post { At: Point3(0mm,0mm,0mm); On: GuitarX0.Neck.StringD; }+ }</Part>- <Part String5 = GuitarString<D:0.68mm,Lead:732.589494mm,Tail:64.073073mm,Deflection:12.805738deg>>- Placement { From: Origin; To: World; TranslateLocal: [25.5mm,-75mm,65mm]; Normal: [-0.0102313880420824,0.999947657979523,0]; Up: [-0.674337565008175,-0.00689977044687765,0.738390981517668]; }+ <Part String3 = GuitarString<D:0.52mm>>+ material: Steel;+ Placement { from: Origin; to: World; }+ bind {+ Tail { At: Point3(5.1mm,0mm,0mm); On: GuitarX0.Bridge.TailStringPlane; }+ Nut { At: Point2(NutLayout.Crossings.String3.X,0mm); On: GuitarX0.Neck.StringPlane; }+ Post { At: Point3(0mm,0mm,0mm); On: GuitarX0.Neck.StringG; }+ }</Part>- <Part String4 = GuitarString<D:0.6mm,Lead:732.509486mm,Tail:100.649868mm,Deflection:14.372058deg>>- Placement { From: Origin; To: World; TranslateLocal: [15.3mm,-75mm,65mm]; Normal: [-0.00613903847430546,0.999981155925756,0]; Up: [-0.669164958053743,-0.00410810683661916,0.743102538261814]; }+ <Part String4 = GuitarString<D:0.6mm>>+ material: Steel;+ Placement { from: Origin; to: World; }+ bind {+ Tail { At: Point3(15.3mm,0mm,0mm); On: GuitarX0.Bridge.TailStringPlane; }+ Nut { At: Point2(NutLayout.Crossings.String4.X,0mm); On: GuitarX0.Neck.StringPlane; }+ Post { At: Point3(0mm,0mm,0mm); On: GuitarX0.Neck.StringB; }+ }</Part>- <Part String3 = GuitarString<D:0.52mm,Lead:732.474127mm,Tail:137.301981mm,Deflection:15.022472deg>>- Placement { From: Origin; To: World; TranslateLocal: [5.1mm,-75mm,65mm]; Normal: [-0.00204638043552803,0.999997906161364,0]; Up: [-0.662627199851135,-0.00135599017704871,0.748948165968837]; }+ <Part String5 = GuitarString<D:0.68mm>>+ material: Steel;+ Placement { from: Origin; to: World; }+ bind {+ Tail { At: Point3(25.5mm,0mm,0mm); On: GuitarX0.Bridge.TailStringPlane; }+ Nut { At: Point2(NutLayout.Crossings.String5.X,0mm); On: GuitarX0.Neck.StringPlane; }+ Post { At: Point3(0mm,0mm,0mm); On: GuitarX0.Neck.StringHighE; }+ }</Part></Assembly>-- Anchor: GuitarStrings;+ anchor: GuitarStrings;}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/tuner.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/tuner.firmamentindex 1cef44cd..02475bd5 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/tuner.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/tuner.firmament@@ -1,17 +1,28 @@// One complete tuner placeholder. The button projects along local -X.// The opposite row clocks this same component 180deg about its mounting normal.Subassembly GuitarTuner {- <Assembly GuitarTuner>- <Part TunerWasher = Drum<R:7mm,H:1.5mm>>- Placement { From: BottomSeat.Frame; To: World; }- </Part>- <Part TunerPost = Drum<R:4mm,H:8mm>>- Placement { From: BottomSeat.Frame; To: World; }- </Part>- <Part TunerButton = Panel<L:15mm,W:19mm,H:6mm,R:5mm>>- Placement { From: BottomSeat.Frame; To: World; TranslateLocal: [-22mm,0mm,-7mm]; }- </Part>- </Assembly>- Anchor: GuitarTuner;- Expose { DatumFrame Mount = TunerWasher.BottomSeat.Frame; }+ <Assembly GuitarTuner>+ <Part TunerWasher = Drum<R:7mm,H:1.5mm>>+ material: Steel;+ Placement { from: BottomSeat.Frame; to: World; }+ </Part>+ <Part TunerPost = Drum<R:4mm,H:8mm,EntryHeight:5mm>>+ material: Steel;+ Placement { from: BottomSeat.Frame; to: World; }+ </Part>+ <Part TunerButton = Panel<L:15mm,W:19mm,H:6mm,R:5mm>>+ material: IvoryPolymer;+ Placement { from: BottomSeat.Frame; to: World; translateLocal: [-22mm, 0mm, -7mm]; }+ </Part>+ // Lateral spindle joins the button to the head, below the veneer surface.+ // It belongs to the reusable tuner, so both patterned rows share this solid.+ <Part ButtonStem = Drum<R:2.5mm,H:16mm>>+ material: Steel with { appearance: PolishedNickel; };+ Placement { from: BottomSeat.Frame; to: World;+ translateLocal: [-16mm, 0mm, -4mm];+ rotateLocal: { axis: Y; angle: 90deg } }+ </Part>+ </Assembly>+ anchor: GuitarTuner;+ expose { DatumFrame Mount = TunerWasher.BottomSeat.Frame; DatumFrame StringEntry = TunerPost.StringEntry.Frame; }}diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/tuners-assembly.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/tuners-assembly.firmamentindex f7b19a13..afe17ab5 100644--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/tuners-assembly.firmament+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/tuners-assembly.firmament@@ -1,26 +1,35 @@-Include "tuner.firmament";+include "tuner.firmament";// Mounting sites are expressed in the headstock-front coordinate system.Linear Sites BassTunerSites {- Keys: [Low, Middle, High];- Start: [-27mm,58mm,0mm];- Step: [0mm,36mm,0mm];+ keys: [Low, Middle, High];+ start: [-27mm,58mm,0mm];+ step: [0mm,36mm,0mm];}Mirrored Sites TrebleTunerSites From BassTunerSites { Across: YZ; }Subassembly GuitarTuners {<Assembly GuitarTuners>- Pattern BassRow Over BassTunerSites {+ Pattern BassRow over BassTunerSites {site => <Assembly Tuner = GuitarTuner>- Placement { From: Mount; To: World; TranslateLocal: [site.X,site.Y,site.Z]; }+ Placement { from: Mount; to: World; translateLocal: [site.X,site.Y,site.Z]; }</Assembly>}- Pattern TrebleRow Over TrebleTunerSites {+ Pattern TrebleRow over TrebleTunerSites {site => <Assembly Tuner = GuitarTuner>- Placement { From: Mount; To: World; TranslateLocal: [site.X,site.Y,site.Z];- RotateLocal: { Axis: Z; Angle: 180deg } }+ Placement { from: Mount; to: World; translateLocal: [site.X,site.Y,site.Z];+ rotateLocal: { axis: Z; angle: 180deg } }</Assembly>}</Assembly>- Anchor: GuitarTuners;+ anchor: GuitarTuners;++ expose {+ DatumFrame StringLowE = BassRow.Low.Tuner.StringEntry;+ DatumFrame StringA = BassRow.Middle.Tuner.StringEntry;+ DatumFrame StringD = BassRow.High.Tuner.StringEntry;+ DatumFrame StringHighE = TrebleRow.Low.Tuner.StringEntry;+ DatumFrame StringB = TrebleRow.Middle.Tuner.StringEntry;+ DatumFrame StringG = TrebleRow.High.Tuner.StringEntry;+ }}diff --git a/fixtures/Canonical/AssemblyInterfaces/coaxial-knob.firmasm b/fixtures/Canonical/AssemblyInterfaces/coaxial-knob.firmasmindex 78ae3e65..ca53e9db 100644--- a/fixtures/Canonical/AssemblyInterfaces/coaxial-knob.firmasm+++ b/fixtures/Canonical/AssemblyInterfaces/coaxial-knob.firmasm@@ -1,3 +1,4 @@+Include "GuitarX0/materials.firmament";Include "GuitarX0/hardware-definitions.firmament";Include "GuitarX0/knob.firmament";// One Concept spindle drives the complete rigid knob, along world X.diff --git a/fixtures/Canonical/Profiles/template-control-arithmetic.firmament b/fixtures/Canonical/Profiles/template-control-arithmetic.firmamentnew file mode 100644index 00000000..e1ddb4c0--- /dev/null+++ b/fixtures/Canonical/Profiles/template-control-arithmetic.firmament@@ -0,0 +1,23 @@+Template<W: Length,H: Length> Profile ControlRectangle {+ Point2 A { Position: [-W / 2,-H / 2] }+ Point2 B { Position: [W / 2,-H / 2] }+ Point2 C { Position: [W / 2,H / 2] }+ Point2 D { Position: [-W / 2,H / 2] }+ Point2 HandleA { Position: [-W / 6,-H / 2] }+ Point2 HandleB { Position: [W / 6,-H / 2] }+ CubicBezier2 Bottom { From: A; Control1: HandleA; Control2: HandleB; To: B }+ Line2 Right { From: B; To: C }+ Line2 Top { From: C; To: D }+ Line2 Left { From: D; To: A }+ Loop Outer {+ Segment Bottom { Trace: Bottom; From: A; To: B }+ Segment Right { Trace: Right; From: B; To: C }+ Segment Top { Trace: Top; From: C; To: D }+ Segment Left { Trace: Left; From: D; To: A }+ }+}+Model ControlArithmetic {+ Units: mm+ Profile P = ControlRectangle<W:40mm,H:20mm>+ Struct Body { Extrude Plate { Profile: P; From: 0mm; To: 2mm } }+}diff --git a/fixtures/Canonical/WireForm/line-guide.firmament b/fixtures/Canonical/WireForm/line-guide.firmamentnew file mode 100644index 00000000..3f4e86ac--- /dev/null+++ b/fixtures/Canonical/WireForm/line-guide.firmament@@ -0,0 +1,16 @@+Model GuidedLead {+ Units: mm+ Concept Struct HarnessLayout {+ Line3 Groove { From: Point3(0mm,0mm,0mm); To: Point3(100mm,0mm,0mm); }+ }+ WireRoute Signal {+ Diameter: 2mm;+ Material: Standard.Materials.StainlessSteel.304_Annealed;+ MinimumBendRadius: 10mm;+ Path {+ Start { At: Point3(0mm,-40mm,0mm); }+ Follow MainGroove { Curve: HarnessLayout.Groove; From: 20mm; Distance: 60mm; Direction: Forward; }+ End { At: Point3(120mm,0mm,0mm); }+ }+ }+}diff --git a/fixtures/Canonical/WireForm/point-route.firmament b/fixtures/Canonical/WireForm/point-route.firmamentnew file mode 100644index 00000000..5023b306--- /dev/null+++ b/fixtures/Canonical/WireForm/point-route.firmament@@ -0,0 +1,12 @@+schema WireForm+Model PointRoute {+ WireRoute Lead {+ Diameter: 1mm;+ MinimumBendRadius: 4mm;+ Path {+ Start { At: Point3(0mm,0mm,0mm); }+ Corner Bend { At: Point3(0mm,30mm,0mm); Radius: 4mm; }+ End { At: Point3(20mm,30mm,20mm); }+ }+ }+}diff --git a/scripts/check-guitar-x0.py b/scripts/check-guitar-x0.pyindex bb2cd8f9..2b4942ab 100644--- a/scripts/check-guitar-x0.py+++ b/scripts/check-guitar-x0.py@@ -8,7 +8,7 @@ root=Path(sys.argv[1] if len(sys.argv)>1 else 'artifacts/local/guitar-x0')document=json.loads((root/'display.json').read_text())results=[]for definition in document['mesh']['definitions']:- if 'File<' not in definition['identity'] and not definition['identity'].startswith(('GuitarString<','Humbucker<')):+ if 'File<' not in definition['identity'] and not definition['identity'].startswith(('GuitarString<','Humbucker<','TailpieceRail<','HeadstockScarf<','Drum<R:2.5mm,H:16mm>')):continueraw=definition['positions']points=[tuple(round(v,6) for v in raw[i:i+3]) for i in range(0,len(raw),3)]diff --git a/scripts/create-guitar-x0.py b/scripts/create-guitar-x0.pyindex dd38e00f..aa426781 100644--- a/scripts/create-guitar-x0.py+++ b/scripts/create-guitar-x0.py@@ -1,395 +1,38 @@-"""Author the bounded X0 witness as ordinary Firmament, never as a render mesh.+"""Reproduce the source-owned guitar through Aetheris.CLI; never rewrite fixtures.-Run from the repository root. All durable source goes into fixtures; generated-exports and renders belong under artifacts/local/guitar-x0.+Run after a Release CLI build. Optional --out selects an ignored artifact folder.+Rendering remains the independent render-guitar-x0.py downstream step."""from pathlib import Path-import math-import json-import re-from textwrap import dedent, indent--ROOT = Path('fixtures/Canonical/AssemblyInterfaces/GuitarX0')-ROOT.mkdir(parents=True, exist_ok=True)--# Original single-cut outline, millimetres; photographs are proportion references.-OUTLINE = [(0,-220),(115,-195),(168,-115),(148,-35),(105,28),- (118,95),(124,140),(113,160),(91,142),(48,137),- (28,204),(-42,205),(-111,174),(-119,115),(-95,40),- (-137,-32),(-168,-115),(-115,-195)]--def number(v):- return f'{v:.6f}'.rstrip('0').rstrip('.') if abs(v)>1e-7 else '0'--def profile(name, pts):- # Uniform periodic cubic interpolation gives shared tangent directions.- rows=[]- n=len(pts)- for i,p in enumerate(pts):- before,after=pts[(i-1)%n],pts[(i+1)%n]- h=((after[0]-before[0])/6,(after[1]-before[1])/6)- for label,q in [('P',p),('A',(p[0]+h[0],p[1]+h[1])),('B',(p[0]-h[0],p[1]-h[1]))]:- rows.append(f' Point2 {name}{label}{i} {{ Position: [{number(q[0])}mm,{number(q[1])}mm] }}')- for i in range(n):- j=(i+1)%n- rows.append(f' CubicBezier2 {name}C{i} {{ From: {name}P{i}; Control1: {name}A{i}; Control2: {name}B{j}; To: {name}P{j} }}')- rows.append(f' Profile {name} {{ Loop Outer {{')- for i in range(n):- rows.append(f' Segment Edge{i} {{ Trace: {name}C{i}; From: {name}P{i}; To: {name}P{(i+1)%n} }}')- rows.append(' } }')- return '\n'.join(rows)--def body_chain(name, stations, continuity):- rows=['Include "body-outline.firmament";', f'Model {name} {{', ' Units: mm', ' Concept Struct Frames {']- for i,(z,scale) in enumerate(stations):- rows.append(f' S{i}: Plane {{ Origin: [0mm,0mm,{z}mm]; Normal: [0,0,1]; Up: [0,1,0] }}')- rows.append(' }')- rows.append(' Concept Struct SectionLayout {')- for i,(z,scale) in enumerate(stations):- rows.append(f' Curve2 Outline{i} {{ From: BodyOutline; On: XY; Scale: {number(scale)}; Pivot: [0mm,-25mm]; Translate: [0mm,0mm]; Rotate: 0deg }}')- rows.append(' }')- for i,(z,scale) in enumerate(stations):- rows.append(f' Construction Plane F{i} {{ Trace: Frames.S{i} }}')- rows.append(f' Profile P{i} Using SectionLayout {{ Loop Outer {{ Outline{i} |> TraceLoop }} }}')- rows.append(f' SectionChain {name} {{ Continuity: {continuity}')- for i in range(len(stations)):- rows.append(f' Section S{i} {{ Frame: F{i}\n Profile: P{i}\n Seam: LowerTreble_Span0 }}')- rows.extend([' Start: Cap', ' End: Cap', ' }'])- if name == 'CarvedMaple':- rows.append(' Expose { Semantic TopSeat { DatumFrame Frame = CarvedMaple.Section.S4.Frame; } }')- rows.append('}')- (ROOT/f'{name}.firmament').write_text('\n'.join(rows)+'\n')--def body_outline():- # Named Concept chords are the closed seed. Pure Profile edits inherit their- # endpoints; explicit Hermite derivatives preserve the existing silhouette.- groups = [('Tail', 'LowerTreble', 0), ('TrebleWaist', 'HornRise', 4),- ('Horn', 'Cutaway', 7), ('NeckSeat', 'Shoulder', 10),- ('BassShoulder', 'UpperBass', 12), ('BassWaist', 'LowerBass', 14)]- vector = lambda p: '[' + ','.join(number(v)+'mm' for v in p) + ']'- rows = ['// Shared named body boundary; no authored spline control cage.',- 'Static Landmarks: Set<Point2> {']- for landmark, _, index in groups:- x,y = OUTLINE[index]- rows.append(f' {landmark} => Point2({number(x)}mm,{number(y)}mm)')- rows.extend(['}', 'Concept Struct BodyLayout {',- ' Polygon2<Explicit> Scaffold { Vertices: Landmarks }', '}',- 'Profile BodyOutline Using BodyLayout {', ' From: Scaffold'])- for k,(landmark,edit,start) in enumerate(groups):- next_landmark,_,end = groups[(k+1)%len(groups)]- if end <= start: end += len(OUTLINE)- knots = list(range(start,end+1))- through = ', '.join(vector(OUTLINE[i%len(OUTLINE)]) for i in knots[1:-1])- derivatives = []- for i in knots:- before,after = OUTLINE[(i-1)%len(OUTLINE)],OUTLINE[(i+1)%len(OUTLINE)]- derivatives.append(((after[0]-before[0])/2,(after[1]-before[1])/2))- rows.extend([f' Replace {edit} {{', f' On: Scaffold.{landmark}_{next_landmark}',- f' Through: [{through}]',- ' Derivatives: ['+', '.join(vector(d) for d in derivatives)+']', ' }'])- rows.append('}')- return '\n'.join(rows)+'\n'--(ROOT/'body-outline.firmament').write_text(body_outline())-body_chain('MahoganyBack',[(0,1),(38,1)],'G0')-body_chain('IvoryBinding',[(38,1),(40,1)],'G0')-body_chain('CarvedMaple',[(40,.992),(43,.955),(48,.84),(52,.76),(53,.72)],'G1')--# A closed D-section neck: flat fretboard seat, elliptical back, shaped heel and-# a shallow nut transition that actually meets the tilted headstock base.-def neck_profile(name, width, depth):- r=width/2; k=.55228475- curves=[((-r,0),(-r/3,0),(r/3,0),(r,0)),- ((r,0),(r,-k*depth),(k*r,-depth),(0,-depth)),- ((0,-depth),(-k*r,-depth),(-r,-k*depth),(-r,0))]- curves=[tuple(reversed(c)) for c in reversed(curves)]- rows=[]- for i,curve in enumerate(curves):- for j,(x,z) in enumerate(curve):- rows.append(f' Point2 {name}C{i}P{j} {{ Position: [{number(x)}mm,{number(z)}mm] }}')- rows.append(f' CubicBezier2 {name}C{i} {{ From: {name}C{i}P0; Control1: {name}C{i}P1; Control2: {name}C{i}P2; To: {name}C{i}P3 }}')- rows.append(f' Profile {name} {{ Loop Outer {{')- for i in range(3):- rows.append(f' Segment Edge{i} {{ Trace: {name}C{i}; From: {name}C{i}P0; To: {name}C{i}P3 }}')- rows.append(' } }')- return '\n'.join(rows)--# Collinear shaft stations keep the lengthwise back straight. The extra station-# before y=240 isolates heel fairing from the long shaft derivative.-neck_stations=[(145,40),(195,36),(220,13+2/7),(240,13),(440,13-20/7),(660,7)]-rows=['Model Neck {',' Units: mm',' Concept Struct Frames {']-for i,(y,depth) in enumerate(neck_stations):- rows.append(f' S{i}: Plane {{ Origin: [0mm,{y}mm,55mm]; Normal: [0,1,0]; Up: [0,0,1] }}')-rows.append(' }')-for i,(y,depth) in enumerate(neck_stations):- rows.append(f' Construction Plane F{i} {{ Trace: Frames.S{i} }}')- width=56-13*(y-120)/540- rows.append(neck_profile(f'P{i}',width,depth))-rows.append(' SectionChain Neck { Continuity: G1')-for i in range(len(neck_stations)):- rows.append(f' Section S{i} {{ Frame: F{i}\n Profile: P{i}\n Seam: Edge0 }}')-rows.extend([' Start: Cap',' End: Cap',' }',- ' Expose { Semantic NutMount { DatumFrame Frame = Neck.Section.S5.Frame; }',- ' Semantic HeelMount { DatumFrame Frame = Neck.Section.S0.Frame; } }','}'])-(ROOT/'Neck.firmament').write_text('\n'.join(rows)+'\n')--templates='''// GUITAR-SURFACING-X0. Original design inspired by the single-cut family.-// Every visible product part is compiled Firmament geometry. Finish is downstream.-Template<D: Length, Lead: Length, Tail: Length, Deflection: Angle> Struct GuitarString {- WireForm String {- Diameter: D- Material: Standard.Materials.StainlessSteel.304_Annealed- StartFrame { Origin: [0mm,0mm,0mm]; Tangent: [0,0,1]; Up: [1,0,0] }- Straight SpeakingLength { Length: Lead }- Bend NutBreak { Radius: 4mm; Angle: Deflection; Plane: Up }- Straight TunerLead { Length: Tail }- }-}-Template<L: Length, W: Length, H: Length, R: Length> Struct Panel {- Expose { Semantic BottomSeat { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; } }- RoundedRect2 Outline { Center: [0mm,0mm] Size: [L,W] Radius: R }- Profile P { Loop Outer { Outline |> TraceLoop } }- Extrude Body { Profile: P From: 0mm To: H }-}-Template<R: Length,H: Length> Struct Drum {- Expose { Semantic BottomSeat { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; }- Semantic SpindleSeat { Axis Axis = [0mm,0mm,0mm] -> [0,0,1];- DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; } }- Circle2 Outline { Center: [0mm,0mm] Radius: R }- Profile P { Loop Outer { Outline |> TraceLoop } }- Extrude Body { Profile: P From: 0mm To: H }-}-Template<L: Length,W: Length,H: Length> Struct Surround {- RoundedRect2 Outer { Center: [0mm,0mm] Size: [L,W] Radius: 4mm }- // Solid decorative seat; the black bobbins sit on it. No routed opening claim.- Profile P { Loop Outer { Outer |> TraceLoop } }- Extrude Body { Profile: P From: 0mm To: H }-}-Template<H: Length> Struct Board {- Point2 RightNut { Position: [21.5mm,660mm] }- Point2 LeftNut { Position: [-21.5mm,660mm] }- Concept Path Outline { Start: Point2(-28mm,120mm) Heading: 0deg- Line End { Length: 56mm }- Line Right { To: RightNut }- Line Nut { To: LeftNut }- Close Left- }- Profile P From Outline- Extrude Body { Profile: P From: 0mm To: H }-}-Template<H: Length> Struct Head {- Expose { Semantic Base { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }- Semantic Front { DatumFrame Frame = [0mm,0mm,H] x [1,0,0] y [0,1,0] z [0,0,1]; } }- Point2 RFlare { Position: [34mm,40mm] }- Point2 RSide { Position: [39mm,154mm] }- Point2 RCrown { Position: [12mm,160mm] }- Point2 LCrown { Position: [-12mm,160mm] }- Point2 LSide { Position: [-39mm,154mm] }- Point2 LFlare { Position: [-34mm,40mm] }- Concept Path Outline { Start: Point2(-21.5mm,0mm) Heading: 0deg- Line Base { Length: 43mm }- Line FlareR { To: RFlare }- Line SideR { To: RSide }- Line CrownR { To: RCrown }- Line Crown { To: LCrown }- Line CrownL { To: LSide }- Line SideL { To: LFlare }- Close FlareL- }- Profile P From Outline- Extrude Body { Profile: P From: 0mm To: H }-}-'''-parts=[]-def part(name,definition,x=0,y=0,z=0,angle=0,axis='z'):- rotate=f' RotateLocal: {{ Axis: {axis.upper()}; Angle: {number(angle)}deg }}' if angle else ''- translation=','.join(number(v)+'mm' for v in (x,y,z))- parts.append(f' <Part {name} = {definition}>\n Placement {{ From: Origin; To: World; TranslateLocal: [{translation}];{rotate} }}\n </Part>')--def formed_string(name, start, nut, end, diameter):- def subtract(a,b):return [x-y for x,y in zip(a,b)]- def length(v):return math.sqrt(sum(x*x for x in v))- lead=subtract(nut,start);tail=subtract(end,nut)- lead_length,tail_length=length(lead),length(tail)- zaxis=[v/lead_length for v in lead];target=[v/tail_length for v in tail]- normal=[zaxis[1]*target[2]-zaxis[2]*target[1],zaxis[2]*target[0]-zaxis[0]*target[2],zaxis[0]*target[1]-zaxis[1]*target[0]]- xaxis=[v/length(normal) for v in normal]- yaxis=[zaxis[1]*xaxis[2]-zaxis[2]*xaxis[1],zaxis[2]*xaxis[0]-zaxis[0]*xaxis[2],zaxis[0]*xaxis[1]-zaxis[1]*xaxis[0]]- angle=math.acos(sum(a*b for a,b in zip(zaxis,target)))- # A 4mm nut bend keeps the revised post leads clear at every string gauge.- setback=4*math.tan(angle/2)- definition=f'GuitarString<D:{number(diameter)}mm,Lead:{number(lead_length-setback)}mm,Tail:{number(tail_length-setback)}mm,Deflection:{number(math.degrees(angle))}deg>'- vector=lambda vs:','.join(f'{v:.15g}' for v in vs)- parts.append(f' <Part {name} = {definition}>\n Placement {{ From: Origin; To: World; TranslateLocal: [{",".join(number(v)+"mm" for v in start)}]; Normal: [{vector(zaxis)}]; Up: [{vector(yaxis)}]; }}\n </Part>')- if name=='String5':- # The same formed route as a standalone CLI inspection/STEP witness.- vector=lambda vs:','.join(f'{v:.15g}' for v in vs)- (ROOT/'string-low-e.firmament').write_text(f'''schema WireForm-Model GuitarLowE {{- Units: mm- WireForm String {{- Diameter: {number(diameter)}mm- Material: Standard.Materials.StainlessSteel.304_Annealed- StartFrame {{ Origin: [{','.join(number(v)+'mm' for v in start)}]; Tangent: [{vector(zaxis)}]; Up: [{vector(xaxis)}] }}- Straight SpeakingLength {{ Length: {number(lead_length-setback)}mm }}- Bend NutBreak {{ Radius: 4mm; Angle: {number(math.degrees(angle))}deg; Plane: Up }}- Straight TunerLead {{ Length: {number(tail_length-setback)}mm }}- }}-}}-''')--for name in ['MahoganyBack','IvoryBinding','CarvedMaple','Neck']:- part(name,f'SectionChainFile<"{name}.firmament">')-part('BoardBinding','Board<H:5mm>',z=55)-part('Rosewood','Board<H:2mm>',z=60)-parts.append('''<Part Headstock = Head<H:14mm>>- Placement { From: Base.Frame; To: HeadTilt.Frame; }-</Part>-<Part HeadVeneer = Head<H:1mm>>-</Part>''')-part('Nut','Panel<L:44mm,W:4mm,H:3mm,R:1mm>',y=658,z=62)-part('Bridge','Panel<L:82mm,W:12mm,H:10mm,R:5mm>',y=-35,z=53)-part('Tailpiece','Panel<L:88mm,W:15mm,H:7mm,R:6mm>',y=-75,z=53)-for i in range(6):- x=(i-2.5)*10.2- part(f'Saddle{i}','Panel<L:7mm,W:9mm,H:2mm,R:1mm>',x=x,y=-35,z=63)-for i in range(1,23):- y=658-628*(1-2**(-i/12))- width=43+(660-y)/540*13- part(f'Fret{i}',f'Panel<L:{number(width-1)}mm,W:1.2mm,H:1mm,R:0.5mm>',y=y,z=62)- if i in [3,5,7,9,12,15,17,19,21]:- previous=658-628*(1-2**(-(i-1)/12))- part(f'PearlInlay{i}','Panel<L:25mm,W:12mm,H:0.3mm,R:1mm>',y=(y+previous)/2,z=62)-for side in [-1,1]:- for i in range(3):- yy=58+i*36- y=660+yy*math.cos(math.radians(13))+20*math.sin(math.radians(13))- z=48-yy*math.sin(math.radians(13))+20*math.cos(math.radians(13))- string_index=i if side==-1 else 5-i- formed_string(f'String{string_index}',((string_index-2.5)*10.2,-75,65),((string_index-2.5)*7.2,658,65),(side*27,y,z),.28+string_index*.08)-# Finite keyed occurrence families. Values remain ordinary checked Firmament-# Records; the compiler owns expansion, identities, and definition sharing.-catalog=[]-for family,matcher in [- ('Saddles',r'Saddle[0-5]')]:- selected=[]- for declaration in parts:- match=re.fullmatch(r'\s*<Part (\w+) = (.+)>\n\s*Placement \{ From: Origin; To: World; TranslateLocal: \[([^,]+),([^,]+),([^]]+)\]; \}\n\s*</Part>',declaration)- if match and re.fullmatch(matcher,match[1]):- selected.append((declaration,match))- assert selected, family- definitions={m[2] for _,m in selected}- assert len(definitions)==1, family- catalog.append(f'Static {family}Sites: Set<HardwareSite> {{\n'+ '\n'.join(- f' {m[1]} => HardwareSite {{ X: {m[3]}; Y: {m[4]}; Z: {m[5]} }}' for _,m in selected)+'\n}')- for declaration,_ in selected: parts.remove(declaration)- leaf=family.removesuffix('s')- parts.append(f'''Pattern {family} Over {family}Sites {{- site => <Part {leaf} = {next(iter(definitions))}>- Placement {{ From: Origin; To: World; TranslateLocal: [site.X,site.Y,site.Z]; }}- </Part>-}}''')-def write_module(filename, name, members, rows=(), includes=(), relations='', exposes=''):- prefix=''.join(f'Include "{item}";\n' for item in includes)- text=prefix+'\n'.join(rows)+f'\nSubassembly {name} {{\n <Assembly {name}>\n'- text+='\n'.join(indent(dedent(member).strip(),' ') for member in members)+f'\n </Assembly>\n{relations}\n Anchor: {name};\n'- if exposes:text+=' Expose { '+exposes+' }\n'- text+='}\n'- (ROOT/filename).write_text(text)--groups={name:[] for name in ('Body','Neck','Bridge','Strings')}-for declaration in parts:- name=re.search(r'(?:<Part|Pattern)\s+(\w+)',declaration)[1]- if name in ('MahoganyBack','IvoryBinding','CarvedMaple'): group='Body'- elif name in ('Bridge','Tailpiece','Saddles'):group='Bridge'- elif name.startswith('String'):group='Strings'- else:group='Neck'- groups[group].append(declaration)--def occurrence(name,definition):- return f'<Assembly {name} = {definition}>\n Placement {{ From: Origin; To: World; }}\n</Assembly>'--def rows_for(prefixes):- return [row for row in catalog if any(row.startswith('Static '+prefix) for prefix in prefixes)]--# Common geometry definitions are separate from product containment. The string-# definition belongs to its route module rather than the common hardware catalog.-string_end=templates.index('Template<L: Length')-string_template=templates[:string_end]-(ROOT/'hardware-definitions.firmament').write_text(templates[string_end:]+'\nRecord HardwareSite { X: Length; Y: Length; Z: Length }\n')-# Concept layout is authored once and shared by each owning subassembly.-(ROOT/'hardware-layout.firmament').write_text('''Concept Struct GuitarLayout {- Plane HardwareDeck { From: SectionChainFile<"CarvedMaple.firmament">.TopSeat.Frame; Offset: 0mm; Clocking: 0deg }- DatumFrame BodySeat { On: HardwareDeck; At: [0mm,0mm]; X: [1,0] }- DatumFrame NeckPickupSeat { On: HardwareDeck; At: [0mm,98mm]; X: [1,0] }- DatumFrame BridgePickupSeat { On: HardwareDeck; At: [0mm,0mm]; X: [1,0] }- DatumFrame BridgeSeat { On: HardwareDeck; At: [0mm,-35mm]; X: [1,0] }-}-''')-groups['Body']=[re.sub(r'\s*Placement\s*\{[^}]*\}', '', p) if '<Part CarvedMaple ' in p else p for p in groups['Body']]-write_module('body-assembly.firmament','GuitarBody',groups['Body'],includes=('hardware-layout.firmament',),relations='''- Interface<Fixed> BodyDeckSeat { Datum: GuitarLayout.HardwareDeck; Members: [GuitarBody.CarvedMaple.TopSeat] }- Mate BodyOnDeck: BodyDeckSeat { Member: GuitarBody.CarvedMaple.TopSeat; At: GuitarLayout.BodySeat; Orientation: SameDirection; Support: true; }-''')-# Tuner, knob and selector modules are directly authored Firmament components.-# Preserve their site recipes and local mounting ports rather than generating coordinates.-neck_relations=''' FrameTransform NutWorld { From: GuitarNeck.Neck.NutMount.Frame; Normal: [0,1,0]; Up: [0,0,1]; TranslateLocal: [0mm,-7mm,0mm]; }- FrameTransform HeadTilt { From: NutWorld.Frame; RotateLocal: { Axis: X; Angle: -13deg } }- Interface<Fixed> VeneerSeat { A: GuitarNeck.Headstock.Front.Frame; B: GuitarNeck.HeadVeneer.Base.Frame; Gap: 0mm; Clocking: 0deg; }'''-write_module('neck-assembly.firmament','GuitarNeck',groups['Neck']+['''<Assembly Tuners = GuitarTuners>- // Front includes the 14mm headstock; 1mm seats on its veneer.- Placement { From: Origin; To: GuitarNeck.Headstock.Front.Frame; TranslateLocal: [0mm,0mm,1mm]; }-</Assembly>'''],- includes=('tuners-assembly.firmament',),relations=neck_relations,- exposes='DatumFrame NutMount = Neck.NutMount.Frame; DatumFrame HeelMount = Neck.HeelMount.Frame; DatumFrame HeadFront = Headstock.Front.Frame;')-# Pickup construction is authored in Firmament, not generated pole/coil coordinates.-write_module('pickups-assembly.firmament','GuitarPickups',[- '<Part NeckPickup = Humbucker<Spec: StandardPickup>></Part>',- '<Part BridgePickup = Humbucker<Spec: StandardPickup>></Part>'],- includes=('pickup.firmament','hardware-layout.firmament'), relations="""- Interface<Fixed> PickupsDeckSeat { Datum: GuitarLayout.HardwareDeck; Members: [GuitarPickups.NeckPickup.Mount,GuitarPickups.BridgePickup.Mount] }- Mate NeckPickupOnDeck: PickupsDeckSeat { Member: GuitarPickups.NeckPickup.Mount; At: GuitarLayout.NeckPickupSeat; Orientation: SameDirection; }- Mate BridgePickupOnDeck: PickupsDeckSeat { Member: GuitarPickups.BridgePickup.Mount; At: GuitarLayout.BridgePickupSeat; Orientation: SameDirection; }-""")-pickup_source=(ROOT/'pickup.firmament').read_text()-pickup_source=re.sub(r' Expose \{ Semantic Mount \{[^\n]+\n','',pickup_source)-(ROOT.parents[1]/'Feature'/'pickup-functional.firmament').write_text('schema Mechanical\nModel PickupFunctional {\n Units: mm\n'+pickup_source+'\n Struct Product = Humbucker<Spec: StandardPickup>\n}\n')-# electronics-assembly.firmament owns the named control seats and component occurrences.-groups['Bridge']=[re.sub(r'\s*Placement\s*\{[^}]*\}', '', p) if '<Part Bridge ' in p else p for p in groups['Bridge']]-write_module('bridge-assembly.firmament','GuitarBridge',groups['Bridge'],rows_for(('Saddles',)),includes=('hardware-layout.firmament',),relations='''- Interface<Fixed> BridgeDeckSeat { Datum: GuitarLayout.HardwareDeck; Members: [GuitarBridge.Bridge.BottomSeat] }- Mate BridgeOnDeck: BridgeDeckSeat { Member: GuitarBridge.Bridge.BottomSeat; At: GuitarLayout.BridgeSeat; Orientation: SameDirection; }-''')-write_module('strings-assembly.firmament','GuitarStrings',groups['Strings'],rows=(string_template,))-assembly='''// GUITAR-SURFACING-X0: composition root. Geometry and local layout live in modules.-Include "hardware-definitions.firmament";-Include "body-assembly.firmament";-Include "neck-assembly.firmament";-Include "electronics-assembly.firmament";-Include "bridge-assembly.firmament";-Include "strings-assembly.firmament";-Assembly GuitarX0 {- <Assembly GuitarX0>-'''+ '\n'.join(indent(occurrence(name,'Guitar'+name),' ') for name in ('Body','Neck','Electronics','Bridge','Strings'))+'''- </Assembly>- Anchor: GuitarX0;-}-'''-(ROOT/'guitar.firmasm').write_text(assembly)-# Retain the old fixture entry as a tiny source-compatible composition root.-(ROOT/'guitar-x0.firmament').write_text('// Compatibility entry; prefer guitar.firmasm.\n'+assembly)-looks={- 'SectionChainFile<"CarvedMaple.firmament">':(.65,.28,.035,0,.35),- 'SectionChainFile<"MahoganyBack.firmament">':(.15,.025,.012,0,.4),- 'SectionChainFile<"IvoryBinding.firmament">':(.72,.59,.36,0,.4),- 'SectionChainFile<"Neck.firmament">':(.15,.025,.012,0,.4),- 'Board<H:5mm>':(.72,.59,.36,0,.4),- 'Board<H:2mm>':(.055,.017,.008,0,.4),- 'Head<H:1mm>':(.008,.008,.008,0,.4),- 'Head<H:14mm>':(.15,.025,.012,0,.4),- 'Humbucker<Spec: StandardPickup>':(.025,.025,.025,.15,.3),- 'Drum<R:9mm,H:9mm>':(.38,.13,.013,.2,.3),- 'Panel<L:25mm,W:12mm,H:0.3mm,R:1mm>':(.74,.73,.62,.1,.3),-}-(ROOT/'preview-materials.json').write_text(json.dumps({k:dict(zip(['red','green','blue','metallic','roughness'],v)) for k,v in looks.items()},indent=2)+'\n')-print(f'Authored guitar with four keyed hardware patterns and two feature-built pickups in {ROOT}; inspect via Aetheris.CLI for expanded occurrence counts.')+import argparse+import hashlib+import subprocess++REPO = Path(__file__).resolve().parents[1]+ROOT = REPO / 'fixtures/Canonical/AssemblyInterfaces/GuitarX0'++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--out', type=Path, default=REPO / 'artifacts/local/guitar-x0')+ args = parser.parse_args()+ output = args.out.resolve()+ allowed = (REPO / 'artifacts/local').resolve()+ if output != allowed and allowed not in output.parents:+ parser.error('--out must be inside artifacts/local')+ output.mkdir(parents=True, exist_ok=True)+ cli = REPO / 'Aetheris.CLI/bin/Release/net10.0/aetheris.dll'+ if not cli.exists():+ subprocess.run(['dotnet', 'build', 'Aetheris.CLI', '-c', 'Release', '-m:1'], cwd=REPO, check=True)+ sources = sorted(ROOT.glob('*.firm*'))+ before = {p: hashlib.sha256(p.read_bytes()).digest() for p in sources}+ def run(*command):+ subprocess.run(['dotnet', str(cli), *map(str, command)], cwd=REPO, check=True)+ root = ROOT / 'guitar.firmasm'+ run('inspect', root, '--json', '--profile', '--repeat', '2', '--out', output / 'inspect.json')+ run('build', root, '--output', output / 'guitar.step', '--json')+ run('asm', 'export-usd', root, output / 'guitar.usda', '--evidence', output / 'display.json', '--json')+ assert all(hashlib.sha256(p.read_bytes()).digest() == before[p] for p in sources), 'Source changed during reproduction'+ print(f'Guitar reproduced from immutable authored sources: {output}')++if __name__ == '__main__':+ main()diff --git a/scripts/render-guitar-x0.py b/scripts/render-guitar-x0.pyindex 097ed27f..be688ffc 100644--- a/scripts/render-guitar-x0.py+++ b/scripts/render-guitar-x0.py@@ -9,7 +9,6 @@ import hashlibimport jsonimport mathimport sys-import reimport timefrom pathlib import Pathfrom mathutils import Vector, Matrix@@ -26,7 +25,7 @@ bpy.ops.wm.usd_import(filepath=str(source),support_scene_instancing=False,load_seconds=time.perf_counter()-startedscene=bpy.context.sceneproducts=[o for o in scene.objects if o.type=='MESH']-assert len(products) in (91,107), len(products)+assert len(products) in (91,99,107), len(products)def material(name,color,metal=0,rough=.25,coat=.35):m=bpy.data.materials.new(name);m.use_nodes=True@@ -89,9 +88,21 @@ def signature():original_signature=signature()pickup_shaded=0+pearl_shaded=0+def semantic_appearance(obj):+ while obj is not None:+ if 'aetheris_appearance' in obj:+ return obj['aetheris_appearance']+ obj = obj.parent+ raise RuntimeError('USD product has no authored appearance metadata')++looks={'PolishedSteel':chrome,'PolishedNickel':chrome,'WarmIvory':cream,+ 'BlackPolymer':black,'EbonyLacquer':ebony,'Pearl':pearl,'Amber':amber,+ 'Brass':gold,'CherryMahogany':wood,'Rosewood':rose,'GoldenMaple':wood}+for obj in products:- name=obj.parent.name if obj.parent else obj.name- if 'CarvedMaple' in name:+ look=semantic_appearance(obj)+ if look=='Sunburst':m=burstimport numpy as nppts=np.array([tuple(obj.matrix_world @ v.co) for v in obj.data.vertices])@@ -102,7 +113,7 @@ for obj in products:for start in range(0,len(pts),256):distances=np.sqrt(((pts[start:start+256,None,:2]-edge[None,:,:])**2).sum(axis=2)).min(axis=1)for i,d in enumerate(distances,start):attr.data[i].value=min(1,float(d)/.065)- elif re.search(r'(?:^|_)(?:NeckPickup|BridgePickup)(?:_\d+)?$',name.split('.')[0]):+ elif look=='PickupComposite':# Appearance only: exact feature-built pickup geometry is imported intact.# Default witness axial levels are base 0..4, coils 4..9, poles 9..10 mm.obj.data.materials.clear()@@ -113,19 +124,14 @@ for obj in products:poly.material_index=2 if level>.900001 else 1 if level>.400001 else 0pickup_shaded+=1continue- elif any(s in name for s in ['MahoganyBack','Headstock','Neck_']):m=wood- elif 'Rosewood' in name:m=rose- elif 'HeadVeneer' in name:m=ebony- elif any(s in name for s in ['IvoryBinding','BoardBinding','Cream','Nut_','TunerButton','SelectorTip','SelectorRing']):m=cream- elif 'PearlInlay' in name:m=pearl- elif 'AmberKnob' in name:m=amber- elif 'KnobCap' in name or 'KnobSkirt' in name:m=gold- elif 'Coil' in name or 'Cover' in name:m=black- else:m=chrome+ else:+ m=looks[look]+ if look=='Pearl':pearl_shaded+=1obj.data.materials.clear();obj.data.materials.append(m)assert signature()==original_signature, 'Shading must not alter imported product topology'-assert len(products)!=91 or pickup_shaded==2, f'Expected two feature-built pickup appearance assignments; found {pickup_shaded}'+assert len(products)==107 or pickup_shaded==2, f'Expected two feature-built pickup appearance assignments; found {pickup_shaded}'+assert len(products)==107 or pearl_shaded==9, f'Expected nine pearl inlay appearance assignments; found {pearl_shaded}'floor=material('Studio charcoal',(.014,.018,.024),.12,.32,0)bpy.ops.mesh.primitive_plane_add(size=200,location=(0,.3,-.004))@@ -171,15 +177,18 @@ views=[('hero',(.73,-.18,1.6),(0,.30,.04),1.23,1800,2200),('carve-detail',(.45,-.48,.62),(0,-.005,.047),.60,2200,1600),('shaded-isometric',(.9,-.5,1.05),(0,.30,.04),1.28,1800,2200),('neck-side',(.65,.48,.045),(0,.48,.045),.66,1600,2200),- ('neck-back',(.25,.49,-.7),(0,.49,.035),.70,1600,2200)]+ ('neck-back',(.25,.49,-.7),(0,.49,.035),.70,1600,2200),+ ('head-detail',(.15,.69,.34),(0,.722,.039),.21,1800,2000),+ ('head-join-side',(.5,.67,.050),(0,.67,.050),.11,1600,1800),+ ('head-back',(.12,.73,-.5),(0,.71,.035),.20,1800,2000)]if selected_view:views=[v for v in views if v[0]==selected_view]assert views, f'Unknown view: {selected_view}'renders=[]print('GUITAR_SCENE_READY',scene.cycles.device, 'samples',scene.cycles.samples,flush=True)for name,location,target,scale,w,h in sorted(views,key=lambda v:not v[0].startswith('neck-')):- stage.hide_render=name.startswith('neck-')- rear.hide_render=not name.startswith('neck-')+ stage.hide_render=name.startswith(('neck-','head-'))+ rear.hide_render=not name.startswith(('neck-','head-'))camera.location=location;aim(camera,target);d.ortho_scale=scalescene.render.resolution_x=w//2 if preview else w;scene.render.resolution_y=h//2 if preview else hif name=='shaded-isometric':@@ -201,5 +210,5 @@ bpy.ops.wm.save_as_mainfile(filepath=str(root/'guitar-studio.blend'))usdSha256=hashlib.sha256(source.read_bytes()).hexdigest(),devices=[device.name for device in prefs.devices if device.use],productMeshObjects=len(products),productTopologyHash=original_signature,- productTopologyUnchanged=signature()==original_signature,pickupAppearance='Default feature axial height bands; shading only',pickupObjectsStyled=pickup_shaded,renders=renders),indent=2)+'\n')+ productTopologyUnchanged=signature()==original_signature,pickupAppearance='Default feature axial height bands; shading only',pickupObjectsStyled=pickup_shaded,pearlObjectsStyled=pearl_shaded,renders=renders),indent=2)+'\n')print('GUITAR_RENDER_COMPLETE',json.dumps(renders))