Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add assembly motion command and support authored datum frames
Yuechen Lid9288cc6a9b0
diff --git a/Aetheris.CLI.Tests/AssemblyMotionCommandTests.cs b/Aetheris.CLI.Tests/AssemblyMotionCommandTests.csnew file mode 100644index 00000000..c5c619ce--- /dev/null+++ b/Aetheris.CLI.Tests/AssemblyMotionCommandTests.cs@@ -0,0 +1,25 @@+using System.Text.Json;++namespace Aetheris.CLI.Tests;++public sealed class AssemblyMotionCommandTests+{+ [Fact]+ public void CliSamplesAdmittedClipAndRejectsMissingMotion()+ {+ var root = new DirectoryInfo(AppContext.BaseDirectory);+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx"))) root = root.Parent;+ var fixture = Path.Combine(root!.FullName, "fixtures/Canonical/AssemblyInterfaces/articulated-motion.firmament");+ var stdout = new StringWriter(); var stderr = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["asm", "motion", fixture, "--clip", "Cycle", "--time", "1.25", "--json"], stdout, stderr));+ using var response = JsonDocument.Parse(stdout.ToString());+ Assert.True(response.RootElement.GetProperty("success").GetBoolean());+ Assert.Equal(450, response.RootElement.GetProperty("state").GetProperty("Shoulder").GetDouble());+ Assert.Equal(9, response.RootElement.GetProperty("state").GetProperty("Slide").GetDouble());+ stdout.GetStringBuilder().Clear();+ Assert.Equal(1, CliRunner.Run(["asm", "motion", fixture, "--clip", "Missing", "--time", "0", "--json"], stdout, stderr));+ using var invalid = JsonDocument.Parse(stdout.ToString());+ Assert.False(invalid.RootElement.GetProperty("success").GetBoolean());+ Assert.Equal("assembly-motion-invalid-query", invalid.RootElement.GetProperty("diagnostics")[0].GetProperty("code").GetString());+ }+}diff --git a/Aetheris.CLI/AssemblyMotionCommand.cs b/Aetheris.CLI/AssemblyMotionCommand.csnew file mode 100644index 00000000..2165805a--- /dev/null+++ b/Aetheris.CLI/AssemblyMotionCommand.cs@@ -0,0 +1,46 @@+using System.Globalization;+using System.Text.Json;+using Aetheris.Kernel.Firmament.Assembly;++namespace Aetheris.CLI;++internal static class AssemblyMotionCommand+{+ internal const string Usage = "aetheris asm motion <assembly.firmament|assembly.firmasm> --clip Name --time seconds [--endpoint] [--json]";+ internal static int Run(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0 || args[0] is "-h" or "--help")+ { (args.Length == 0 ? stderr : stdout).WriteLine(Usage); return args.Length == 0 ? 1 : 0; }+ try+ {+ string? clip = null; double? time = null; var endpoint = false; var json = false;+ for (var i = 1; i < args.Length; i++)+ {+ if (args[i] == "--clip" && i + 1 < args.Length && clip is null) clip = args[++i];+ else if (args[i] == "--time" && i + 1 < args.Length && time is null+ && double.TryParse(args[++i], NumberStyles.Float, CultureInfo.InvariantCulture, out var seconds) && double.IsFinite(seconds)) time = seconds;+ else if (args[i] == "--endpoint") endpoint = true;+ else if (args[i] == "--json") json = true;+ else throw new ArgumentException("Unknown or invalid Motion option: " + args[i]);+ }+ if (clip is null || time is null) throw new ArgumentException("Motion sampling requires --clip Name and --time finite-seconds.");+ var source = Path.GetFullPath(args[0]);+ var compiled = new AssemblyM1Pipeline().CompileFile(source);+ var pose = compiled.IsSuccess ? AssemblyMotion.Evaluate(compiled.Ir!, clip, time.Value, endpoint) : null;+ var diagnostics = compiled.Diagnostics.Concat(pose?.Diagnostics ?? []).ToArray();+ var success = compiled.IsSuccess && pose?.IsSuccess == true;+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success, source, clip, timeSeconds = time, state = pose?.State,+ transforms = pose?.Instances.Select(i => new { id = i.StableId, path = i.Path.ToString(), matrix = i.ResolvedTransform?.Matrix }),+ diagnostics }, new JsonSerializerOptions(JsonSerializerDefaults.Web) { Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter() } }));+ else+ {+ foreach (var diagnostic in diagnostics)+ (diagnostic.Severity == AssemblyDiagnosticSeverity.Error ? stderr : stdout).WriteLine($"{diagnostic.SourceSpan?.Source ?? source}{(diagnostic.SourceSpan is { } span ? $"@{span.Start}+{span.Length}" : "")}: {diagnostic.Severity} {diagnostic.Code}: {diagnostic.Message}");+ if (success) stdout.WriteLine($"Motion {clip} at {time.Value.ToString("R", CultureInfo.InvariantCulture)}s: {pose!.Instances.Count} occurrence transforms; shared geometry retained.");+ }+ return success ? 0 : 1;+ }+ catch (Exception e) when (e is IOException or UnauthorizedAccessException or ArgumentException)+ { stderr.WriteLine("assembly-motion-command-invalid: " + e.Message); return 1; }+ }+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 5b7ae4bf..ee6c0988 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -3903,6 +3903,8 @@ Model CanonicalPanel {return RunAsmExportAp242(args.Skip(1).ToArray(), stdout, stderr);if (string.Equals(args[0], "export-usd", StringComparison.Ordinal))return AssemblyUsdCommand.Run(args.Skip(1).ToArray(), stdout, stderr);+ if (string.Equals(args[0], "motion", StringComparison.Ordinal))+ return AssemblyMotionCommand.Run(args.Skip(1).ToArray(), stdout, stderr);if (string.Equals(args[0], "export-glb", StringComparison.Ordinal))return AssemblyGlbCommand.Run(args.Skip(1).ToArray(), stdout, stderr);@@ -5618,6 +5620,7 @@ Model CanonicalPanel {stdout.WriteLine($" or: {AsmImportStepUsage[7..]}");stdout.WriteLine($" or: {AsmExportAp242Usage[7..]}");stdout.WriteLine($" or: {AssemblyUsdCommand.Usage}");+ stdout.WriteLine($" or: {AssemblyMotionCommand.Usage}");stdout.WriteLine($" or: {AssemblyGlbCommand.Usage}");stdout.WriteLine($" or: {Presentation3DCommand.Usage}");stdout.WriteLine();diff --git a/Aetheris.Forge/Abstractions/FirmamentInterop/FirmamentValues.cs b/Aetheris.Forge/Abstractions/FirmamentInterop/FirmamentValues.csindex 7d501c98..f6b4377e 100644--- a/Aetheris.Forge/Abstractions/FirmamentInterop/FirmamentValues.cs+++ b/Aetheris.Forge/Abstractions/FirmamentInterop/FirmamentValues.cs@@ -25,7 +25,8 @@ public enum FirmamentValueKindLength,Angle,String,- Bool+ Bool,+ Time}public sealed record FirmamentScalarValue(diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/ArticulatedSubassemblyTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/ArticulatedSubassemblyTests.csnew file mode 100644index 00000000..e4c558cf--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/ArticulatedSubassemblyTests.cs@@ -0,0 +1,204 @@+using Aetheris.Kernel.Firmament.Assembly;+using Aetheris.Semantics;++namespace Aetheris.Kernel.Firmament.Tests.Assembly;++public sealed class ArticulatedSubassemblyTests+{+ [Fact]+ public void RepeatedArticulatedDefinitionsKeepIndependentStateAndResolveRigidAncestry()+ {+ var compiled = new AssemblyM1Pipeline().CompileFile(Fixture("articulated-subassemblies.firmament"));+ Assert.True(compiled.IsSuccess, Evidence(compiled.Diagnostics));+ var ir = compiled.Ir!;+ Assert.Equal(2, compiled.Geometry!.Artifact.Definitions.Count);+ var definition = Assert.Single(ir.AssemblyDefinitions!);+ Assert.Single(definition.LocalJoints!);+ Assert.Equal(5, ir.Joints!.Count);+ var zero = AssemblyKinematics.Evaluate(ir, new Dictionary<string, double>());+ Assert.True(zero.IsSuccess, Evidence(zero.Diagnostics));+ foreach (var instance in ir.Instances)+ AssertMatrix(instance.ResolvedTransform!.Matrix, zero.Instances.Single(i => i.StableId == instance.StableId).ResolvedTransform!.Matrix);+ var state = new Dictionary<string, double> { ["Shoulder"] = 90, ["Articulated.First.Elbow"] = 45, ["Articulated.Second.Elbow"] = -30 };+ var pose = AssemblyKinematics.Evaluate(ir, state);+ Assert.True(pose.IsSuccess, Evidence(pose.Diagnostics));+ var tip = pose.Instances.Single(i => i.Path.ToString() == "Articulated.First.Tip");+ Assert.Equal(0, tip.ResolvedTransform!.Matrix[12], 9);+ Assert.Equal(20, tip.ResolvedTransform.Matrix[13], 9);+ Assert.Equal(Math.Cos(135 * Math.PI / 180), tip.ResolvedTransform.Matrix[0], 9);+ var follower = pose.Instances.Single(i => i.Path.ToString() == "Articulated.Follower");+ AssertMatrix(tip.ResolvedTransform.Matrix, follower.ResolvedTransform!.Matrix);+ var port = ir.Instances.Single(i => i.Path.ToString() == "Articulated.First").SemanticRoot.ExposedMembers["Tool"];+ var tool = Assert.IsType<ExactDatumFrameBinding>(AssemblyWorldQuery.Resolve(ir with { Instances = pose.Instances }, port.StableIdentity));+ Assert.Equal(tip.ResolvedTransform.Matrix[0], tool.XAxisX, 9);+ Assert.Equal(tip.ResolvedTransform.Matrix[13], tool.OriginY, 9);+ var second = pose.Instances.Single(i => i.Path.ToString() == "Articulated.Second.Tip");+ Assert.Equal(120, second.ResolvedTransform!.Matrix[12], 9);+ Assert.Equal(-0.5, second.ResolvedTransform.Matrix[1], 9);+ var again = AssemblyKinematics.Evaluate(ir, state.Reverse().ToDictionary(p => p.Key, p => p.Value));+ foreach (var instance in pose.Instances)+ {+ AssertMatrix(instance.ResolvedTransform!.Matrix, again.Instances.Single(i => i.StableId == instance.StableId).ResolvedTransform!.Matrix);+ Assert.Same(ir.Instances.Single(i => i.StableId == instance.StableId).SemanticRoot, instance.SemanticRoot);+ }+ Assert.True(AssemblyIrAp242Exporter.Export(compiled).IsSuccess);+ }++ [Fact]+ public void SharedDerivedFramesComposeBeforeSeating()+ {+ var compiled = new AssemblyM1Pipeline().CompileFile(Fixture("derived-datum-frames.firmament"));+ Assert.True(compiled.IsSuccess, Evidence(compiled.Diagnostics));+ var cam = Assert.Single(compiled.Ir!.Instances, i => i.Kind == AssemblyInstanceKind.Part);+ var matrix = cam.ResolvedTransform!.Matrix;+ Assert.Equal(3 + 100 / Math.Sqrt(2), matrix[12], 9);+ Assert.Equal(4 + 100 / Math.Sqrt(2), matrix[13], 9);+ Assert.Equal(25, matrix[14], 9);+ Assert.Equal(1, matrix[0], 9);+ Assert.Equal(0, matrix[1], 9);+ }++ [Fact]+ public void PlainPlacementFollowsAMovingTargetWithoutCreatingAPhysicalJoint()+ {+ var compiled = new AssemblyM1Pipeline().CompileFile(Fixture("relative-moving-frames.firmament"));+ Assert.True(compiled.IsSuccess, Evidence(compiled.Diagnostics));+ var ir = compiled.Ir!;+ Assert.Equal(2, ir.Joints!.Count);+ Assert.Single(ir.FrameDependencies);+ var pose = AssemblyKinematics.Evaluate(ir, new Dictionary<string, double> { ["Base"] = 90, ["Elbow"] = 45 });+ Assert.True(pose.IsSuccess, Evidence(pose.Diagnostics));+ foreach (var name in new[] { "Rigid", "Tip" })+ {+ var item = pose.Instances.Single(i => i.Path.ToString() == "RelativeFrames." + name);+ Assert.Equal(0, item.ResolvedTransform!.Matrix[12], 9);+ Assert.Equal(20, item.ResolvedTransform.Matrix[13], 9);+ }+ var tip = pose.Instances.Single(i => i.Path.ToString() == "RelativeFrames.Tip");+ Assert.Equal(Math.Cos(135 * Math.PI / 180), tip.ResolvedTransform!.Matrix[0], 9);+ var usd = AssemblyUsdExporter.Export(compiled);+ Assert.DoesNotContain("PhysicsFixedJoint", usd);+ Assert.Contains("PhysicsRevoluteJoint", usd);+ }++ [Theory]+ [InlineData("B: Articulated.First.Mount", "B: Articulated.First.Tool")]+ [InlineData("from: Mount;", "from: Tool;")]+ public void MovingInternalPortsCannotSilentlyBecomeRigidInstallationMounts(string from, string to)+ {+ var source = File.ReadAllText(Fixture("articulated-subassemblies.firmament")).Replace(from, to);+ var parsed = new AssemblyM0Parser().Parse(source);+ Assert.True(parsed.IsSuccess, Evidence(parsed.Diagnostics));+ var compiled = new AssemblyM0Compiler().Compile(parsed.Source!);+ Assert.False(compiled.IsSuccess);+ Assert.Contains(compiled.Diagnostics, d => d.Code == "assembly-kinematic-moving-mount-unsupported");+ }++ [Fact]+ public void ExposedMovingParentRetainsAuthoredGapAndClocking()+ {+ var source = File.ReadAllText(Fixture("articulated-subassemblies.firmament"))+ .Replace("Interface<Fixed> Follow {", "Interface<Fixed> Follow { gap: 2mm; clocking: 30deg;");+ var compiled = new AssemblyM1Pipeline().Compile(source);+ Assert.True(compiled.IsSuccess, Evidence(compiled.Diagnostics));+ var ir = compiled.Ir!;+ var zero = AssemblyKinematics.Evaluate(ir, new Dictionary<string, double>());+ foreach (var instance in ir.Instances)+ AssertMatrix(instance.ResolvedTransform!.Matrix, zero.Instances.Single(i => i.StableId == instance.StableId).ResolvedTransform!.Matrix);+ var pose = AssemblyKinematics.Evaluate(ir, new Dictionary<string, double> { ["Shoulder"] = 90, ["Articulated.First.Elbow"] = 45 });+ Assert.True(pose.IsSuccess, Evidence(pose.Diagnostics));+ var follower = pose.Instances.Single(i => i.Path.ToString() == "Articulated.Follower");+ Assert.Equal(2, follower.ResolvedTransform!.Matrix[14], 9);+ Assert.Equal(Math.Cos(165 * Math.PI / 180), follower.ResolvedTransform.Matrix[0], 9);+ }++ [Theory]+ [InlineData("Interface Drive = Elbow;")]+ public void UnimplementedPublicInterfaceContractsDoNotDisappear(string exposure)+ {+ var source = File.ReadAllText(Fixture("articulated-subassemblies.firmament"))+ .Replace("DatumFrame Tool = Tip.Pivot.Frame;", "DatumFrame Tool = Tip.Pivot.Frame; " + exposure);+ var parsed = new AssemblyM0Parser().Parse(source);+ Assert.False(parsed.IsSuccess);+ Assert.Contains(parsed.Diagnostics, d => d.Code == "assembly-expose-kind-unsupported");+ }++ [Fact]+ public void UnresolvedPublicMateAliasRejectsRatherThanDisappearing()+ {+ var source = File.ReadAllText(Fixture("articulated-subassemblies.firmament")).Replace("Mate Bend = Elbow;", "Mate Bend = Missing;");+ var parsed = new AssemblyM0Parser().Parse(source);+ Assert.False(parsed.IsSuccess);+ Assert.Contains(parsed.Diagnostics, d => d.Code == "assembly-expose-mate-unresolved");+ }++ [Fact]+ public void PublicMateChannelCanBeReexportedThroughANestedReusableDefinition()+ {+ var source = File.ReadAllText(Fixture("articulated-subassemblies.firmament"));+ var wrapper = """+ Subassembly Sleeve {+ <Assembly Sleeve><Assembly Unit = Arm>+ Placement { from: Mount; to: World; }+ </Assembly></Assembly>+ anchor: Sleeve;+ expose { DatumFrame Mount = Unit.Mount; DatumFrame Tool = Unit.Tool; Mate Bend = Unit.Bend; }+ }+ """;+ source = source.Replace("Assembly Articulated {", wrapper + "\nAssembly Articulated {")+ .Replace("<Assembly First = Arm>", "<Assembly First = Sleeve>")+ .Replace("<Assembly Second = Arm>", "<Assembly Second = Sleeve>");+ source += "\n" + string.Join('\n', File.ReadAllLines(Fixture("articulated-motion.firmament")).Where(l => !l.StartsWith("include ", StringComparison.Ordinal)));+ var compiled = new AssemblyM1Pipeline().Compile(source);+ Assert.True(compiled.IsSuccess, Evidence(compiled.Diagnostics));+ var joint = Assert.Single(compiled.Ir!.Joints!, j => j.PublicNames.Contains("Articulated.First.Bend"));+ Assert.Equal("Articulated.First.Unit.Elbow", joint.Name);+ var pose = AssemblyMotion.Evaluate(compiled.Ir, "Cycle", 1.25);+ Assert.True(pose.IsSuccess, Evidence(pose.Diagnostics));+ Assert.Equal(225, pose.State[joint.Name], 9);+ }++ [Fact]+ public void InventoryImportsShareOneArticulatedDefinitionWithIndependentPublicChannels()+ {+ var compiled = new AssemblyM1Pipeline().CompileFile(Fixture("articulated-module-motion.firmament"));+ Assert.True(compiled.IsSuccess, Evidence(compiled.Diagnostics));+ var ir = compiled.Ir!;+ Assert.Single(ir.AssemblyDefinitions!);+ Assert.Equal(2, compiled.Geometry!.Artifact.Definitions.Count);+ var pose = AssemblyMotion.Evaluate(ir, "Cycle", .25);+ Assert.True(pose.IsSuccess, Evidence(pose.Diagnostics));+ Assert.Equal(90, pose.State["ModularMotion.First.Elbow"], 9);+ Assert.Equal(-180, pose.State["ModularMotion.Second.Elbow"], 9);+ }++ [Theory]+ [InlineData("from: Shaft", "from: Missing", "assembly-datum-source-unresolved")]+ [InlineData("from: Shaft", "from: Cam", "assembly-datum-dependency-cycle")]+ [InlineData("angle: -45deg", "angle: -45mm", "firmament-v2-field-value-invalid")]+ [InlineData("translateLocal:", "translateLocla:", "firmament-v2-canonical-field-unknown")]+ public void InvalidDerivedFramesAreRejected(string from, string to, string code)+ {+ var source = File.ReadAllText(Fixture("derived-datum-frames.firmament")).Replace(from, to);+ var parsed = new AssemblyM0Parser().Parse(source, "derived-datum-frames.firmament");+ Assert.False(parsed.IsSuccess);+ Assert.Contains(parsed.Diagnostics, d => d.Code == code);+ }++ [Fact]+ public void UnusedDerivedDatumStillRequiresAResolvedDeclaredSource()+ {+ var source = File.ReadAllText(Fixture("derived-datum-frames.firmament"))+ .Replace("Concept Struct Layout {", "Concept Struct Layout { DatumFrame Unused { from: Layout.Missing }");+ var parsed = new AssemblyM0Parser().Parse(source);+ Assert.False(parsed.IsSuccess);+ Assert.Contains(parsed.Diagnostics, d => d.Code == "assembly-datum-source-unresolved");+ }++ private static string Fixture(string name) => FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/" + name);+ private static string Evidence(IReadOnlyList<AssemblyDiagnostic> diagnostics) => string.Join("\n", diagnostics.Select(d => d.Code + ": " + d.Message));+ private static void AssertMatrix(double[] expected, double[] actual)+ {+ for (var i = 0; i < 16; i++) Assert.Equal(expected[i], actual[i], 9);+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyMotionTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyMotionTests.csnew file mode 100644index 00000000..ef0dc17c--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyMotionTests.cs@@ -0,0 +1,77 @@+using Aetheris.Kernel.Firmament.Assembly;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests.Assembly;++public sealed class AssemblyMotionTests+{+ private static string Fixture => FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/articulated-motion.firmament");++ [Fact]+ public void TypedClipSamplesUnwrappedAnglesNestedJointsAndPeriodicLiftWithoutGeometryRebuild()+ {+ var compiled = new AssemblyM1Pipeline().CompileFile(Fixture);+ Assert.True(compiled.IsSuccess, Evidence(compiled.Diagnostics));+ var ir = compiled.Ir!;+ var clip = Assert.Single(ir.Motions);+ Assert.Equal(2, clip.DurationSeconds);+ Assert.Equal(3, clip.Tracks.Count);+ Assert.All(clip.Tracks, t => Assert.Contains(ir.Joints!, j => j.MateStableId == t.MateStableId));+ // Deliberately random/non-key and reverse time queries.+ foreach (var time in new[] { 1.25, .231, 1.749, 0, 2, -0.75, 3.25, 1.25 })+ {+ var pose = AssemblyMotion.Evaluate(ir, "Cycle", time);+ Assert.True(pose.IsSuccess, Evidence(pose.Diagnostics));+ var local = (time % 2 + 2) % 2;+ var angle = local * 360;+ Assert.Equal(angle, pose.State["Shoulder"], 10);+ Assert.Equal(angle / 2, pose.State["Articulated.First.Elbow"], 10);+ var lift = Aetheris.Kernel.Core.Mechanisms.PrescribedMotion.ValveLift(angle, 360, 180, 9);+ Assert.Equal(lift, pose.State["Slide"], 10);+ Assert.Equal(lift, pose.Instances.Single(i => i.Path.ToString() == "Articulated.Slider").ResolvedTransform!.Matrix[14], 10);+ Assert.Same(ir.Instances[0].SemanticRoot, pose.Instances[0].SemanticRoot);+ }+ var end = AssemblyMotion.Evaluate(ir, "Cycle", 2, preserveEndpoint: true);+ Assert.Equal(720, end.State["Shoulder"]);+ Assert.Equal(360, end.State["Articulated.First.Elbow"]);+ Assert.False(AssemblyMotion.Evaluate(ir, "Missing", 0).IsSuccess);+ Assert.False(AssemblyMotion.Evaluate(ir, "Cycle", double.NaN).IsSuccess);+ }++ [Theory]+ [InlineData("duration: playback.duration", "duration: 2mm", "assembly-motion-duration-invalid")]+ [InlineData("target: Articulated.First.Bend.angle", "target: Articulated.First.Elbow.angle", "assembly-motion-target-invalid")]+ [InlineData("target: Articulated.Slide.translation", "target: Articulated.Follow.angle", "assembly-motion-target-invalid")]+ [InlineData("target: Articulated.Slide.translation", "target: Articulated.Shoulder.angle", "assembly-motion-multiple-writers")]+ [InlineData("input: Articulated.Shoulder.angle", "input: Articulated.Unknown.angle", "assembly-motion-input-type-mismatch")]+ [InlineData("input: Articulated.Shoulder.angle", "input: Articulated.First.Bend.angle", "assembly-motion-driver-cycle")]+ [InlineData("at: 450deg", "at: 360deg", "assembly-motion-key-order-invalid")]+ [InlineData("value: 9mm", "value: 9deg", "assembly-motion-key-type-mismatch")]+ [InlineData("interpolation: Linear", "interpolation: Magic", "assembly-motion-interpolation-invalid")]+ [InlineData("value: 720deg", "value: 719deg", "assembly-motion-loop-discontinuous")]+ [InlineData("repeat: Loop", "repeat: Loop; speeed: 12", "assembly-motion-field-invalid")]+ public void InvalidIntentIsRejectedWithSourceEvidence(string from, string to, string code)+ {+ var text = File.ReadAllText(Fixture).Replace(from, to);+ var parsed = new AssemblyM0Parser().Parse(text, Fixture);+ var result = parsed.IsSuccess ? new AssemblyM0Compiler().Compile(parsed.Source!) : new(null, parsed.Diagnostics);+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, d => d.Code == code && d.SourceSpan is not null);+ }++ [Fact]+ public void ReusableTimeCurveUsesClipTimeWithoutAnArtificialJointInput()+ {+ var source = File.ReadAllText(Fixture).Replace("Keyframes<Angle,Angle> HalfSpeed", "Keyframes<Time,Angle> HalfSpeed")+ .Replace("at: 0deg; value: 0deg", "at: 0s; value: 0deg")+ .Replace("at: 720deg; value: 360deg", "at: 2s; value: 360deg")+ .Replace("values: HalfSpeed; input: Articulated.Shoulder.angle", "values: HalfSpeed");+ var compiled = new AssemblyM1Pipeline().Compile(source, Fixture);+ Assert.True(compiled.IsSuccess, Evidence(compiled.Diagnostics));+ var pose = AssemblyMotion.Evaluate(compiled.Ir!, "Cycle", 1.25);+ Assert.True(pose.IsSuccess, Evidence(pose.Diagnostics));+ Assert.Equal(225, pose.State["Articulated.First.Elbow"], 10);+ }++ private static string Evidence(IReadOnlyList<AssemblyDiagnostic> diagnostics) => string.Join("\n", diagnostics.Select(d => d.Code + ": " + d.Message));+}diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/CoaxialDatumTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/CoaxialDatumTests.csindex 3cf6b649..95866db0 100644--- a/Aetheris.Kernel.Firmament.Tests/Assembly/CoaxialDatumTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/CoaxialDatumTests.cs@@ -27,7 +27,8 @@ public sealed class CoaxialDatumTestsAssert.Equal(30, seat.Seating.ClockingDegrees);Assert.Equal(3, Assert.Single(ir.AssemblyDefinitions!).LocalAxisSeats!.Count);Assert.All(ir.AssemblyDefinitions![0].LocalAxisSeats!, e => { Assert.True(e.Passed); Assert.Equal(0,e.DegreesOfFreedom); });- var joint = Assert.Single(ir.Joints!);+ var joint = Assert.Single(ir.Joints!, j => j.DegreesOfFreedom == 1);+ Assert.Equal(3, ir.Joints!.Count(j => j.Family == MechanicalInterfaceFamily.Fixed));Assert.Equal("VolumeRotation", joint.Name);Assert.Equal(MechanicalInterfaceFamily.Revolute, joint.Family);var zero = AssemblyKinematics.Evaluate(ir, new Dictionary<string,double>());@@ -123,7 +124,7 @@ public sealed class CoaxialDatumTests[InlineData("-> [0,0,1]","-> [1,0,0]","assembly-axis-port-invalid")][InlineData("Axis Axis = [0mm,0mm,0mm]","Axis Axis = [1mm,0mm,0mm]","assembly-axis-port-invalid")][InlineData("<Assembly VolumeKnob = ControlKnob></Assembly>","<Assembly VolumeKnob = ControlKnob> Placement { From: Origin; To: World; } </Assembly>","assembly-placement-authority-conflict")]- [InlineData("Interface<Fixed> CoaxialStack","Interface<Revolute> CoaxialStack","assembly-axis-internal-motion-unsupported")]+ [InlineData("Interface<Fixed> CoaxialStack","Interface<Revolute> CoaxialStack","assembly-axis-revolute-member-count")]public void InvalidAxisContractsFailClosed(string from,string to,string code){Assert.Contains(from, Source);diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/GuitarSurfacingWitnessTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/GuitarSurfacingWitnessTests.csindex c362bc4c..ef0beb8d 100644--- a/Aetheris.Kernel.Firmament.Tests/Assembly/GuitarSurfacingWitnessTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/GuitarSurfacingWitnessTests.cs@@ -46,7 +46,7 @@ public sealed class GuitarSurfacingWitnessTestsAssert.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.All(compiled.Ir.Joints!, joint => Assert.Equal(0, joint.DegreesOfFreedom));Assert.Equal(10, compiled.Ir.AssemblyDefinitions!.Count);Assert.Single(compiled.Ir.AssemblyDefinitions.Single(d => d.DefinitionIdentity == "GuitarNeck").LocalMates,mate => mate.Name == "VeneerSeat");diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyDatumAuthoring.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyDatumAuthoring.csindex 45730aeb..2fc07d80 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyDatumAuthoring.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyDatumAuthoring.cs@@ -2,6 +2,7 @@ using System.Globalization;using System.Text.RegularExpressions;using Aetheris.Kernel.Core.Math;using Aetheris.Semantics;+using Aetheris.Kernel.Firmament.FirmamentV2;using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;namespace Aetheris.Kernel.Firmament.Assembly;@@ -20,7 +21,9 @@ internal static class AssemblyDatumAuthoring{if (!IsTopLevel(source, header.Index)) continue;var body = AssemblyM0Parser.BalancedBody(source, header.Index + header.Length - 1, diagnostics, "Concept layout");- if (body is null || !Regex.IsMatch(body, @"\b(?:Plane|Axis)\s+\w+\s*\{")) continue;+ if (body is null) continue;+ var members = FirmamentSyntaxParser.Parse(body, sourceIdentity).Document.Statements.OfType<DeclarationSyntax>().ToArray();+ if (!members.Any(m => m.Type.Name.Text is "Plane" or "Axis" or "DatumFrame")) continue;var owner = header.Groups["name"].Value;var remaining = body;var planes = new Dictionary<string, AssemblyFrameTransformSource>(StringComparer.Ordinal);@@ -81,23 +84,43 @@ internal static class AssemblyDatumAuthoringresult.Add(new(owner + "." + name, owner + "." + name, transform));remaining = remaining.Replace(member.Value + fields + "}", "", StringComparison.Ordinal);}- foreach (Match member in Regex.Matches(body, @"\bDatumFrame\s+(?<name>\w+)\s*\{"))+ foreach (var member in members.Where(m => m.Type.Name.Text == "DatumFrame")){- var fields = AssemblyM0Parser.BalancedBody(body, member.Index + member.Length - 1, diagnostics, "layout frame")!;- if (fields is null) continue;- var planeName = Field(fields, "On", diagnostics);- var at = Vector(fields, "At", 2, true, diagnostics);- var x = Vector(fields, "X", 2, false, diagnostics);- CheckFields(fields, ["On", "At", "X"], diagnostics);- if (!planes.TryGetValue(planeName, out var plane))- { diagnostics.Add(new("assembly-datum-plane-unresolved", $"Frame '{owner}.{member.Groups["name"].Value}' references unknown plane '{planeName}'.")); continue; }- if (Math.Sqrt(x[0]*x[0] + x[1]*x[1]) < 1e-12)- diagnostics.Add(new("assembly-datum-invalid-direction", "DatumFrame X must be nonzero."));- var angle = Math.Atan2(x[1], x[0]) * 180 / Math.PI;- var name = member.Groups["name"].Value;- var frame = new AssemblyFrameTransformSource(owner + "_" + name, owner + "." + planeName, [at[0], at[1], 0], "Z", angle, SourceSpan: plane.SourceSpan);- result.Add(new(owner + "." + name, owner + "." + planeName, frame));- remaining = remaining.Replace(member.Value + fields + "}", "", StringComparison.Ordinal);+ var name = member.Name!.Text;+ var text = body.Substring(member.Span.Start, member.Span.Length);+ if (member.Body?.Statements.OfType<FieldSyntax>().Any(f => FirmamentSyntaxFields.SameField(f.Name.Text, "From")) == true)+ {+ var derived = AssemblyFrameAuthoring.Parse(member, sourceIdentity, diagnostics, header.Index + header.Length);+ if (derived is not null)+ {+ var from = derived.From;+ if (from != "World" && members.Any(m => m.Name?.Text == from)) from = owner + "." + from;+ derived = derived with { Name = owner + "_" + name, From = from,+ SourceSpan = new(sourceIdentity, header.Index + header.Length + member.Span.Start, member.Span.Length) };+ // A derived frame is a complete 3D datum, suitable for an+ // axial seat as well as another frame's from reference.+ result.Add(new(owner + "." + name, owner + "." + name, derived, IsAxis: true));+ }+ }+ else+ {+ var fields = member.Body is null ? "" : body.Substring(member.Body.ContentSpan.Start, member.Body.ContentSpan.Length);+ var planeName = Field(fields, "On", diagnostics);+ var at = Vector(fields, "At", 2, true, diagnostics);+ var x = Vector(fields, "X", 2, false, diagnostics);+ CheckFields(fields, ["On", "At", "X"], diagnostics);+ if (!planes.TryGetValue(planeName, out var plane))+ diagnostics.Add(new("assembly-datum-plane-unresolved", $"Frame '{owner}.{name}' references unknown plane '{planeName}'."));+ else+ {+ if (Math.Sqrt(x[0]*x[0] + x[1]*x[1]) < 1e-12)+ diagnostics.Add(new("assembly-datum-invalid-direction", "DatumFrame X must be nonzero."));+ var angle = Math.Atan2(x[1], x[0]) * 180 / Math.PI;+ var frame = new AssemblyFrameTransformSource(owner + "_" + name, owner + "." + planeName, [at[0], at[1], 0], "Z", angle, SourceSpan: plane.SourceSpan);+ result.Add(new(owner + "." + name, owner + "." + planeName, frame));+ }+ }+ remaining = remaining.Replace(text, "", StringComparison.Ordinal);}if (!string.IsNullOrWhiteSpace(remaining.Replace(";", "")))diagnostics.Add(new("assembly-datum-invalid-layout", $"Unsupported members in Concept Struct '{owner}'."));@@ -107,6 +130,11 @@ internal static class AssemblyDatumAuthoringdiagnostics.Add(new("assembly-datum-duplicate", "Concept layout datum identities must be unique."));foreach (var value in result){+ var from = value.Transform.From;+ var localOwner = from.Contains('.') ? from[..from.LastIndexOf('.')] : null;+ if (from != "World" && !result.Any(d => d.Identity == from)+ && (!from.Contains('.') || result.Any(d => d.Identity.StartsWith(localOwner + ".", StringComparison.Ordinal))))+ diagnostics.Add(new("assembly-datum-source-unresolved", $"Datum '{value.Identity}' references unknown declared datum '{from}'.") { SourceSpan = value.Transform.SourceSpan });var seen = new HashSet<string>(StringComparer.Ordinal);var current = value;while (current is not null)diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyFrameAuthoring.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyFrameAuthoring.csindex 2375e524..4b4aaefb 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyFrameAuthoring.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyFrameAuthoring.cs@@ -10,6 +10,50 @@ namespace Aetheris.Kernel.Firmament.Assembly;/// <summary>Bounded frame authoring; lowers layout to the existing frame constraint solver.</summary>internal static class AssemblyFrameAuthoring{+ internal static AssemblyFrameTransformSource? Parse(DeclarationSyntax declaration, string sourceIdentity,+ List<AssemblyDiagnostic> diagnostics, int sourceOffset = 0)+ {+ var errors = new List<string>();+ var fields = new FirmamentSyntaxFields(declaration, errors);+ var from = fields.Reference("From");+ if (from is null) fields.Invalid("From");+ var translation = Vector("TranslateLocal", "mm", [0, 0, 0]);+ var normal = Vector("Normal", "", null);+ var up = Vector("Up", "", null);+ var axis = "Z";+ var angle = 0d;+ if (fields.Take("RotateLocal") is { } rotation)+ {+ if (rotation is ObjectSyntax obj)+ {+ // The anonymous rotation object has the same fields as ordinary+ // Placement/FrameTransform rotation, with no source rewriting.+ var type = new IdentifierSyntax("RotateLocal", obj.Span);+ var rotate = new FirmamentSyntaxFields(new(new(type, [], obj.Span), null, [], [], null, null, [], null, obj.Body, false, obj.Span), errors);+ axis = rotate.Reference("Axis") ?? "";+ angle = rotate.Number("Angle", "deg");+ if (axis is not ("X" or "Y" or "Z") || !double.IsFinite(angle)) rotate.Invalid("Angle");+ rotate.Complete();+ }+ else fields.Invalid("RotateLocal");+ }+ if ((normal is null) != (up is null)) fields.Invalid("Normal/Up");+ fields.Complete();+ foreach (var error in errors)+ diagnostics.Add(new(error.Split(':')[0], $"Frame '{declaration.Name?.Text}': {Aetheris.Kernel.Firmament.FirmamentV2.FirmamentInterop.FirmamentV2DiagnosticAdapter.MessageFor(error)}")+ { SourceSpan = new(sourceIdentity, sourceOffset + declaration.Span.Start, declaration.Span.Length) });+ return errors.Count == 0 ? new(declaration.Name!.Text, from!, translation!, axis, angle, normal, up,+ new(sourceIdentity, sourceOffset + declaration.Span.Start, declaration.Span.Length)) : null;++ double[]? Vector(string name, string unit, double[]? fallback)+ {+ var expression = fields.Take(name);+ if (expression is null) return fallback;+ if (FirmamentSyntaxValues.Vector(expression, unit, out var values) && values.Length == 3) return values;+ fields.Invalid(name); return fallback;+ }+ }+internal static AssemblyFrameTransformSource? Parse(string name, string body, string targetField,string sourceIdentity, List<AssemblyDiagnostic> diagnostics){@@ -63,7 +107,8 @@ internal static class AssemblyFrameAuthoring}internal static (AssemblySource Source, IReadOnlyList<AssemblyInstanceIr> Instances) Lower(- AssemblySource source, IReadOnlyList<AssemblyInstanceIr> original, List<AssemblyDiagnostic> diagnostics)+ AssemblySource source, IReadOnlyList<AssemblyInstanceIr> original, List<AssemblyDiagnostic> diagnostics,+ IReadOnlyList<AssemblyJointIr> retainedJoints){var instances = original.ToDictionary(i => i.Path.ToString(), StringComparer.Ordinal);var named = (source.FrameTransforms ?? []).GroupBy(f => f.Name).ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal);@@ -73,13 +118,13 @@ internal static class AssemblyFrameAuthoringdiagnostics.Add(new("assembly-frame-reserved-name", $"FrameTransform '{name}' uses a reserved name."));var interfaces = source.Interfaces.ToList(); var mates = source.Mates.ToList();var root = original.Single(i => i.ParentStableId is null);- (AssemblyInstanceIr Owner, Transform3D Frame)? Resolve(string path, string context, HashSet<string> visiting)+ (AssemblyInstanceIr Owner, Transform3D Frame)? Resolve(string path, string context, HashSet<string> visiting, bool followExposed = false){var key = path.EndsWith(".Frame", StringComparison.Ordinal) ? path[..^6] : path;if (named.TryGetValue(key, out var transform)){if (!visiting.Add(key)) { diagnostics.Add(new("assembly-frame-cycle", $"FrameTransform cycle at '{key}'.")); return null; }- var resolved = Resolve(transform.From, root.Path.ToString(), visiting);+ var resolved = Resolve(transform.From, root.Path.ToString(), visiting, followExposed);visiting.Remove(key);return resolved is { } value ? (value.Owner, Compose(value.Frame, transform, diagnostics)) : null;}@@ -105,6 +150,19 @@ internal static class AssemblyFrameAuthoring{ diagnostics.Add(new("assembly-frame-unresolved", $"'{context}' cannot resolve exact published DatumFrame '{path}'.")); return null; }var owner = instances.Values.Where(i => path == i.Path.ToString() || path.StartsWith(i.Path + ".", StringComparison.Ordinal)).OrderByDescending(i => i.Path.Segments.Count).First();+ var semantic = reference.Value;+ if (!followExposed && !AssemblyKinematics.IsRigidPort(owner, semantic, original, retainedJoints))+ {+ diagnostics.Add(new("assembly-kinematic-moving-mount-unsupported", $"Placement '{context}' requires a rigid source mount; '{path}' moves internally."));+ return null;+ }+ var aliases = new HashSet<string>(StringComparer.Ordinal);+ while (followExposed && semantic.TryBinding<AssemblyExposedSemanticBinding>(out var alias) && aliases.Add(semantic.StableIdentity))+ {+ var target = AssemblyWorldQuery.ExposedTarget(instances.Values.ToArray(), owner, alias);+ owner = target.Owner; semantic = target.Value;+ if (semantic.TryBinding<ExactDatumFrameBinding>(out var exact)) frame = exact;+ }return (owner, Matrix(frame));}AssemblyPath Publish(AssemblyInstanceIr owner, string name, Transform3D frame, string origin)@@ -144,7 +202,7 @@ internal static class AssemblyFrameAuthoring}if (member.ExplicitTransform is not null || source.Mates.Any(DrivesOccurrence))diagnostics.Add(new("assembly-placement-authority-conflict", $"Occurrence '{path}' has both authored placement and another placement driver."));- var from = Resolve(layout.From, path, []); var to = Resolve(layout.Target.From, path, []);+ var from = Resolve(layout.From, path, []); var to = Resolve(layout.Target.From, path, [], followExposed: true);if (from is null || to is null) continue;if (from.Value.Owner.StableId != owner.StableId || to.Value.Owner.StableId == owner.StableId){ diagnostics.Add(new("assembly-placement-invalid-owner", $"Placement '{path}' requires a source frame on itself and a target on another occurrence.")); continue; }@@ -163,7 +221,7 @@ internal static class AssemblyFrameAuthoringelse{interfaces.Add(new("interface:" + name, name, [new("Moving", ["DatumFrameCapable"]),new("Target", ["DatumFrameCapable"])],- [new(PlacementConstraintKind.FrameCoincident,"Moving",".","Target",".")], SourceSpan: layout.Target.SourceSpan));+ [new(PlacementConstraintKind.FrameCoincident,"Moving",".","Target",".")], SourceSpan: layout.Target.SourceSpan, CompilerOwnedExpansion: true) { IsFramePlacement = true });mates.Add(new(name,name,[new("Moving",a),new("Target",b)],layout.Target.SourceSpan));}}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyKinematics.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyKinematics.csindex bd9948b4..df3768f7 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyKinematics.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyKinematics.cs@@ -2,19 +2,82 @@ using Aetheris.Kernel.Core.Math;namespace Aetheris.Kernel.Firmament.Assembly;-/// <summary>Pure occurrence pose evaluation. State keys are Interface names; values are+/// <summary>Pure occurrence pose evaluation. State keys are realized Mate names (qualified by occurrence in reusable definitions); values are/// degrees for Revolute and millimetres for Prismatic. Geometry definitions are reused.</summary>public static class AssemblyKinematics{- public static AssemblyPoseResult Evaluate(AssemblyIr assembly, IReadOnlyDictionary<string, double> state)+ internal static bool IsRigidPort(AssemblyInstanceIr occurrence, Aetheris.Semantics.SemanticValue value,+ IReadOnlyList<AssemblyInstanceIr> instances, IReadOnlyList<AssemblyJointIr> joints)+ {+ var owner = occurrence;+ var seen = new HashSet<string>(StringComparer.Ordinal);+ while (value.TryBinding<AssemblyExposedSemanticBinding>(out var alias))+ {+ if (!seen.Add(value.StableIdentity)) return false;+ var target = AssemblyWorldQuery.ExposedTarget(instances, owner, alias);+ owner = target.Owner; value = target.Value;+ }+ var drivers = joints.DistinctBy(j => j.ChildOccurrenceId).ToDictionary(j => j.ChildOccurrenceId, StringComparer.Ordinal);+ seen.Clear();+ while (owner.StableId != occurrence.StableId)+ {+ if (!seen.Add(owner.StableId)) return false;+ string? parent;+ if (drivers.TryGetValue(owner.StableId, out var joint))+ {+ if (joint.DegreesOfFreedom > 0) return false;+ parent = joint.ParentOccurrenceId;+ }+ else parent = owner.ParentStableId;+ if (parent is null || instances.FirstOrDefault(i => i.StableId == parent) is not { } next) return false;+ owner = next;+ }+ return true;+ }++ internal static IReadOnlyList<AssemblyDiagnostic> ValidateGraph(IReadOnlyList<AssemblyInstanceIr> instances, IReadOnlyList<AssemblyJointIr> joints){- var joints = assembly.Joints ?? [];var diagnostics = new List<AssemblyDiagnostic>();+ foreach (var group in joints.GroupBy(j => j.ChildOccurrenceId).Where(g => g.Count() > 1))+ diagnostics.Add(new("assembly-kinematic-duplicate-child", $"Occurrence '{group.Key}' has multiple pose drivers: {string.Join(", ", group.Select(j => j.Name))}."));+ foreach (var group in joints.GroupBy(j => j.Name).Where(g => g.Count() > 1))+ diagnostics.Add(new("assembly-kinematic-duplicate-name", $"Realized Mate name '{group.Key}' is ambiguous."));+ var drivers = joints.DistinctBy(j => j.ChildOccurrenceId).ToDictionary(j => j.ChildOccurrenceId, StringComparer.Ordinal);+ var dependencies = instances.ToDictionary(i => i.StableId,+ i => drivers.TryGetValue(i.StableId, out var joint) ? joint.ParentOccurrenceId : i.ParentStableId, StringComparer.Ordinal);+ var complete = new HashSet<string>(StringComparer.Ordinal);+ foreach (var id in dependencies.Keys)+ {+ var active = new HashSet<string>(StringComparer.Ordinal);+ string? current = id;+ while (current is not null && !complete.Contains(current))+ {+ if (!active.Add(current))+ {+ diagnostics.Add(new("assembly-kinematic-loop-unsupported", $"Kinematic dependency cycle at occurrence '{current}'."));+ break;+ }+ if (!dependencies.TryGetValue(current, out var next))+ {+ diagnostics.Add(new("assembly-kinematic-unresolved-parent", $"Kinematic dependency '{current}' is outside the assembly."));+ break;+ }+ current = next;+ }+ complete.UnionWith(active);+ }+ return diagnostics;+ }++ public static AssemblyPoseResult Evaluate(AssemblyIr assembly, IReadOnlyDictionary<string, double> state)+ {+ var joints = (assembly.Joints ?? []).Concat(assembly.FrameDependencies).ToArray();+ var diagnostics = ValidateGraph(assembly.Instances, joints).ToList();var movable = joints.Where(joint => joint.DegreesOfFreedom == 1)- .ToDictionary(joint => joint.Name, StringComparer.Ordinal);+ .DistinctBy(joint => joint.Name).ToDictionary(joint => joint.Name, StringComparer.Ordinal);foreach (var (name, value) in state)if (!movable.ContainsKey(name) || !double.IsFinite(value))- diagnostics.Add(new("assembly-kinematic-invalid-state", $"State '{name}' must name a movable Interface and have a finite value."));+ diagnostics.Add(new("assembly-kinematic-invalid-state", $"State '{name}' must name a movable realized Mate and have a finite value."));if (diagnostics.Count > 0) return new([], diagnostics, new System.Collections.ObjectModel.ReadOnlyDictionary<string, double>(state.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal)));var snapshot = new System.Collections.ObjectModel.ReadOnlyDictionary<string, double>(@@ -22,44 +85,50 @@ public static class AssemblyKinematicsvar baseline = assembly.Instances.Where(instance => instance.ResolvedTransform is not null).ToDictionary(instance => instance.StableId, instance => instance.ResolvedTransform!, StringComparer.Ordinal);- var world = new Dictionary<string, AssemblyTransform>(baseline, StringComparer.Ordinal);- var driven = joints.Select(joint => joint.ChildOccurrenceId).ToHashSet(StringComparer.Ordinal);- var pending = joints.ToList();- var resolved = new HashSet<string>(StringComparer.Ordinal);- while (pending.Count > 0)+ var world = new Dictionary<string, AssemblyTransform>(StringComparer.Ordinal);+ var instances = assembly.Instances.ToDictionary(i => i.StableId, StringComparer.Ordinal);+ var drivers = joints.ToDictionary(j => j.ChildOccurrenceId, StringComparer.Ordinal);+ var visiting = new HashSet<string>(StringComparer.Ordinal);+ var failed = new HashSet<string>(StringComparer.Ordinal);+ bool Resolve(string id){- var progress = false;- foreach (var joint in pending.ToArray())+ if (world.ContainsKey(id)) return true;+ if (failed.Contains(id)) return false;+ if (!visiting.Add(id)){- if (driven.Contains(joint.ParentOccurrenceId) && !resolved.Contains(joint.ParentOccurrenceId)) continue;- if (!world.TryGetValue(joint.ParentOccurrenceId, out var parentWorld))+ diagnostics.Add(new("assembly-kinematic-loop-unsupported", $"Kinematic dependency cycle at occurrence '{id}'."));+ failed.Add(id); return false;+ }+ try+ {+ if (!instances.TryGetValue(id, out var instance) || !baseline.TryGetValue(id, out var zero))+ {+ diagnostics.Add(new("assembly-kinematic-unresolved-parent", $"Occurrence '{id}' has no compiled zero pose."));+ failed.Add(id); return false;+ }+ if (drivers.TryGetValue(id, out var joint)){- diagnostics.Add(new("assembly-kinematic-unresolved-parent", $"Interface '{joint.Name}' parent occurrence has no compiled zero pose."));- pending.Remove(joint); progress = true; continue;+ if (!Resolve(joint.ParentOccurrenceId)) { failed.Add(id); return false; }+ var child = Transform3D.FromRowMajor(joint.ChildLocalFrame.Matrix).Inverse()+ * Motion(joint.Family, snapshot.GetValueOrDefault(joint.Name, joint.DefaultState))+ * Transform3D.FromRowMajor(joint.ParentLocalFrame.Matrix)+ * Transform3D.FromRowMajor(world[joint.ParentOccurrenceId].Matrix);+ world[id] = new(child.ToRowMajor());}- var value = snapshot.GetValueOrDefault(joint.Name, joint.DefaultState);- var motion = Motion(joint.Family, value);- var child = Transform3D.FromRowMajor(joint.ChildLocalFrame.Matrix).Inverse()- * motion * Transform3D.FromRowMajor(joint.ParentLocalFrame.Matrix)- * Transform3D.FromRowMajor(parentWorld.Matrix);- world[joint.ChildOccurrenceId] = new(child.ToRowMajor());- resolved.Add(joint.ChildOccurrenceId);- pending.Remove(joint); progress = true;+ else if (instance.ParentStableId is { } parent)+ {+ if (!Resolve(parent)) { failed.Add(id); return false; }+ var relative = Transform3D.FromRowMajor(zero.Matrix) * Transform3D.FromRowMajor(baseline[parent].Matrix).Inverse();+ world[id] = new((relative * Transform3D.FromRowMajor(world[parent].Matrix)).ToRowMajor());+ }+ else world[id] = zero;+ return true;}- if (progress) continue;- diagnostics.Add(new("assembly-kinematic-loop-unsupported", "Kinematic relationships contain an unresolved cycle."));- break;- }- // Descendants without a joint retain their immutable local placement.- foreach (var instance in assembly.Instances.OrderBy(instance => instance.Path.Segments.Count))- {- if (instance.ParentStableId is null || driven.Contains(instance.StableId)- || !baseline.TryGetValue(instance.StableId, out var zero)- || !baseline.TryGetValue(instance.ParentStableId, out var zeroParent)- || !world.TryGetValue(instance.ParentStableId, out var currentParent)) continue;- var relative = Transform3D.FromRowMajor(zero.Matrix) * Transform3D.FromRowMajor(zeroParent.Matrix).Inverse();- world[instance.StableId] = new((relative * Transform3D.FromRowMajor(currentParent.Matrix)).ToRowMajor());+ finally { visiting.Remove(id); }}+ // Resolve rigid ancestry and joints together. A joint on a rigid grandchild+ // of a moving parent must read that parent's current pose, never its rest pose.+ foreach (var instance in assembly.Instances) Resolve(instance.StableId);return new(assembly.Instances.Select(instance => instance with{ResolvedTransform = world.GetValueOrDefault(instance.StableId)diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.csindex 460772f8..df7bf3d5 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs@@ -27,7 +27,10 @@ public sealed class AssemblyM0Compilervar diagnostics = new List<AssemblyDiagnostic>();var bindWatch = Stopwatch.StartNew();var instances = BindInstances(source, diagnostics);- (source, instances) = AssemblyFrameAuthoring.Lower(source, instances, diagnostics);+ var retainedJoints = InstantiateRelations(source.Root, instances).ToArray();+ var retainedFrames = InstantiateRelations(source.Root, instances, frameDependencies: true).ToArray();+ var retainedRelations = retainedJoints.Concat(retainedFrames).ToArray();+ (source, instances) = AssemblyFrameAuthoring.Lower(source, instances, diagnostics, retainedRelations);bindWatch.Stop();var byPath = instances.ToDictionary(x => x.Path.ToString(), StringComparer.Ordinal);var interfaces = source.Interfaces.ToDictionary(x => x.Name, StringComparer.Ordinal);@@ -47,7 +50,12 @@ public sealed class AssemblyM0CompilerResolvedTransform = placements.First(x => x.InstanceStableId == instance.StableId).Transform}).ToArray();mates = ValidateGearInterfaces(mates, interfaces, instances, diagnostics);- var joints = BindJoints(source.Anchor, mates, interfaces, instances, constraints, diagnostics);+ var joints = BindJoints(source.Anchor, mates, interfaces, instances, constraints, diagnostics, retainedRelations)+ .Concat(retainedJoints).ToArray();+ var channels = BindPublicJointChannels(source.ExposedMates, joints, source.Root.Name, diagnostics);+ joints = joints.Select(j => j with { PublicNames = j.PublicNames.Concat(channels.Where(c => c.Value == j.MateStableId).Select(c => c.Key)).Distinct(StringComparer.Ordinal).ToArray() }).ToArray();+ var frameDependencies = BindFrameDependencies(mates, interfaces, instances, constraints).Concat(retainedFrames).ToArray();+ diagnostics.AddRange(AssemblyKinematics.ValidateGraph(instances, joints.Concat(frameDependencies).ToArray()));placementWatch.Stop();var graphWatch = Stopwatch.StartNew();@@ -81,8 +89,18 @@ public sealed class AssemblyM0CompilerAssemblyPmiAuthoring.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, ConceptPoints: source.ConceptPoints, Annotations: source.Annotations) { InventoryBindings = source.ModuleGraph?.InventoryBindings.ToArray() ?? [] };+ constraints, placements, relations, stackups, fits, diagnostics, assemblyDefinitions, panelMateEvidence, datums, datumSolutions, source.SourceDependencies, joints, source.Patterns, ConceptPoints: source.ConceptPoints, Annotations: source.Annotations) { InventoryBindings = source.ModuleGraph?.InventoryBindings.ToArray() ?? [], FrameDependencies = frameDependencies };ir = ir with { AxisSeats = AssemblyDatumAuthoring.ValidateAxisSeats(source, ir, diagnostics) };+ var motionStart = diagnostics.Count;+ var motions = AssemblyMotionAuthoring.Bind(source, ir, diagnostics);+ if (source.MapMotionDiagnostic is { } map)+ {+ for (var i = motionStart; i < diagnostics.Count; i++) diagnostics[i] = map(diagnostics[i]);+ SemanticSourceSpan? MapSpan(SemanticSourceSpan? span) => span is null ? null : map(new("motion-origin", "") { SourceSpan = span }).SourceSpan;+ motions = motions.Select(m => m with { SourceSpan = MapSpan(m.SourceSpan), Tracks = m.Tracks.Select(t => t with+ { SourceSpan = MapSpan(t.SourceSpan), Curve = t.Curve with { Keys = t.Curve.Keys.Select(k => k with { SourceSpan = MapSpan(k.SourceSpan) }).ToArray() } }).ToArray() }).ToArray();+ }+ ir = ir with { Motions = motions };ir = AssemblyAppearanceAuthoring.Bind(ir, source.AppearanceCatalog, diagnostics);return new(ir, diagnostics, perf);@@ -95,6 +113,93 @@ public sealed class AssemblyM0Compiler}}+ internal static IReadOnlyDictionary<string, string> BindPublicJointChannels(IReadOnlyDictionary<string, AssemblyExposedMateSource> aliases,+ IReadOnlyList<AssemblyJointIr> joints, string root, List<AssemblyDiagnostic> diagnostics)+ {+ var result = new Dictionary<string, string>(StringComparer.Ordinal);+ foreach (var (alias, origin) in aliases)+ {+ var target = origin.Target;+ var matches = joints.Where(j => j.PublicNames.Contains(target, StringComparer.Ordinal)+ || j.PublicNames.Contains(root + "." + target, StringComparer.Ordinal)).ToArray();+ if (matches.Length != 1 || matches[0].DegreesOfFreedom != 1)+ diagnostics.Add(new("assembly-expose-mate-unresolved", $"Expose Mate '{alias}' must resolve one movable local Mate or a nested public Mate channel; '{target}' is unavailable.") { SourceSpan = origin.SourceSpan, LocationNote = "Expanded Assembly Expose statement; the legacy definition adapter has no retained original statement span." });+ else if (joints.Any(j => j.MateStableId != matches[0].MateStableId && j.PublicNames.Contains(alias, StringComparer.Ordinal)))+ diagnostics.Add(new("assembly-expose-duplicate-name", $"Public Mate channel '{alias}' conflicts with another realized Mate. Choose a distinct public name.") { SourceSpan = origin.SourceSpan, LocationNote = "Expanded Assembly Expose statement; the legacy definition adapter has no retained original statement span." });+ else result[alias] = matches[0].MateStableId;+ }+ return result;+ }++ private static IEnumerable<AssemblyJointIr> InstantiateRelations(AssemblyMemberSource root, IReadOnlyList<AssemblyInstanceIr> instances, bool frameDependencies = false)+ {+ return Walk(root, new([root.Name]));++ IEnumerable<AssemblyJointIr> Walk(AssemblyMemberSource member, AssemblyPath path)+ {+ if (member.SolvedAssemblyDefinition is { } definition)+ {+ var localRoot = definition.LocalInstances.Single(i => i.ParentStableId is null);+ var byId = definition.LocalInstances.ToDictionary(i => i.StableId, StringComparer.Ordinal);+ AssemblyInstanceIr Occurrence(string id)+ {+ var local = byId[id];+ var target = new AssemblyPath([.. path.Segments, .. local.Path.Segments.Skip(localRoot.Path.Segments.Count)]);+ return instances.Single(i => i.Path.ToString() == target.ToString());+ }+ string Semantic(string id, string owner)+ {+ var local = byId[owner];+ var occurrence = Occurrence(owner);+ var suffix = id[local.SemanticRoot.StableIdentity.Length..];+ return occurrence.SemanticRoot.StableIdentity + suffix;+ }+ foreach (var joint in (frameDependencies ? definition.LocalFrameDependencies : definition.LocalJoints) ?? [])+ yield return joint with+ {+ MateStableId = joint.MateStableId + ":occurrence:" + path,+ Name = path + "." + (joint.Name.StartsWith(localRoot.Path + ".", StringComparison.Ordinal)+ ? joint.Name[(localRoot.Path.ToString().Length + 1)..] : joint.Name),+ ParentOccurrenceId = Occurrence(joint.ParentOccurrenceId).StableId,+ ChildOccurrenceId = Occurrence(joint.ChildOccurrenceId).StableId,+ ParentFrameSemanticId = Semantic(joint.ParentFrameSemanticId, joint.ParentOccurrenceId),+ ChildFrameSemanticId = Semantic(joint.ChildFrameSemanticId, joint.ChildOccurrenceId),+ PublicNames = frameDependencies ? [] : definition.PublicJointChannels.Where(c => c.Value == joint.MateStableId)+ .Select(c => path + "." + c.Key).ToArray()+ };+ // Each retained relation collection already contains nested definitions.+ yield break;+ }+ foreach (var child in member.Children)+ foreach (var joint in Walk(child, path.Append(child.Name))) yield return joint;+ }+ }++ private static IEnumerable<AssemblyJointIr> BindFrameDependencies(IReadOnlyList<MateIr> mates,+ IReadOnlyDictionary<string, InterfaceDefinition> interfaces, IReadOnlyList<AssemblyInstanceIr> instances,+ IReadOnlyList<PlacementConstraintIr> constraints)+ {+ var definitions = interfaces.Values.ToDictionary(i => i.StableId, StringComparer.Ordinal);+ var values = Flatten(instances.Select(i => i.SemanticRoot)).ToDictionary(v => v.StableIdentity, StringComparer.Ordinal);+ foreach (var mate in mates.Where(m => m.ValidationStatus == "valid"))+ {+ var definition = definitions[mate.InterfaceStableId];+ if (!definition.IsFramePlacement) continue;+ var moving = mate.Roles.SingleOrDefault(r => r.Role == "Moving");+ var target = mate.Roles.SingleOrDefault(r => r.Role == "Target");+ var constraint = constraints.SingleOrDefault(c => c.MateStableId == mate.StableId && c.Kind == PlacementConstraintKind.FrameCoincident);+ if (moving is null || target is null || constraint is null) continue;+ var child = OwnerInstance(moving.ParticipantSemanticValueId, instances);+ var parent = OwnerInstance(target.ParticipantSemanticValueId, instances);+ if (child is null || parent is null+ || !values[moving.ParticipantSemanticValueId].TryBinding<ExactDatumFrameBinding>(out var from)+ || !values[target.ParticipantSemanticValueId].TryBinding<ExactDatumFrameBinding>(out var to)) continue;+ yield return new(mate.StableId, mate.Name, MechanicalInterfaceFamily.Fixed, parent.StableId, child.StableId,+ target.ParticipantSemanticValueId, moving.ParticipantSemanticValueId,+ new(AssemblyFrameAuthoring.Matrix(to).ToRowMajor()), new(AssemblyFrameAuthoring.Matrix(from).ToRowMajor()), 0);+ }+ }+private static IReadOnlyList<MateIr> ValidateInterfaceRequirements(IReadOnlyList<MateIr> mates,IReadOnlyDictionary<string, InterfaceDefinition> interfaces, List<AssemblyDiagnostic> diagnostics){@@ -423,7 +528,7 @@ public sealed class AssemblyM0Compilerprivate static IReadOnlyList<AssemblyJointIr> BindJoints(AssemblyPath anchorPath, IReadOnlyList<MateIr> mates,IReadOnlyDictionary<string, InterfaceDefinition> interfaces, IReadOnlyList<AssemblyInstanceIr> instances,- IReadOnlyList<PlacementConstraintIr> constraints, List<AssemblyDiagnostic> diagnostics)+ IReadOnlyList<PlacementConstraintIr> constraints, List<AssemblyDiagnostic> diagnostics, IReadOnlyList<AssemblyJointIr> retainedJoints){var values = Flatten(instances.Select(instance => instance.SemanticRoot)).ToDictionary(value => value.StableIdentity, StringComparer.Ordinal);@@ -467,30 +572,29 @@ public sealed class AssemblyM0Compiler(aFrame, bFrame) = (bFrame, aFrame);(parentSemanticId, childSemanticId) = (childSemanticId, parentSemanticId);}+ if (!AssemblyKinematics.IsRigidPort(child, values[childSemanticId], instances, retainedJoints))+ {+ diagnostics.Add(new("assembly-kinematic-moving-mount-unsupported", $"Mate '{mate.Name}' must seat the complete occurrence through a rigid public mount; its B port moves internally."));+ continue;+ }+ var parentIsSeat = frame.SeatFrameSemanticId == parentSemanticId;+ // An A port exported by an articulated definition follows its actual+ // local occurrence. B still seats the complete child occurrence.+ var parentValue = values[parentSemanticId];+ var aliases = new HashSet<string>(StringComparer.Ordinal);+ while (parentValue.TryBinding<AssemblyExposedSemanticBinding>(out var alias) && aliases.Add(parentValue.StableIdentity))+ {+ var target = AssemblyWorldQuery.ExposedTarget(instances, parent, alias);+ parent = target.Owner;+ parentValue = target.Value;+ parentSemanticId = parentValue.StableIdentity;+ if (parentValue.TryBinding<ExactDatumFrameBinding>(out var exact)) aFrame = exact;+ }result.Add(new(mate.StableId, mate.Name, family, parent.StableId, child.StableId,parentSemanticId, childSemanticId,- new((frame.Seating is null ? FrameMatrix(aFrame,frame.Orientation) : frame.SeatFrameSemanticId==parentSemanticId ? SeatMatrix(aFrame,frame.Seating) : FrameMatrix(aFrame,DatumOrientationRelation.SameDirection)).ToRowMajor()),+ new((frame.Seating is null ? FrameMatrix(aFrame,frame.Orientation) : parentIsSeat ? SeatMatrix(aFrame,frame.Seating) : FrameMatrix(aFrame,DatumOrientationRelation.SameDirection)).ToRowMajor()),new((frame.Seating is not null && frame.SeatFrameSemanticId==childSemanticId ? SeatMatrix(bFrame,frame.Seating) : FrameMatrix(bFrame, DatumOrientationRelation.SameDirection)).ToRowMajor()),- family == MechanicalInterfaceFamily.Fixed ? 0 : 1));- }- foreach (var group in result.Where(joint => joint.DegreesOfFreedom == 1)- .GroupBy(joint => joint.ChildOccurrenceId).Where(group => group.Count() > 1))- diagnostics.Add(new("assembly-kinematic-duplicate-child", $"Occurrence '{group.Key}' is driven by multiple kinematic Interfaces: {string.Join(", ", group.Select(joint => joint.Name))}."));- var parentByChild = result.Where(joint => joint.DegreesOfFreedom == 1)- .GroupBy(joint => joint.ChildOccurrenceId).ToDictionary(group => group.Key, group => group.First().ParentOccurrenceId);- foreach (var child in parentByChild.Keys)- {- var seen = new HashSet<string>(StringComparer.Ordinal);- var current = child;- while (parentByChild.TryGetValue(current, out var parent))- {- if (!seen.Add(current))- {- diagnostics.Add(new("assembly-kinematic-loop-unsupported", $"Kinematic loop through occurrence '{current}' requires loop closure, which X0 does not support."));- break;- }- current = parent;- }+ family == MechanicalInterfaceFamily.Fixed ? 0 : 1) { PublicNames = [mate.Name] });}return result;}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.csindex b06a54d9..3e6c86b4 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.cs@@ -1,5 +1,6 @@using Aetheris.Semantics;using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;namespace Aetheris.Kernel.Firmament.Assembly;@@ -49,7 +50,10 @@ public sealed record InterfaceDefinition(IReadOnlyList<InterfacePredicateRequirementDefinition>? PredicateRequirements = null,GearInterfaceOptions? GearOptions = null,FixedSeatingOptions? Seating = null,- AssemblyDatumContract? DatumContract = null);+ AssemblyDatumContract? DatumContract = null)+{+ internal bool IsFramePlacement { get; init; }+}public sealed record AssemblyDatumContract(string Datum, IReadOnlyList<string> Members);public sealed record AssemblyDatumSeat(string Interface, string Datum, string Port, double[] Origin, double[] Normal, bool Support);@@ -100,8 +104,11 @@ public sealed record AssemblyDefinitionSource(IReadOnlyList<AssemblyFrameTransformSource>? FrameTransforms = null){internal IReadOnlyList<InterfaceDefinition>? LocalInterfaces { get; init; }+ internal IReadOnlyDictionary<string, AssemblyExposedMateSource> ExposedMates { get; init; } = new Dictionary<string, AssemblyExposedMateSource>();}+internal sealed record AssemblyExposedMateSource(string Target, SemanticSourceSpan SourceSpan);+public sealed record AssemblyExposedRelationSource(string Name, string PublicFrom, string PublicTo, AssemblyPath InternalFrom, AssemblyPath InternalTo);@@ -124,6 +131,9 @@ public sealed record AssemblySource(AssemblyAppearanceCatalog? AppearanceCatalog = null,AssemblyAnnotations? Annotations = null){+ internal IReadOnlyList<DeclarationSyntax> MotionSyntax { get; init; } = [];+ internal IReadOnlyDictionary<string, AssemblyExposedMateSource> ExposedMates { get; init; } = new Dictionary<string, AssemblyExposedMateSource>();+ internal Func<AssemblyDiagnostic, AssemblyDiagnostic>? MapMotionDiagnostic { get; init; }internal Aetheris.Kernel.Firmament.Modules.FirmamentModuleGraph? ModuleGraph { get; init; }public bool HasModuleBindings => ModuleGraph?.HasModuleBindings == true;}@@ -203,7 +213,15 @@ public sealed record DatumMateSolutionIr(string MateStableId, string FirstDatumS/// Z is the motion axis and X fixes the angular zero. State is degrees or millimetres.</summary>public sealed record AssemblyJointIr(string MateStableId, string Name, MechanicalInterfaceFamily Family,string ParentOccurrenceId, string ChildOccurrenceId, string ParentFrameSemanticId, string ChildFrameSemanticId,- AssemblyTransform ParentLocalFrame, AssemblyTransform ChildLocalFrame, int DegreesOfFreedom, double DefaultState = 0);+ AssemblyTransform ParentLocalFrame, AssemblyTransform ChildLocalFrame, int DegreesOfFreedom, double DefaultState = 0)+{+ public IReadOnlyList<string> PublicNames { get; init; } = [];+}++/// <summary>An exposed semantic keeps its owning occurrence, rather than freezing+/// a moving child's port at the reusable definition's zero pose.</summary>+public sealed record AssemblyExposedSemanticBinding(IReadOnlyList<string> RelativeOccurrencePath, string SemanticPath,+ string SourceSemanticId) : SemanticBinding("AssemblyExposedSemantic", SourceSemanticId);public sealed record AssemblyDefinitionIr(string StableId, string DefinitionIdentity, string TemplateName, string SpecializationIdentity,@@ -217,7 +235,12 @@ public sealed record AssemblyDefinitionIr(IReadOnlyList<AssemblyDatumIr>? LocalDatums = null,IReadOnlyList<DatumMateSolutionIr>? LocalDatumMateSolutions = null,IReadOnlyList<InterfaceFitResultIr>? LocalFitResults = null,- IReadOnlyList<AssemblyAxisSeatEvidence>? LocalAxisSeats = null);+ IReadOnlyList<AssemblyAxisSeatEvidence>? LocalAxisSeats = null,+ IReadOnlyList<AssemblyJointIr>? LocalJoints = null,+ IReadOnlyList<AssemblyJointIr>? LocalFrameDependencies = null)+{+ public IReadOnlyDictionary<string, string> PublicJointChannels { get; init; } = new Dictionary<string, string>();+}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);@@ -246,6 +269,10 @@ public sealed record AssemblyIr(IReadOnlyList<AssemblyRouteBindingEvidence>? RouteBindings = null,AssemblyAnnotations? Annotations = null){+ public IReadOnlyList<AssemblyMotionIr> Motions { get; init; } = [];+ // The same exact frame-relation data drives pose evaluation, but authored+ // Placement is not exported or counted as a physical mechanical joint.+ public IReadOnlyList<AssemblyJointIr> FrameDependencies { get; init; } = [];public IReadOnlyList<Aetheris.Kernel.Firmament.Modules.FirmamentInventoryBinding> InventoryBindings { get; init; } = [];}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.csindex 9f4598b3..cfbee4d6 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs@@ -111,6 +111,18 @@ public sealed class AssemblyM0Parserif (expandedPatterns is null || patternDiagnostics.Count>0) return Done(null);source = expandedPatterns.Source;var concreteSyntax = FirmamentSyntaxParser.Parse(source).Document;+ var motionSyntax = AssemblyMotionAuthoring.Extract(concreteSyntax, ref source, sourceIdentity, diagnostics);+ var motionOrigins = new FirmamentSyntaxOrigins(syntax.Document, concreteSyntax);+ AssemblyDiagnostic MapMotion(AssemblyDiagnostic diagnostic)+ {+ if (diagnostic.SourceSpan is not { } span) return diagnostic;+ var original = motionOrigins.Find(new(span.Start, span.Length));+ var mapped = diagnostic with { SourceSpan = original is null ? null : new(sourceIdentity, original.Start, original.Length),+ LocationNote = original is null ? "Expanded Motion location has no retained original-source counterpart." : diagnostic.LocationNote };+ return projection is null ? mapped : projection.Map(mapped);+ }+ if (exported is not null && motionSyntax.Count > 0)+ diagnostics.Add(new("assembly-motion-definition-unsupported", "Declare Motion on the owning root Assembly; reusable Subassemblies publish joints and do not own playback clips."));var localLayouts = concreteSyntax.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Assembly" && !d.Modifiers.Any(m => m.Name.Text == "Template")).SelectMany(d => d.Body?.Statements.OfType<DeclarationSyntax>() ?? [])@@ -182,9 +194,10 @@ public sealed class AssemblyM0Parservar tree = ParseTree(body, sourceIdentity, diagnostics, assemblyDefinitions, interfaces, specializationCache, gearAuthorities, Ports, graph, source);treePhase.Dispose();if (tree is null) return Done(null);+ var exportedSemantics = ParseAssemblyExposes(body, tree, sourceIdentity, diagnostics, out var exposedMates, assemblyHeader.Index + assemblyHeader.Length);if (exported is not null){- tree = tree with { ExposedSemantics = [.. tree.ExposedSemantics, .. ParseAssemblyExposes(body, tree, sourceIdentity, diagnostics)] };+ tree = tree with { ExposedSemantics = [.. tree.ExposedSemantics, .. exportedSemantics] };tree = graph!.QualifyParts(module!, tree);}var mates = ParseMates(body, sourceIdentity, diagnostics);@@ -197,7 +210,7 @@ public sealed class AssemblyM0Parsertree = AssemblyDatumAuthoring.Bind(body, tree, layout, interfaces, diagnostics, out var datumFrames, Ports);datumbindPhase.Dispose();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, ConceptPoints: expandedPatterns.Document?.ConceptPoints, AppearanceCatalog: appearanceCatalog, Annotations: annotations) { ModuleGraph = graph };+ 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) { ModuleGraph = graph, MotionSyntax = motionSyntax, MapMotionDiagnostic = MapMotion, ExposedMates = exposedMates };return Done(result);ParseResult Done(AssemblySource? value) { watch.Stop(); return new(value,@@ -356,9 +369,7 @@ public sealed class AssemblyM0Parservar root = ParseTree(body, sourceIdentity, diagnostics, result, interfaces, new Dictionary<string, AssemblyMemberSource>(StringComparer.Ordinal), gearAuthorities, publishedPorts, graph, source);if (root is null) continue;root = AssemblyDatumAuthoring.Bind(body, root, layout ?? [], interfaces, diagnostics, out var datumFrames, publishedPorts);- if (root.Children.Any(c => c.FramePlacement?.JointFamily == MechanicalInterfaceFamily.Revolute))- diagnostics.Add(new("assembly-axis-internal-motion-unsupported", "Reusable definitions have rigid solved children. Declare a Revolute mate on the complete occurrence in its owning root assembly."));- var exposed = ParseAssemblyExposes(body, root, sourceIdentity, diagnostics);+ var exposed = ParseAssemblyExposes(body, root, sourceIdentity, diagnostics, out var exposedMates, template.Index + template.Length);root = root with { ExposedSemantics = [.. root.ExposedSemantics, .. exposed], IsEncapsulatedDefinition = true };var name = template.Groups["name"].Value;var claimedConcept = template.Groups["concept"].Success ? template.Groups["concept"].Value : null;@@ -385,7 +396,7 @@ public sealed class AssemblyM0Parser.. claimedConcept is null ? [] : new[] { new SemanticProvenance("assembly-concept-satisfaction", claimedConcept, name, SemanticSourceSpan.Generated(sourceIdentity)) },.. staticProvenance],anchor, localMates, ParseRelations(body, diagnostics), ParseAsserts(body, sourceIdentity, diagnostics), exposedRelations, claimedConcept,- ParseFrameTransforms(body, sourceIdentity, diagnostics).Concat(datumFrames).ToArray()));+ ParseFrameTransforms(body, sourceIdentity, diagnostics).Concat(datumFrames).ToArray()) { ExposedMates = exposedMates });}return result;}@@ -426,14 +437,19 @@ public sealed class AssemblyM0ParserAssemblyPath.Parse(match.Groups["internalFrom"].Value), AssemblyPath.Parse(match.Groups["internalTo"].Value))).ToArray();}- private static IReadOnlyList<SemanticValue> ParseAssemblyExposes(string body, AssemblyMemberSource root, string sourceIdentity, List<AssemblyDiagnostic> diagnostics)+ private static IReadOnlyList<SemanticValue> ParseAssemblyExposes(string body, AssemblyMemberSource root, string sourceIdentity, List<AssemblyDiagnostic> diagnostics,+ out IReadOnlyDictionary<string, AssemblyExposedMateSource> exposedMates, int bodyOffset){+ var channels = new Dictionary<string, AssemblyExposedMateSource>(StringComparer.Ordinal);+ exposedMates = channels;var header = Regex.Match(body, @"\bExpose\s*\{", RegexOptions.CultureInvariant);if (!header.Success) return [];var block = BalancedBody(body, header.Index + header.Length - 1, diagnostics, "Assembly Expose") ?? string.Empty;var result = new List<SemanticValue>();+ var consumed = new List<FirmamentV2SourceSpan>();foreach (Match expose in Regex.Matches(block, @"\b(?<type>Semantic|Axis|Plane|Point|Dimension|DatumFrame|Gear)\s+(?<name>[A-Za-z_]\w*)\s*=\s*(?<path>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*;", RegexOptions.CultureInvariant)){+ consumed.Add(new(expose.Index, expose.Length));var alias = expose.Groups["name"].Value;if (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('.');@@ -463,6 +479,22 @@ public sealed class AssemblyM0Parservalue.ExposedMembers.Values, [.. value.Provenance, new("assembly-expose", alias, expose.Groups["path"].Value, SemanticSourceSpan.Generated(sourceIdentity))],value.AuthoredSourceSpan, value.GeneratedSourceSpan, alias));}+ foreach (var statement in FirmamentSyntaxParser.Parse(block).Document.Statements)+ {+ if (statement is DeclarationSyntax { Type.Name.Text: "Relation" }) continue; // Owned by ParseExposedRelations.+ if (statement is DeclarationSyntax { Type.Name.Text: "Mate", Name: { } alias, Body: null } channel+ && channel.Type.Arguments.Count == 0 && AssemblyInterfaceSyntax.HasContractHeader(channel with { Initializer = null })+ && FirmamentSyntaxValues.Reference(channel.Initializer) is { } path)+ {+ if (result.Concat(root.ExposedSemantics).Any(v => v.ExposedName == alias.Text) || !channels.TryAdd(alias.Text, new(path, new(sourceIdentity + "#expanded-assembly-scope", bodyOffset + header.Index + header.Length + channel.Span.Start, channel.Span.Length))))+ diagnostics.Add(new("assembly-expose-duplicate-name", $"Assembly Expose repeats public name '{alias.Text}'."));+ continue;+ }+ if (consumed.Any(span => span.Start <= statement.Span.Start && span.Start + span.Length >= statement.Span.Start + statement.Span.Length)) continue;+ var kind = (statement as DeclarationSyntax)?.Type.Name.Text ?? "statement";+ diagnostics.Add(new("assembly-expose-kind-unsupported", $"Assembly Expose cannot publish '{kind}' here. Publish a geometric semantic, dimensional Relation or realized Mate alias; public Interface contracts with external roles are not yet admitted.")+ { SourceSpan = SemanticSourceSpan.Generated(sourceIdentity), LocationNote = "Enclosing reusable definition; this legacy exposure owner does not retain an original source offset." });+ }return result;}@@ -522,17 +554,21 @@ public sealed class AssemblyM0Parservar parentWorld = Aetheris.Kernel.Core.Math.Transform3D.FromRowMajor(parent.ResolvedTransform!.Matrix);relative = new((world * parentWorld.Inverse()).ToRowMajor());}- return item with { Children = item.Children.Select(child => ApplyLocal(child, path.Append(child.Name))).ToArray(), ExplicitTransform = relative, FramePlacement = null };+ return item with { Children = item.Children.Select(child => ApplyLocal(child, path.Append(child.Name))).ToArray(),+ ExposedSemantics = localInstance.SemanticRoot.ExposedMembers.Values.ToArray(),+ ExplicitTransform = relative, FramePlacement = null };}specializedRoot = ApplyLocal(specializedRoot, new([specializedRoot.Name]));var publicSemantics = specializedRoot.ExposedSemantics.Select(value => BindPublicSemantic(value, local.Ir, sourceIdentity)).ToArray();var publicRelations = BuildPublicRelations(definition, specializationIdentity, publicSemantics, local.Ir, diagnostics);+ var localRootPath = local.Ir.Instances.Single(i => i.ParentStableId is null).Path.ToString();+ var publicChannels = AssemblyM0Compiler.BindPublicJointChannels(definition.ExposedMates, local.Ir.Joints ?? [], localRootPath, diagnostics);var stableId = "assembly-definition:" + Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(specializationIdentity)))[..16];var definitionIr = new AssemblyDefinitionIr(stableId, specializationIdentity, definition.Name, specializationIdentity,[.. definition.Provenance, new("assembly-template-specialization", definition.Name, specializationIdentity, SemanticSourceSpan.Generated(sourceIdentity))],local.Ir.Instances, local.Ir.Mates, local.Ir.Placements, local.Ir.DimensionalRelations, local.Ir.ToleranceStackups,publicSemantics, publicRelations, watch.Elapsed.TotalMilliseconds,- local.Ir.PlacementConstraints, local.Ir.Datums, local.Ir.DatumMateSolutions, local.Ir.FitResults, local.Ir.AxisSeats);+ local.Ir.PlacementConstraints, local.Ir.Datums, local.Ir.DatumMateSolutions, local.Ir.FitResults, local.Ir.AxisSeats, local.Ir.Joints, local.Ir.FrameDependencies) { PublicJointChannels = publicChannels };specializedRoot = specializedRoot with { ExposedSemantics = publicSemantics, IsEncapsulatedDefinition = true, SolvedAssemblyDefinition = definitionIr, DefinitionIdentity = specializationIdentity };specializationCache[specializationIdentity] = specializedRoot;return RenameOccurrence(specializedRoot, occurrenceName);@@ -545,6 +581,7 @@ public sealed class AssemblyM0Parservar internalPath = exposed.Provenance.LastOrDefault(item => item.Stage == "assembly-expose")?.Evidence;if (internalPath is null || !AssemblyM0Compiler.TryResolve(AssemblyPath.Parse(localIr.Instances.Single(i => i.ParentStableId is null).Path + "." + internalPath), localIr.Instances, out var reference)) return exposed;var bindings = exposed.Bindings.Where(binding => binding is TolerancedDimensionBinding).ToList();+ bindings.Add(Alias(reference!.Value));if (reference!.Value.TryBinding<TypedSemanticAuthorityBinding<GearAir>>(out var gear)){var owner = localIr.Instances.Where(instance => Flatten(instance.SemanticRoot).Any(value => value.StableIdentity == reference.Value.StableIdentity))@@ -563,6 +600,8 @@ public sealed class AssemblyM0Parser// are not source children. Their typed authority retains ownership;// ordinary published composites rebase only corresponding children.var transformed = member.Bindings.Where(binding => binding is not (ExactAxisBinding or ExactPlaneBinding or ExactDatumFrameBinding or ExactPointBinding)).ToList();+ transformed.RemoveAll(binding => binding is AssemblyExposedSemanticBinding);+ transformed.Add(Alias(local));try { transformed.Add(AssemblyWorldQuery.Resolve(localIr, local.StableIdentity)); } catch (InvalidOperationException) { }return new(member.StableIdentity, member.Type, member.Capabilities.Values, transformed,member.ExposedMembers.Values.Select(child => local.ExposedMembers.TryGetValue(child.ExposedName!, out var value)@@ -570,6 +609,13 @@ public sealed class AssemblyM0Parsermember.Provenance, member.AuthoredSourceSpan, member.GeneratedSourceSpan, member.ExposedName);}+ AssemblyExposedSemanticBinding Alias(SemanticValue value)+ {+ var owner = localIr.Instances.Single(instance => Flatten(instance.SemanticRoot).Any(v => v.StableIdentity == value.StableIdentity));+ return new(owner.Path.Segments.Skip(1).ToArray(), value.StableIdentity == owner.SemanticRoot.StableIdentity ? ""+ : value.StableIdentity[(owner.SemanticRoot.StableIdentity.Length + 1)..], value.StableIdentity);+ }+static IEnumerable<SemanticValue> Flatten(SemanticValue value){yield return value;@@ -659,7 +705,7 @@ public sealed class AssemblyM0Parservar definition = new AssemblyDefinitionSource(specializedIdentity, "__Unit", "__Unit", unit.Root,imported.Identity, [new("inventory-module", imported.Path, imported.Definition, imported.Origin)],unit.Anchor, unit.Mates, unit.DimensionalRelations, unit.StackupAsserts, FrameTransforms: unit.FrameTransforms)- { LocalInterfaces = unit.Interfaces };+ { LocalInterfaces = unit.Interfaces, ExposedMates = unit.ExposedMates };instantiated = InstantiateAssemblyDefinition(node.Name, specializedIdentity, [definition], unit.Interfaces,specializationCache ?? new Dictionary<string, AssemblyMemberSource>(StringComparer.Ordinal), imported.Path, diagnostics);}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.csindex bb4fa0fc..8cdc9860 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs@@ -641,11 +641,20 @@ public sealed class AssemblyM1Pipelinepublic static class AssemblyWorldQuery{public static SemanticBinding Resolve(AssemblyIr ir, string semanticValueId)+ => Resolve(ir, semanticValueId, new HashSet<string>(StringComparer.Ordinal));++ private static SemanticBinding Resolve(AssemblyIr ir, string semanticValueId, HashSet<string> visited){+ if (!visited.Add(semanticValueId)) throw new InvalidOperationException($"Cyclic exposed semantic '{semanticValueId}'.");var instance = ir.Instances.FirstOrDefault(candidate => Flatten(candidate.SemanticRoot).Any(value => value.StableIdentity == semanticValueId))?? throw new KeyNotFoundException($"Semantic value '{semanticValueId}' has no owning assembly instance.");if (instance.ResolvedTransform is null) throw new InvalidOperationException($"Instance '{instance.Path}' has no resolved world transform.");var value = Flatten(instance.SemanticRoot).Single(candidate => candidate.StableIdentity == semanticValueId);+ if (value.TryBinding<AssemblyExposedSemanticBinding>(out var alias))+ {+ var target = ExposedTarget(ir.Instances, instance, alias);+ return Resolve(ir, target.Value.StableIdentity, visited);+ }var transform = Transform3D.FromRowMajor(instance.ResolvedTransform.Matrix);if (value.TryBinding<ExactAxisBinding>(out var axis)){@@ -678,6 +687,17 @@ public static class AssemblyWorldQuerythrow new InvalidOperationException($"Semantic value '{semanticValueId}' has no world-queryable exact binding.");}+ internal static (AssemblyInstanceIr Owner, SemanticValue Value) ExposedTarget(IReadOnlyList<AssemblyInstanceIr> instances,+ AssemblyInstanceIr owner, AssemblyExposedSemanticBinding alias)+ {+ var path = new AssemblyPath([.. owner.Path.Segments, .. alias.RelativeOccurrencePath]).ToString();+ var instance = instances.Single(i => i.Path.ToString() == path);+ var value = instance.SemanticRoot;+ if (alias.SemanticPath.Length > 0)+ foreach (var member in alias.SemanticPath.Split('.')) value = value.ExposedMembers[member];+ return (instance, value);+ }+public static IReadOnlyList<AssemblyMateResidualIr> ValidateResiduals(AssemblyIr ir, IReadOnlySet<string> materializedInstanceIds, double positionToleranceMm = 1e-8, double angularToleranceRadians = 1e-8){var result = new List<AssemblyMateResidualIr>();diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyMotion.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyMotion.csnew file mode 100644index 00000000..86a5dfb8--- /dev/null+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyMotion.cs@@ -0,0 +1,97 @@+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;+using Aetheris.Semantics;++namespace Aetheris.Kernel.Firmament.Assembly;++public enum AssemblyMotionDimension { Time, Angle, Length }+public enum AssemblyMotionInterpolation { Linear, Hold, Cosine }+public enum AssemblyMotionRepeat { Once, Loop }+public sealed record AssemblyMotionKeyIr(string Name, double At, double Value, SemanticSourceSpan? SourceSpan);+public sealed record AssemblyMotionCurveIr(string Name, AssemblyMotionDimension Domain, AssemblyMotionDimension ValueDimension,+ AssemblyMotionInterpolation Interpolation, double? Period, IReadOnlyList<AssemblyMotionKeyIr> Keys);+public sealed record AssemblyMotionTrackIr(string Name, string MateStableId, string JointName, AssemblyMotionCurveIr Curve,+ ExpressionSyntax? Input, IReadOnlyList<string> Dependencies, SemanticSourceSpan? SourceSpan);+public sealed record AssemblyMotionIr(string Name, double DurationSeconds, AssemblyMotionRepeat Repeat,+ IReadOnlyList<AssemblyMotionTrackIr> Tracks, SemanticSourceSpan? SourceSpan);++/// <summary>Pure sampling of a compiled finite clip. There is no playback state,+/// source parsing, geometry rebuild or accumulated matrix update here.</summary>+public static class AssemblyMotion+{+ public static AssemblyPoseResult Evaluate(AssemblyIr assembly, string motion, double seconds, bool preserveEndpoint = false)+ {+ var clip = assembly.Motions.SingleOrDefault(m => m.Name == motion);+ if (clip is null || !double.IsFinite(seconds))+ return new([], [new("assembly-motion-invalid-query", $"Motion '{motion}' requires an admitted clip and finite time in seconds.")], new Dictionary<string, double>());+ var time = clip.Repeat == AssemblyMotionRepeat.Loop && !(preserveEndpoint && seconds == clip.DurationSeconds)+ ? Wrap(seconds, clip.DurationSeconds) : Math.Clamp(seconds, 0, clip.DurationSeconds);+ var state = (assembly.Joints ?? []).Where(j => j.DegreesOfFreedom == 1).ToDictionary(j => j.Name, j => j.DefaultState, StringComparer.Ordinal);+ var variables = Variables(assembly, state);+ var joints = (assembly.Joints ?? []).ToDictionary(j => j.MateStableId, StringComparer.Ordinal);+ var writers = clip.Tracks.Select(t => t.MateStableId).ToHashSet(StringComparer.Ordinal);+ var complete = new HashSet<string>(StringComparer.Ordinal);+ var diagnostics = new List<AssemblyDiagnostic>();+ bool Track(AssemblyMotionTrackIr track)+ {+ if (complete.Contains(track.MateStableId)) return true;+ if (track.Dependencies.Any(dependency => writers.Contains(dependency) && !complete.Contains(dependency)))+ { diagnostics.Add(new("assembly-motion-driver-cycle", $"Motion '{motion}' has an invalid compiled driver order at '{track.Name}'.") { SourceSpan = track.SourceSpan }); return false; }+ var input = time;+ if (track.Input is not null)+ {+ if (!FirmamentNumericEvaluation.TryEvaluate(track.Input, out var value, variables) || value.Unit != Unit(track.Curve.Domain))+ { diagnostics.Add(new("assembly-motion-input-invalid", $"Track '{track.Name}' input did not produce finite {track.Curve.Domain}.") { SourceSpan = track.SourceSpan }); return false; }+ input = value.Number;+ }+ var sampled = Sample(track.Curve, input);+ if (!double.IsFinite(sampled))+ { diagnostics.Add(new("assembly-motion-value-invalid", $"Track '{track.Name}' produced a nonfinite value.") { SourceSpan = track.SourceSpan }); return false; }+ state[track.JointName] = sampled;+ foreach (var name in CoordinateNames(assembly.Name, joints[track.MateStableId], track.Curve.ValueDimension))+ variables[name] = new(sampled, Unit(track.Curve.ValueDimension));+ complete.Add(track.MateStableId); return true;+ }+ foreach (var track in clip.Tracks) if (!Track(track)) return new([], diagnostics, state);+ return AssemblyKinematics.Evaluate(assembly, state);+ }++ public static double Sample(AssemblyMotionCurveIr curve, double input)+ {+ if (!double.IsFinite(input)) throw new ArgumentOutOfRangeException(nameof(input));+ if (curve.Period is { } period) input = Wrap(input, period);+ if (input <= curve.Keys[0].At) return curve.Keys[0].Value;+ for (var i = 1; i < curve.Keys.Count; i++)+ {+ var end = curve.Keys[i]; if (input > end.At) continue;+ if (input == end.At) return end.Value;+ var start = curve.Keys[i - 1]; var t = (input - start.At) / (end.At - start.At);+ var weight = curve.Interpolation switch+ { AssemblyMotionInterpolation.Hold => 0, AssemblyMotionInterpolation.Cosine => (1 - Math.Cos(Math.PI * t)) / 2, _ => t };+ return start.Value + (end.Value - start.Value) * weight;+ }+ return curve.Keys[^1].Value;+ }++ internal static Dictionary<string, FirmamentNumericEvaluation.Value> Variables(AssemblyIr assembly, IReadOnlyDictionary<string, double> state)+ {+ var result = new Dictionary<string, FirmamentNumericEvaluation.Value>(StringComparer.Ordinal);+ foreach (var joint in assembly.Joints ?? [])+ {+ var dimension = joint.Family == MechanicalInterfaceFamily.Prismatic ? AssemblyMotionDimension.Length : AssemblyMotionDimension.Angle;+ foreach (var name in CoordinateNames(assembly.Name, joint, dimension))+ result[name] = new(state.GetValueOrDefault(joint.Name, joint.DefaultState), Unit(dimension));+ }+ return result;+ }+ internal static IEnumerable<string> CoordinateNames(string assembly, AssemblyJointIr joint, AssemblyMotionDimension dimension)+ {+ var suffix = dimension == AssemblyMotionDimension.Angle ? ".angle" : ".translation";+ foreach (var name in joint.PublicNames)+ {+ yield return name + suffix;+ if (!name.StartsWith(assembly + ".", StringComparison.Ordinal)) yield return assembly + "." + name + suffix;+ }+ }+ internal static string Unit(AssemblyMotionDimension dimension) => dimension switch { AssemblyMotionDimension.Time => "s", AssemblyMotionDimension.Angle => "deg", _ => "mm" };+ private static double Wrap(double value, double period) => (value % period + period) % period;+}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyMotionAuthoring.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyMotionAuthoring.csnew file mode 100644index 00000000..efbe0cf5--- /dev/null+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyMotionAuthoring.cs@@ -0,0 +1,187 @@+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;+using Aetheris.Semantics;++namespace Aetheris.Kernel.Firmament.Assembly;++/// <summary>Motion is admitted from the shared AST into the existing occurrence+/// graph. This owner never creates product instances or interprets geometry.</summary>+internal static class AssemblyMotionAuthoring+{+ internal static IReadOnlyList<DeclarationSyntax> Extract(DocumentSyntax document, ref string source, string file, List<AssemblyDiagnostic> diagnostics)+ {+ var allowed = document.Statements.OfType<DeclarationSyntax>().SelectMany(d => d.Type.Name.Text == "Assembly" && d.Modifiers.Count == 0+ ? new[] { d }.Concat(d.Body?.Statements.OfType<DeclarationSyntax>() ?? []) : [d]).ToArray();+ var result = FirmamentSyntaxTraversal.Declarations(document).Where(d => d.Type.Name.Text is "Motion" or "Keyframes").ToArray();+ foreach (var d in result.Where(d => !allowed.Contains(d)))+ diagnostics.Add(Error("scope-unsupported", "Motion and Keyframes belong to the root Assembly or its module, not a reusable definition or construction scope.", file, d.Span));+ var chars = source.ToCharArray();+ foreach (var d in result) Array.Fill(chars, ' ', d.Span.Start, d.Span.Length);+ source = new(chars); return result;+ }++ internal static IReadOnlyList<AssemblyMotionIr> Bind(AssemblySource source, AssemblyIr assembly, List<AssemblyDiagnostic> diagnostics)+ {+ if (source.MotionSyntax.Count == 0) return [];+ var coordinates = (assembly.Joints ?? []).SelectMany(j => AssemblyMotion.CoordinateNames(assembly.Name, j,+ j.Family == MechanicalInterfaceFamily.Prismatic ? AssemblyMotionDimension.Length : AssemblyMotionDimension.Angle).Select(name => (Name: name, Joint: j)));+ foreach (var group in coordinates.GroupBy(c => c.Name).Where(g => g.Select(c => c.Joint.MateStableId).Distinct().Count() > 1))+ diagnostics.Add(new("assembly-motion-coordinate-ambiguous", $"Coordinate '{group.Key}' names more than one realized Mate; give the Mates unambiguous names."));+ if (diagnostics.Any(d => d.Severity == AssemblyDiagnosticSeverity.Error)) return [];+ var curves = new Dictionary<string, AssemblyMotionCurveIr>(StringComparer.Ordinal);+ foreach (var d in source.MotionSyntax.Where(d => d.Type.Name.Text == "Keyframes"))+ {+ var read = new Reader(d, source.SourceIdentity, diagnostics, "Keyframe", generic: true);+ var types = d.Type.Arguments.Select(a => a is { Name: null, Default: null, Value: ReferenceSyntax r } ? r.Name.Text : "").ToArray();+ if (types.Length != 2 || !Dimension(types.ElementAtOrDefault(0), out var domain) || domain == AssemblyMotionDimension.Length+ || !Dimension(types.ElementAtOrDefault(1), out var value) || value == AssemblyMotionDimension.Time)+ { read.Error("curve-types-invalid", "Keyframes requires <Time|Angle, Angle|Length>."); read.Complete(); continue; }+ var periodExpression = read.Fields.Take("Period"); double? period = null;+ if (periodExpression is not null)+ {+ if (FirmamentSyntaxValues.TryMeasure(periodExpression, AssemblyMotion.Unit(domain), out var number) && number > 0) period = number;+ else read.Error("period-invalid", $"Keyframes period requires positive {domain}.");+ }+ var curve = Curve(read, domain, value, period);+ if (!curves.TryAdd((d.Name?.Text ?? "<unnamed>"), curve)) read.Error("curve-duplicate", $"Keyframes '{d.Name?.Text}' is duplicated.");+ read.Complete();+ }+ var result = new List<AssemblyMotionIr>();+ foreach (var d in source.MotionSyntax.Where(d => d.Type.Name.Text == "Motion"))+ {+ var read = new Reader(d, source.SourceIdentity, diagnostics, "Track");+ var duration = read.Fields.Number("Duration", "s");+ if (!double.IsFinite(duration) || duration <= 0) read.Error("duration-invalid", "Motion duration requires a positive Time in s or ms.");+ var repeat = read.Fields.Reference("Repeat");+ if (!Enum.TryParse<AssemblyMotionRepeat>(repeat, out var repeating) || !Enum.IsDefined(repeating))+ read.Error("repeat-invalid", "Motion repeat requires Once or Loop.");+ var tracks = new List<AssemblyMotionTrackIr>();+ foreach (var track in d.Body?.Statements.OfType<DeclarationSyntax>().Where(t => t.Type.Name.Text == "Track") ?? [])+ {+ var item = new Reader(track, source.SourceIdentity, diagnostics, "Keyframe");+ var target = item.Fields.Reference("Target") ?? "";+ var joint = (assembly.Joints ?? []).SingleOrDefault(j => AssemblyMotion.CoordinateNames(assembly.Name, j,+ j.Family == MechanicalInterfaceFamily.Prismatic ? AssemblyMotionDimension.Length : AssemblyMotionDimension.Angle).Contains(target, StringComparer.Ordinal));+ if (joint is null || joint.DegreesOfFreedom != 1)+ { item.Error("target-invalid", $"Track '{track.Name?.Text}' target '{target}' must name one realized Revolute angle or Prismatic translation."); item.Complete(); continue; }+ var dimension = joint.Family == MechanicalInterfaceFamily.Revolute ? AssemblyMotionDimension.Angle : AssemblyMotionDimension.Length;+ var values = item.Fields.Reference("Values");+ var input = item.Fields.Take("Input");+ AssemblyMotionCurveIr curve;+ var dependencies = new List<string>();+ if (values is null)+ {+ if (input is not null) item.Error("input-invalid", "Inline Keyframes use clip Time; input requires a reusable values profile.");+ curve = Curve(item, AssemblyMotionDimension.Time, dimension, null);+ if (curve.Keys.Count > 0 && (curve.Keys[0].At != 0 || curve.Keys[^1].At != duration))+ item.Error("key-domain-invalid", "Inline keys must start at 0s and end at Motion duration.");+ }+ else+ {+ if (!curves.TryGetValue(values, out curve!))+ { item.Error("curve-unresolved", $"Keyframes '{values}' was not found."); item.Complete(); continue; }+ if (curve.ValueDimension != dimension) item.Error("value-type-mismatch", $"Track target requires {dimension}; '{values}' supplies {curve.ValueDimension}.");+ if (track.Body?.Statements.OfType<DeclarationSyntax>().Any() == true)+ item.Error("multiple-values", "Track cannot combine a values profile with inline Keyframes.");+ var variables = AssemblyMotion.Variables(assembly, new Dictionary<string, double>());+ if (input is null ? curve.Domain != AssemblyMotionDimension.Time+ : !FirmamentNumericEvaluation.TryEvaluate(input, out var value, variables, typeOnly: true) || value.Unit != AssemblyMotion.Unit(curve.Domain))+ item.Error("input-type-mismatch", $"Track input must resolve joint coordinates and produce {curve.Domain}.");+ if (input is not null)+ {+ var doc = new DocumentSyntax(source.SourceIdentity, [new ExpressionStatementSyntax(input, input.Span)], [], input.Span);+ var references = FirmamentSyntaxTraversal.Expressions(doc).Select(FirmamentSyntaxValues.Reference).OfType<string>().ToHashSet(StringComparer.Ordinal);+ dependencies.AddRange((assembly.Joints ?? []).Where(j => AssemblyMotion.CoordinateNames(assembly.Name, j,+ j.Family == MechanicalInterfaceFamily.Prismatic ? AssemblyMotionDimension.Length : AssemblyMotionDimension.Angle).Any(references.Contains)).Select(j => j.MateStableId));+ }+ }+ tracks.Add(new((track.Name?.Text ?? "<unnamed>"), joint.MateStableId, joint.Name, curve, input, dependencies, item.Span));+ item.Complete();+ }+ if (tracks.Count == 0) read.Error("tracks-missing", "Motion requires at least one admitted Track.");+ foreach (var group in tracks.GroupBy(t => t.Name).Where(g => g.Count() > 1)) read.Error("track-duplicate", $"Track name '{group.Key}' is duplicated.");+ foreach (var group in tracks.GroupBy(t => t.MateStableId).Where(g => g.Count() > 1)) read.Error("multiple-writers", $"Multiple Tracks drive realized Mate '{group.First().JointName}'.");+ if (result.Any(m => m.Name == (d.Name?.Text ?? "<unnamed>"))) read.Error("duplicate", $"Motion '{(d.Name?.Text ?? "<unnamed>")}' is duplicated.");+ var ordered = new List<AssemblyMotionTrackIr>();+ var pending = tracks.ToList();+ var written = tracks.Select(t => t.MateStableId).ToHashSet(StringComparer.Ordinal);+ var resolved = new HashSet<string>(StringComparer.Ordinal);+ while (pending.Count > 0)+ {+ var ready = pending.Where(t => t.Dependencies.All(id => !written.Contains(id) || resolved.Contains(id))).ToArray();+ if (ready.Length == 0) { read.Error("driver-cycle", "Motion coordinate drivers contain a dependency cycle."); break; }+ foreach (var track in ready) { ordered.Add(track); resolved.Add(track.MateStableId); pending.Remove(track); }+ }+ result.Add(new((d.Name?.Text ?? "<unnamed>"), duration, repeating, ordered, read.Span));+ read.Complete();+ }+ if (diagnostics.Any(d => d.Severity == AssemblyDiagnosticSeverity.Error)) return result;+ var compiled = assembly with { Motions = result };+ foreach (var clip in result)+ {+ var start = AssemblyMotion.Evaluate(compiled, clip.Name, 0);+ var end = AssemblyMotion.Evaluate(compiled, clip.Name, clip.DurationSeconds, preserveEndpoint: true);+ diagnostics.AddRange(start.Diagnostics.Concat(end.Diagnostics).Distinct());+ if (clip.Repeat == AssemblyMotionRepeat.Loop && start.IsSuccess && end.IsSuccess+ && start.Instances.Zip(end.Instances).Any(pair => pair.First.ResolvedTransform!.Matrix.Zip(pair.Second.ResolvedTransform!.Matrix).Any(v => Math.Abs(v.First - v.Second) > 1e-9)))+ diagnostics.Add(new("assembly-motion-loop-discontinuous", $"Motion '{clip.Name}' has discontinuous occurrence poses at its loop endpoints.") { SourceSpan = clip.SourceSpan });+ }+ return result;+ }++ private static AssemblyMotionCurveIr Curve(Reader read, AssemblyMotionDimension domain, AssemblyMotionDimension value, double? period)+ {+ var interpolation = read.Fields.Reference("Interpolation");+ if (!Enum.TryParse<AssemblyMotionInterpolation>(interpolation, out var mode) || !Enum.IsDefined(mode))+ read.Error("interpolation-invalid", "Specify Linear, Hold or Cosine interpolation.");+ var keys = new List<AssemblyMotionKeyIr>();+ foreach (var key in read.Declaration.Body?.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Keyframe") ?? [])+ {+ var item = new Reader(key, read.File, read.Diagnostics);+ var at = item.Fields.Number("At", AssemblyMotion.Unit(domain));+ var amount = item.Fields.Number("Value", AssemblyMotion.Unit(value));+ if (!double.IsFinite(at) || !double.IsFinite(amount)) item.Error("key-type-mismatch", $"Keyframe requires finite {domain} at and {value} value.");+ if (keys.Any(k => k.Name == (key.Name?.Text ?? "<unnamed>"))) item.Error("key-duplicate", $"Keyframe '{(key.Name?.Text ?? "<unnamed>")}' is duplicated.");+ if (keys.Count > 0 && at <= keys[^1].At) item.Error("key-order-invalid", "Keyframe at values must be strictly increasing and unique.");+ keys.Add(new((key.Name?.Text ?? "<unnamed>"), at, amount, item.Span)); item.Complete();+ }+ if (keys.Count < 2) read.Error("keys-missing", "A curve requires at least two named Keyframes.");+ if (period is { } length && keys.Count > 0)+ {+ if (keys[0].At != 0 || keys[^1].At != length) read.Error("period-endpoints-invalid", "Periodic curves must include keys at zero and period.");+ if (keys[0].Value != keys[^1].Value) read.Error("period-values-discontinuous", "Periodic profile endpoint values must agree; use unwrapped inline keys for full-turn motion.");+ }+ return new((read.Declaration.Name?.Text ?? "<unnamed>"), domain, value, mode, period, keys);+ }+ private static bool Dimension(string? name, out AssemblyMotionDimension dimension) => Enum.TryParse(name, out dimension) && Enum.IsDefined(dimension);+ private static AssemblyDiagnostic Error(string code, string message, string file, FirmamentV2SourceSpan span) =>+ new("assembly-motion-" + code, message) { SourceSpan = new(file, span.Start, span.Length) };+ private sealed class Reader+ {+ internal readonly DeclarationSyntax Declaration;+ internal readonly string File;+ internal readonly List<AssemblyDiagnostic> Diagnostics;+ internal readonly FirmamentSyntaxFields Fields;+ private readonly List<string> errors = [];+ internal SemanticSourceSpan Span => new(File, Declaration.Span.Start, Declaration.Span.Length);+ internal Reader(DeclarationSyntax declaration, string file, List<AssemblyDiagnostic> diagnostics, string? child = null, bool generic = false)+ {+ Declaration = declaration; File = file; Diagnostics = diagnostics;+ Fields = new(declaration with { Body = declaration.Body is null ? null : declaration.Body with+ { Statements = declaration.Body.Statements.OfType<FieldSyntax>().Cast<StatementSyntax>().ToArray() } }, errors);+ if (declaration.Name is null || declaration.Body is null || declaration.Modifiers.Count > 0 || declaration.Clauses.Count > 0+ || declaration.Annotation is not null || declaration.ResultType is not null || declaration.Initializer is not null || declaration.Target is not null+ || declaration.HasParameterList || declaration.Occurrence || !generic && declaration.Type.Arguments.Count > 0)+ Error("header-invalid", $"Invalid {declaration.Type.Name.Text} declaration header.");+ foreach (var statement in declaration.Body?.Statements.Where(s => s is not FieldSyntax) ?? [])+ if (statement is not DeclarationSyntax d || d.Type.Name.Text != child)+ Diagnostics.Add(AssemblyMotionAuthoring.Error("statement-unknown", $"{declaration.Type.Name.Text} admits fields{(child is null ? "" : " and " + child + " declarations")}.", File, statement.Span));+ }+ internal void Error(string code, string message) => Diagnostics.Add(AssemblyMotionAuthoring.Error(code, message, File, Declaration.Span));+ internal void Complete()+ {+ Fields.Complete();+ foreach (var message in errors) Error("field-invalid", Aetheris.Kernel.Firmament.FirmamentV2.FirmamentInterop.FirmamentV2DiagnosticAdapter.MessageFor(message));+ }+ }+}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyRouteBindings.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyRouteBindings.csindex dbbbf5a3..34f49558 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyRouteBindings.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyRouteBindings.cs@@ -50,7 +50,7 @@ internal static class AssemblyRouteBindingsif (!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())+ if ((placed.Ir.Joints ?? []).Any(joint => joint.DegreesOfFreedom > 0)){ 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)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.csindex df0ddc63..8f021053 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs@@ -566,7 +566,7 @@ internal static class CanonicalStaticAuthoring}private static bool IsSupportedSetElementType(string type, IReadOnlyDictionary<string, FirmamentV2RecordTypeDecl> records) =>- type is "Point2" or "Point3" or "Vector2" or "Length" or "Angle" or "Int" or "Float" or "Bool" || records.ContainsKey(type);+ type is "Point2" or "Point3" or "Vector2" or "Length" or "Angle" or "Time" or "Int" or "Float" or "Bool" || records.ContainsKey(type);private static bool ValueMatchesType(string value, string type){@@ -580,6 +580,7 @@ internal static class CanonicalStaticAuthoring}return type switch{+ "Time" => FirmamentNumericEvaluation.TryEvaluate(value, out var duration) && duration.Unit == "s","Length" => Regex.IsMatch(value, @"^[-+]?\d+(?:\.\d+)?mm$", RegexOptions.CultureInvariant),"Angle" => Regex.IsMatch(value, @"^[-+]?\d+(?:\.\d+)?deg$", RegexOptions.CultureInvariant),"Int" => Regex.IsMatch(value, @"^[-+]?\d+$", RegexOptions.CultureInvariant),diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentConcepts.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentConcepts.csindex e65b96cb..544b9a5e 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentConcepts.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentConcepts.cs@@ -341,6 +341,7 @@ internal sealed class FirmamentConceptsFirmamentV2PrimitiveType.Bool => new LiteralSyntax(LiteralKind.Boolean, "true", span),FirmamentV2PrimitiveType.String => new LiteralSyntax(LiteralKind.String, "\"sample\"", span),FirmamentV2PrimitiveType.Length => new QuantitySyntax(new LiteralSyntax(LiteralKind.Number, "1", span), new("mm", span), span),+ FirmamentV2PrimitiveType.Time => new QuantitySyntax(new LiteralSyntax(LiteralKind.Number, "1", span), new("s", span), span),FirmamentV2PrimitiveType.Angle => new QuantitySyntax(new LiteralSyntax(LiteralKind.Number, "1", span), new("deg", span), span),_ => new LiteralSyntax(LiteralKind.Number, primitive == FirmamentV2PrimitiveType.Float ? "1.5" : "1", span)};diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2InteropValueAdapter.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2InteropValueAdapter.csindex d8dabad4..ea7466f9 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2InteropValueAdapter.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2InteropValueAdapter.cs@@ -54,6 +54,7 @@ internal static class FirmamentV2InteropValueAdapterFirmamentV2PrimitiveType.Float => FirmamentValueKind.Float,FirmamentV2PrimitiveType.Length => FirmamentValueKind.Length,FirmamentV2PrimitiveType.Angle => FirmamentValueKind.Angle,+ FirmamentV2PrimitiveType.Time => FirmamentValueKind.Time,FirmamentV2PrimitiveType.String => FirmamentValueKind.String,FirmamentV2PrimitiveType.Bool => FirmamentValueKind.Bool,_ => throw new ArgumentOutOfRangeException(nameof(primitiveType), primitiveType, "Unsupported Firmament V2 primitive type.")diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.csindex 646927a4..ad685c3f 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs@@ -20,9 +20,9 @@ public sealed record FirmamentLanguageFormat(string Document, string Revision, spublic static class FirmamentLanguageAnalysisService{internal sealed record Lexeme(int Start, int Length, string Text, string Shape, string? Error = null);- 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", "As", "as", "Output", "tol", "Concept", "Require"];- private static readonly HashSet<string> DeclarationKinds = ["Model", "Struct", "Subassembly", "Assembly", "Template", "Profile", "Static", "Record", "Function", "Pattern", "Section", "SectionChain", "FrameTransform", "Points", "Path", "Semantic", "Enum", "Concept"];- private static readonly HashSet<string> Types = ["Length", "Angle", "Float", "Int", "Bool", "Box3", "Plane", "Point2", "Point3"];+ 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", "As", "as", "Output", "tol", "Concept", "Require", "Motion", "Track", "Keyframes", "Keyframe"];+ private static readonly HashSet<string> DeclarationKinds = ["Model", "Struct", "Subassembly", "Assembly", "Template", "Profile", "Static", "Record", "Function", "Pattern", "Section", "SectionChain", "FrameTransform", "Points", "Path", "Semantic", "Enum", "Concept", "Motion", "Track", "Keyframes", "Keyframe"];+ private static readonly HashSet<string> Types = ["Length", "Angle", "Time", "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);@@ -287,7 +287,7 @@ public static class FirmamentLanguageAnalysisServiceif (Types.Contains(token.Text)) return "type";if (index + 1 < tokens.Count && tokens[index + 1].Text == ":" &&FirmamentSemanticSchemas.All.Any(item => item.Fields.Any(field => field.Name == token.Text))) return "field";- if (token.Text is "mm" or "cm" or "m" or "deg" or "rad") return "unit";+ if (token.Text is "mm" or "cm" or "m" or "deg" or "rad" or "s" or "ms") return "unit";if (Choices.Contains(token.Text)) return "value";if (token.Text == "face" && index + 1 < tokens.Count && tokens[index + 1].Text == "(") return "selector";return "identifier";diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.csindex d6639b49..a1314647 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs@@ -225,7 +225,7 @@ public static class FirmamentSourceSpellingAdd("Assembly Subassembly", "Anchor Provenance Appearance");Add("Part Occurrence", "Material Appearance");Add("Plane DatumPlane", "Origin Normal Up From Offset RotateLocal Clocking");- Add("DatumFrame", "On At X");+ Add("DatumFrame", "On At X From TranslateLocal RotateLocal Normal Up");Add("Point2 Point3", "Position");Add("Axis Axis2 Line3", "Origin Direction Start End Reference");Add("Circle2", "Center Radius");diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.csindex 2c6f1284..6eaffaf1 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs@@ -21,7 +21,7 @@ public sealed record FirmamentV2ThreadDecl(string Name, string SupportSolid, strdouble MajorDiameterMm, double PitchMm, double LengthMm, double? StartOffsetMm,string Hand, FirmamentV2SourceSpan SourceSpan);public sealed record FirmamentV2AuthoredField(string Name, FirmamentV2SourceSpan DeclarationSpan, FirmamentV2SourceSpan ValueSpan);-public enum FirmamentV2PrimitiveType { Int, Float, Length, Angle, String, Bool }+public enum FirmamentV2PrimitiveType { Int, Float, Length, Angle, String, Bool, Time }public enum FirmamentV2ToleranceKind { Bilateral, Asymmetric }public sealed record FirmamentV2Tolerance(FirmamentV2ToleranceKind Kind, double Plus, double Minus, string Unit, FirmamentV2PrimitiveType Type, FirmamentV2SourceSpan SourceSpan);public sealed record FirmamentV2LiteralValue(FirmamentV2PrimitiveType Type, object Value, double? NumericValue = null, string? Unit = null, string? Raw = null);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csindex 62817c1c..739d2f72 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -757,11 +757,12 @@ public static partial class FirmamentV2Parser"float" or "Float" => FirmamentV2PrimitiveType.Float,"length" or "Length" => FirmamentV2PrimitiveType.Length,"angle" or "Angle" => FirmamentV2PrimitiveType.Angle,+ "time" or "Time" => FirmamentV2PrimitiveType.Time,"string" or "String" => FirmamentV2PrimitiveType.String,"bool" or "Bool" => FirmamentV2PrimitiveType.Bool,_ => default};- return text is "int" or "float" or "length" or "angle" or "string" or "bool" or "Int" or "Float" or "Length" or "Angle" or "String" or "Bool";+ return text is "Time" or "time" or "int" or "float" or "length" or "angle" or "string" or "bool" or "Int" or "Float" or "Length" or "Angle" or "String" or "Bool";}private static FirmamentV2ValueExpression? ParseLetValueExpression(FirmamentV2PrimitiveType type, string literal, List<string> diagnostics)@@ -844,6 +845,9 @@ public static partial class FirmamentV2Parserif (m.Groups["unit"].Value != "deg") { diagnostics.Add(m.Groups["unit"].Success ? LetUnitMismatch : LetTypeMismatch); return null; }var angle = double.Parse(m.Groups["num"].Value, CultureInfo.InvariantCulture);return new(type, angle, angle, "deg", literal);+ case FirmamentV2PrimitiveType.Time:+ if (!FirmamentNumericEvaluation.TryEvaluate(literal, out var time) || time.Unit != "s") { diagnostics.Add(LetUnitMismatch); return null; }+ return new(type, time.Number, time.Number, "s", literal);case FirmamentV2PrimitiveType.String:if (!Regex.IsMatch(literal, "^\\\"[^\\\"]*\\\"$", RegexOptions.CultureInvariant)) { diagnostics.Add(LetInvalidLiteral); return null; }return new(type, literal[1..^1], null, null, literal);@@ -1000,7 +1004,7 @@ public static partial class FirmamentV2Parserreturn new(type, double.NaN, double.NaN, Raw: raw);var d = computed.Number;object value = type == FirmamentV2PrimitiveType.Int ? (object)(int)d : d;- return new(type, value, d, type == FirmamentV2PrimitiveType.Length ? "mm" : type == FirmamentV2PrimitiveType.Angle ? "deg" : null, raw);+ return new(type, value, d, type == FirmamentV2PrimitiveType.Length ? "mm" : type == FirmamentV2PrimitiveType.Angle ? "deg" : type == FirmamentV2PrimitiveType.Time ? "s" : null, raw);}}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.csindex 6c11cbb5..d038d906 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.cs@@ -34,6 +34,7 @@ public static partial class FirmamentV2ParserToleranceSyntax t => InferType(t.Nominal, visiting),QuantitySyntax { Unit.Text: "mm" } => FirmamentV2PrimitiveType.Length,QuantitySyntax { Unit.Text: "deg" } => FirmamentV2PrimitiveType.Angle,+ QuantitySyntax { Unit.Text: "s" or "ms" } => FirmamentV2PrimitiveType.Time,LiteralSyntax { Kind: LiteralKind.Boolean } => FirmamentV2PrimitiveType.Bool,LiteralSyntax { Kind: LiteralKind.String } => FirmamentV2PrimitiveType.String,LiteralSyntax { Kind: LiteralKind.Number } n => n.Raw.Contains('.') || n.Raw.Contains('e', StringComparison.OrdinalIgnoreCase) ? FirmamentV2PrimitiveType.Float : FirmamentV2PrimitiveType.Int,@@ -175,7 +176,7 @@ public static partial class FirmamentV2Parser? new FirmamentV2BinaryExpression(l, op, rgt, text) : null;}var unit = e is QuantitySyntax q ? q.Unit.Text : e is UnarySyntax { Operand: QuantitySyntax uq } ? uq.Unit.Text : "";- var inferred = unit switch { "mm" => FirmamentV2PrimitiveType.Length, "deg" => FirmamentV2PrimitiveType.Angle,+ var inferred = unit switch { "mm" => FirmamentV2PrimitiveType.Length, "deg" => FirmamentV2PrimitiveType.Angle, "s" or "ms" => FirmamentV2PrimitiveType.Time,"" => expected is FirmamentV2PrimitiveType.String or FirmamentV2PrimitiveType.Bool ? expected: text.Contains('.') || text.Contains('e', StringComparison.OrdinalIgnoreCase) ? FirmamentV2PrimitiveType.Float : FirmamentV2PrimitiveType.Int, _ => (FirmamentV2PrimitiveType?)null };if (inferred is null) return null;@@ -191,10 +192,10 @@ public static partial class FirmamentV2Parser}catch (System.Text.Json.JsonException) { return null; }}- if (!FirmamentSyntaxValues.TryMeasure(e, unit, out var n) || inferred == FirmamentV2PrimitiveType.Int && (n < int.MinValue || n > int.MaxValue || n != Math.Truncate(n))) return null;+ if (!FirmamentSyntaxValues.TryMeasure(e, inferred == FirmamentV2PrimitiveType.Time ? "s" : unit, out var n) || inferred == FirmamentV2PrimitiveType.Int && (n < int.MinValue || n > int.MaxValue || n != Math.Truncate(n))) return null;// Float declarations admit integer-written constants, as legacy let did.if (inferred == FirmamentV2PrimitiveType.Int && expected == FirmamentV2PrimitiveType.Float) inferred = expected;- return new FirmamentV2LiteralExpression(new(inferred.Value, inferred == FirmamentV2PrimitiveType.Int ? (object)(int)n : n, n, unit.Length == 0 ? null : unit, text));+ return new FirmamentV2LiteralExpression(new(inferred.Value, inferred == FirmamentV2PrimitiveType.Int ? (object)(int)n : n, n, inferred == FirmamentV2PrimitiveType.Time ? "s" : unit.Length == 0 ? null : unit, text));}}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.csindex d5cdd37b..60f0a673 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs@@ -610,7 +610,8 @@ internal static class FirmamentV2TemplateExpansionFirmamentCompileTimeValues? scalars = null) => scalars?.Contains(value) == true ? scalars.HasType(value, type) : type switch{"Point2" or "Point3" or "Vector2" => MatchesCoordinates(value, type),- "Length" => Regex.IsMatch(value, @"^[-+]?[0-9]+(?:\.[0-9]+)?mm$", RegexOptions.CultureInvariant),+ "Time" => FirmamentNumericEvaluation.TryEvaluate(value, out var duration) && duration.Unit == "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),"Version" => Regex.IsMatch(value, @"^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)$", RegexOptions.CultureInvariant),diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentNumericEvaluation.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentNumericEvaluation.csindex 7cbac94d..37e395bb 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentNumericEvaluation.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentNumericEvaluation.cs@@ -38,9 +38,9 @@ internal static class FirmamentNumericEvaluationreturn variables is not null && variables.TryGetValue(r.Name.Text, out result);case MemberSyntax m when FirmamentSyntaxValues.Reference(m) is { } name:return variables is not null && variables.TryGetValue(name, out result);- case QuantitySyntax q when q.Unit.Text is "mm" or "deg" or "rad":+ case QuantitySyntax q when q.Unit.Text is "mm" or "deg" or "rad" or "s" or "ms":if (!Evaluate(q.Value, depth + 1, out var quantity) || quantity.Unit.Length != 0) return false;- result = quantity with { Unit = q.Unit.Text }; return true;+ result = new(q.Unit.Text == "ms" ? quantity.Number / 1000d : quantity.Number, q.Unit.Text == "ms" ? "s" : q.Unit.Text); return true;case UnarySyntax { Operator: UnaryOperator.Positive or UnaryOperator.Negative } u:if (!Evaluate(u.Operand, depth + 1, out result)) return false;if (u.Operator == UnaryOperator.Negative) result = result with { Number = -result.Number };@@ -62,7 +62,7 @@ internal static class FirmamentNumericEvaluationresult = new(typeOnly ? 1 : Math.Pow(args[0].Number, args[1].Number), "");else if (functions is not null) result = functions(target.Name.Text, args);else return false;- return (result.Unit is "" or "mm" or "deg" or "rad") && (typeOnly || double.IsFinite(result.Number));+ return (result.Unit is "" or "mm" or "deg" or "rad" or "s" or "ms") && (typeOnly || double.IsFinite(result.Number));default: return false;}}@@ -74,7 +74,7 @@ internal static class FirmamentNumericEvaluation{result = default;static FirmamentV2PrimitiveType? Type(string unit) => unit switch- { "" => FirmamentV2PrimitiveType.Float, "mm" => FirmamentV2PrimitiveType.Length, "deg" or "rad" => FirmamentV2PrimitiveType.Angle, _ => null };+ { "" => FirmamentV2PrimitiveType.Float, "mm" => FirmamentV2PrimitiveType.Length, "deg" or "rad" => FirmamentV2PrimitiveType.Angle, "s" => FirmamentV2PrimitiveType.Time, _ => null };var symbol = op switch { BinaryOperator.Add => "+", BinaryOperator.Subtract => "-", BinaryOperator.Multiply => "*", BinaryOperator.Divide => "/", _ => "" };if (Type(left.Unit) is not { } lt || Type(right.Unit) is not { } rt || ResultType(lt, symbol, rt) is not { } type|| left.Unit.Length > 0 && right.Unit.Length > 0 && left.Unit != right.Unit@@ -82,14 +82,14 @@ internal static class FirmamentNumericEvaluationvar number = typeOnly ? 1 : op switch{ BinaryOperator.Add => left.Number + right.Number, BinaryOperator.Subtract => left.Number - right.Number,BinaryOperator.Multiply => left.Number * right.Number, _ => left.Number / right.Number };- result = new(number, type is FirmamentV2PrimitiveType.Length or FirmamentV2PrimitiveType.Angle+ result = new(number, type is FirmamentV2PrimitiveType.Length or FirmamentV2PrimitiveType.Angle or FirmamentV2PrimitiveType.Time? left.Unit.Length > 0 ? left.Unit : right.Unit : "");return typeOnly || double.IsFinite(result.Number);}internal static FirmamentV2PrimitiveType? ResultType(FirmamentV2PrimitiveType a, string op, FirmamentV2PrimitiveType b) => op switch{- "+" or "-" when a == b && a is FirmamentV2PrimitiveType.Int or FirmamentV2PrimitiveType.Float or FirmamentV2PrimitiveType.Length or FirmamentV2PrimitiveType.Angle => a,+ "+" or "-" when a == b && a is FirmamentV2PrimitiveType.Int or FirmamentV2PrimitiveType.Float or FirmamentV2PrimitiveType.Length or FirmamentV2PrimitiveType.Angle or FirmamentV2PrimitiveType.Time => a,"+" or "-" when IsNumeric(a) && IsNumeric(b) => FirmamentV2PrimitiveType.Float,"*" when IsNumeric(a) && IsNumeric(b) => a == FirmamentV2PrimitiveType.Int && b == FirmamentV2PrimitiveType.Int ? FirmamentV2PrimitiveType.Int : FirmamentV2PrimitiveType.Float,"*" when IsDim(a) && IsNumeric(b) => a,@@ -100,7 +100,7 @@ internal static class FirmamentNumericEvaluation_ => null};private static bool IsNumeric(FirmamentV2PrimitiveType t) => t is FirmamentV2PrimitiveType.Int or FirmamentV2PrimitiveType.Float;- private static bool IsDim(FirmamentV2PrimitiveType t) => t is FirmamentV2PrimitiveType.Length or FirmamentV2PrimitiveType.Angle;+ private static bool IsDim(FirmamentV2PrimitiveType t) => t is FirmamentV2PrimitiveType.Length or FirmamentV2PrimitiveType.Angle or FirmamentV2PrimitiveType.Time;internal static bool TryEvaluateScalar(string expression, out double value, out string unit){diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.csindex 57f94b1e..dca8bb97 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs@@ -484,7 +484,7 @@ public static class FirmamentSyntaxParser{ left = new ObjectSyntax(left, Block(), Span(start)); continue; }if (allowObject && Take("with")) { left = new WithSyntax(left, Block(), Span(start)); continue; }if (Current.Kind == SyntaxTokenKind.Identifier && !LineBreak &&- (Current.Text is "mm" or "cm" or "m" or "deg" or "rad" or "N" or "kN" or "MN" or "Pa" or "kPa" or "MPa" or "GPa"+ (Current.Text is "mm" or "cm" or "m" or "deg" or "rad" or "s" or "ms" or "N" or "kN" or "MN" or "Pa" or "kPa" or "MPa" or "GPa"|| left is LiteralSyntax { Kind: LiteralKind.Number } && Current.Span.Start == left.Span.Start + left.Span.Length)&& left is LiteralSyntax or SequenceSyntax or ReferenceSyntax){ left = new QuantitySyntax(left, Identifier(), Span(start)); continue; }diff --git a/Aetheris.Kernel.Firmament/Modules/FirmamentModuleGraph.cs b/Aetheris.Kernel.Firmament/Modules/FirmamentModuleGraph.csindex 3abed723..c2d66891 100644--- a/Aetheris.Kernel.Firmament/Modules/FirmamentModuleGraph.cs+++ b/Aetheris.Kernel.Firmament/Modules/FirmamentModuleGraph.cs@@ -342,6 +342,9 @@ internal sealed class FirmamentModuleGraphinternal Reference LocalPart(Module module, string definition){if (TryReference(definition, out var existing)) return existing;+ // The reference identifies the declaration; QualifyParts/PartIdentity+ // carry invocation arguments exactly once on each occurrence.+ definition = Base(definition);var identity = "__Module_" + Hash(IdentityPath(module.Path) + "\0local-part\0" + definition)[..20];var reference = new Reference(identity, "Part", module.Path, module, null, definition, new(module.Path, 0, 0));references.TryAdd(identity, reference); return reference;diff --git a/Aetheris.Web.Perf/Aetheris.Web.Perf.csproj b/Aetheris.Web.Perf/Aetheris.Web.Perf.csprojindex 00592b5f..a6f04cc0 100644--- a/Aetheris.Web.Perf/Aetheris.Web.Perf.csproj+++ b/Aetheris.Web.Perf/Aetheris.Web.Perf.csproj@@ -17,5 +17,6 @@<Compile Include="CompareStep.cs" /><Compile Include="VerifyBridge.cs" /><Compile Include="VerifyIncremental.cs" />+ <Compile Include="VerifyMotion.cs" /></ItemGroup></Project>diff --git a/Aetheris.Web.Perf/PerfProgram.cs b/Aetheris.Web.Perf/PerfProgram.csindex 77437d99..d6928b84 100644--- a/Aetheris.Web.Perf/PerfProgram.cs+++ b/Aetheris.Web.Perf/PerfProgram.cs@@ -12,6 +12,7 @@ public static class PerfProgramif (args.Length > 0 && args[0] == "showcase") return ShowcasePerf.Run(args[1..]);if (args.Length > 0 && args[0] == "compare-step") return CompareStep.Run(args[1..]);if (args.Length > 0 && args[0] == "verify-bridge") return VerifyBridge.Run(args[1..]);+ if (args.Length > 0 && args[0] == "verify-motion") return VerifyMotion.Run(args[1..]);if (args.Length > 0 && args[0] == "verify-incremental") return VerifyIncremental.Run(args[1..]);if (args.Length > 0 && args[0] == "profile") return ProfileOne(args[1..]);if (args.Length != 1) { Console.Error.WriteLine("Usage: Aetheris.Web.Perf <helix-fixture> | Aetheris.Web.Perf showcase --help | Aetheris.Web.Perf compare-step <a.step> <b.step>"); return 2; }diff --git a/Aetheris.Web.Perf/VerifyMotion.cs b/Aetheris.Web.Perf/VerifyMotion.csnew file mode 100644index 00000000..65fb87a6--- /dev/null+++ b/Aetheris.Web.Perf/VerifyMotion.cs@@ -0,0 +1,53 @@+using System.Text.Json;+using Aetheris.Kernel.Firmament.Assembly;++namespace Aetheris.Web.Perf;++internal static class VerifyMotion+{+ public static int Run(string[] args)+ {+ if (args.Length != 1) { Console.Error.WriteLine("Usage: Aetheris.Web.Perf verify-motion <articulated-motion.firmament>"); return 2; }+ var path = Path.GetFullPath(args[0]);+ var motion = File.ReadAllText(path);+ var source = File.ReadAllText(Path.Combine(Path.GetDirectoryName(path)!, "articulated-subassemblies.firmament"))+ + "\n" + string.Join('\n', motion.Split('\n').Where(l => !l.StartsWith("include ", StringComparison.Ordinal)));+ var native = new AssemblyM1Pipeline().Compile(source, "motion.firmament");+ if (!native.IsSuccess) throw new InvalidOperationException(string.Join(';', native.Diagnostics.Select(d => d.Message)));+ JsonElement Call(object request)+ {+ using var response = JsonDocument.Parse(Runtime.Program.Invoke(JsonSerializer.Serialize(request)));+ if (!response.RootElement.GetProperty("ok").GetBoolean()) throw new InvalidOperationException(response.RootElement.ToString());+ return response.RootElement.GetProperty("result").Clone();+ }+ var built = Call(new { operation = "compile", source, sourceName = "motion.firmament" });+ if (!built.GetProperty("success").GetBoolean()) throw new InvalidOperationException(built.ToString());+ var model = built.GetProperty("model");+ var sessionId = model.GetProperty("id").GetString();+ if (model.GetProperty("motions").GetArrayLength() != 1) throw new InvalidOperationException("Missing compiled Motion metadata.");+ foreach (var seconds in new[] { 0, 1.25, .231, 1.749, 2, -0.75, 3.25 })+ {+ var actual = Call(new { operation = "sampleMotion", sessionId, motion = "Cycle", timeSeconds = seconds });+ var expected = AssemblyMotion.Evaluate(native.Ir!, "Cycle", seconds);+ if (!expected.IsSuccess) throw new InvalidOperationException("Native pose failed.");+ foreach (var transform in actual.GetProperty("transforms").EnumerateArray())+ {+ var item = expected.Instances.Single(i => i.StableId == transform.GetProperty("id").GetString());+ if (!item.ResolvedTransform!.Matrix.SequenceEqual(transform.GetProperty("matrix").EnumerateArray().Select(v => v.GetDouble())))+ throw new InvalidOperationException("Native/runtime Motion mismatch: " + item.Path);+ }+ }+ // Invalid edits retain both the visible geometry and its matching graph.+ Call(new { operation = "setSource", sessionId, source = source.Replace("repeat: Loop", "repeat: Unknown") });+ var failed = Call(new { operation = "rebuild", sessionId });+ if (failed.GetProperty("success").GetBoolean()) throw new InvalidOperationException("Invalid Motion was admitted.");+ var located = failed.GetProperty("diagnostics").EnumerateArray().First(d => d.GetProperty("code").GetString() == "assembly-motion-repeat-invalid").GetProperty("source");+ if (located.GetProperty("line").GetInt32() <= 1 || located.GetProperty("start").GetInt32() != source.IndexOf("Motion Cycle", StringComparison.Ordinal))+ throw new InvalidOperationException("Motion source provenance was lost in the runtime projection.");+ var retained = Call(new { operation = "sampleMotion", sessionId, motion = "Cycle", timeSeconds = 1.25 });+ if (retained.GetProperty("revision").GetInt32() != model.GetProperty("revision").GetInt32()) throw new InvalidOperationException("Motion revision drift.");+ Call(new { operation = "disposeSession", sessionId });+ Console.WriteLine("PASS: native/runtime Motion parity at seven times; cached graph and last-valid revision retained.");+ return 0;+ }+}diff --git a/Aetheris.Web.Runtime/Program.cs b/Aetheris.Web.Runtime/Program.csindex df4d11d0..ebb91641 100644--- a/Aetheris.Web.Runtime/Program.cs+++ b/Aetheris.Web.Runtime/Program.cs@@ -64,6 +64,7 @@ public static partial class Program"describeConstruct" => DescribeConstruct(request),"rewriteField" => RewriteField(request),"snapshot" => Session(request).Snapshot,+ "sampleMotion" => Session(request).SampleMotion(request),"setProperty" => SetProperty(request),"setSource" => SetSource(request),"rebuild" => Rebuild(request),@@ -260,7 +261,7 @@ public static partial class Programstring? SourceRevision = null, int? Offset = null, string? ConstructSemanticId = null,string? FieldId = null, FirmamentProjectedValue? FieldValue = null, int? BuildRevision = null,bool Performance = false, IReadOnlyDictionary<string, string>? ProjectDocuments = null, string? ProjectRoot = null,- int? Bridge = null);+ int? Bridge = null, string? Motion = null, double? TimeSeconds = null, bool PreserveEndpoint = false);/// <summary>/// BUILD-PERF-M3 response bridge (request <c>bridge: 1</c>, sent by the SDK). Large numeric arrays@@ -293,7 +294,18 @@ public static partial class Programprivate readonly FirmamentCompilationSession _compilationSession = new();private readonly FirmamentSceneSession _sceneSession = new();private AssemblyCompilationReuse? _lastReuse;- public void Dispose() { _compilationSession.Dispose(); _sceneSession.Dispose(); }+ private AssemblyIr? _assembly;+ private AssemblyIr? _pendingAssembly;+ public void Dispose() { _assembly = null; _pendingAssembly = null; _compilationSession.Dispose(); _sceneSession.Dispose(); }+ internal object SampleMotion(WebRequest request)+ {+ if (_assembly is null || request.Motion is null || request.TimeSeconds is null)+ throw new WebRuntimeException("assembly-motion-query-required", "sampleMotion requires a compiled Assembly, Motion name and timeSeconds.");+ var pose = AssemblyMotion.Evaluate(_assembly, request.Motion, request.TimeSeconds.Value, request.PreserveEndpoint);+ if (!pose.IsSuccess) throw new WebRuntimeException(pose.Diagnostics[0].Code, pose.Diagnostics[0].Message);+ return new { revision = Revision, motion = request.Motion, timeSeconds = request.TimeSeconds, state = pose.State,+ transforms = pose.Instances.Select(i => new { id = i.StableId, matrix = i.ResolvedTransform!.Matrix }).ToArray() };+ }private IReadOnlyList<WebProperty> _properties = [];private IReadOnlyList<FirmamentConstructProjection> _projections = [];private readonly Dictionary<string, WebPropertyValue> _overrides = new(StringComparer.Ordinal);@@ -394,6 +406,7 @@ public static partial class PrograminspectPhase.Dispose();var effective = ApplyOverrides(_source, sourceProperties, _overrides);_lastReuse = null;+ _pendingAssembly = null;var nextProperties = sourceProperties;foreach (var (propertyId, value) in _overrides){@@ -407,6 +420,7 @@ public static partial class Programreturn compiled with { Revision = Revision, RetainedPreviousGeometry = _lastSnapshot is not null };Revision++;+ _assembly = _pendingAssembly;_properties = nextProperties;_projections = compiled.Projections ?? [];_stepText = compiled.StepText;@@ -429,7 +443,9 @@ public static partial class Program{id = Id, name = Name, revision = Revision, source = _source, sourceName = _sourceName,tree = compiled.Tree, properties = _properties, mesh = compiled.Mesh,- diagnostics = compiled.Diagnostics, changes, timings+ diagnostics = compiled.Diagnostics, changes, timings,+ motions = (_assembly?.Motions ?? []).Select(m => new { m.Name, m.DurationSeconds, repeat = m.Repeat.ToString(),+ tracks = m.Tracks.Select(t => new { t.Name, t.MateStableId, t.JointName, valueDimension = t.Curve.ValueDimension.ToString() }) }).ToArray()};_currentDefinitions = compiled.Mesh is AssemblyDisplayMeshDocument document ? document.Definitions.Cast<object>().ToArray() : [];// The snapshot carries tree, mesh and entity ids; the response does not repeat them.@@ -524,7 +540,18 @@ public static partial class Program_lastReuse = compilation.Reuse;var compileMs = watch.Elapsed.TotalMilliseconds;if (!compilation.IsSuccess || compilation.Ir is null || compilation.Geometry is null)- return WebBuildResult.Failed(compilation.Diagnostics.Select(d => new WebDiagnostic(d.Severity == AssemblyDiagnosticSeverity.Error ? "error" : "warning", d.Code, d.Message, SourceRef(_sourceName, 0, effective.Length))).ToArray(), compileMs);+ return WebBuildResult.Failed(compilation.Diagnostics.Select(d => new WebDiagnostic(d.Severity == AssemblyDiagnosticSeverity.Error ? "error" : "warning", d.Code, d.Message,+ DiagnosticSource(d), d.LocationNote)).ToArray(), compileMs);+ WebSourceRef? DiagnosticSource(AssemblyDiagnostic diagnostic)+ {+ if (diagnostic.SourceSpan is not { } span) return null;+ var text = span.Source == _sourceName ? effective : _projectDocuments?.GetValueOrDefault(span.Source);+ if (text is null) return new(span.Source, 0, 0, span.Start, span.Length);+ var start = Math.Clamp(span.Start, 0, text.Length);+ var prefix = text.AsSpan(0, start);+ var line = 1; foreach (var character in prefix) if (character == '\n') line++;+ return new(span.Source, line, start - prefix.LastIndexOf('\n'), span.Start, span.Length);+ }var assemblyStepPhase = BuildPerfTrace.Phase("web.assembly-step-prepare");var step = AssemblyIrAp242Exporter.PrepareExport(compilation);assemblyStepPhase.Dispose();@@ -546,6 +573,7 @@ public static partial class Programvar children = nodes.Where(node => node.ParentId == compilation.Ir.RootInstanceStableId).Select(node => node.Id).ToArray();var root = new WebTreeNode(compilation.Ir.RootInstanceStableId, "Assembly", compilation.Ir.Name, null, children, true, SourceRef(_sourceName, 0, effective.Length));var tree = new { rootId = root.Id, nodes = nodes.Prepend(root).DistinctBy(node => node.Id).ToArray() };+ _pendingAssembly = compilation.Ir;return WebBuildResult.Passed(null, tree, mesh, nodes.Select(node => node.Id).Prepend(root.Id).Distinct().ToArray(), compileMs, meshMs) with { StepWriter = StepWriter };}diff --git a/Aetheris.Web.Runtime/sdk/README.md b/Aetheris.Web.Runtime/sdk/README.mdindex c9347638..378c5e06 100644--- a/Aetheris.Web.Runtime/sdk/README.md+++ b/Aetheris.Web.Runtime/sdk/README.md@@ -89,3 +89,13 @@ production preview retains its existing fingerprint cache policy.Shared Assembly/Scene face ranges carry BRep face IDs. A range without an ownedfeature semantic ID uses `semanticEntityId: null`; selection resolves through thepicked occurrence. This does not grant a source selector to a runtime-only face.+++Compiled Assembly snapshots include `motions`, with clip names, durations,+repeat modes and realized Mate targets. `await model.sampleMotion(name, seconds,+{ preserveEndpoint: false })` returns occurrence transforms and scalar joint+state at the current successful revision. Sampling uses the retained compiler+graph, reuses the existing mesh definitions, and does not rebuild geometry or+change the engineering STEP snapshot. Consumers own their playback clock and+apply the returned occurrence matrices. An unsuccessful source rebuild retains+the previous admitted graph together with the previous geometry.diff --git a/Aetheris.Web.Runtime/sdk/src/index.d.ts b/Aetheris.Web.Runtime/sdk/src/index.d.tsindex e38c1046..0a909332 100644--- a/Aetheris.Web.Runtime/sdk/src/index.d.ts+++ b/Aetheris.Web.Runtime/sdk/src/index.d.ts@@ -1,5 +1,5 @@export type DiagnosticSeverity = 'info' | 'warning' | 'error';-export type Unit = 'mm' | 'cm' | 'm' | 'deg' | 'rad';+export type Unit = 'mm' | 'cm' | 'm' | 'deg' | 'rad' | 's' | 'ms';export interface SourceReference { readonly source: string; readonly line: number; readonly column: number; readonly start: number; readonly length: number }export interface Diagnostic { readonly severity: DiagnosticSeverity; readonly code: string; readonly message: string; readonly source?: SourceReference; readonly details?: string }export interface UnitValue { readonly value: number; readonly unit: Unit }@@ -64,7 +64,11 @@ export class Aetheris {dispose(): Promise<void>;terminate(): void;}+export interface MotionClip { readonly name: string; readonly durationSeconds: number; readonly repeat: 'Once' | 'Loop'; readonly tracks: readonly { readonly name: string; readonly mateStableId: string; readonly jointName: string; readonly valueDimension: 'Angle' | 'Length' }[] }+export interface MotionPose { readonly revision: number; readonly motion: string; readonly timeSeconds: number; readonly state: Readonly<Record<string, number>>; readonly transforms: readonly { readonly id: string; readonly matrix: readonly number[] | Float64Array }[] }export class ModelSession {+ readonly motions: readonly MotionClip[];+ sampleMotion(motion: string, timeSeconds: number, options?: OperationOptions & { readonly preserveEndpoint?: boolean }): Promise<MotionPose>;readonly id: string; readonly name: string; readonly revision: number; readonly source: string; readonly sourceName: string;readonly tree: ModelTree; readonly properties: readonly EditableProperty[]; readonly mesh: DisplayMesh; readonly diagnostics: readonly Diagnostic[]; readonly changes: ChangeSet;readonly timings?: { readonly compileMilliseconds: number; readonly meshMilliseconds?: number; readonly totalBeforeSnapshotMilliseconds?: number; readonly profile?: { readonly phases: readonly { readonly name: string; readonly inclusiveMilliseconds: number; readonly exclusiveMilliseconds: number; readonly allocatedBytes: number }[]; readonly counts: Readonly<Record<string, number>>; readonly gc0: number; readonly gc1: number; readonly gc2: number } };diff --git a/Aetheris.Web.Runtime/sdk/src/index.js b/Aetheris.Web.Runtime/sdk/src/index.jsindex 23ab8289..ffabefa1 100644--- a/Aetheris.Web.Runtime/sdk/src/index.js+++ b/Aetheris.Web.Runtime/sdk/src/index.js@@ -162,6 +162,14 @@ export class ModelSession {async setSource(source, options = {}) {return this.serial(async () => { throwIfAborted(options.signal); await this.transport.request({ operation: 'setSource', sessionId: this.id, source, sourceName: options.sourceName, sourceRevision: options.sourceRevision, projectDocuments: options.projectDocuments }); return this.rebuild(options); });}+ async sampleMotion(motion, timeSeconds, options = {}) {+ return this.serial(async () => {+ throwIfAborted(options.signal);+ const pose = await this.transport.request({ operation: 'sampleMotion', sessionId: this.id, motion, timeSeconds, preserveEndpoint: options.preserveEndpoint === true });+ if (pose.revision !== this.revision) throw new AetherisError('motion-revision-mismatch', 'The sampled Motion belongs to a different build revision.');+ return pose;+ });+ }async describeConstruct(semanticId, options = {}) {throwIfAborted(options.signal);return this.transport.request({ operation: 'describeConstruct', sessionId: this.id, constructSemanticId: semanticId });diff --git a/Aetheris.Web.Runtime/sdk/tests/bridge.test.mjs b/Aetheris.Web.Runtime/sdk/tests/bridge.test.mjsindex d61b681d..b63232da 100644--- a/Aetheris.Web.Runtime/sdk/tests/bridge.test.mjs+++ b/Aetheris.Web.Runtime/sdk/tests/bridge.test.mjs@@ -48,3 +48,21 @@ test('a retained definition the session does not hold is an error, not a silentassert.throws(() => session.apply({ revision: 2, mesh: { definitions: [{ id: 'missing', identity: 'missing', retained: true }], occurrences: [] } }),error => error.code === 'retained-definition-missing');});+++test('Motion sampling uses the cached runtime graph without replacing shared meshes', async () => {+ const requests = [];+ const mesh = { definitions: [], occurrences: [] };+ const transport = { async request(request) {+ requests.push(request);+ return { revision: 3, motion: request.motion, timeSeconds: request.timeSeconds, state: { Shaft: 450 }, transforms: [] };+ } };+ const session = new ModelSession(transport, { id: 'model-1', revision: 3, mesh, motions: [] });+ const pose = await session.sampleMotion('Cycle', 1.25);+ assert.equal(pose.state.Shaft, 450);+ assert.equal(session.mesh, mesh);+ assert.equal(requests.length, 1);+ assert.equal(requests[0].operation, 'sampleMotion');+ transport.request = async () => ({ revision: 2 });+ await assert.rejects(session.sampleMotion('Cycle', 1), error => error.code === 'motion-revision-mismatch');+});diff --git a/docs/development/architecture/FIRMAMENT-V8-RELATIONS-AND-MOTION-PROPOSAL.md b/docs/development/architecture/FIRMAMENT-V8-RELATIONS-AND-MOTION-PROPOSAL.mdnew file mode 100644index 00000000..cee80208--- /dev/null+++ b/docs/development/architecture/FIRMAMENT-V8-RELATIONS-AND-MOTION-PROPOSAL.md@@ -0,0 +1,407 @@+# Firmament V8: shared datums, articulated assemblies and keyframes++Date: 2026-10-16. Status: **approved design; partially implemented in the production compiler**.+Reviewed checkout: `9cf7b4af`.++## Decision++Represent the engine as reusable components connected to shared design datums,+with motion expressed through typed joint coordinates and finite keyframe curves.+The compiler derives dependent poses. Authors do not supply rod/piston rest+coordinates, trigonometric basis components or per-Part animation matrices.++Keep the existing Part/Subassembly/Assembly/Scene hierarchy, Inventory Records,+Concept Structs, Interfaces, Mates and finite Patterns. Extend their current AST+and semantic owners. Do not introduce a V8 parser, a second assembly solver or a+general simulation language.++This is one production refactoring pass, implemented in dependency order. It is+not another shadow-only milestone. The examples below are proposed design+fragments, not complete programs that current Firmament accepts.++## What the current source actually does++The current project already uses one CylinderUnit template and one keyed Pattern+for eight occurrences. The old eight-file duplication is gone. The remaining+friction is elsewhere:++| Evidence | Consequence |+| --- | --- |+| `assemblies/cylinder.firmament`: 74 lines, 19 Mate declarations and five stack Interfaces | The piston, wrist pin, lugs, valve stem and retainers are seated independently rather than moving as complete rigid components. |+| `rest-configurations.firmament` and `CylinderRest` | Source carries precomputed rod coordinates, sine/cosine values, piston position, valve lift and spring pitch. These are derived mechanism state, not independent design inputs. |+| `engine.firmasm` and `assemblies/crankshaft.firmament` | Common bank/shaft frames are partially present, but repeated bases such as `0.7071067811865476` still leak into placement declarations. |+| `EngineProject.Create` | C# serializes derived rest values back into Firmament using round-trip numeric spelling. |+| `EngineMotion.cs` and `web/engine-motion.mjs` | The demo classifies and animates individual Parts outside the authored joint graph. The two adapters share primitive motion laws but retain V8-specific transform logic. |+| Current `asm inspect` result | 193 occurrences: 171 Parts and 22 Assembly nodes. Twelve joints, all Fixed; no Revolute or Prismatic joints. |+| `AssemblyM0Parser` reusable-definition admission | Internal Revolute frame placement is explicitly rejected with `assembly-axis-internal-motion-unsupported`: reusable children are currently rigid. |+| `AssemblyM0Compiler` / `AssemblyKinematics` | Ordinary joints form a directed placement graph; unresolved kinematic cycles are rejected. A slider-crank needs an explicitly admitted closure relation. |++The 41 Firmament-family files contain 976 lines. Line count alone is not the+acceptance metric: meaningful geometry declarations should remain. The target is+removing duplicated placement and motion authority.++Read-only reproduction:++```powershell+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll asm inspect fixtures/Canonical/EditableV8/engine.firmasm --json --out artifacts/local/v8-declarative-proposal/current-assembly.json+```++This inspection succeeded without diagnostics. It is current-state evidence, not+qualification of the proposed features. The demo generator was not run and no+source or geometry was regenerated during this design pass.++## 1. Shared assembly scaffolding++The engine should own one Concept Struct containing its shaft frame, bank frames,+deck planes, cam frames and keyed cylinder installation frames. Components keep+their intrinsic local datums and publish meaningful ports. Do not make a reusable+component capture an enclosing assembly's names implicitly.++Extend derived DatumFrame authoring to use the existing frame-composition+semantics directly:++```firmament+Concept Struct EngineLayout {+ DatumFrame Shaft { from: World }+ DatumFrame RightBank {+ from: Shaft+ rotateLocal: { axis: Z; angle: -45deg }+ }+ DatumFrame LeftBank {+ from: Shaft+ rotateLocal: { axis: Z; angle: 45deg }+ }+ DatumFrame RightCam {+ from: RightBank+ translateLocal: [0mm, d.camHeight, d.camStation]+ }+}+```++This example assumes local +Y is the bore direction and +Z the shaft direction.+Under right-handed rotation, rotating +Y toward +X uses -45deg about +Z. The+actual migration must account for the current first-main-journal origin and its+shaft station; the sketch is not permission to move that origin.++Translations are expressed in the referenced `from` frame, consistent with+current FrameTransform behavior. A rotation does not silently rotate a sibling+translation. When radial placement needs the rotated basis, derive the bank or+throw frame first, then place relative to it. Planes can reference these frames;+a Plane alone does not define an in-plane origin and clocking for a rigid body.++Extend the existing finite Pattern owner to produce datum families inside Concept+Structs. Explicit keyed addressing should connect the datum and occurrence+families without constructing path strings:++```firmament+Concept Struct EngineLayout {+ // Shaft, RightBank and LeftBank declarations precede this fragment.+ Pattern CylinderSeats over cylinderSites {+ (key, site) => DatumFrame Mount {+ from: site.bank+ translateLocal: [0mm, 0mm, site.station]+ }+ }+}+```++The matching occurrence Pattern consumes `EngineLayout.CylinderSeats[key].Mount`.+The two-name binding exposes the existing Set key separately from its row. It is+an extension of finite Pattern binding, not a new loop executor. Typed keyed+addressing must retain stable identities under Set reordering.++Record/Set fields that carry a bank datum or actual journal must bind typed+semantic references, not strings or copied matrices. Reuse the existing+structural Concept contracts to describe a journal port's Axis/Frame/Dimension+requirements. Preserve the real Part-owned journal diameter and the existing fit+checks. An assembly datum is not a replacement for physical geometry authority.++## 2. Assemble complete rigid components++Introduce no new rigid-group keyword. Use existing Subassemblies:++- Piston assembly: crown, skirt, lugs and wrist pin; one public pin/mount contract.+- Valve assembly: valve, stem and retainer; one guide coordinate for the complete+ moving component. Intake and exhaust reuse a definition where geometry permits.+- Crank throw: paired pin and two webs; a keyed Pattern places four complete+ throws by station and angle. Main journals use their own finite row Pattern.+- Cylinder unit: fixed sleeve/head, piston assembly, rod, two valve assemblies+ and two springs.++Fixed component offsets are declared once, against their defining local datums.+The engine still owns the bank and installation layout. Each moving component+has one pose authority; its rigid children inherit that pose.++Split geometry inputs from installation/motion inputs. A cylinder's bank,+journal reference and firing phase should not specialize its geometry template.+The eight installation rows should retain meaningful choices such as bank,+station, actual journal and ignition angle. Remove `rodX`, `rodY`, `rodSin`,+`rodCos`, `pistonY`, precomputed lift and precomputed pitch from author input.++Use one typed EngineSpec for independent engineering dimensions. Derived values+such as crank radius, deck height and the crank-web envelope should remain+checked expressions in their defining owner. A JSON/CLI adapter may still supply+the independent specification; it must not generate a second rest-pose program.+Qualify any missing bounded math intrinsic through the existing typed value+owner, rather than adding another expression evaluator or rounding the result.++## 3. Articulated Subassemblies and public relation ports++This is the main IR change, not syntax sugar. Reusable definitions must retain+their local joint/relation graph as well as their static geometry and zero frames.+Instancing creates independently keyed joint state and bindings for each+occurrence, while immutable geometry and relation definitions remain shared.++Extend Expose to publish typed Interface contracts and realized Mate channels.+A reusable Interface may bind its local roles and leave explicitly required+external roles for its parent to realize. For example, a CylinderUnit publishes+its slider-crank contract with local rod/piston/guide participants already bound;+the parent supplies the actual crankpin:++```firmament+Pattern Cylinders over cylinderSites {+ (key, site) => {+ <Assembly Cylinder = Units.cylinder<spec: cylinderSpec>></Assembly>+ // Existing Fixed seating installs Cylinder.Mount at the matching+ // EngineLayout.CylinderSeats[key].Mount datum.+ Mate Drive: Cylinder.Drive { crankPin: site.journal }+ }+}+```++`Cylinder.Drive` is a proposed exported relationship contract, not a private child+path. The Mate completes one realization; it must not create a second placement+driver for the same mechanism. Required external roles can remain open only in a+reusable definition. Building an occurrence with an unbound role fails.++The same boundary exposes named joint coordinates such as `Intake.translation`.+Animation targets the realized Mate instance's stable ID, never a shared+Interface definition name or an ambiguous leaf name. Repeated cylinders own+independent channels even when they reuse one relationship definition.++Pose evaluation must propagate a moving parent's transform through rigid+descendants before a dependent joint or closure reads their ports. In particular,+a crankpin nested inside a rotating crankshaft cannot be read at its old rest+world position. Evaluation is a dependency graph over occurrence frames and+relation outputs, not a late pass that overwrites world matrices.++## 4. Kinematic mates, including bounded closure++Retain Fixed, Revolute and Prismatic. Add a bounded `Interface<SliderCrank>` family+whose Mate binds actual ports:++```firmament+Interface<SliderCrank> PistonDrive {}+Mate Stroke: PistonDrive {+ crankPin: Crankshaft.Pin1+ rodBigEnd: Rod.BigEnd+ rodSmallEnd: Rod.SmallEnd+ sliderPin: Piston.Pin+ guide: Layout.Bore+ branch: Extended+}+```++This is a one-cylinder fragment; the reusable version binds local roles inside+CylinderUnit and receives the crankpin through its public contract.++Reuse `Core.Mechanisms.SliderCrank` as the analytical authority. Derive the crank+radius and rod center distance from checked published ports/dimensions; do not+ask authors to repeat geometry as an unrelated motion specification. Admit the+current in-line geometry and its explicit Extended branch. Validate compatible+axes, guide alignment, axial seating and the domain `L > r > 0`. Other mechanisms+and branches remain rejected until deliberately qualified.++The crank rotation is an independent coordinate. Rod orientation and slider+position are outputs of this relation. Do not independently keyframe the piston+and then hope its wrist pin still meets the rod.++Retain ordinary cycle rejection. A SliderCrank is one admitted closure node with+known inputs, outputs and residual checks; enabling it is not permission to+remove `assembly-kinematic-loop-unsupported` for arbitrary cycles.++Cam rotation uses the existing prescribed 1:2 angular relationship. A proposed+typed `drive` field on a realized Mate may derive its free coordinate, for+example `drive: Crank.angle / 2`. This is a prescribed ratio, not a claim that+physical timing gears or cam contact were modeled.++## 5. Declarative keyframes++Add `Motion`, `Track`, `Keyframe` and reusable `Keyframes<Domain, Value>` values.+They share one typed curve/interpolation owner. Add Time with seconds and+milliseconds to the existing units/binding system rather than parsing time as an+untyped Float special case.++```firmament+Motion FourStroke {+ duration: 2s+ repeat: Loop+ Track CrankRotation {+ target: Engine.Crank.angle+ interpolation: Linear+ Keyframe Start { at: 0s; value: 0deg }+ Keyframe Finish { at: 2s; value: 720deg }+ }+}+```++`Engine.Crank` denotes a realized Revolute Mate, not a mesh or Interface type.+Two authored keys drive the whole mechanism. Playback rate changes how the+consumer advances clip time; it does not change geometry or the motion law.++A valve lift profile is keyed by crank phase, not by a second independent clock:++```firmament+Keyframes<Angle, Length> IntakeLift {+ period: 720deg+ interpolation: Cosine+ Keyframe Rest { at: 0deg; value: 0mm }+ Keyframe Opening { at: 360deg; value: 0mm }+ Keyframe Peak { at: 450deg; value: 9mm }+ Keyframe Closing { at: 540deg; value: 0mm }+ Keyframe CycleEnd { at: 720deg; value: 0mm }+}+```++Two half-cosine segments through 0 → lift → 0 reproduce the current sin² lift law+mathematically. Equal-valued intervals remain constant. Exhaust uses its existing+180deg opening; per-cylinder ignition offset comes from meaningful firing data.+Do not replace the current law with unspecified smooth interpolation.++A Track can reference a reusable profile with `values: IntakeLift` and+`input: Crank.angle - site.ignition`, targeting the exposed valve translation.+Its sign follows the declared guide axis; the current outward-positive guide+requires negative translation for inward valve lift. Motion-scope Patterns reuse+the same finite keyed expansion to bind the two valve channels for each cylinder.++Rules:++- Track domains are Time or Angle in the first pass; values are typed Angle or+ Length. Inline time keys infer their value type from the target joint.+- Interpolation is explicit: Linear, Hold or Cosine initially. No implicit cubic+ overshoot, arbitrary runtime callbacks or per-frame source evaluation.+- Preserve unwrapped angles: 0deg → 720deg is two revolutions, not identity and+ not a shortest-path quaternion interpolation.+- Loop wraps clip time. Preserve the final authored key for endpoint sampling;+ validate continuity of the physical pose and dependent channels at the seam.+ Unwrapped angular endpoint values may differ by complete turns.+- Key domains are checked, finite, ordered and unique. Periodic profiles include+ their domain endpoints explicitly. Profile input wraps by its declared period.+- One active writer per independent coordinate. A Track, Mate drive expression+ and closure cannot simultaneously own the same output. Fixed coordinates and+ closure outputs are not writable animation targets.+- Scrubbing in arbitrary order must give the same pose. No accumulated matrix+ updates or previous-frame solver state.++## 6. Springs need a separate, explicit deformation relation++The current viewer compresses a WireForm coil along its published winding axis.+A Prismatic joint can move a spring but cannot change its length. Do not conceal+that difference behind a rigid pose transform.++Propose a bounded `Interface<AxialSpring>` relation binding the actual Winding,+fixed seat and moving retainer seat. It derives compression from those ports,+retains the fixed seat, and uses the existing qualified axis-aware presentation+deformation. Free length, turn count and clear diameter belong to the spring's+published geometry, not another V8-specific manifest table.++At a baked engineering pose, specialize the existing WireForm using the derived+pitch and materialize a real coil. In particular, phase zero already contains+compressed springs in the current engine: replacing them with free coils would+change the existing STEP geometry. A visual scale is not an exact posed STEP.+If exact pose baking for a requested deformation is unavailable, report that+boundary instead of exporting undeformed geometry as if it matched the pose.++No spring force, stress, contact or dynamics is implied. This family is an+explicit prescribed geometric/presentation relation.++## 7. One compiled authority, multiple consumers++Compile the new syntax through the unified AST into typed datum, joint, closure+and Motion IR. Retain source spans, definition/occurrence identities and a finite+dependency graph. Reuse the existing kinematic and mechanism owners, extending+their graph admission; no source-text motion expansion or regex dispatch.++Default/rest pose is a named deterministic query of this graph. It replaces the+current author-supplied CylinderRest table. Generated matrices and sampled curves+are legitimate artifacts; they should not become authoring source again.++Native CLI and the browser's existing WASM runtime evaluate the same compiled+graph. The viewer owns its clock, scrubbing and drawing, not a switch over V8+Part kinds. Load/cache the compiled graph once; do not parse or rebuild BRep every+frame. Retire demo-specific transform/binding logic only after parity is proven.++STEP exports a selected static pose, with real geometry for any baked deformation.+USD uses existing joint/state sample support with an explicit seconds-to-timecode+conversion. GLB animation, when emitted, must retain intermediate rotations so+two endpoint quaternions cannot erase a 720deg turn. If an output cannot retain+the motion contract, diagnose it or export an explicitly selected static pose.++This remains compile-time Firmament authoring that emits static geometry and a+finite animation description. Playback evaluates a bounded artifact; Firmament+does not become a general runtime or a dynamics simulator.++## Implementation order and acceptance++1. Qualify shared derived frames and typed keyed datum references. Refactor bank,+ crank throw and cam placement against the existing rest-pose geometry.+2. Retain articulated local graphs in reusable definitions and bind public+ Interface/Mate ports per occurrence. Qualify parent/child pose propagation.+3. Admit the bounded SliderCrank and axial spring relations through the current+ engineering owners, with closure residuals and exact default-pose baking.+4. Add typed keyframes and one coordinate-driver graph. Connect existing native,+ WASM and export consumers to it; remove V8-specific animation ownership.+5. Re-author V8 around the shared layout, rigid components and meaningful keyed+ cylinder data; update syntax.md only for syntax that actually passes production+ admission. Keep this proposal separate from the accepted-language tutorial.++Completion requires real production-path evidence:++- One reusable CylinderUnit source instantiated eight times; no authored+ CylinderRest data, basis sine/cosine literals or per-Part motion bindings.+- All 171 physical Parts accounted for. Additional rigid grouping may change+ Assembly-node counts and paths; explicitly map those hierarchy changes.+- Preserve each Part's engineering geometry, world placement at the current+ default pose, fits, spring winding axes and explicit PMI/provenance. Compare+ definition geometry and posed bounds/topology; do not demand a byte-identical+ whole-assembly STEP after an intentional product-tree change.+- Derive dimensions from authored inputs rather than round-trip G17 literals.+ Do not globally round geometry, change tolerances or hide classified numerical+ differences behind a widened test threshold.+- Sweep the existing baseline and +6mm-stroke variant through 0–720deg at the+ established 1deg stations. Preserve rod closure, firing TDC, valve timing,+ spring seat/axis checks and the existing bounded clearance checks.+- Check non-key times, reverse/random scrubbing, loop endpoints, nested moving+ parents and independent state for repeated cylinder occurrences.+- Reject conflicting writers, missing roles, unit errors, unsupported mechanism+ geometry and arbitrary cycles with precise source diagnostics.+- Qualify native/WASM pose agreement and actual browser playback, plus exact+ default/selected-pose STEP and the advertised animation export paths.+- Run focused checks and the complete serial .NET regression, then recheck+ canonical assemblies. Preserve shared definitions and reap task runtime hosts.++The practical target is one shared engine layout, four crank-throw rows, eight+cylinder installation/firing rows, one reusable articulated cylinder, and one+keyframed crank driver. Rod/piston positions, cam rotation, valve motion and+spring compression follow declared relationships. No line-reduction percentage+or general collision certification is promised before implementation.++## Original design-pass outcome++**Success as a design pass:** current source and production inspection identify+the actual friction and the missing owners. This document makes the language and+IR decisions concrete. No compiler, model, geometry or motion implementation was+changed. No .NET build/test qualification of proposed syntax is claimed.+++## Implementation checkpoint++Shared derived frames, articulated local joint retention, moving exposed+geometric ports, typed finite clips and cached native/WASM sampling now have+production implementations. Syntax admitted by this checkpoint is documented in+`docs/public/firmament/syntax.md`; the rest of this design remains proposed.+The V8's common cam datums use the shared-frame path. Its closed mechanism,+external Interface roles and exact spring deformation have not migrated.+See `docs/release/FIRMAMENT-V8-DECLARATIVE-MOTION.md` for qualification and the+specific remaining ownership boundary. This is not acceptance of the complete+V8 refactor described above.diff --git a/docs/public/firmament/assemblies.md b/docs/public/firmament/assemblies.mdindex 43cd19a8..6e8a8b0e 100644--- a/docs/public/firmament/assemblies.md+++ b/docs/public/firmament/assemblies.md@@ -134,3 +134,33 @@ Subassembly composition never exports a child STEP and imports it into its parenA capped, closed `SectionChain` or bounded `Loft<Hollow>` can serve as a ruled assembly part from a separate authored `.firmament` file. Write `<Part Shade = LoftFile<"lamp-shade-loft.firmament">>` (or `SectionChainFile` for a directly authored chain); the path is relative to the assembly source. Both use the SectionChain materializer, and assembly imports its AP242 body into the ordinary product tree. Open shells are rejected as part definitions. The [Cartesian lamp fixture](../../../fixtures/Canonical/ThreeDm/lamp-visible-intent.firmament) exercises this path with a tilted ruled shade.Legacy JSON `.firmasm` remains a compatibility/import lane. Canonical reusable semantic authoring uses `.firmament`; the compatibility format does not gain runtime inclusion or become the design authority.+++## Articulated definitions and finite clips++Reusable definitions preserve their solved zero frames and local joint graph.+Each occurrence receives its own realized Mate identity and qualified name;+geometry remains shared. Pose evaluation resolves both rigid ancestry and+kinematic dependencies before a dependent joint reads a published port. Exposed+ports retain the actual child occurrence rather than a frozen rest-frame copy.+Fixed local relationships remain Fixed and do not make a route-bound assembly+moving.++See [shared datums and motion syntax](syntax.md#shared-datums-and-articulated-motion)+and the executable [articulated assembly](../../../fixtures/Canonical/AssemblyInterfaces/articulated-subassemblies.firmament)+and [clip](../../../fixtures/Canonical/AssemblyInterfaces/articulated-motion.firmament).+`AssemblyMotion.Evaluate(ir, name, seconds, preserveEndpoint)` samples an admitted+clip; `AssemblyKinematics.Evaluate` remains the direct realized-Mate-state API.+A clip does not make arbitrary closed mechanical loops admissible.++Ordinary `Placement` keeps its exact frame dependency when its target moves.+It uses the same occurrence evaluator as the mechanical joints, but does not+create a physical Fixed joint in USD. An installation source mount on a reusable+Subassembly must remain rigid within that unit; using an internally moving port+as that mount rejects explicitly.++A reusable definition publishes a movable coordinate with+`expose { Mate Bend = Elbow; }`. Its parent can target `Unit.Bend.angle` or+`Unit.Travel.translation`, according to the actual Mate family. Wrappers can+re-export nested public channels. Private local Mate names remain developer+state-query names and do not bypass this Motion authoring boundary.diff --git a/docs/public/firmament/editable-mechanisms.md b/docs/public/firmament/editable-mechanisms.mdindex 5f166af6..62223ce1 100644--- a/docs/public/firmament/editable-mechanisms.md+++ b/docs/public/firmament/editable-mechanisms.md@@ -32,7 +32,9 @@ Edit a Part, Concept layout or unit directly and inspect the consuming root withAetheris.CLI. The paired demo workflow refreshes dimension/rest input data from`V8Spec`; it does not synthesize the product tree or geometry. Moving membershipchanges still require matching motion bindings and reject if a Part is missing or-unbound. Motion laws and animation syntax are a separate design pass.+unbound. The [shared-datum and declarative motion proposal](../../development/architecture/FIRMAMENT-V8-RELATIONS-AND-MOTION-PROPOSAL.md)+describes the next refactoring pass. Its Motion/keyframe syntax and articulated+Subassembly extensions are proposed, not currently admitted language features.## Build and revise@@ -122,3 +124,18 @@ dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll asm export-ap242 fixtures/Cdotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll scene export-glb fixtures/Canonical/EditableV8/scene.firmament artifacts/local/demos/editable-v8/engine.glb --json```+++## Declarative migration status++The V8's common Shaft, bank and cam frames now use derived DatumFrames. Cam+positions are expressed relative to a shared bank, with clocking restored at the+cam datum; the first-main-journal origin and existing engineering configuration+remain the qualification reference.++The compiler now retains articulated Subassembly graphs and admits typed Motion+clips through its ordinary Assembly path. See [syntax](syntax.md#shared-datums-and-articulated-motion).+The V8 has **not** switched to those clips yet: its SliderCrank closure, external+relation roles and axial spring baking still need compiler admission. Its+`CylinderRest` records and existing native/browser motion adapter remain active.+Do not infer full declarative V8 motion from the general rigid-joint witness.diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex 35578f9d..bd045e1c 100644--- a/docs/public/firmament/syntax.md+++ b/docs/public/firmament/syntax.md@@ -277,7 +277,7 @@ Model Product = Plate<width: 40mm, height: 20mm>with literal or checked scalar Static inputs. Defining a Concept alone imposesno check: `Concept AlwaysFalse => false` is a legal definition, but a Requirethat applies it fails. Definitions are type-checked even when unapplied.-Predicate parameters are scalar Length, Angle, Int, Float, Bool or String;+Predicate parameters are scalar Length, Angle, Time, Int, Float, Bool or String;positional and named calls are admitted. Pass Record scalar members as arguments.Concepts do not introduce runtime functions, implicit unit conversion, Recordparameters, arbitrary geometry queries or a general constraint solver. Toleranced@@ -822,6 +822,107 @@ use the typed families; use `Interface<Custom>` only when explicit atomicrelations are necessary. Unknown clauses, duplicate assignments and unresolvedroles reject rather than disappearing. See [Assemblies](assemblies.md).+## Shared datums and articulated motion++An assembly `Concept Struct` can publish derived three-dimensional frames. Use+`from`, `translateLocal` and `rotateLocal` rather than authoring trigonometric+basis components:++```firmament+Concept Struct Layout {+ DatumFrame Shaft { from: World; translateLocal: [3mm,4mm,5mm] }+ DatumFrame Bank { from: Shaft; rotateLocal: { axis: Z; angle: -45deg } }+ DatumFrame Cam { from: Bank; translateLocal: [0mm,100mm,20mm] }+}+```++A local name such as `Bank` resolves within this Concept Struct. A qualified+name can reference another declared datum. Translation is expressed in the+referenced frame. A sibling `rotateLocal` changes orientation without rotating+that translation; derive an intermediate frame when translation should follow+its rotated basis. Required lengths and angles are dimension checked. Unknown+fields, unresolved sources and datum cycles reject. The existing `DatumFrame`+form with `on`, `at` and `X` on a Plane remains supported.++Reusable Subassemblies retain their local Fixed, Revolute and Prismatic joint+graphs. Occurrences share geometry and own independent coordinates. Exposed+geometric ports follow their actual child occurrence when it moves. At the+compiler API boundary, a nested realized Mate is qualified by occurrence, for+example `Articulated.First.Elbow`; a root Mate keeps its declared name. Names in+motion source address those realized Mates, not the shared Interface type.+Reusable definitions publish their motion coordinates explicitly, for example+`expose { Mate Bend = Elbow; }`. A parent Track uses+`Articulated.First.Bend.angle`; the private local `Elbow` name is not a parent+Motion target. A wrapper can re-export a nested public channel with+`Mate Bend = Unit.Bend;`. These aliases retain the realized Mate's stable ID,+so two public aliases cannot become independent writers for one coordinate.++Declare `Motion` and reusable `Keyframes` in the root Assembly or its module:++```firmament+Motion Cycle {+ duration: 2s+ repeat: Loop+ Track Rotation {+ target: Machine.Crank.angle+ interpolation: Linear+ Keyframe Start { at: 0s; value: 0deg }+ Keyframe Finish { at: 2000ms; value: 720deg }+ }+}+```++This fragment requires an admitted Revolute Mate named `Crank` in `Machine`.+`Time` is a compile-time scalar with `s` and `ms`, normalized to seconds; it can+flow through checked Record fields. Time is distinct from Length and Angle.+A Revolute track writes `angle` in degrees; a Prismatic track writes+`translation` in millimetres. Angles remain unwrapped: 720deg means two turns.+Inline keys use Time, start at zero and end at the declared duration.++Reusable curves declare their domain and value dimensions explicitly:++```firmament+Keyframes<Angle,Length> Lift {+ period: 720deg+ interpolation: Cosine+ Keyframe Rest { at: 0deg; value: 0mm }+ Keyframe Open { at: 360deg; value: 0mm }+ Keyframe Peak { at: 450deg; value: 9mm }+ Keyframe Close { at: 540deg; value: 0mm }+ Keyframe End { at: 720deg; value: 0mm }+}+```++A Track can use `values: Lift` with `input: Machine.Crank.angle`. Input+expressions use the existing typed arithmetic owner; for example, negate the+input for a clockwise crank coordinate or divide an angular coordinate by two.+Reusable Time curves use clip time when input is omitted. Curve domains are+Time or Angle; values are Angle or Length. Interpolation is+explicitly Linear, Hold or Cosine. A periodic curve includes zero and period+keys with equal endpoint values. Without `period`, a curve holds its endpoint+values outside its key domain.++Keys must have unique names and strictly increasing finite domain values.+`repeat: Once` clamps clip time; `repeat: Loop` wraps it, including negative+scrub times, and requires matching physical poses at the clip seam. Compiler+sampling can preserve the final endpoint explicitly. Each independent Mate has+one Track writer per clip. Unknown targets, Fixed targets, conflicting writers,+incorrect dimensions and driver cycles reject with source diagnostics.+Sampling is stateless and retains shared geometry; it does not accumulate the+last frame's transforms.++The complete executable witness is+[`articulated-motion.firmament`](../../../fixtures/Canonical/AssemblyInterfaces/articulated-motion.firmament).+Inspect or sample it with `aetheris asm inspect` and+`aetheris asm motion <file> --clip Cycle --time 1.25 --json`.++These tracks prescribe admitted rigid joints. They do not yet admit SliderCrank+closure, deform a WireForm spring, export an open Interface contract from a+Subassembly, or create Motion-scoped Patterns. The editable V8 still uses its+existing qualified mechanism adapter for those relationships. A static STEP+export is the compiled engineering configuration; sampling a clip does not+silently replace it with a different posed artifact.+## Reading older sourceNew ordinary parts should use the forms at the top of this page. Historicaldiff --git a/docs/release/FIRMAMENT-V8-DECLARATIVE-MOTION.md b/docs/release/FIRMAMENT-V8-DECLARATIVE-MOTION.mdnew file mode 100644index 00000000..8f3329fd--- /dev/null+++ b/docs/release/FIRMAMENT-V8-DECLARATIVE-MOTION.md@@ -0,0 +1,151 @@+# V8 declarative assembly and motion implementation checkpoint++Date: 2026-10-16. Starting checkout: `9cf7b4af`.++## Verdict++**Meaningful progression.** Shared datum composition, articulated reusable+Subassemblies, moving exposed geometric ports and typed finite Motion clips now+run through the production compiler and occurrence evaluator. The complete V8+migration is not accepted: public external relationship roles, SliderCrank+closure and exact axial spring baking remain unimplemented. The V8 retains its+qualified mechanism adapter and authored rest configuration until those owners+are admitted together.++This is executable compiler work, not a shadow frontend. The approved broader+design is [the relations and motion proposal](../development/architecture/FIRMAMENT-V8-RELATIONS-AND-MOTION-PROPOSAL.md).++## Repairs and authority++- Derived assembly `DatumFrame` fields bind shared AST expressions and compose+ through the existing frame owner. `from`, `translateLocal` and `rotateLocal`+ eliminate authored basis constants for the V8's common bank/cam frames.+ Translation follows the referenced basis, independently of a sibling rotation.+ Existing Plane-relative `on`/`at`/`X` frames remain admitted.+- Reusable definitions retain their local joints alongside solved zero frames.+ Instancing rebases occurrence and semantic IDs; nested graphs are instantiated+ once, and each repeated occurrence owns independent realized Mate coordinates.+- Source mounting frames synthesized during local compilation remain available+ in the instantiated semantic tree. They are not dropped when solved placement+ replaces authored placement.+- One graph admission check covers joint drivers and rigid ancestry. Pose+ evaluation resolves both dependencies together rather than updating rigid+ descendants after all joints have already read their parents.+- Plain Placement retains a separate frame-dependency collection, consumed by+ the same pose evaluator and retained through instancing. A moving target+ therefore drives its relative placements, without exporting a fabricated+ physical Fixed joint.+- Exposed geometric semantics retain their actual internal occurrence. World+ queries and relationships from those ports follow its current pose. Fixed+ seating gap and clocking survive that rebinding.+- An internally moving public port cannot serve as the complete Subassembly's+ rigid installation mount. Both typed-Mate and Placement paths reject it with+ `assembly-kinematic-moving-mount-unsupported` instead of freezing its rest frame.+- Fixed local joints remain visible in IR. The route-binding guard now checks+ actual degrees of freedom, so retaining Fixed relationships does not+ incorrectly classify a static routed assembly as moving.+- Unsupported public Interface exports fail explicitly instead of being+ dropped by the legacy geometric exposure adapter. Realized Mate aliases are+ published explicitly and can be re-exported through nested Subassemblies. Unknown local datum sources+ also reject when the derived datum is unused.++`Time` joins the existing typed scalar and arithmetic owner. Seconds and+milliseconds normalize to seconds; existing enum ordinals remain unchanged.+Record-supplied durations use this binding path. Time cannot replace engineering+Length or Angle values.++`Motion`, `Track`, `Keyframe` and `Keyframes<Domain,Value>` bind the unified AST.+Domains are Time/Angle; values are Angle/Length. Curves admit explicit Linear,+Hold or Cosine interpolation. Angular values remain unwrapped. Periodic profiles+require explicit, matching endpoints; Loop clips also check physical pose+continuity. Input expressions reuse the existing typed expression evaluator.+Local templated Parts in Inventory modules now keep declaration identity separate+from invocation arguments, fixing doubled specializations during module binding.+The imported two-occurrence witness qualifies public channels and geometry sharing.++The compiler orders coordinate writers once; duplicate writers and dependency+cycles reject before sampling.++Motion targets resolve to actual Mate stable IDs, with qualified realized names+for repeated Subassemblies. Sampling is a pure time-to-state/pose query; it does+not rebuild BRep, mutate shared geometry or accumulate prior transforms. There+is no backend playback state machine to synchronize. Transport controls belong+to the consumer; adding an agent/state-machine dependency for the pure sampler+would add no authority.++## Consumers and diagnostics++`aetheris asm motion <file> --clip Cycle --time 1.25 --json` admits the real+assembly and samples its clip. Inspection includes compiled Motion metadata.+JSON diagnostics remain structured. Text diagnostics preserve file, source+extent, severity, code and explanation.++The existing web runtime retains the admitted Assembly IR per successful+session revision. The SDK's `model.sampleMotion` requests only occurrence+transforms and scalar joint state; meshes remain shared. Failed source rebuilds+retain the prior geometry and its matching graph. Disposal releases both.++Motion spans map through the existing syntax-origin and module-projection+owners. The SDK Assembly error projection preserves those file/span/line+locations instead of substituting the whole root document. Unknown provenance+is left unavailable rather than fabricated.++Motion sampling does not change the default engineering configuration or its+STEP export. This checkpoint does not advertise clip-to-STEP deformation baking,+USD clip timecode conversion, GLB animation baking or V8 browser migration.+Existing direct joint-state export APIs remain their current owners.++## Source witnesses++- `fixtures/Canonical/AssemblyInterfaces/derived-datum-frames.firmament`:+ a shared bank frame places a Cam at measurably oblique world coordinates.+- `articulated-subassemblies.firmament` in the same directory: repeated local+ joint graphs, a rigid intermediate node below a moving parent, and an external+ component following an exposed moving port.+- `articulated-motion.firmament`: a typed Record duration, unwrapped two-turn+ rotation, a dependent half-speed joint and a cosine lift profile.+- `fixtures/Regression/AssemblyMotion/slider-crank.pending.firmament`: an+ explicitly pending design witness, not a must-build regression. Current+ admission rejects its unimplemented Interface family.++Tests assert admission/rejection, actual world transforms, zero-pose parity,+shared definitions, arbitrary/reverse/non-key time queries, final endpoint+sampling, published-port behavior and source evidence. They do not only match+error sentences.++## Qualification++Evidence is generated under ignored `artifacts/local/`. Final results are+recorded below after qualification. No whole-V8 declarative-motion claim is+implied by successful rigid-joint clip qualification.++## Exact remaining ownership boundary++`AssemblyM0Parser.InstantiateAssemblyDefinition` still locally compiles a+reusable definition before its parent realizes it. Missing roles and unresolved+local placements therefore reject before a parent can supply an external+crankpin. The public exposure owner exports geometric semantics and dimensional+relations; it does not yet export a partially bound Interface contract with external+roles. Source-level aliases for already realized Mate channels are implemented.++The next implementation must retain that open, typed contract in the reusable+definition, instantiate its roles and driver identities per occurrence, then+complete it in the parent. Add SliderCrank as a bounded closure node using+`Core.Mechanisms.SliderCrank`, with actual port-derived geometry/domain checks.+Do not relax general cycle rejection or independently keyframe the piston.++`AssemblyM1Pipeline.CompileParsed` also currently materializes Part definitions+before engineering mate compilation. Exact default-pose spring baking needs a+bounded admission/materialization ordering that can derive its pitch first.++An axial spring also changes geometry, rather than just rigid occurrence pose.+Its selected/default engineering configuration must materialize the existing+WireForm with derived pitch. The already-compressed phase-zero coils cannot be+replaced by free coils or a scaled display mesh in STEP.++Once those owners exist, regroup piston/valve/crank-throw components, replace+CylinderRest and per-Part motion bindings, expand datum/Motion Patterns through+the existing finite owner, and qualify the baseline/+6mm-stroke sweeps and all+advertised exports. The current V8 source deliberately retains its working+mechanism adapter instead of presenting incomplete crank-only motion as a+complete engine.diff --git a/fixtures/Canonical/AssemblyInterfaces/articulated-module-motion.firmament b/fixtures/Canonical/AssemblyInterfaces/articulated-module-motion.firmamentnew file mode 100644index 00000000..be1c69a2--- /dev/null+++ b/fixtures/Canonical/AssemblyInterfaces/articulated-module-motion.firmament@@ -0,0 +1,30 @@+Inventory Record Units {+ arm: Subassembly = Firmament("articulated-subassemblies").Arm+}+Assembly ModularMotion {+ <Assembly ModularMotion>+ <Assembly First = Units.arm>+ Placement { from: Mount; to: World; }+ </Assembly>+ <Assembly Second = Units.arm>+ Placement { from: Mount; to: World; translateLocal: [100mm,0mm,0mm]; }+ </Assembly>+ </Assembly>+ anchor: ModularMotion;+}+Motion Cycle {+ duration: 1s+ repeat: Loop+ Track First {+ target: ModularMotion.First.Bend.angle+ interpolation: Linear+ Keyframe Start { at: 0s; value: 0deg }+ Keyframe End { at: 1s; value: 360deg }+ }+ Track Second {+ target: ModularMotion.Second.Bend.angle+ interpolation: Linear+ Keyframe Start { at: 0s; value: 0deg }+ Keyframe End { at: 1s; value: -720deg }+ }+}diff --git a/fixtures/Canonical/AssemblyInterfaces/articulated-motion.firmament b/fixtures/Canonical/AssemblyInterfaces/articulated-motion.firmamentnew file mode 100644index 00000000..baf98ee2--- /dev/null+++ b/fixtures/Canonical/AssemblyInterfaces/articulated-motion.firmament@@ -0,0 +1,29 @@+include "articulated-subassemblies";+Record Playback { duration: Time }+Static playback: Playback = Playback { duration: 2000ms }+Keyframes<Angle,Length> Lift {+ period: 720deg+ interpolation: Cosine+ Keyframe Rest { at: 0deg; value: 0mm }+ Keyframe Open { at: 360deg; value: 0mm }+ Keyframe Peak { at: 450deg; value: 9mm }+ Keyframe Close { at: 540deg; value: 0mm }+ Keyframe End { at: 720deg; value: 0mm }+}+Keyframes<Angle,Angle> HalfSpeed {+ interpolation: Linear+ Keyframe Start { at: 0deg; value: 0deg }+ Keyframe End { at: 720deg; value: 360deg }+}+Motion Cycle {+ duration: playback.duration+ repeat: Loop+ Track Shaft {+ target: Articulated.Shoulder.angle+ interpolation: Linear+ Keyframe Start { at: 0s; value: 0deg }+ Keyframe End { at: 2000ms; value: 720deg }+ }+ Track Bend { target: Articulated.First.Bend.angle; values: HalfSpeed; input: Articulated.Shoulder.angle }+ Track Valve { target: Articulated.Slide.translation; values: Lift; input: Articulated.Shoulder.angle }+}diff --git a/fixtures/Canonical/AssemblyInterfaces/articulated-subassemblies.firmament b/fixtures/Canonical/AssemblyInterfaces/articulated-subassemblies.firmamentnew file mode 100644index 00000000..f7d047b9--- /dev/null+++ b/fixtures/Canonical/AssemblyInterfaces/articulated-subassemblies.firmament@@ -0,0 +1,35 @@+// Two independent occurrences share geometry and a local joint graph.+Template<H: Length> Struct Link {+ Circle2 C { center: [0mm,0mm]; radius: 1mm }+ Profile P { Loop Outer { C |> TraceLoop } }+ Extrude Body { profile: P; from: 0mm; to: H }+ Expose { Semantic Pivot { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; } }+}+Subassembly Arm {+ <Assembly Arm>+ <Part Base = Link<H:2mm>></Part>+ <Assembly Rigid>+ Placement { from: Origin; to: Arm.Base.Pivot.Frame; translateLocal: [20mm,0mm,0mm]; }+ Semantic Tip { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }+ </Assembly>+ <Part Tip = Link<H:4mm>></Part>+ </Assembly>+ anchor: Arm.Base.Pivot;+ Interface<Revolute> Elbow { A: Arm.Rigid.Tip.Frame; B: Arm.Tip.Pivot.Frame; }+ Expose { DatumFrame Mount = Base.Pivot.Frame; DatumFrame Tool = Tip.Pivot.Frame; Mate Bend = Elbow; }+}+Assembly Articulated {+ <Assembly Articulated>+ Semantic Root { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }+ <Assembly First = Arm></Assembly>+ <Part Slider = Link<H:4mm>></Part>+ <Part Follower = Link<H:4mm>></Part>+ <Assembly Second = Arm>+ Placement { from: Mount; to: World; translateLocal: [100mm,0mm,0mm]; }+ </Assembly>+ </Assembly>+ anchor: Articulated;+ Interface<Prismatic> Slide { A: Articulated.Root.Frame; B: Articulated.Slider.Pivot.Frame; }+ Interface<Fixed> Follow { A: Articulated.First.Tool; B: Articulated.Follower.Pivot.Frame; }+ Interface<Revolute> Shoulder { A: Articulated.Root.Frame; B: Articulated.First.Mount; }+}diff --git a/fixtures/Canonical/AssemblyInterfaces/derived-datum-frames.firmament b/fixtures/Canonical/AssemblyInterfaces/derived-datum-frames.firmamentnew file mode 100644index 00000000..8d95797f--- /dev/null+++ b/fixtures/Canonical/AssemblyInterfaces/derived-datum-frames.firmament@@ -0,0 +1,17 @@+Concept Struct Layout {+ DatumFrame Shaft { from: World; translateLocal: [3mm,4mm,5mm] }+ DatumFrame Bank { from: Shaft; rotateLocal: { axis: Z; angle: -45deg } }+ DatumFrame Cam { from: Bank; translateLocal: [0mm,100mm,20mm]; rotateLocal: { axis: Z; angle: 45deg } }+}+Template<H:Length> Struct Pin {+ Circle2 C { center: [0mm,0mm]; radius: 1mm }+ Profile P { Loop Outer { C |> TraceLoop } }+ Extrude Body { profile: P; from: 0mm; to: H }+ Expose { Semantic Mount { Axis Axis = [0,0,0] -> [0,0,1]; DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; } }+}+Assembly SharedFrames {+ <Assembly SharedFrames><Part Cam = Pin<H:4mm>></Part></Assembly>+ Interface<Fixed> CamSeat { datum: Layout.Cam; members: [SharedFrames.Cam.Mount] }+ Mate Install: CamSeat { member: SharedFrames.Cam.Mount; at: 0mm; clocking: 0deg }+ anchor: SharedFrames;+}diff --git a/fixtures/Canonical/AssemblyInterfaces/relative-moving-frames.firmament b/fixtures/Canonical/AssemblyInterfaces/relative-moving-frames.firmamentnew file mode 100644index 00000000..accc05dd--- /dev/null+++ b/fixtures/Canonical/AssemblyInterfaces/relative-moving-frames.firmament@@ -0,0 +1,24 @@+Template<H:Length> Struct Link {+ Circle2 C { center: [0mm,0mm]; radius: 1mm }+ Profile P { Loop Outer { C |> TraceLoop } }+ Extrude Body { profile: P; from: 0mm; to: H }+}+Assembly RelativeFrames {+ <Assembly RelativeFrames>+ Semantic Ground { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }+ <Part Rotor = Link<H:4mm>>+ Semantic Input { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }+ Semantic Output { DatumFrame Frame = [20,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }+ </Part>+ <Part Rigid = Link<H:4mm>>+ Placement { from: Origin; to: RelativeFrames.Rotor.Output.Frame; }+ Semantic Output { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }+ </Part>+ <Part Tip = Link<H:4mm>>+ Semantic Input { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }+ </Part>+ </Assembly>+ Interface<Revolute> Base { A: RelativeFrames.Ground.Frame; B: RelativeFrames.Rotor.Input.Frame; }+ Interface<Revolute> Elbow { A: RelativeFrames.Rigid.Output.Frame; B: RelativeFrames.Tip.Input.Frame; }+ anchor: RelativeFrames;+}diff --git a/fixtures/Canonical/EditableV8/engine.firmasm b/fixtures/Canonical/EditableV8/engine.firmasmindex 6167c27f..cdf1b55c 100644--- a/fixtures/Canonical/EditableV8/engine.firmasm+++ b/fixtures/Canonical/EditableV8/engine.firmasm@@ -12,9 +12,19 @@ Inventory Record Units {}Concept Struct EngineLayout {- Axis Shaft { origin: [0mm,0mm,d.cylinderSpacing / 2]; direction: [0,0,1]; reference: [1,0,0]; }- Axis RightCam { origin: [0.7071067811865475 * d.camHeight,0.7071067811865476 * d.camHeight,2 * d.cylinderSpacing]; direction: [0,0,1]; reference: [1,0,0]; }- Axis LeftCam { origin: [-0.7071067811865475 * d.camHeight,0.7071067811865476 * d.camHeight,2 * d.cylinderSpacing]; direction: [0,0,1]; reference: [1,0,0]; }+ DatumFrame Shaft { from: World; translateLocal: [0mm,0mm,d.cylinderSpacing / 2] }+ DatumFrame RightBank { from: World; rotateLocal: { axis: Z; angle: -45deg } }+ DatumFrame LeftBank { from: World; rotateLocal: { axis: Z; angle: 45deg } }+ DatumFrame RightCam {+ from: RightBank+ translateLocal: [0mm,d.camHeight,2 * d.cylinderSpacing]+ rotateLocal: { axis: Z; angle: 45deg }+ }+ DatumFrame LeftCam {+ from: LeftBank+ translateLocal: [0mm,d.camHeight,2 * d.cylinderSpacing]+ rotateLocal: { axis: Z; angle: -45deg }+ }}// Product ownership is separate from the prescribed analytical motion.Assembly EditableV8 {diff --git a/fixtures/Regression/AssemblyMotion/README.md b/fixtures/Regression/AssemblyMotion/README.mdnew file mode 100644index 00000000..28690fb8--- /dev/null+++ b/fixtures/Regression/AssemblyMotion/README.md@@ -0,0 +1,14 @@+# Articulated motion boundary++`slider-crank.pending.firmament` preserves an approved design fragment that is+not yet admitted. Current parsing rejects `Interface<SliderCrank>` with+`assembly-interface-family-invalid`. This is an explicit missing capability,+not an accepted geometry regression or a source spelling to work around.++The implemented rigid-joint and typed-curve witnesses live under+`fixtures/Canonical/AssemblyInterfaces/articulated-*.firmament` and+`derived-datum-frames.firmament`.++The pending witness becomes a positive qualification specimen when the bounded+closure owner and its actual port/domain checks are implemented. It does not+justify relaxing ordinary kinematic cycle rejection.diff --git a/fixtures/Regression/AssemblyMotion/slider-crank.pending.firmament b/fixtures/Regression/AssemblyMotion/slider-crank.pending.firmamentnew file mode 100644index 00000000..ea22b1d1--- /dev/null+++ b/fixtures/Regression/AssemblyMotion/slider-crank.pending.firmament@@ -0,0 +1,27 @@+// Approved design witness; currently rejected, not a canonical must-build case.+// The next owner is bounded closure admission and public external-role binding.+Assembly PendingSliderCrank {+ <Assembly PendingSliderCrank>+ Semantic Guide { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }+ <Part Crank = Panel<L:10mm,W:5mm,H:2mm,R:0mm>>+ Semantic Pin { DatumFrame Frame = [0,44,0] x [1,0,0] y [0,1,0] z [0,0,1]; }+ </Part>+ <Part Rod = Panel<L:145mm,W:5mm,H:2mm,R:0mm>>+ Semantic BigEnd { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }+ Semantic SmallEnd { DatumFrame Frame = [0,145,0] x [1,0,0] y [0,1,0] z [0,0,1]; }+ </Part>+ <Part Slider = Panel<L:10mm,W:5mm,H:2mm,R:0mm>>+ Semantic Pin { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }+ </Part>+ </Assembly>+ Interface<SliderCrank> Drive {}+ Mate Stroke: Drive {+ crankPin: PendingSliderCrank.Crank.Pin+ rodBigEnd: PendingSliderCrank.Rod.BigEnd+ rodSmallEnd: PendingSliderCrank.Rod.SmallEnd+ sliderPin: PendingSliderCrank.Slider.Pin+ guide: PendingSliderCrank.Guide+ branch: Extended+ }+ anchor: PendingSliderCrank;+}diff --git a/scripts/qualify-assembly-motion-browser.mts b/scripts/qualify-assembly-motion-browser.mtsnew file mode 100644index 00000000..e321b9ef--- /dev/null+++ b/scripts/qualify-assembly-motion-browser.mts@@ -0,0 +1,81 @@+import { createServer } from 'node:http';+import { readFile, mkdir, writeFile } from 'node:fs/promises';+import { execFileSync } from 'node:child_process';+import { resolve, extname, sep } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';++// Bounded integration harness: real CLI oracle, public SDK, real WASM, headless+// Edge. The ephemeral static fixture server and browser close in finally.+const repo = resolve(fileURLToPath(new URL('..', import.meta.url)));+const modulePath = process.argv[2];+if (!modulePath) throw new Error('Pass an explicit Playwright module path.');+const { chromium } = await import(pathToFileURL(resolve(modulePath)).href);+const fixture = resolve(repo, 'fixtures/Canonical/AssemblyInterfaces/articulated-motion.firmament');+const source = await readFile(resolve(repo, 'fixtures/Canonical/AssemblyInterfaces/articulated-subassemblies.firmament'), 'utf8')+ + '\n' + (await readFile(fixture, 'utf8')).split('\n').filter(line => !line.startsWith('include ')).join('\n');+const times = [0, 1.25, .231, 1.749, 2, -.75, 3.25];+const expected = times.map(time => JSON.parse(execFileSync('dotnet', [resolve(repo, 'Aetheris.CLI/bin/Release/net10.0/aetheris.dll'),+ 'asm', 'motion', fixture, '--clip', 'Cycle', '--time', String(time), '--json'], { cwd: repo, encoding: 'utf8', maxBuffer: 8 * 1024 * 1024 })));+const server = createServer(async (request, response) => {+ try {+ const url = new URL(request.url!, 'http://localhost');+ if (url.pathname === '/') { response.setHeader('Content-Type', 'text/html'); response.end('<!doctype html><title>Assembly Motion qualification</title>'); return; }+ const file = resolve(repo, '.' + decodeURIComponent(url.pathname));+ if (!file.startsWith(repo + sep)) throw new Error('outside repository');+ const bytes = await readFile(file);+ const types: Record<string, string> = { '.js': 'text/javascript', '.mjs': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm' };+ response.setHeader('Content-Type', types[extname(file)] ?? 'application/octet-stream');+ response.setHeader('Cache-Control', 'no-store');+ response.end(bytes);+ } catch { response.statusCode = 404; response.end('not found'); }+});+await new Promise<void>(done => server.listen(0, '127.0.0.1', done));+const address = server.address();+if (!address || typeof address === 'string') throw new Error('no port');+let browser;+try {+ browser = await chromium.launch({ executablePath: 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', headless: true });+ const page = await browser.newPage();+ await page.goto(`http://127.0.0.1:${address.port}/`);+ const result = await page.evaluate(async ({ source, times, expected }) => {+ const { Aetheris } = await import('/Aetheris.Web.Runtime/sdk/src/index.js');+ const cad = await Aetheris.create({ wasmUrl: new URL('/Aetheris.Web.Runtime/bin/Release/net10.0/wwwroot/', location.href) });+ try {+ const built = await cad.compile(source, { sourceName: 'motion.firmament' });+ const model = built.model;+ if (!model) throw new Error(JSON.stringify(built.diagnostics));+ if (model.motions.length !== 1) throw new Error('Missing compiled clip');+ const definitions = model.mesh.definitions;+ let maximum = 0; let compared = 0;+ for (let index = 0; index < times.length; index++) {+ const pose = await model.sampleMotion('Cycle', times[index]);+ const native = new Map(expected[index].transforms.map((t: { id: string; matrix: number[] }) => [t.id, t.matrix]));+ for (const actual of pose.transforms) {+ const matrix = native.get(actual.id) as number[] | undefined;+ if (!matrix) throw new Error('Unknown occurrence ' + actual.id);+ actual.matrix.forEach((v: number, i: number) => { maximum = Math.max(maximum, Math.abs(v - matrix[i])); compared++; });+ }+ if (model.mesh.definitions !== definitions) throw new Error('Sampling rebuilt shared geometry');+ }+ if (maximum > 1e-9) throw new Error('Native/WASM pose mismatch ' + maximum);+ const endpoint = await model.sampleMotion('Cycle', 2, { preserveEndpoint: true });+ if (endpoint.state.Shoulder !== 720 || endpoint.state['Articulated.First.Elbow'] !== 360)+ throw new Error('Unwrapped final endpoint was lost');+ const revision = model.revision;+ const edited = await model.setSource(source.replace('repeat: Loop', 'repeat: Unknown'));+ if (edited.success) throw new Error('Invalid Motion admitted');+ const retained = await model.sampleMotion('Cycle', 1.25);+ if (retained.revision !== revision) throw new Error('Last-valid graph revision changed');+ await model.dispose();+ return { status: 'pass', runtime: 'real browser WASM via public SDK', samples: times.length, compared, maximumError: maximum,+ sharedDefinitionsRetained: true, lastValidGraphRetained: true };+ } finally { await cad.dispose(); }+ }, { source, times, expected });+ const output = resolve(repo, 'artifacts/local/v8-relations');+ await mkdir(output, { recursive: true });+ await writeFile(resolve(output, 'motion-browser.json'), JSON.stringify(result, null, 2));+ console.log(JSON.stringify(result));+} finally {+ await browser?.close();+ await new Promise<void>((done, reject) => server.close(error => error ? reject(error) : done()));+}