Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add semantic workflow templates for scenes and assemblies
Yuechen Li476f64da211b
diff --git a/Aetheris.CLI.Tests/GarmentCommandTests.cs b/Aetheris.CLI.Tests/GarmentCommandTests.csindex 3b915cc6..5ab1b815 100644--- a/Aetheris.CLI.Tests/GarmentCommandTests.cs+++ b/Aetheris.CLI.Tests/GarmentCommandTests.cs@@ -4,6 +4,134 @@ namespace Aetheris.CLI.Tests;public sealed class GarmentCommandTests{+ [Fact]+ public void FittingBuildExportsCompiledCommandsWithoutMaterializingConceptGeometry()+ {+ var root = new DirectoryInfo(AppContext.BaseDirectory);+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx")))+ {+ root = root.Parent;+ }+ string input = Path.Combine(root!.FullName, "fixtures/Canonical/Garment/temporary-fitting.firmament");+ string output = Path.Combine(root.FullName, "artifacts/local/tests/garment", Guid.NewGuid().ToString("N"));+ var stdout = new StringWriter();+ var stderr = new StringWriter();+ int code = CliRunner.Run(["garment", "build", input, "--out-dir", output, "--json"], stdout, stderr);+ Assert.Equal(0, code);+ using var evidence = JsonDocument.Parse(stdout.ToString());+ var document = evidence.RootElement;+ Assert.Equal(0, document.GetProperty("pins").GetInt32());+ Assert.Equal(1, document.GetProperty("panels").GetArrayLength());+ var guide = Assert.Single(document.GetProperty("fittingGuides").EnumerateArray());+ Assert.Equal("guides.collarFloor", guide.GetProperty("conceptPlane").GetString());+ Assert.Equal(1, guide.GetProperty("offset").GetSingle());+ Assert.Equal(5, guide.GetProperty("releaseAfter").GetInt32());+ Assert.Equal(JsonValueKind.Null, document.GetProperty("drape").ValueKind);+ Assert.DoesNotContain("collarFloor", File.ReadAllText(Path.Combine(output, "garment.obj")));+ Assert.DoesNotContain("collarFloor", File.ReadAllText(Path.Combine(output, "garment.usda")));+ }++ [Theory]+ [InlineData("--substeps", "0")]+ [InlineData("--substeps", "65")]+ [InlineData("--iterations", "0")]+ [InlineData("--iterations", "65")]+ public void InvalidSolverBudgetsStopBeforeReadingInput(string option, string value)+ {+ var stderr = new StringWriter();+ Assert.Equal(1, CliRunner.Run(["garment", "drape", "missing.firmament", option, value], new StringWriter(), stderr));+ Assert.Contains("Unknown or incomplete garment option", stderr.ToString());+ }++ [Theory]+ [InlineData("--substeps", "8")]+ [InlineData("--iterations", "24")]+ [InlineData("--until-settled", null)]+ public void SolverOptionsCannotSilentlyAffectBuildOrPreview(string option, string? value)+ {+ foreach (string operation in new[] { "build", "preview", "inspect", "pose" })+ {+ var args = new List<string> { "garment", operation, "missing.firmament", option };+ if (value is not null)+ {+ args.Add(value);+ }+ var stderr = new StringWriter();+ Assert.Equal(1, CliRunner.Run(args.ToArray(), new StringWriter(), stderr));+ Assert.Contains("Solver and settling options belong to garment drape", stderr.ToString());+ }+ }++ [Fact]+ public void GarmentCodeImportWritesEditablePatternsAndInvalidInputWritesNothing()+ {+ var root = new DirectoryInfo(AppContext.BaseDirectory);+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx")))+ {+ root = root.Parent;+ }+ Assert.NotNull(root);+ string input = Path.Combine(root!.FullName, "fixtures/Canonical/Garment/GarmentCode/dress.json");+ string output = Path.Combine(root.FullName, "artifacts/local/tests/garment", Guid.NewGuid().ToString("N"));+ string original = File.ReadAllText(input);+ var stdout = new StringWriter();+ var stderr = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["garment", "import-garmentcode", input, "--out-dir", output, "--json"], stdout, stderr));+ using var evidence = JsonDocument.Parse(stdout.ToString());+ Assert.False(evidence.RootElement.GetProperty("simulated").GetBoolean());+ Assert.False(evidence.RootElement.GetProperty("meshed").GetBoolean());+ Assert.Equal(4, evidence.RootElement.GetProperty("panels").GetArrayLength());+ Assert.Equal(original, File.ReadAllText(Path.Combine(output, "specification.json")));+ string source = Path.Combine(output, "garment.firmament");+ Assert.Equal(0, CliRunner.Run(["garment", "build", source, "--out-dir", Path.Combine(output, "build"), "--json"],+ new StringWriter(), stderr));+ string invalidInput = Path.Combine(output, "invalid.json");+ File.WriteAllText(invalidInput, "{}");+ string rejected = Path.Combine(output, "rejected");+ Assert.Equal(1, CliRunner.Run(["garment", "import-garmentcode", invalidInput, "--out-dir", rejected, "--json"],+ new StringWriter(), stderr));+ Assert.False(Directory.Exists(rejected));+ Assert.Equal(original, File.ReadAllText(input));+ }++ [Fact]+ public void PoseCommandExportsWithoutMeshingAndPreservesBodyIdentity()+ {+ var root = new DirectoryInfo(AppContext.BaseDirectory);+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx")))+ {+ root = root.Parent;+ }+ Assert.NotNull(root);+ string directory = Path.Combine(root!.FullName, "artifacts/local/tests/garment", Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(directory);+ string sourcePath = Path.Combine(directory, "pose.firmament");+ string bodyPath = Path.Combine(directory, "body.json");+ string output = Path.Combine(directory, "posed");+ File.WriteAllText(sourcePath, "Pose fitting { figure: Anatolia; from: TPose; }");+ var canonical = Aetheris.Humanoid.HumanoidRestPoseNormalizer.Normalize(Aetheris.Humanoid.CanonicalAdultTemplate.Create());+ Aetheris.Humanoid.HumanoidGameplayBody.Save(new(Aetheris.Humanoid.HumanoidGameplayBody.Schema,+ "cli-test-body", canonical.Surface, canonical.Skeleton, [], canonical.Provenance), bodyPath);+ byte[] original = File.ReadAllBytes(bodyPath);+ var stdout = new StringWriter();+ var stderr = new StringWriter();+ int code = CliRunner.Run(["garment", "pose", sourcePath, "--body", bodyPath, "--pose", "fitting",+ "--out-dir", output, "--json"], stdout, stderr);+ Assert.True(code is 0 or 2, stderr.ToString());+ using var report = JsonDocument.Parse(stdout.ToString());+ Assert.Equal(report.RootElement.GetProperty("success").GetBoolean() ? 0 : 2, code);+ Assert.False(report.RootElement.GetProperty("simulated").GetBoolean());+ Assert.Equal(canonical.Skeleton.RestPoseId, report.RootElement.GetProperty("restPoseId").GetString());+ Assert.Equal("cli-test-body", report.RootElement.GetProperty("id").GetString());+ Assert.Equal(["body.obj", "evidence.json"], Directory.GetFiles(output).Select(Path.GetFileName).Order());+ Assert.Equal(original, File.ReadAllBytes(bodyPath));+ var body = Aetheris.Humanoid.HumanoidGameplayBody.Load(bodyPath);+ var recipe = Aetheris.Kernel.Firmament.Humanoid.HumanoidPoseAuthoring.Parse(File.ReadAllText(sourcePath)).Poses["fitting"];+ var solved = Aetheris.Kernel.Firmament.Humanoid.HumanoidPoseAuthoring.Solve(recipe, body);+ Assert.Equal(Aetheris.Kernel.Firmament.Garment.GarmentExport.BodyObj(body, body.EvaluatePositions(solved)),+ File.ReadAllText(Path.Combine(output, "body.obj")));+ }+[Fact]public void RealSchemaRoutesThroughValidateInspectBuildAndLanguageFormatting(){@@ -26,10 +154,20 @@ public sealed class GarmentCommandTests}var buildOutput = new StringWriter();var errors = new StringWriter();+ string previewDirectory = Path.Combine(output, "preview");+ var previewOutput = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["garment", "preview", input, "--out-dir", previewDirectory, "--json"], previewOutput, errors));+ Assert.Equal(["evidence.json", "patterns.svg"], Directory.GetFiles(previewDirectory).Select(Path.GetFileName).Order());+ using var preview = JsonDocument.Parse(previewOutput.ToString());+ Assert.False(preview.RootElement.GetProperty("meshed").GetBoolean());+ Assert.False(preview.RootElement.GetProperty("simulated").GetBoolean());Assert.True(CliRunner.Run(["garment", "build", input, "--out-dir", output, "--json"], buildOutput, errors) == 0, errors.ToString());foreach (string file in new[] { "garment.json", "garment.obj", "garment.usda", "patterns.svg", "evidence.json" })Assert.True(new FileInfo(Path.Combine(output, file)).Length > 0, file);using var artifact = JsonDocument.Parse(File.ReadAllText(Path.Combine(output, "garment.json")));+ using var buildEvidence = JsonDocument.Parse(buildOutput.ToString());+ Assert.Equal(0, buildEvidence.RootElement.GetProperty("meshQuality").GetProperty("unreferencedVertices").GetInt32());+ Assert.True(buildEvidence.RootElement.GetProperty("meshQuality").GetProperty("minimumEdgeLength").GetDouble() > 0);Assert.Equal("aetheris.garment.v1", artifact.RootElement.GetProperty("schema").GetString());Assert.NotEqual(0, CliRunner.Run(["build", input], new StringWriter(), errors));Assert.Contains("garment-step-export-unsupported", errors.ToString());diff --git a/Aetheris.CLI/GarmentCommand.cs b/Aetheris.CLI/GarmentCommand.csindex ec9af2ee..9fcd9855 100644--- a/Aetheris.CLI/GarmentCommand.cs+++ b/Aetheris.CLI/GarmentCommand.cs@@ -3,12 +3,13 @@ using System.Text;using System.Text.Json;using Aetheris.Humanoid;using Aetheris.Kernel.Firmament.Garment;+using Aetheris.Kernel.Firmament.Humanoid;namespace Aetheris.CLI;internal static class GarmentCommand{- internal const string Usage = "aetheris garment <inspect|build|drape> <garment.firmament> [--body gameplay-body.json] [--ticks 1..600] [--out-dir directory] [--json]";+ internal const string Usage = "aetheris garment <pose|preview|inspect|build|drape> <garment.firmament> [--body gameplay-body.json] [--figure Anatolia] [--pose namedPose] [--ticks 1..600] [--substeps 1..64] [--iterations 1..64] [--until-settled] [--out-dir directory] [--json]\naetheris garment import-garmentcode <specification.json> [--out-dir directory] [--json]";internal static int Run(string[] args, TextWriter stdout, TextWriter stderr){@@ -19,28 +20,129 @@ internal static class GarmentCommand}try{- if (args.Length < 2 || args[0] is not ("inspect" or "build" or "drape")) throw new ArgumentException(Usage);+ if (args[0] == "import-garmentcode")+ {+ return ImportGarmentCode(args, stdout, stderr);+ }+ if (args.Length < 2 || args[0] is not ("pose" or "preview" or "inspect" or "build" or "drape")) throw new ArgumentException(Usage);string operation = args[0];string input = Path.GetFullPath(args[1]);bool json = false;string? bodyPath = null;string? outputDirectory = null;+ string figureName = "Anatolia";+ string? poseName = null;int ticks = 60;+ var drapeSettings = new GarmentDrapeSettings();+ bool drapeOptions = false;for (int i = 2; i < args.Length; i++){switch (args[i]){case "--json": json = true; break;case "--body" when i + 1 < args.Length: bodyPath = Path.GetFullPath(args[++i]); break;+ case "--figure" when i + 1 < args.Length: figureName = args[++i]; break;+ case "--pose" when i + 1 < args.Length: poseName = args[++i]; break;case "--out-dir" when i + 1 < args.Length: outputDirectory = Path.GetFullPath(args[++i]); break;case "--ticks" when i + 1 < args.Length && int.TryParse(args[++i], out ticks) && ticks is >= 1 and <= 600: break;+ case "--substeps" when i + 1 < args.Length && int.TryParse(args[++i], out int substeps) && substeps is >= 1 and <= 64:+ drapeSettings = drapeSettings with { Substeps = substeps };+ drapeOptions = true;+ break;+ case "--iterations" when i + 1 < args.Length && int.TryParse(args[++i], out int iterations) && iterations is >= 1 and <= 64:+ drapeSettings = drapeSettings with { Iterations = iterations };+ drapeOptions = true;+ break;+ case "--until-settled":+ drapeSettings = drapeSettings with { StopWhenSettled = true };+ drapeOptions = true;+ break;default: throw new ArgumentException("Unknown or incomplete garment option: " + args[i]);}}- if (operation != "drape" && (bodyPath is not null || ticks != 60)) throw new ArgumentException("--body and --ticks belong to garment drape.");+ if (operation != "drape" && ticks != 60) throw new ArgumentException("--ticks belongs to garment drape.");+ if (operation != "drape" && drapeOptions) throw new ArgumentException("Solver and settling options belong to garment drape.");if (operation == "inspect" && outputDirectory is not null) throw new ArgumentException("inspect does not write output.");+ if (operation != "pose" && poseName is not null)+ {+ throw new ArgumentException("--pose belongs to garment pose; drape selects its pose in Firmament.");+ }var watch = Stopwatch.StartNew();- var compiled = GarmentCompiler.Compile(File.ReadAllText(input), input);+ string source = File.ReadAllText(input);+ HumanoidGameplayBody? body = bodyPath is null ? null : HumanoidGameplayBody.Load(bodyPath);+ GarmentFigureBinding? binding = body is null ? null : new(figureName, body,+ Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(bodyPath!))));+ if (operation == "pose")+ {+ if (body is null || poseName is null)+ {+ throw new ArgumentException("garment pose requires --body and --pose.");+ }+ var document = HumanoidPoseAuthoring.Parse(source);+ var recipe = document.Resolve(poseName, figureName);+ var solved = HumanoidPoseAuthoring.Solve(recipe, body);+ var surface = body.Evaluate(solved);+ outputDirectory ??= Path.GetFullPath(Path.Combine("artifacts", "local", "garment", Path.GetFileNameWithoutExtension(input), "poses", poseName));+ if (new[] { "body.obj", "evidence.json" }.Any(name => Path.Combine(outputDirectory, name).Equals(input, StringComparison.OrdinalIgnoreCase)+ || Path.Combine(outputDirectory, name).Equals(bodyPath, StringComparison.OrdinalIgnoreCase)))+ {+ throw new ArgumentException("Pose output must not replace an input artifact.");+ }+ Directory.CreateDirectory(outputDirectory);+ Write("body.obj", GarmentExport.BodyObj(body, surface.Positions));+ string poseEvidence = JsonSerializer.Serialize(new+ {+ success = surface.Evidence.IsAdmissible,+ stage = "posed-figure",+ body.Id,+ body.Skeleton.SkeletonId,+ body.Skeleton.RestPoseId,+ bodyArtifactHash = binding!.ArtifactHash,+ sourceHash = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(source))),+ recipe,+ solved.SemanticResiduals,+ surface = surface.Evidence,+ outputDirectory,+ simulated = false,+ }, CliRunner.JsonOptions);+ Write("evidence.json", poseEvidence);+ stdout.WriteLine(poseEvidence);+ return surface.Evidence.IsAdmissible ? 0 : 2;+ }+ if (operation == "preview")+ {+ var parsed = GarmentAuthoring.Parse(source, input, binding);+ if (!parsed.IsSuccess)+ {+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = false, domain = "Garment", diagnostics = parsed.Diagnostics }, CliRunner.JsonOptions));+ else foreach (var diagnostic in parsed.Diagnostics) stderr.WriteLine(diagnostic.Code + ": " + diagnostic.Message);+ return 1;+ }+ outputDirectory ??= Path.GetFullPath(Path.Combine("artifacts", "local", "garment", Path.GetFileNameWithoutExtension(input), "preview"));+ if (new[] { "patterns.svg", "evidence.json" }.Any(name => Path.Combine(outputDirectory, name).Equals(input, StringComparison.OrdinalIgnoreCase)+ || Path.Combine(outputDirectory, name).Equals(bodyPath, StringComparison.OrdinalIgnoreCase)))+ {+ throw new ArgumentException("Garment output must not replace an input artifact.");+ }+ Directory.CreateDirectory(outputDirectory);+ Write("patterns.svg", GarmentPatternPreview.Svg(parsed.Source!));+ string previewEvidence = JsonSerializer.Serialize(new+ {+ success = true,+ domain = "Garment",+ stage = "resolved-patterns",+ parsed.Source!.SourceHash,+ figureFits = parsed.Source.FigureFits,+ seams = GarmentPatternInspection.Inspect(parsed.Source),+ outputDirectory,+ meshed = false,+ simulated = false,+ }, CliRunner.JsonOptions);+ Write("evidence.json", previewEvidence);+ stdout.WriteLine(json ? previewEvidence : "Pattern preview: " + Path.Combine(outputDirectory, "patterns.svg"));+ return 0;+ }+ var compiled = GarmentCompiler.Compile(source, input, binding);if (!compiled.IsSuccess){if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = false, domain = "Garment", diagnostics = compiled.Diagnostics }, CliRunner.JsonOptions));@@ -49,17 +151,18 @@ internal static class GarmentCommand}var garment = compiled.Garment!;GarmentDrapeResult? drape = null;- HumanoidGameplayBody? body = null;if (operation == "drape"){if (bodyPath is null) throw new ArgumentException("garment-body-required: Bind the declared figure with --body gameplay-body.json.");- body = HumanoidGameplayBody.Load(bodyPath);- drape = GarmentDraping.Settle(garment, body, ticks);+ drape = GarmentDraping.Settle(garment, body!, ticks, progress => stderr.WriteLine(+ FormattableString.Invariant($"garment {progress.Phase}: {progress.Completed}/{progress.Total} ({progress.ElapsedSeconds:F1}s)")), drapeSettings);}if (operation != "inspect"){outputDirectory ??= Path.GetFullPath(Path.Combine("artifacts", "local", "garment", Path.GetFileNameWithoutExtension(input)));- string[] names = ["garment.json", "garment.obj", "garment.usda", "patterns.svg", "body.obj", "evidence.json"];+ string[] names = ["garment.json", "garment.obj", "garment.usda", "patterns.svg", "body.obj", "evidence.json",+ "guided-garment.obj", "guided-body.obj",+ "fitting-garment.obj", "fitting-body.obj", "midway-garment.obj", "midway-body.obj", "wearing-garment.obj", "wearing-body.obj"];if (names.Select(name => Path.Combine(outputDirectory, name)).Any(path => path.Equals(input, StringComparison.OrdinalIgnoreCase)|| path.Equals(bodyPath, StringComparison.OrdinalIgnoreCase))){@@ -70,11 +173,35 @@ internal static class GarmentCommandWrite("garment.obj", GarmentExport.Obj(garment, drape?.Snapshot));Write("garment.usda", GarmentExport.Usd(garment, drape?.Snapshot));Write("patterns.svg", GarmentExport.PatternsSvg(garment));- if (body is not null) Write("body.obj", GarmentExport.BodyObj(body));+ foreach (var checkpoint in drape?.FittingCheckpoints ?? [])+ {+ Write(checkpoint.Name + "-garment.obj", GarmentExport.Obj(garment, checkpoint.Snapshot));+ }+ if (body is not null)+ {+ var positions = drape?.BodyPositions;+ if (positions is null && garment.Source.Pose is not null && garment.Source.Pose != "Rest")+ {+ var recipe = garment.Source.Posing!.Resolve(garment.Source.Pose, garment.Source.Figure!);+ positions = body.EvaluatePositions(HumanoidPoseAuthoring.Solve(recipe, body));+ }+ Write("body.obj", GarmentExport.BodyObj(body, positions));+ foreach (var frame in drape?.Frames ?? [])+ {+ Write(frame.Name + "-garment.obj", GarmentExport.Obj(garment, frame.Snapshot));+ Write(frame.Name + "-body.obj", GarmentExport.BodyObj(body, frame.BodyPositions));+ }+ foreach (var checkpoint in drape?.FittingCheckpoints ?? [])+ {+ Write(checkpoint.Name + "-body.obj", GarmentExport.BodyObj(body, checkpoint.BodyPositions));+ }+ }}- bool qualified = drape is null || (drape.Metrics.Finite && drape.ReplayExact- && drape.MaximumSeamGap <= .01f && drape.Metrics.MaximumSurfacePenetration <= .005f- && drape.Metrics.MaximumStretch <= .15f);+ bool qualified = drape is null || (drape.ReplayExact && drape.TransitionReplayExact+ && drape.GuidesReleased+ && GarmentDrapeLimits.Accept(drape.Metrics, drape.MaximumSeamGap)+ && drape.Frames.All(frame => frame.BodyEvidence.IsAdmissible+ && GarmentDrapeLimits.Accept(frame.Metrics, frame.MaximumSeamGap)));var report = new{success = qualified,@@ -86,15 +213,35 @@ internal static class GarmentCommandupAxis = "Z",vertices = garment.Cloth.Definition.Positions.Length,triangles = garment.Cloth.Definition.Indices.Length / 3,+ meshQuality = GarmentMeshInspection.Measure(garment),pins = garment.Cloth.Definition.Pins.Length,seamConstraints = garment.Cloth.Definition.Stitches.Length,panels = garment.Panels.Select(panel => new { panel.Identity, panel.VertexCount, edges = panel.Edges.Keys }),features = garment.Source.Features,+ figureFits = garment.Source.FigureFits,+ fittingGuides = garment.FittingGuides.Select(guide => new+ {+ guide.ConceptPlane,+ guide.ReleaseAfter,+ guide.Constraint.Id,+ guide.Constraint.Vertices,+ normal = new[] { guide.Constraint.Normal.X, guide.Constraint.Normal.Y, guide.Constraint.Normal.Z },+ guide.Constraint.Offset,+ guide.Constraint.Compliance,+ }),+ posing = garment.Source.Posing,+ transition = garment.Source.Transition,patterns = garment.Source.Patterns,drape = drape is null ? null : new{settleTicks = ticks,sewingTicks = 30,+ drape.CompletedSettlingTicks,+ drape.StopReason,+ drape.Settings,+ drape.Samples,+ drape.GuidesReleased,+ fittingCheckpoints = drape.FittingCheckpoints.Select(checkpoint => new { checkpoint.Name, checkpoint.Snapshot.Tick }),snapshotTick = drape.Snapshot.Tick,bodyArtifactHash = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(bodyPath!))),drape.BodyId,@@ -103,10 +250,23 @@ internal static class GarmentCommanddrape.MaximumSeamGap,drape.Metrics,drape.ReplayExact,+ drape.TransitionReplayExact,+ drape.MaximumBodySubstepTravel,+ frames = drape.Frames.Select(frame => new+ {+ frame.Name,+ frame.MotionSeconds,+ tick = frame.Snapshot.Tick,+ frame.Metrics,+ frame.MaximumSeamGap,+ frame.BodyEvidence,+ frame.Joints,+ }),drape.ContactOutliers,+ drape.SurfaceContactOutliers,drape.StretchOutliers,qualification = qualified ? "passed" : "failed; inspect the retained geometry and metrics",- limits = new[] { "Static Rest pose", "Explicit authored supports", "Discrete oriented body contact", "No CCD, friction or garment self-contact", "CPU body-contact backend" },+ limits = new[] { "Authored one-way body poses", "Explicit authored supports", "Discrete oriented body contact", "No CCD, friction or garment self-contact", "CPU body-contact backend", "Checkpoint qualification does not certify every intermediate surface" },},outputDirectory,elapsedMilliseconds = watch.Elapsed.TotalMilliseconds,@@ -125,4 +285,73 @@ internal static class GarmentCommandreturn 1;}}++ private static int ImportGarmentCode(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length < 2)+ {+ throw new ArgumentException(Usage);+ }+ string input = Path.GetFullPath(args[1]);+ string output = Path.GetFullPath(Path.Combine("artifacts", "local", "garment", Path.GetFileNameWithoutExtension(input)));+ bool json = false;+ for (int i = 2; i < args.Length; i++)+ {+ switch (args[i])+ {+ case "--json":+ json = true;+ break;+ case "--out-dir" when i + 1 < args.Length:+ output = Path.GetFullPath(args[++i]);+ break;+ default:+ throw new ArgumentException("Unknown or incomplete import option: " + args[i]);+ }+ }+ string source = File.ReadAllText(input);+ var imported = GarmentCodeImport.Import(source, input);+ if (!imported.IsSuccess)+ {+ if (json)+ {+ stdout.WriteLine(JsonSerializer.Serialize(new { success = false, imported.Diagnostics }, CliRunner.JsonOptions));+ }+ else+ {+ foreach (var diagnostic in imported.Diagnostics)+ {+ stderr.WriteLine(diagnostic.Code + ": " + diagnostic.Message);+ }+ }+ return 1;+ }+ string[] files = ["garment.firmament", "specification.json", "patterns.svg", "import-evidence.json"];+ if (files.Select(file => Path.Combine(output, file)).Any(path => path.Equals(input, StringComparison.OrdinalIgnoreCase)))+ {+ throw new ArgumentException("Import output must not replace the input specification.");+ }+ var parsed = GarmentAuthoring.Parse(imported.Source!, input);+ string evidence = JsonSerializer.Serialize(new+ {+ success = true,+ stage = "imported-patterns",+ imported.InputHash,+ imported.Panels,+ seams = GarmentPatternInspection.Inspect(parsed.Source!),+ sourceSpecification = input,+ outputDirectory = output,+ meshed = false,+ simulated = false,+ limits = new[] { "Resolved patterns only", "Fabric and grain use explicit Aetheris defaults",+ "Placement is retained, not fitted to a new body", "Keep the source specification's license with derivatives" },+ }, CliRunner.JsonOptions);+ Directory.CreateDirectory(output);+ File.WriteAllText(Path.Combine(output, "garment.firmament"), imported.Source, new UTF8Encoding(false));+ File.WriteAllText(Path.Combine(output, "specification.json"), source, new UTF8Encoding(false));+ File.WriteAllText(Path.Combine(output, "patterns.svg"), GarmentPatternPreview.Svg(parsed.Source!), new UTF8Encoding(false));+ File.WriteAllText(Path.Combine(output, "import-evidence.json"), evidence, new UTF8Encoding(false));+ stdout.WriteLine(json ? evidence : "Imported sewing pattern: " + Path.Combine(output, "garment.firmament"));+ return 0;+ }}diff --git a/Aetheris.Cloth3D/ClothBodySurface3D.cs b/Aetheris.Cloth3D/ClothBodySurface3D.csindex aa994138..5f092531 100644--- a/Aetheris.Cloth3D/ClothBodySurface3D.cs+++ b/Aetheris.Cloth3D/ClothBodySurface3D.cs@@ -11,7 +11,15 @@ public interface IClothBodySurface3DClothBodySample3D Query(Vector3 position);}-/// <summary>Immutable pose snapshot with a nearest-triangle BVH. Outward triangle winding+/// <summary>Externally authored motion sampled at an explicit absolute time.+/// Replay requires the same BodyTimeSeconds input alongside the cloth snapshot.</summary>+public interface IClothKinematicBodySurface3D : IClothBodySurface3D+{+ void Sample(double seconds);+}++/// <summary>Topology-owned pose snapshot with a nearest-triangle BVH. Refit is an explicit,+/// externally synchronized operation between solver substeps. Outward triangle winding/// is a caller contract. This is a discrete oriented surface query, not a watertight SDF or CCD.</summary>public sealed class ClothTriangleBody3D : IClothBodySurface3D{@@ -62,6 +70,67 @@ public sealed class ClothTriangleBody3D : IClothBodySurface3DBuild(0, triangles.Length);}+ public void Refit(IReadOnlyList<Vector3> updatedPositions)+ {+ if (updatedPositions.Count != positions.Length)+ {+ throw new ArgumentException("Body refit must preserve vertex count and triangle topology.");+ }+ var updatedNormals = new Vector3[positions.Length];+ foreach (var position in updatedPositions)+ {+ ClothValidation3D.Finite(position);+ }+ for (int face = 0; face < indices.Length; face += 3)+ {+ int a = indices[face];+ int b = indices[face + 1];+ int c = indices[face + 2];+ var normal = Vector3.Cross(updatedPositions[b] - updatedPositions[a], updatedPositions[c] - updatedPositions[a]);+ if (normal.LengthSquared() <= 1e-20f)+ {+ throw new ArgumentException("Body refit has a degenerate triangle.");+ }+ updatedNormals[a] += normal;+ updatedNormals[b] += normal;+ updatedNormals[c] += normal;+ }+ for (int vertex = 0; vertex < positions.Length; vertex++)+ {+ positions[vertex] = updatedPositions[vertex];+ normals[vertex] = updatedNormals[vertex];+ if (normals[vertex].LengthSquared() > 1e-20f)+ {+ normals[vertex] = Vector3.Normalize(normals[vertex]);+ }+ }+ // Build records parents before children, so the reverse traversal refits leaves first.+ for (int index = nodes.Count - 1; index >= 0; index--)+ {+ var node = nodes[index];+ Vector3 minimum = new(float.PositiveInfinity);+ Vector3 maximum = new(float.NegativeInfinity);+ if (node.Count == 0)+ {+ minimum = Vector3.Min(nodes[node.Left].Minimum, nodes[node.Right].Minimum);+ maximum = Vector3.Max(nodes[node.Left].Maximum, nodes[node.Right].Maximum);+ }+ else+ {+ for (int triangle = node.Start; triangle < node.Start + node.Count; triangle++)+ {+ for (int corner = 0; corner < 3; corner++)+ {+ var point = positions[indices[triangles[triangle] * 3 + corner]];+ minimum = Vector3.Min(minimum, point);+ maximum = Vector3.Max(maximum, point);+ }+ }+ }+ nodes[index] = node with { Minimum = minimum, Maximum = maximum };+ }+ }+public ClothBodySample3D Query(Vector3 position){ClothValidation3D.Finite(position);diff --git a/Aetheris.Cloth3D/ClothGpuData3D.cs b/Aetheris.Cloth3D/ClothGpuData3D.csindex 61ba316a..210f01e5 100644--- a/Aetheris.Cloth3D/ClothGpuData3D.cs+++ b/Aetheris.Cloth3D/ClothGpuData3D.cs@@ -188,6 +188,10 @@ public sealed class ClothGpuData3Dpublic float[] Header(ClothStepOptions3D options, ClothContacts3D contacts, ClothDispatch3D dispatch, float fraction){+ if (!contacts.Guides.IsEmpty)+ {+ throw new NotSupportedException("AUR-CLOTH-005: Temporary fitting guides currently require the CPU solver.");+ }float h = options.DeltaSeconds / options.Substeps;float[] header = new float[32];if (!Enum.IsDefined(dispatch.Phase))diff --git a/Aetheris.Cloth3D/ClothSimulation3D.cs b/Aetheris.Cloth3D/ClothSimulation3D.csindex b8901812..16ab8036 100644--- a/Aetheris.Cloth3D/ClothSimulation3D.cs+++ b/Aetheris.Cloth3D/ClothSimulation3D.cs@@ -35,7 +35,9 @@ public sealed record ClothStepOptions3D/// sphere contact covers vertices AND triangle interiors. No CCD or self-contact claim.</summary>public sealed record ClothContacts3D{+ public ImmutableArray<ClothHalfSpaceGuide3D> Guides { get; init; } = [];public IClothBodySurface3D? BodySurface { get; init; }+ public double BodyTimeSeconds { get; init; }public float BodyClearance { get; init; }public Vector3? PlaneNormal { get; init; }public float PlaneOffset { get; init; }@@ -44,6 +46,26 @@ public sealed record ClothContacts3Dpublic void Validate(){+ if (Guides.IsDefault || Guides.Length > 32 || Guides.Sum(guide => (long)guide.Vertices.Length) > 32768)+ {+ throw new ArgumentException("Cloth fitting guides exceed the bounded guide budget.");+ }+ var names = new HashSet<string>(StringComparer.Ordinal);+ foreach (var guide in Guides)+ {+ ClothValidation3D.Finite(guide.Normal);+ if (string.IsNullOrWhiteSpace(guide.Id) || !names.Add(guide.Id)+ || guide.Vertices.IsDefaultOrEmpty || guide.Vertices.Distinct().Count() != guide.Vertices.Length+ || MathF.Abs(guide.Normal.LengthSquared() - 1) > .0001f+ || !float.IsFinite(guide.Offset) || !float.IsFinite(guide.Compliance) || guide.Compliance < 0)+ {+ throw new ArgumentException("Invalid cloth fitting guide identity, vertices, plane or compliance.");+ }+ }+ if (!double.IsFinite(BodyTimeSeconds) || BodyTimeSeconds < 0)+ {+ throw new ArgumentException("Body sample time must be finite and nonnegative.");+ }if (PlaneNormal is { } normal){ClothValidation3D.Finite(normal);@@ -71,6 +93,11 @@ public sealed record ClothContacts3D}}+/// <summary>Temporary vertex subset constraint: dot(normal, position) >= offset.+/// Construction geometry is compiled away; this is an explicit solver command.</summary>+public sealed record ClothHalfSpaceGuide3D(string Id, ImmutableArray<int> Vertices,+ Vector3 Normal, float Offset, float Compliance);+public sealed record ClothSnapshot3D(string ContentKey, long Tick, ImmutableArray<Vector3> Positions,ImmutableArray<Vector3> Velocities, ImmutableArray<Vector3> PinTargets);@@ -134,17 +161,30 @@ public sealed class ClothSolver3D : IClothSolver3Dpublic void Step(ClothStepOptions3D options, ClothContacts3D contacts){ClothState3D.ValidateStep(Plan, options, contacts);+ if (contacts.BodySurface is IClothKinematicBodySurface3D initialBody)+ {+ initialBody.Sample(contacts.BodyTimeSeconds);+ }if (Plan.ContactTopology is not null){ClothOffsetContact3D.ValidateInitial(Plan, Capture(), contacts);}float h = options.DeltaSeconds / options.Substeps;+ var guideMultipliers = contacts.Guides.Select(guide => new float[guide.Vertices.Length]).ToArray();float damping = MathF.Exp(-options.VelocityDamping * h);positions.CopyTo(pinStarts, 0);for (int substep = 0; substep < options.Substeps; substep++){+ if (contacts.BodySurface is IClothKinematicBodySurface3D movingBody)+ {+ movingBody.Sample(contacts.BodyTimeSeconds + (substep + 1d) * h);+ }Array.Clear(lambda);Array.Clear(contactLambda);+ foreach (var multipliers in guideMultipliers)+ {+ Array.Clear(multipliers);+ }RefreshBounds(options, contacts);float fraction = (substep + 1f) / options.Substeps;for (int vertex = 0; vertex < positions.Length; vertex++)@@ -173,6 +213,7 @@ public sealed class ClothSolver3D : IClothSolver3D}for (int contact = 0; contact < options.ContactIterations; contact++){+ ProjectGuides(contacts.Guides, guideMultipliers, h);ProjectContacts(contacts);ProjectOffsetContacts(options, h);}@@ -185,6 +226,29 @@ public sealed class ClothSolver3D : IClothSolver3DTick++;}+ private void ProjectGuides(ImmutableArray<ClothHalfSpaceGuide3D> guides, float[][] multipliers, float h)+ {+ for (int index = 0; index < guides.Length; index++)+ {+ var guide = guides[index];+ float alpha = guide.Compliance / (h * h);+ for (int local = 0; local < guide.Vertices.Length; local++)+ {+ int vertex = guide.Vertices[local];+ float weight = Plan.InverseMasses[vertex];+ if (weight == 0)+ {+ continue;+ }+ float distance = Vector3.Dot(guide.Normal, positions[vertex]) - guide.Offset;+ float previousLambda = multipliers[index][local];+ float nextLambda = MathF.Max(0, previousLambda + (-distance - alpha * previousLambda) / (weight + alpha));+ multipliers[index][local] = nextLambda;+ Move(vertex, guide.Normal * (weight * (nextLambda - previousLambda)));+ }+ }+ }+private void RefreshBounds(ClothStepOptions3D options, ClothContacts3D contacts){if (Plan.ContactTopology is null)@@ -439,6 +503,14 @@ public static class ClothState3Doptions.Validate();contacts.Validate();float h = options.DeltaSeconds / options.Substeps;+ foreach (var guide in contacts.Guides)+ {+ if (guide.Vertices.Any(vertex => vertex < 0 || vertex >= plan.InverseMasses.Length)+ || !float.IsFinite(guide.Compliance / (h * h)))+ {+ throw new ArgumentException("Cloth fitting guide vertices or timestep are invalid.");+ }+ }if (plan.Constraints.Any(constraint => !float.IsFinite(constraint.Compliance / (h * h)))){throw new ArgumentException("Cloth compliance and timestep exceed finite solver arithmetic.");diff --git a/Aetheris.Humanoid/HumanoidFigureFit.cs b/Aetheris.Humanoid/HumanoidFigureFit.csnew file mode 100644index 00000000..1419f3eb--- /dev/null+++ b/Aetheris.Humanoid/HumanoidFigureFit.cs@@ -0,0 +1,207 @@+using Aetheris.Kernel.Core.Math;+using System.Security.Cryptography;++namespace Aetheris.Humanoid;++public sealed record HumanoidFitSection(double HeightMm, double CircumferenceMm,+ double MinimumX, double MaximumX, double MinimumY, double MaximumY, int Segments);+public sealed record HumanoidFigureFit(string BodyId, string TopologyHash, string SkeletonId, string RestPoseId,+ Point3D LeftShoulder, Point3D RightShoulder, Point3D Neck, HumanoidFitSection Chest, HumanoidFitSection Hip,+ string RestSurfaceHash)+{+ public string MeasurementPoseId { get; init; } = "Rest";+}++/// <summary>Measurements of the supplied gameplay surface, not canonical-template landmarks.+/// Sections must form a closed contour containing the torso joint. Shoulder guides are explicit joint proxies.</summary>+public static class HumanoidFigureFitting+{+ private const double WeldToleranceMm = .0001;++ public static HumanoidFigureFit Measure(HumanoidGameplayBody body, double? chestHeightMm = null,+ double? hipHeightMm = null, SolvedHumanoidPose? pose = null)+ {+ ArgumentNullException.ThrowIfNull(body);+ var chest = Joint(HumanoidJointKind.Chest);+ var pelvis = Joint(HumanoidJointKind.Pelvis);+ var positions = pose is null ? body.Surface.Vertices.Select(vertex => vertex.Position).ToArray() : body.EvaluatePositions(pose);+ return new HumanoidFigureFit(body.Id, body.Surface.ConnectivityHash, body.Skeleton.SkeletonId, body.Skeleton.RestPoseId,+ Joint(HumanoidJointKind.LeftShoulder), Joint(HumanoidJointKind.RightShoulder), Joint(HumanoidJointKind.Neck),+ Section(body.Surface, positions, chestHeightMm ?? chest.Z, chest),+ Section(body.Surface, positions, hipHeightMm ?? pelvis.Z, pelvis), SurfaceHash(body))+ {+ MeasurementPoseId = pose?.PoseState.PoseId ?? "Rest",+ };++ Point3D Joint(HumanoidJointKind kind)+ {+ var joint = body.Skeleton.Joints.SingleOrDefault(joint => joint.Kind == kind)+ ?? throw new InvalidOperationException("garment-fit-joint-missing: " + kind);+ int index = body.Skeleton.Joints.ToList().FindIndex(candidate => candidate.Kind == kind);+ var transform = pose?.GlobalTransforms[index] ?? joint.GlobalBind;+ return new(transform.M41, transform.M42, transform.M43);+ }+ }++ public static string SurfaceHash(HumanoidGameplayBody body)+ {+ using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);+ Span<byte> coordinates = stackalloc byte[24];+ foreach (var vertex in body.Surface.Vertices)+ {+ System.Buffers.Binary.BinaryPrimitives.WriteDoubleLittleEndian(coordinates, vertex.Position.X);+ System.Buffers.Binary.BinaryPrimitives.WriteDoubleLittleEndian(coordinates[8..], vertex.Position.Y);+ System.Buffers.Binary.BinaryPrimitives.WriteDoubleLittleEndian(coordinates[16..], vertex.Position.Z);+ hash.AppendData(coordinates);+ }+ Span<byte> indices = stackalloc byte[12];+ foreach (var face in body.Surface.Faces)+ {+ System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(indices, face.A);+ System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(indices[4..], face.B);+ System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(indices[8..], face.C);+ hash.AppendData(indices);+ }+ return Convert.ToHexStringLower(hash.GetHashAndReset());+ }++ public static HumanoidFitSection Section(HumanoidGameplayBody body, double heightMm, Point3D torsoProbe)+ {+ return Section(body.Surface, body.Surface.Vertices.Select(vertex => vertex.Position).ToArray(), heightMm, torsoProbe);+ }++ private static HumanoidFitSection Section(HumanoidSurface surface, IReadOnlyList<Point3D> positions,+ double heightMm, Point3D torsoProbe)+ {+ if (!double.IsFinite(heightMm))+ {+ throw new ArgumentException("garment-fit-section-invalid: Height must be finite.");+ }+ var points = new List<Point3D>();+ var pointIds = new Dictionary<(long X, long Y), int>();+ var adjacency = new Dictionary<int, HashSet<int>>();+ var faces = surface.Components.Where(component => component.Kind == HumanoidComponentKind.OuterSkin)+ .SelectMany(component => component.FaceIndices).Distinct().Order();+ foreach (int faceIndex in faces)+ {+ var face = surface.Faces[faceIndex];+ var triangle = new[] { positions[face.A], positions[face.B], positions[face.C] };+ var crossings = new List<Point3D>();+ for (int edge = 0; edge < 3; edge++)+ {+ var a = triangle[edge];+ var b = triangle[(edge + 1) % 3];+ if (Math.Abs(a.Z - heightMm) < 1e-8)+ {+ throw new InvalidOperationException("garment-fit-section-coincident: Move the section height away from a mesh vertex.");+ }+ if ((a.Z > heightMm) == (b.Z > heightMm))+ {+ continue;+ }+ double fraction = (heightMm - a.Z) / (b.Z - a.Z);+ crossings.Add(new(a.X + (b.X - a.X) * fraction, a.Y + (b.Y - a.Y) * fraction, heightMm));+ }+ if (crossings.Count != 2)+ {+ continue;+ }+ int first = PointId(crossings[0]);+ int second = PointId(crossings[1]);+ if (first == second)+ {+ continue;+ }+ adjacency[first].Add(second);+ adjacency[second].Add(first);+ }+ var visited = new HashSet<int>();+ var candidates = new List<IReadOnlyList<Point3D>>();+ foreach (int seed in adjacency.Keys.Order())+ {+ if (visited.Contains(seed))+ {+ continue;+ }+ var component = new List<int>();+ var pending = new Stack<int>();+ pending.Push(seed);+ while (pending.TryPop(out int vertex))+ {+ if (!visited.Add(vertex))+ {+ continue;+ }+ component.Add(vertex);+ foreach (int neighbor in adjacency[vertex])+ {+ pending.Push(neighbor);+ }+ }+ // Never repair an open/branched body section into a guessed circumference.+ if (component.Any(vertex => adjacency[vertex].Count != 2))+ {+ if (component.Any(vertex => Math.Abs(points[vertex].X - torsoProbe.X) < 250))+ {+ throw new InvalidOperationException("garment-fit-section-open: Torso section is open or branched at " + heightMm + "mm.");+ }+ continue;+ }+ var loop = new List<Point3D>();+ int previous = -1;+ int current = seed;+ do+ {+ loop.Add(points[current]);+ int next = adjacency[current].Order().First(neighbor => neighbor != previous);+ previous = current;+ current = next;+ } while (current != seed && loop.Count <= component.Count);+ if (Contains(loop, torsoProbe))+ {+ candidates.Add(loop);+ }+ }+ if (candidates.Count != 1)+ {+ throw new InvalidOperationException("garment-fit-section-ambiguous: Expected one closed torso contour at " + heightMm + "mm, found " + candidates.Count + ".");+ }+ var contour = candidates[0];+ double circumference = 0;+ for (int index = 0; index < contour.Count; index++)+ {+ circumference += (contour[(index + 1) % contour.Count] - contour[index]).Length;+ }+ return new(heightMm, circumference, contour.Min(point => point.X), contour.Max(point => point.X),+ contour.Min(point => point.Y), contour.Max(point => point.Y), contour.Count);++ int PointId(Point3D point)+ {+ var key = ((long)Math.Round(point.X / WeldToleranceMm), (long)Math.Round(point.Y / WeldToleranceMm));+ if (!pointIds.TryGetValue(key, out int index))+ {+ index = points.Count;+ points.Add(point);+ pointIds.Add(key, index);+ adjacency.Add(index, []);+ }+ return index;+ }+ }++ private static bool Contains(IReadOnlyList<Point3D> polygon, Point3D point)+ {+ bool inside = false;+ for (int index = 0; index < polygon.Count; index++)+ {+ var a = polygon[index];+ var b = polygon[(index + 1) % polygon.Count];+ if ((a.Y > point.Y) != (b.Y > point.Y)+ && point.X < (b.X - a.X) * (point.Y - a.Y) / (b.Y - a.Y) + a.X)+ {+ inside = !inside;+ }+ }+ return inside;+ }+}diff --git a/Aetheris.Humanoid/HumanoidGameplayBody.cs b/Aetheris.Humanoid/HumanoidGameplayBody.csindex 59d7f479..93a44d3f 100644--- a/Aetheris.Humanoid/HumanoidGameplayBody.cs+++ b/Aetheris.Humanoid/HumanoidGameplayBody.cs@@ -71,6 +71,13 @@ public sealed class HumanoidGameplayBodyreturn new(positions, evidence);}+ /// <summary>Evaluate the admitted skinning pose without a repeated surface screen.+ /// Authoring checkpoints use Evaluate to retain deformation diagnostics.</summary>+ public IReadOnlyList<Aetheris.Kernel.Core.Math.Point3D> EvaluatePositions(SolvedHumanoidPose pose)+ {+ return binding.Evaluate(pose);+ }+public IReadOnlyList<HumanoidSkinDualQuaternion> CreatePalette(SolvedHumanoidPose pose) =>binding.CreatePalette(pose);diff --git a/Aetheris.Humanoid/HumanoidPoseRecipes.cs b/Aetheris.Humanoid/HumanoidPoseRecipes.csnew file mode 100644index 00000000..e70fffde--- /dev/null+++ b/Aetheris.Humanoid/HumanoidPoseRecipes.cs@@ -0,0 +1,59 @@+namespace Aetheris.Humanoid;++public enum HumanoidPosePreset { Rest, APose, TPose }++/// <summary>Reusable absolute anatomical pose recipes. The original bind skeleton remains authoritative.</summary>+public static class HumanoidPoseRecipes+{+ public static IReadOnlyList<AnatomicalJointRequest> Preset(HumanoidPosePreset preset)+ {+ if (preset == HumanoidPosePreset.Rest)+ {+ return [];+ }+ if (preset is not (HumanoidPosePreset.APose or HumanoidPosePreset.TPose))+ {+ throw new ArgumentOutOfRangeException(nameof(preset));+ }+ return Array.AsReadOnly(CanonicalHumanoidRestPose.Requests.Select(request =>+ {+ if (preset == HumanoidPosePreset.TPose+ && request.Joint is HumanoidJointKind.LeftShoulder or HumanoidJointKind.RightShoulder)+ {+ return request with { AbductionDegrees = 90 };+ }+ return request;+ }).ToArray());+ }++ public static IReadOnlyList<AnatomicalJointRequest> Blend(HumanoidGameplayBody body,+ IReadOnlyList<AnatomicalJointRequest> from, IReadOnlyList<AnatomicalJointRequest> to, double fraction)+ {+ if (!double.IsFinite(fraction) || fraction is < 0 or > 1)+ {+ throw new ArgumentOutOfRangeException(nameof(fraction));+ }+ var first = from.ToDictionary(request => request.Joint);+ var second = to.ToDictionary(request => request.Joint);+ var rest = body.Skeleton.Joints.Select(joint => joint.GlobalBind).ToArray();+ return Array.AsReadOnly(first.Keys.Union(second.Keys).Order().Select(joint =>+ {+ var start = At(first, joint);+ var end = At(second, joint);+ return new AnatomicalJointRequest(joint,+ start.FlexionDegrees + (end.FlexionDegrees - start.FlexionDegrees) * fraction,+ start.AbductionDegrees + (end.AbductionDegrees - start.AbductionDegrees) * fraction,+ start.TwistDegrees + (end.TwistDegrees - start.TwistDegrees) * fraction);+ }).ToArray());++ AnatomicalJointRequest At(Dictionary<HumanoidJointKind, AnatomicalJointRequest> requests, HumanoidJointKind joint)+ {+ if (requests.TryGetValue(joint, out var requested))+ {+ return requested;+ }+ var measured = HumanoidPoseSemantics.Measure(body.Skeleton, rest, joint);+ return new(joint, measured.FlexionDegrees, measured.AbductionDegrees, measured.TwistDegrees);+ }+ }+}diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/PlanarMeshQualityTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/PlanarMeshQualityTests.csindex fb3bd790..3eb74c46 100644--- a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/PlanarMeshQualityTests.cs+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/PlanarMeshQualityTests.cs@@ -5,6 +5,67 @@ namespace Aetheris.Kernel.Core.Tests.Brep.Tessellation;public sealed class PlanarMeshQualityTests{+ [Fact]+ public void InteriorFillPreservesConcaveDomainAndBoundaryWhileImprovingPointDistribution()+ {+ Point3D[] points = [new(0, 0, 0), new(100, 0, 0), new(100, 40, 0),+ new(40, 40, 0), new(40, 100, 0), new(0, 100, 0)];+ int[] seed = [0, 1, 3, 1, 2, 3, 0, 3, 5, 3, 4, 5];+ var filled = PlanarMeshQuality.FillInterior(points, seed, 20);+ var repeated = PlanarMeshQuality.FillInterior(points, seed, 20);+ Assert.Equal(filled.Points, repeated.Points);+ Assert.Equal(filled.Indices, repeated.Indices);+ Assert.Equal(points, filled.Points.Take(points.Length));+ Assert.True(filled.Points.Count > points.Length);+ var boundary = new Dictionary<(int, int), int>();+ double area = 0;+ for (int face = 0; face < filled.Indices.Count; face += 3)+ {+ int a = filled.Indices[face];+ int b = filled.Indices[face + 1];+ int c = filled.Indices[face + 2];+ var pa = filled.Points[a];+ var pb = filled.Points[b];+ var pc = filled.Points[c];+ double cross = (pb.X - pa.X) * (pc.Y - pa.Y) - (pb.Y - pa.Y) * (pc.X - pa.X);+ Assert.True(cross > 0);+ area += cross * .5;+ Assert.False((pa.X + pb.X + pc.X) / 3 > 40 && (pa.Y + pb.Y + pc.Y) / 3 > 40);+ int[] triangle = [a, b, c];+ for (int edge = 0; edge < 3; edge++)+ {+ int first = triangle[edge];+ int second = triangle[(edge + 1) % 3];+ var key = (System.Math.Min(first, second), System.Math.Max(first, second));+ boundary[key] = boundary.GetValueOrDefault(key) + 1;+ }+ }+ Assert.Equal(6400, area, 7);+ Assert.Equal(6, boundary.Count(entry => entry.Value == 1));+ for (int edge = 0; edge < points.Length; edge++)+ {+ int other = (edge + 1) % points.Length;+ Assert.Equal(1, boundary[(System.Math.Min(edge, other), System.Math.Max(edge, other))]);+ }+ }++ [Fact]+ public void FillRejectsExcessiveWorkAndNonplanarGeometryWithoutMutatingInputs()+ {+ Point3D[] points = [new(0, 0, 0), new(100, 0, 0), new(0, 100, 0)];+ int[] indices = [0, 1, 2];+ Assert.Throws<ArgumentNullException>(() => PlanarMeshQuality.FillInterior(null!, indices, 20));+ Assert.Throws<ArgumentNullException>(() => PlanarMeshQuality.FillInterior(points, null!, 20));+ Assert.Throws<ArgumentException>(() => PlanarMeshQuality.FillInterior(points, [0, 1, 2, 0, 1, 2, 0, 1, 2], 20));+ Assert.Throws<ArgumentException>(() => PlanarMeshQuality.FillInterior(points, indices, double.NaN));+ Assert.Throws<InvalidOperationException>(() => PlanarMeshQuality.FillInterior(points, indices, .01));+ Assert.Throws<InvalidOperationException>(() => PlanarMeshQuality.FillInterior(points, indices, 20, 3));+ Assert.Equal(3, points.Length);+ Assert.Equal(new Point3D(100, 0, 0), points[1]);+ points[1] = new(100, 0, 1);+ Assert.Throws<ArgumentException>(() => PlanarMeshQuality.FillInterior(points, indices, 20));+ }+[Fact]public void SkewQuadrilateralFlipsItsBadDiagonalWithoutChangingBoundaryOrArea(){diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/PlanarMeshQuality.cs b/Aetheris.Kernel.Core/Brep/Tessellation/PlanarMeshQuality.csindex acffc187..5227a4e1 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/PlanarMeshQuality.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/PlanarMeshQuality.cs@@ -2,10 +2,147 @@ using Aetheris.Kernel.Core.Math;namespace Aetheris.Kernel.Core.Brep.Tessellation;-/// <summary>Bounded Lawson flips on a counterclockwise XY triangulation. Boundary-/// edges and vertex identities remain unchanged. This does not insert or move geometry.</summary>+public sealed record PlanarMeshFillResult(IReadOnlyList<Point3D> Points, IReadOnlyList<int> Indices);++/// <summary>Bounded point-distribution refinement and Lawson flips on an XY triangulation.+/// Existing boundary segments and vertex identities remain unchanged.</summary>public static class PlanarMeshQuality{+ /// <summary>Populate a constrained XY triangulation with a bounded triangular lattice,+ /// then legalize its interior edges. Existing vertices and boundary segments are retained.+ /// Clearance avoids packing new interior points beside short authored boundary features;+ /// this is size/point-distribution control, not a guaranteed minimum-angle mesher.</summary>+ public static PlanarMeshFillResult FillInterior(IReadOnlyList<Point3D> sourcePoints,+ IReadOnlyList<int> sourceIndices, double spacing, int maximumVertices = 8192)+ {+ ArgumentNullException.ThrowIfNull(sourceIndices);+ var grid = FillGrid(sourcePoints, spacing, maximumVertices);+ var points = sourcePoints.ToList();+ var indices = Improve(sourcePoints, sourceIndices).ToList();+ if (indices.Count == 0)+ {+ throw new ArgumentException("Planar fill requires a nonempty constant-Z triangulation.");+ }+ var counts = new Dictionary<(int, int), int>();+ for (int face = 0; face < indices.Count; face += 3)+ {+ for (int edge = 0; edge < 3; edge++)+ {+ int a = indices[face + edge];+ int b = indices[face + (edge + 1) % 3];+ var key = (System.Math.Min(a, b), System.Math.Max(a, b));+ counts.TryGetValue(key, out int count);+ counts[key] = count + 1;+ }+ }+ if (counts.Any(entry => entry.Value > 2))+ {+ throw new ArgumentException("Planar fill requires manifold triangle edges.");+ }+ var boundary = counts.Where(entry => entry.Value == 1).Select(entry => entry.Key).ToArray();+ double clearanceSquared = spacing * spacing * .16;+ for (int row = 0; row < grid.Rows; row++)+ {+ double y = grid.MinimumY + (row + .5) * grid.RowSpacing;+ double offset = row % 2 == 0 ? .5 : 1;+ for (int column = 0; column < grid.Columns; column++)+ {+ var point = new Point3D(grid.MinimumX + (column + offset) * spacing, y, points[0].Z);+ if (boundary.Any(edge => SegmentDistanceSquared(point, points[edge.Item1], points[edge.Item2]) < clearanceSquared)+ || points.Any(existing => DistanceSquared(point, existing) < clearanceSquared))+ {+ continue;+ }+ var containing = new List<int>();+ for (int face = 0; face < indices.Count; face += 3)+ {+ if (Cross(points[indices[face]], points[indices[face + 1]], point) >= -1e-8+ && Cross(points[indices[face + 1]], points[indices[face + 2]], point) >= -1e-8+ && Cross(points[indices[face + 2]], points[indices[face]], point) >= -1e-8)+ {+ containing.Add(face);+ }+ }+ if (containing.Count == 0)+ {+ continue;+ }+ if (points.Count == maximumVertices)+ {+ throw new InvalidOperationException("planar-mesh-fill-budget: Interior fill exceeds its vertex budget.");+ }+ int inserted = points.Count;+ points.Add(point);+ foreach (int face in containing.OrderDescending())+ {+ int[] triangle = indices.Skip(face).Take(3).ToArray();+ indices.RemoveRange(face, 3);+ for (int edge = 0; edge < 3; edge++)+ {+ int a = triangle[edge];+ int b = triangle[(edge + 1) % 3];+ if (Cross(points[a], points[b], point) > 1e-8)+ {+ indices.AddRange([a, b, inserted]);+ }+ }+ }+ }+ }+ return new(points, Improve(points, indices));++ static double Cross(Point3D a, Point3D b, Point3D c)+ {+ return (b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X);+ }+ static double DistanceSquared(Point3D a, Point3D b)+ {+ double x = a.X - b.X;+ double y = a.Y - b.Y;+ return x * x + y * y;+ }+ static double SegmentDistanceSquared(Point3D point, Point3D a, Point3D b)+ {+ double x = b.X - a.X;+ double y = b.Y - a.Y;+ double t = System.Math.Clamp(((point.X - a.X) * x + (point.Y - a.Y) * y) / (x * x + y * y), 0, 1);+ return DistanceSquared(point, new(a.X + x * t, a.Y + y * t, a.Z));+ }+ }++ /// <summary>Check fill admission before a caller pays for seed triangulation.+ /// The same checks run in FillInterior; this does not validate polygon topology.</summary>+ public static void ValidateFillBudget(IReadOnlyList<Point3D> points, double spacing, int maximumVertices = 8192)+ {+ _ = FillGrid(points, spacing, maximumVertices);+ }++ private static (double MinimumX, double MinimumY, double Columns, double Rows, double RowSpacing)+ FillGrid(IReadOnlyList<Point3D> points, double spacing, int maximumVertices)+ {+ ArgumentNullException.ThrowIfNull(points);+ if (!double.IsFinite(spacing) || spacing <= 0 || maximumVertices is < 3 or > 65536+ || points.Count > maximumVertices)+ {+ throw new ArgumentException("Invalid planar fill spacing or vertex budget.");+ }+ if (points.Count < 3 || points.Any(point => !double.IsFinite(point.X) || !double.IsFinite(point.Y)+ || !double.IsFinite(point.Z) || System.Math.Abs(point.Z - points[0].Z) > 1e-9))+ {+ throw new ArgumentException("Planar fill requires finite constant-Z points.");+ }+ double minimumX = points.Min(point => point.X);+ double minimumY = points.Min(point => point.Y);+ double rowSpacing = spacing * System.Math.Sqrt(3) * .5;+ double columns = System.Math.Ceiling((points.Max(point => point.X) - minimumX) / spacing);+ double rows = System.Math.Ceiling((points.Max(point => point.Y) - minimumY) / rowSpacing);+ if (!double.IsFinite(columns * rows) || columns * rows > maximumVertices * 16d)+ {+ throw new InvalidOperationException("planar-mesh-fill-budget: Candidate grid exceeds its bounded work budget.");+ }+ return (minimumX, minimumY, columns, rows, rowSpacing);+ }+public static IReadOnlyList<int> Improve(IReadOnlyList<Point3D> points, IReadOnlyList<int> source){ArgumentNullException.ThrowIfNull(points);diff --git a/Aetheris.Kernel.Firmament.Tests/ClothKinematicBodyTests.cs b/Aetheris.Kernel.Firmament.Tests/ClothKinematicBodyTests.csnew file mode 100644index 00000000..4dfca49c--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/ClothKinematicBodyTests.cs@@ -0,0 +1,80 @@+using System.Collections.Immutable;+using System.Numerics;+using Aetheris.Cloth3D;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class ClothKinematicBodyTests+{+ [Fact]+ public void RefitMatchesRebuiltHierarchyAndRejectsInvalidGeometryAtomically()+ {+ // Eighteen triangles exercise internal nodes as well as leaves.+ var grid = ClothDefinition3D.Grid("body", 4, 4, new(1, 1), Vector3.Zero);+ var surface = new ClothTriangleBody3D(grid.Positions, grid.Indices);+ var moved = grid.Positions.Select(point => new Vector3(point.X * 1.2f + .2f,+ .1f * point.X + .3f, point.Z * .8f - .2f)).ToImmutableArray();+ surface.Refit(moved);+ var rebuilt = new ClothTriangleBody3D(moved, grid.Indices);+ Vector3[] queries = [new(.4f, .5f, .2f), new(-1, .1f, -.5f), new(2, 1, 3)];+ foreach (var point in queries)+ {+ var expected = rebuilt.Query(point);+ var actual = surface.Query(point);+ Assert.InRange(Vector3.Distance(expected.Point, actual.Point), 0, 1e-6f);+ Assert.InRange(Vector3.Distance(expected.Normal, actual.Normal), 0, 1e-6f);+ Assert.InRange(MathF.Abs(expected.SignedDistance - actual.SignedDistance), 0, 1e-6f);+ }+ var before = surface.Query(queries[0]);+ var degenerate = moved.ToArray();+ degenerate[grid.Indices[1]] = degenerate[grid.Indices[0]];+ Assert.Throws<ArgumentException>(() => surface.Refit(degenerate));+ Assert.Equal(before, surface.Query(queries[0]));+ Assert.Throws<ArgumentException>(() => surface.Refit(moved.Take(3).ToArray()));+ var nonfinite = moved.ToArray();+ nonfinite[^1] = new(float.NaN, 0, 0);+ Assert.Throws<ArgumentException>(() => surface.Refit(nonfinite));+ Assert.Equal(before, surface.Query(queries[0]));+ }++ [Fact]+ public void MovingContactSamplesExplicitSubstepTimesAndReplaysExactly()+ {+ var plan = ClothDefinition3D.Grid("moving-contact", 2, 2, new(.1f, .1f), Vector3.Zero).Compile();+ using var solver = new ClothSolver3D(plan);+ var body = new MovingPlane();+ var contacts = new ClothContacts3D { BodySurface = body, BodyTimeSeconds = .25 };+ var options = new ClothStepOptions3D { DeltaSeconds = .04f, Substeps = 4, Gravity = Vector3.Zero };+ var before = solver.Capture();+ solver.Step(options, contacts);+ Assert.Equal(5, body.Times.Count);+ for (int index = 0; index < 5; index++)+ {+ Assert.InRange(Math.Abs(body.Times[index] - (.25 + index * .01)), 0, 1e-8);+ }+ var expected = solver.Capture();+ Assert.All(expected.Positions, position => Assert.True(position.Y > .02f));+ solver.Restore(before);+ solver.Step(options, contacts);+ Assert.Equal(expected.Positions.ToArray(), solver.Capture().Positions.ToArray());+ Assert.Equal(expected.Velocities.ToArray(), solver.Capture().Velocities.ToArray());+ Assert.Throws<ArgumentException>(() => solver.Step(options, contacts with { BodyTimeSeconds = double.NaN }));+ }++ private sealed class MovingPlane : IClothKinematicBodySurface3D+ {+ public List<double> Times { get; } = [];+ private float height;++ public void Sample(double seconds)+ {+ Times.Add(seconds);+ height = (float)seconds * .1f;+ }++ public ClothBodySample3D Query(Vector3 position)+ {+ return new(new(position.X, height, position.Z), Vector3.UnitY, position.Y - height);+ }+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.csindex b973b7c1..f15c01d8 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs@@ -8,7 +8,15 @@ public sealed class FirmamentSemanticSchemaTestspublic void GeneratedRegistry_IsStableOptInAndCoversFirstConstructs(){Assert.Equal("firmament-semantic-schema/1", FirmamentSemanticSchemas.Version);- Assert.Equal(["Appearance", "FrameTransform", "Placement", "Pmi", "Note", "Provenance", "Box", "Concept", "Points", "Door", "Drape", "Fabric", "Garment", "Helix", "Hole", "Interface<Fixed>", "Interface<Prismatic>", "Interface<Revolute>", "Interface<Stitch>", "Loft", "Panel", "Perforation", "Material", "Linear", "Series", "Room", "Scene", "Camera", "Section", "Thread", "Window", "Follow", "WireRoute"], FirmamentSemanticSchemas.All.Select(s => s.Name));+ string[] expectedNames =+ [+ "Appearance", "FrameTransform", "Placement", "Pmi", "Note", "Provenance",+ "Box", "Concept", "Points", "Door", "Drape", "Fabric", "FigureFit", "Fitting", "Garment",+ "Helix", "Hole", "Interface<Fixed>", "Interface<Prismatic>", "Interface<Revolute>",+ "Interface<Stitch>", "Joint", "Loft", "Panel", "Perforation", "Material", "Linear", "Series", "Pose", "PoseTransition",+ "Room", "Scene", "Camera", "Section", "Thread", "Window", "Follow", "WireRoute",+ ];+ Assert.Equal(expectedNames, FirmamentSemanticSchemas.All.Select(schema => schema.Name));var hole = Assert.IsType<FirmamentConstructSchema>(FirmamentSemanticSchemas.Get("Hole"));var diameter = Assert.Single(hole.Fields, f => f.Name == "Diameter");Assert.Equal("Hole.Diameter", diameter.Id.Value);diff --git a/Aetheris.Kernel.Firmament.Tests/GarmentAuthoringTests.cs b/Aetheris.Kernel.Firmament.Tests/GarmentAuthoringTests.csindex 7a2098d9..0d208f26 100644--- a/Aetheris.Kernel.Firmament.Tests/GarmentAuthoringTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/GarmentAuthoringTests.cs@@ -8,6 +8,25 @@ namespace Aetheris.Kernel.Firmament.Tests;public sealed class GarmentAuthoringTests{+ [Fact]+ public void ExcessivePanelFillReturnsAnOwnedBudgetDiagnostic()+ {+ const string source = """+ schema Garment+ Rect2 blank { center: [0mm, 0mm]; size: [20000mm, 20000mm]; }+ Profile cut { from: blank; }+ Garment test {+ meshSize: 20mm;+ Fabric cotton { thickness: 2mm; arealDensity: 0.2; }+ Panel sheet { profile: cut; origin: [0mm, 0mm, 0mm]; }+ }+ """;+ var result = GarmentCompiler.Compile(source, "budget.firmament");+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == "garment-mesh-budget"+ && diagnostic.SourceIdentity == "budget.firmament");+ }+[Theory][InlineData("tunic", 2, 4)][InlineData("shorts", 4, 8)]@@ -58,7 +77,7 @@ public sealed class GarmentAuthoringTests[InlineData("grain: [0, 1]", "grain: [0, 2]", "garment-grain-invalid")][InlineData("v: [0, 0, 1]", "v: [0, 0, 2]", "garment-panel-frame-invalid")][InlineData("meshSize: 65mm", "meshSize: 1mm", "garment-mesh-budget")]- [InlineData("pose: Rest", "pose: Walk", "garment-pose-unsupported")]+ [InlineData("pose: Rest", "pose: Walk", "humanoid-pose-reference")][InlineData("front => SidePlacement", "front: SidePlacement", "firmament-v2-static-set-entry")]public void InvalidAuthoringStopsWithAnOwnedDiagnostic(string before, string after, string code){diff --git a/Aetheris.Kernel.Firmament.Tests/GarmentCodeImportTests.cs b/Aetheris.Kernel.Firmament.Tests/GarmentCodeImportTests.csnew file mode 100644index 00000000..5cb9195a--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/GarmentCodeImportTests.cs@@ -0,0 +1,273 @@+using System.Numerics;+using System.Text.Json;+using System.Text.Json.Nodes;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Garment;+using Aetheris.Kernel.Firmament.Materializer;+using Aetheris.Cloth3D;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class GarmentCodeImportTests+{+ [Fact]+ public void KnownDressMeshHasNoSliversAndRetainsTheAnalyticCutAndSeamReferences()+ {+ var imported = GarmentCodeImport.Import(Fixture("dress.json"));+ var garment = GarmentCompiler.Compile(imported.Source!).Garment!;+ var quality = GarmentMeshInspection.Measure(garment);+ Assert.Equal(611, garment.Cloth.Definition.Positions.Length);+ Assert.Equal(992, garment.Cloth.Definition.Indices.Length / 3);+ Assert.Equal(0, quality.UnreferencedVertices);+ Assert.Equal(0, quality.TrianglesBelowTenDegrees);+ Assert.InRange(quality.MinimumTriangleAngleDegrees, 10, 11);+ Assert.InRange(quality.MinimumEdgeLength, .006, .007);+ Assert.InRange(quality.MaximumLumpedAreaRatio, 25, 27);+ Assert.InRange(quality.MaximumEdgeLength, 0, garment.Source.MeshSize * 1.001);+ foreach (var panel in garment.Source.Panels)+ {+ var mesh = garment.Panels.Single(candidate => candidate.Name == panel.Name);+ double area = 0;+ for (int face = mesh.IndexStart; face < mesh.IndexStart + mesh.IndexCount; face += 3)+ {+ var a = garment.Cloth.Definition.Positions[garment.Cloth.Definition.Indices[face]];+ var b = garment.Cloth.Definition.Positions[garment.Cloth.Definition.Indices[face + 1]];+ var c = garment.Cloth.Definition.Positions[garment.Cloth.Definition.Indices[face + 2]];+ Assert.True(Vector3.Cross(b - a, c - a).Z > 0);+ area += Vector3.Cross(b - a, c - a).Length() * .5;+ }+ double analyticArea = ResolvedProfile2DValidator.Validate(panel.Profile).SignedArea;+ // Curved edges are approximated with <=1mm geometric error, never replaced by a new cut.+ Assert.InRange(Math.Abs(area - analyticArea * 1e-6), 0, .00025);+ Assert.All(mesh.Edges.Values, boundary => Assert.True(boundary.Length >= 2));+ }+ Assert.Equal(6, GarmentPatternInspection.Inspect(garment.Source).Count);+ }++ [Fact]+ public void StaticReferenceBodyUsesSharedSewingAndReplayWithoutInventingARig()+ {+ const string source = """+ schema Garment+ Rect2 blank { center: [0mm, 0mm]; size: [100mm, 100mm] }+ Profile cut { from: blank; }+ Garment test {+ Fabric cotton { thickness: 2mm; arealDensity: 0.2; }+ Panel sheet { profile: cut; origin: [0mm, 0mm, 1000mm]; }+ }+ """;+ var garment = GarmentCompiler.Compile(source).Garment!;+ var drape = GarmentDraping.SettleOnSurface(garment, new GroundPlane(), "reference", "plane", 1);+ Assert.True(drape.ReplayExact);+ Assert.True(drape.Metrics.Finite);+ Assert.Equal("reference", drape.BodyId);+ Assert.Empty(drape.BodyPositions);+ Assert.Empty(drape.Frames);+ var bound = GarmentCompiler.Compile(source.Replace("Panel sheet", "Drape { figure: Anatolia; pose: Rest; } Panel sheet")).Garment!;+ var rejected = Assert.Throws<InvalidOperationException>(() =>+ GarmentDraping.SettleOnSurface(bound, new GroundPlane(), "reference", "plane", 1));+ Assert.StartsWith("garment-reference-surface-static", rejected.Message);+ }++ [Fact]+ public void KnownDressTemplateChangesItsHemWithoutGuessingNewArmholesOrNecklines()+ {+ string path = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(FixturePath("dress.json")))!, "garmentcode-dress-template.firmament");+ string source = File.ReadAllText(path);+ var baseline = GarmentCompiler.Compile(source);+ Assert.True(baseline.IsSuccess, string.Join("; ", baseline.Diagnostics));+ var upstream = GarmentCompiler.Compile(GarmentCodeImport.Import(Fixture("dress.json")).Source!);+ Assert.Equal(upstream.Garment!.Cloth.ContentKey, baseline.Garment!.Cloth.ContentKey);+ string modified = source.Replace("Pattern();", "Pattern(hemDrop: 100mm);");+ var longer = GarmentCompiler.Compile(modified);+ Assert.True(longer.IsSuccess, string.Join("; ", longer.Diagnostics));+ Assert.NotEqual(baseline.Garment.Cloth.ContentKey, longer.Garment!.Cloth.ContentKey);+ foreach (var panel in baseline.Garment.Source.Panels)+ {+ var original = GarmentPatternInspection.Boundaries(panel);+ var changedPanel = longer.Garment.Source.Panels.Single(candidate => candidate.Name == panel.Name);+ var changed = GarmentPatternInspection.Boundaries(changedPanel);+ foreach (string name in original.Keys.Where(name => name.Contains("armhole") || name.Contains("collar")))+ {+ Assert.Equal(original[name].Segments.Single().Geometry, changed[name].Segments.Single().Geometry);+ }+ Assert.Equal(panel.Origin, changedPanel.Origin);+ }+ Assert.Equal(baseline.Garment.Source.Stitches.Select(seam => (seam.A, seam.B, seam.Reversed)),+ longer.Garment.Source.Stitches.Select(seam => (seam.A, seam.B, seam.Reversed)));+ var referenceSeams = GarmentPatternInspection.Inspect(baseline.Garment.Source);+ foreach (var seam in GarmentPatternInspection.Inspect(longer.Garment.Source))+ {+ var reference = referenceSeams.Single(item => item.Name == seam.Name);+ Assert.InRange(Math.Abs((seam.LengthAMm - seam.LengthBMm)+ - (reference.LengthAMm - reference.LengthBMm)), 0, .00001);+ }+ }++ [Theory]+ [InlineData("dress", 4, 6)]+ [InlineData("shirt", 8, 16)]+ public void RealUpstreamPatternsMatchItsIndependentCurveReaderAndBuild(string name, int panels, int seams)+ {+ string json = Fixture(name + ".json");+ var imported = GarmentCodeImport.Import(json);+ Assert.True(imported.IsSuccess, string.Join("; ", imported.Diagnostics));+ Assert.Equal(panels, imported.Panels.Count);+ var parsed = GarmentAuthoring.Parse(imported.Source!);+ Assert.True(parsed.IsSuccess, string.Join("; ", parsed.Diagnostics));+ Assert.Equal(seams, parsed.Source!.Stitches.Length);+ Assert.Equal(panels, parsed.Source.Features.Count);+ if (name == "dress")+ {+ string svg = GarmentPatternPreview.Svg(parsed.Source);+ Assert.Contains("Envelope 250.299525", svg);+ Assert.DoesNotContain("1075.299813", svg);+ }+ using var oracle = JsonDocument.Parse(Fixture(name + "-curves.json"));+ foreach (var expected in oracle.RootElement.EnumerateArray())+ {+ var mapping = imported.Panels.Single(panel => panel.UpstreamName == expected.GetProperty("panel").GetString());+ string edgeName = mapping.Edges[expected.GetProperty("edge").GetInt32()];+ var panel = parsed.Source.Panels.Single(panel => panel.Name == mapping.PanelName);+ var boundary = GarmentPatternInspection.Boundaries(panel)[edgeName];+ Assert.InRange(Math.Abs(boundary.LengthMm - expected.GetProperty("lengthMm").GetDouble()), 0, .00001);+ var samples = expected.GetProperty("samplesMm").EnumerateArray().ToArray();+ for (int i = 0; i < samples.Length; i++)+ {+ double t = i / 4d;+ var point = At(boundary.Segments.Single().Geometry, mapping.BoundaryReversed ? 1 - t : t);+ Assert.InRange(Math.Abs(point.X - samples[i][0].GetDouble()), 0, .00001);+ Assert.InRange(Math.Abs(point.Y - samples[i][1].GetDouble()), 0, .00001);+ }+ }+ var compiled = GarmentCompiler.Compile(imported.Source!);+ Assert.True(compiled.IsSuccess, string.Join("; ", compiled.Diagnostics));+ var repeated = GarmentCompiler.Compile(GarmentCodeImport.Import(json).Source!);+ Assert.Equal(compiled.Garment!.Cloth.ContentKey, repeated.Garment!.Cloth.ContentKey);+ Assert.All(compiled.Garment.Cloth.Definition.Positions, point => Assert.Equal(0, point.Z));+ Assert.NotEmpty(compiled.Garment.Cloth.Definition.Stitches);+ string formatted = FirmamentLanguageAnalysisService.Format(imported.Source!, "import.firmament", "1").Text;+ Assert.Equal(compiled.Garment.Cloth.ContentKey, GarmentCompiler.Compile(formatted).Garment!.Cloth.ContentKey);+ }++ [Fact]+ public void FrameAndSeamDirectionSurviveClockwiseNormalizationAndRightWrongFlags()+ {+ var root = JsonNode.Parse(Fixture("dress.json"))!;+ var pattern = root["pattern"]!;+ pattern["panels"]!["left_btorso"]!["rotation"] = new JsonArray(13, 27, -19);+ pattern["stitches"]![0]!.AsArray().Add("right_wrong");+ var imported = GarmentCodeImport.Import(root.ToJsonString());+ Assert.True(imported.IsSuccess, string.Join("; ", imported.Diagnostics));+ var parsed = GarmentAuthoring.Parse(imported.Source!).Source!;+ var panel = parsed.Panels.Single(panel => panel.Name == "left_btorso");+ var rotation = Matrix4x4.CreateRotationX(13 * MathF.PI / 180)+ * Matrix4x4.CreateRotationY(27 * MathF.PI / 180)+ * Matrix4x4.CreateRotationZ(-19 * MathF.PI / 180);+ var expectedU = Vector3.Transform(Vector3.UnitX, rotation);+ var expectedV = Vector3.Transform(Vector3.UnitY, rotation);+ Assert.InRange(Vector3.Distance(panel.U, new(expectedU.X, expectedU.Z, expectedU.Y)), 0, 1e-6f);+ Assert.InRange(Vector3.Distance(panel.V, new(expectedV.X, expectedV.Z, expectedV.Y)), 0, 1e-6f);+ var translation = pattern["panels"]!["left_btorso"]!["translation"]!;+ Assert.InRange(Vector3.Distance(panel.Origin, new(translation[0]!.GetValue<float>() * .01f,+ translation[2]!.GetValue<float>() * .01f, translation[1]!.GetValue<float>() * .01f)), 0, 1e-6f);+ var original = GarmentAuthoring.Parse(GarmentCodeImport.Import(Fixture("dress.json")).Source!).Source!;+ Assert.NotEqual(original.Stitches[0].Reversed, parsed.Stitches[0].Reversed);+ Assert.Equal(original.Stitches.Skip(1).ToArray(), parsed.Stitches.Skip(1).ToArray());+ }++ [Theory]+ [InlineData("units", "garmentcode-units-invalid")]+ [InlineData("normalization", "garmentcode-normalization-required")]+ [InlineData("curve", "garmentcode-curve-unsupported")]+ [InlineData("endpoint", "garmentcode-endpoint-invalid")]+ [InlineData("seam", "garmentcode-stitch-reference")]+ [InlineData("reuse", "garment-stitch-edge-reused")]+ [InlineData("arc", "garmentcode-circle-invalid")]+ [InlineData("loop", "garmentcode-loop-invalid")]+ [InlineData("parameter", "garmentcode-parameters-unresolved")]+ [InlineData("control", "garmentcode-json-invalid")]+ public void InvalidInputStopsBeforePublishingAnEditableSource(string mutation, string code)+ {+ var root = JsonNode.Parse(Fixture("dress.json"))!;+ var panel = root["pattern"]!["panels"]!["left_btorso"]!;+ var edges = panel["edges"]!;+ switch (mutation)+ {+ case "units": root["properties"]!["units_in_meter"] = 0; break;+ case "normalization": root["properties"]!["normalize_panel_translation"] = true; break;+ case "curve": edges[3]!["curvature"]!["type"] = "spline"; break;+ case "endpoint": edges[0]!["endpoints"]![0] = 999; break;+ case "seam": root["pattern"]!["stitches"]![0]![0]!["panel"] = "missing"; break;+ case "reuse": root["pattern"]!["stitches"]!.AsArray().Add(root["pattern"]!["stitches"]![0]!.DeepClone()); break;+ case "arc": edges[1]!["curvature"]!["params"]![0] = .001; break;+ case "loop": edges[0]!["endpoints"]![1] = 2; break;+ case "parameter": root["parameters"]!["length"] = 2; break;+ case "control":+ edges[3]!["curvature"]!["type"] = "quadratic";+ edges[3]!["curvature"]!["params"] = new JsonArray();+ break;+ }+ var result = GarmentCodeImport.Import(root.ToJsonString(), "bad.json");+ Assert.False(result.IsSuccess);+ Assert.Null(result.Source);+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == code);+ }++ [Fact]+ public void QuadraticCurvesAreElevatedExactlyAndUnitsAreExplicit()+ {+ const string json = """+ {"properties":{"curvature_coords":"relative","normalize_panel_translation":false,"units_in_meter":1000},+ "pattern":{"panels":{"square":{"translation":[0,0,0],"rotation":[0,0,0],+ "vertices":[[0,0],[20,0],[20,20],[0,20]],+ "edges":[{"endpoints":[0,1],"curvature":{"type":"quadratic","params":[[0.5,-0.2]]}},+ {"endpoints":[1,2]},{"endpoints":[2,3]},{"endpoints":[3,0]}]}},"stitches":[]}}+ """;+ var imported = GarmentCodeImport.Import(json);+ Assert.True(imported.IsSuccess, string.Join("; ", imported.Diagnostics));+ var panel = GarmentAuthoring.Parse(imported.Source!).Source!.Panels.Single();+ var cubic = Assert.IsType<LineArcCubicBezier2D>(panel.Profile.Loops.Single().Segments[0].Geometry);+ for (int i = 0; i <= 8; i++)+ {+ double t = i / 8d;+ var point = At(cubic, t);+ Assert.InRange(Math.Abs(point.X - 20 * t), 0, 1e-10);+ Assert.InRange(Math.Abs(point.Y - 2 * (1 - t) * t * -4), 0, 1e-10);+ }+ }++ private static (double X, double Y) At(LineArcProfileCurve2D curve, double t)+ {+ double u = 1 - t;+ return curve switch+ {+ LineArcLineSegment2D line => (line.Start.X * u + line.End.X * t, line.Start.Y * u + line.End.Y * t),+ LineArcCircularArc2D arc => (arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians + arc.SweepAngleRadians * t),+ arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians + arc.SweepAngleRadians * t)),+ LineArcCubicBezier2D cubic => (u * u * u * cubic.Start.X + 3 * u * u * t * cubic.Control1.X+ + 3 * u * t * t * cubic.Control2.X + t * t * t * cubic.End.X,+ u * u * u * cubic.Start.Y + 3 * u * u * t * cubic.Control1.Y+ + 3 * u * t * t * cubic.Control2.Y + t * t * t * cubic.End.Y),+ _ => throw new NotSupportedException(),+ };+ }++ private static string Fixture(string name) => File.ReadAllText(FixturePath(name));++ private static string FixturePath(string name)+ {+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx")))+ {+ directory = directory.Parent;+ }+ Assert.NotNull(directory);+ return Path.Combine(directory!.FullName, "fixtures/Canonical/Garment/GarmentCode", name);+ }++ private sealed class GroundPlane : IClothBodySurface3D+ {+ public ClothBodySample3D Query(Vector3 position) => new(new(position.X, position.Y, 0), Vector3.UnitZ, position.Z);+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/GarmentFittingTests.cs b/Aetheris.Kernel.Firmament.Tests/GarmentFittingTests.csnew file mode 100644index 00000000..ffb4b2b8--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/GarmentFittingTests.cs@@ -0,0 +1,204 @@+using System.Collections.Immutable;+using System.Numerics;+using Aetheris.Cloth3D;+using Aetheris.Kernel.Firmament.Garment;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Humanoid;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class GarmentFittingTests+{+ [Fact]+ public void KnownPatternComposesGuidesAndPoseMotionWithoutChangingTheCutOrBind()+ {+ string path = FirmamentCorpusHarness.ResolveFixtureFullPath(+ "fixtures/Canonical/Garment/garmentcode-dress-guided.firmament");+ string source = File.ReadAllText(path);+ var body = HumanoidPoseAuthoringTests.Body();+ var binds = body.Skeleton.Joints.Select(joint => joint.GlobalBind).ToArray();+ var binding = new GarmentFigureBinding("Anatolia", body);+ var authored = GarmentCompiler.Compile(source, path, binding);+ Assert.True(authored.IsSuccess, string.Join("; ", authored.Diagnostics));++ int fittingDeclaration = source.IndexOf(" Fitting collar", StringComparison.Ordinal);+ Assert.True(fittingDeclaration >= 0);+ string controlSource = source[..fittingDeclaration] + "Drape { figure: Anatolia; pose: Rest; } }";+ var control = GarmentCompiler.Compile(controlSource, path, binding);+ Assert.True(control.IsSuccess, string.Join("; ", control.Diagnostics));+ var garment = authored.Garment!;+ Assert.Equal(control.Garment!.Cloth.ContentKey, garment.Cloth.ContentKey);+ Assert.Empty(garment.Cloth.Definition.Pins);+ Assert.Equal(20, Assert.Single(garment.FittingGuides).ReleaseAfter);++ var posing = garment.Source.Posing!;+ var transition = posing.Transitions[garment.Source.Transition!];+ var fitting = posing.Resolve(transition.From, "Anatolia");+ var wearing = posing.Resolve(transition.To, "Anatolia");+ var fittingPose = HumanoidPoseAuthoring.Solve(fitting, body);+ var wearingPose = HumanoidPoseAuthoring.Solve(wearing, body);+ Assert.NotEqual(body.EvaluatePositions(fittingPose).ToArray(), body.EvaluatePositions(wearingPose).ToArray());+ Assert.Equal(binds, body.Skeleton.Joints.Select(joint => joint.GlobalBind));+ }++ [Fact]+ public void FittingToolingOffersFieldsAndFormattingPreservesTheCompiledSchedule()+ {+ const string draft = "schema Garment\nGarment draft {\n Fitting collar {\n ";+ var completion = FirmamentLanguageService.Complete(draft, "draft.firmament", "1", draft.Length);+ Assert.Equal("Fitting", completion.Context);+ Assert.Contains(completion.MissingRequiredFields, field => field == "ReleaseAfter");+ var format = FirmamentLanguageAnalysisService.Format(Fixture(), "fitting.firmament", "1");+ var original = GarmentCompiler.Compile(Fixture()).Garment!;+ var formatted = GarmentCompiler.Compile(format.Text).Garment!;+ Assert.Equal(original.Cloth.ContentKey, formatted.Cloth.ContentKey);+ Assert.Equal(original.FittingGuides[0].ReleaseAfter, formatted.FittingGuides[0].ReleaseAfter);+ Assert.True(original.FittingGuides[0].Constraint.Vertices.SequenceEqual(formatted.FittingGuides[0].Constraint.Vertices));+ }++ [Theory]+ [InlineData("1030mm - 30mm")]+ [InlineData("1e3mm")]+ [InlineData("Pow(10, 3) * 1mm")]+ public void ConceptPlaneCoordinatesUseTheExistingCompileTimeScalarEvaluator(string height)+ {+ string source = Fixture();+ int coordinate = source.IndexOf("1000mm]", StringComparison.Ordinal);+ Assert.True(coordinate >= 0);+ source = source.Remove(coordinate, "1000mm".Length).Insert(coordinate, height);+ var result = GarmentCompiler.Compile(source);+ Assert.True(result.IsSuccess, string.Join("; ", result.Diagnostics));+ Assert.Equal(1, Assert.Single(result.Garment!.FittingGuides).Constraint.Offset);+ }++ [Fact]+ public void ConceptPlaneBindsEdgesWithoutChangingMaterialTopologyOrPermanentPins()+ {+ string source = Fixture();+ var compiled = GarmentCompiler.Compile(source);+ Assert.True(compiled.IsSuccess, string.Join("; ", compiled.Diagnostics));+ var garment = compiled.Garment!;+ var control = GarmentCompiler.Compile(source[..source.IndexOf(" Fitting collar", StringComparison.Ordinal)] + "}").Garment!;+ Assert.Equal(control.Cloth.ContentKey, garment.Cloth.ContentKey);+ Assert.Empty(garment.Cloth.Definition.Pins);+ Assert.Single(garment.Panels);+ var guide = Assert.Single(garment.FittingGuides);+ Assert.Equal("guides.collarFloor", guide.ConceptPlane);+ Assert.Equal(Vector3.UnitZ, guide.Constraint.Normal);+ Assert.Equal(1, guide.Constraint.Offset);+ Assert.Equal(5, guide.ReleaseAfter);+ Assert.Equal(guide.Constraint.Vertices.Length, guide.Constraint.Vertices.Distinct().Count());+ }++ [Theory]+ [InlineData("guides.collarFloor;", "guides.missing;", "garment-fitting-plane")]+ [InlineData("sheet.edges.Left", "sheet.edges.missing", "garment-fitting-edge-unknown")]+ [InlineData("releaseAfter: 5", "releaseAfter: 5.5", "garment-fitting-properties")]+ [InlineData("normal: [0, 0, 1]", "normal: [0, 0, 2]", "garment-fitting-properties")]+ [InlineData("normal: [0, 0, 1]", "normal: [0, 0, 1mm]", "garment-fitting-plane")]+ [InlineData("collarFloor: Plane", "collarFloor: true\n collarFloor: Plane", "garment-fitting-plane")]+ public void InvalidBindingsHaveOwnedDiagnostics(string before, string after, string code)+ {+ var result = GarmentCompiler.Compile(Fixture().Replace(before, after, StringComparison.Ordinal));+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == code);+ }++ [Fact]+ public void RealDrapeReleasesGuidesAndMeasuresUnsupportedMotion()+ {+ var garment = GarmentCompiler.Compile(Fixture()).Garment!;+ var result = GarmentDraping.SettleOnSurface(garment, new GroundPlane(), "test", "ground", 20,+ settings: new() { Substeps = 2, Iterations = 4, StopWhenSettled = true });+ Assert.True(result.GuidesReleased);+ Assert.True(result.ReplayExact);+ Assert.Equal(20, result.CompletedSettlingTicks);+ var supported = Assert.Single(result.FittingCheckpoints).Snapshot;+ Assert.Equal(35, supported.Tick);+ Assert.All(garment.FittingGuides[0].Constraint.Vertices,+ vertex => Assert.InRange(supported.Positions[vertex].Z, .99999f, 1.00001f));+ Assert.True(result.Snapshot.Positions.Max(position => position.Z) < .99f);+ Assert.All(result.Samples.Where(sample => sample.Phase == "sewing" || sample.Frame <= 5), sample =>+ {+ Assert.True(Assert.Single(sample.Guides).Active);+ Assert.False(sample.Settled);+ });+ Assert.All(result.Samples.Where(sample => sample.Phase == "settling" && sample.Frame > 5),+ sample => Assert.False(Assert.Single(sample.Guides).Active));+ Assert.Throws<InvalidOperationException>(() => GarmentDraping.SettleOnSurface(+ garment, new GroundPlane(), "test", "ground", 19));+ }++ [Fact]+ public void CompliantHalfSpaceHasXpbdResidualAndExactReplayWithoutIterationStiffening()+ {+ var plan = Triangle().Compile();+ var guide = new ClothHalfSpaceGuide3D("test", [0, 1, 2], Vector3.UnitZ, 1, .00001f);+ var contacts = new ClothContacts3D { Guides = [guide] };+ var options = new ClothStepOptions3D { Gravity = Vector3.Zero, Substeps = 1, Iterations = 1, ContactIterations = 1 };+ using var solver = new ClothSolver3D(plan);+ var before = solver.Capture();+ solver.Step(options, contacts);+ var expected = solver.Capture();+ float alpha = guide.Compliance / (options.DeltaSeconds * options.DeltaSeconds);+ float height = plan.InverseMasses[0] / (plan.InverseMasses[0] + alpha);+ Assert.InRange(MathF.Abs(expected.Positions[0].Z - height), 0, .000001f);+ solver.Restore(before);+ solver.Step(options with { Iterations = 12 }, contacts);+ Assert.InRange(Vector3.Distance(expected.Positions[0], solver.Capture().Positions[0]), 0, .000001f);+ solver.Restore(before);+ solver.Step(options, contacts);+ Assert.True(expected.Positions.SequenceEqual(solver.Capture().Positions));+ Assert.True(expected.Velocities.SequenceEqual(solver.Capture().Velocities));+ }++ [Fact]+ public void PhysicalContactWinsWhenAConstructionGuideConflictsWithTheBody()+ {+ var plan = Triangle().Compile();+ using var solver = new ClothSolver3D(plan);+ var contacts = new ClothContacts3D+ {+ Guides = [new("floor", [0, 1, 2], Vector3.UnitZ, 1, 0)],+ PlaneNormal = -Vector3.UnitZ,+ PlaneOffset = -.5f,+ };+ solver.Step(new() { Gravity = Vector3.Zero, Substeps = 1, Iterations = 4, ContactIterations = 1 }, contacts);+ Assert.All(solver.Capture().Positions, position => Assert.True(position.Z < .51f));+ Assert.InRange(ClothState3D.Measure(plan, solver.Capture(), contacts).MaximumSurfacePenetration, 0, .000001f);+ }++ [Fact]+ public void InvalidGuideStopsBeforeStateMutationAndGpuCannotSilentlyIgnoreIt()+ {+ var plan = Triangle().Compile();+ using var solver = new ClothSolver3D(plan);+ var before = solver.Capture();+ var bad = new ClothContacts3D { Guides = [new("bad", [3], Vector3.UnitZ, 1, 0)] };+ Assert.Throws<ArgumentException>(() => solver.Step(new(), bad));+ Assert.Equal(0, solver.Tick);+ Assert.True(before.Positions.SequenceEqual(solver.Capture().Positions));+ var contacts = new ClothContacts3D { Guides = [new("good", [0], Vector3.UnitZ, 1, 0)] };+ var error = Assert.Throws<NotSupportedException>(() => new ClothGpuData3D(plan).Header(+ new(), contacts, new(ClothPhase3D.Predict, 0, 1), 1));+ Assert.Contains("AUR-CLOTH-005", error.Message);+ }++ private static ClothDefinition3D Triangle() => new("guide", [new(0, 0, 0), new(1, 0, 0), new(0, 1, 0)],+ [new(0, 0), new(1, 0), new(0, 1)], [0, 1, 2]);++ private static string Fixture()+ {+ var root = new DirectoryInfo(AppContext.BaseDirectory);+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx")))+ {+ root = root.Parent;+ }+ return File.ReadAllText(Path.Combine(root!.FullName, "fixtures", "Canonical", "Garment", "temporary-fitting.firmament"));+ }++ private sealed class GroundPlane : IClothBodySurface3D+ {+ public ClothBodySample3D Query(Vector3 point) => new(new(point.X, point.Y, 0), Vector3.UnitZ, point.Z);+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/GarmentPatternWorkflowTests.cs b/Aetheris.Kernel.Firmament.Tests/GarmentPatternWorkflowTests.csnew file mode 100644index 00000000..7ff76808--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/GarmentPatternWorkflowTests.cs@@ -0,0 +1,162 @@+using System.Numerics;+using System.Xml.Linq;+using Aetheris.Humanoid;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament.Garment;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class GarmentPatternWorkflowTests+{+ [Fact]+ public void FigureFitMeasuresTheSuppliedSurfaceAndChangingItChangesTheCut()+ {+ var body = BoxBody();+ var fit = HumanoidFigureFitting.Measure(body, 1280, 960);+ Assert.Equal(1200, fit.Chest.CircumferenceMm, 6);+ Assert.Equal(1200, fit.Hip.CircumferenceMm, 6);+ Assert.Equal(8, fit.Chest.Segments);+ var original = CompileDress(body);+ var enlarged = CompileDress(BoxBody(1.2));+ Assert.NotEqual(original.Cloth.ContentKey, enlarged.Cloth.ContentKey);+ Assert.NotEqual(original.Cloth.Definition.Positions.ToArray(), enlarged.Cloth.Definition.Positions.ToArray());+ Assert.Equal(original.Source.SourceHash, enlarged.Source.SourceHash);+ Assert.Single(original.Source.FigureFits);+ Assert.Equal("dressLayout.body", original.Source.FigureFits[0].Identity);+ Assert.Equal("synthetic-box", original.Source.FigureFits[0].Measurements.BodyId);+ Assert.Throws<InvalidOperationException>(() => GarmentDraping.Settle(original, BoxBody(1.2), 1));+ }++ [Fact]+ public void OpenBodySectionsAndMissingBindingsStayExplicitFailures()+ {+ var parsed = GarmentAuthoring.Parse(Dress());+ Assert.False(parsed.IsSuccess);+ Assert.Contains(parsed.Diagnostics, diagnostic => diagnostic.Code == "garment-fit-body-required");+ var body = BoxBody(open: true);+ var failed = GarmentAuthoring.Parse(Dress(), figureBinding: new("Anatolia", body));+ Assert.False(failed.IsSuccess);+ Assert.Contains(failed.Diagnostics, diagnostic => diagnostic.Message.Contains("garment-fit-section-open"));+ var unknown = GarmentAuthoring.Parse(Dress().Replace("body.torsoCircumference", "body.guessedBust"),+ figureBinding: new("Anatolia", BoxBody()));+ Assert.Contains(unknown.Diagnostics, diagnostic => diagnostic.Code == "garment-fit-member-unknown");+ }++ [Fact]+ public void FigureFieldsComeFromTheGeneratedSchemaAndSundressUsesTheSamePipeline()+ {+ string source = "schema Garment\nConcept Struct fit { FigureFit body {\n ";+ var completion = FirmamentLanguageService.Complete(source, "dress.firmament", "1", source.Length);+ Assert.Equal("FigureFit", completion.Context);+ Assert.Contains(completion.Fields, field => field.Name == "ChestHeight");+ string dress = File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Garment/sundress.firmament"));+ var result = GarmentCompiler.Compile(dress, figureBinding: new("Anatolia", BoxBody()));+ Assert.True(result.IsSuccess, string.Join("; ", result.Diagnostics));+ Assert.Equal(4, result.Garment!.Source.Stitches.Length);+ Assert.Contains(result.Garment.Panels[0].Edges.Keys, name => name == "rightArmholeLower");+ Assert.DoesNotContain(result.Garment.Source.Stitches, seam => seam.A.Contains("Armhole", StringComparison.Ordinal));+ }++ [Fact]+ public void ResolvedPreviewIsIdenticalAcrossMeshDensitiesAndRetainsCurvesAndOpenCuffs()+ {+ var binding = new GarmentFigureBinding("Anatolia", BoxBody());+ var coarse = GarmentAuthoring.Parse(Dress(), figureBinding: binding);+ var fine = GarmentAuthoring.Parse(Dress().Replace("meshSize: 55mm", "meshSize: 35mm"), figureBinding: binding);+ Assert.True(coarse.IsSuccess, string.Join("; ", coarse.Diagnostics));+ Assert.True(fine.IsSuccess, string.Join("; ", fine.Diagnostics));+ string svg = GarmentPatternPreview.Svg(coarse.Source!);+ Assert.Equal(svg, GarmentPatternPreview.Svg(fine.Source!));+ var document = XDocument.Parse(svg);+ XNamespace ns = "http://www.w3.org/2000/svg";+ Assert.Contains(document.Descendants(ns + "path"), path => path.Attribute("d")!.Value.Contains(" C "));+ Assert.Contains(document.Descendants(ns + "path"), path => path.Attribute("data-boundary")?.Value == "rightSleeveOpening"+ && path.Attribute("stroke")!.Value == "#3274a0");+ Assert.Equal(8, GarmentPatternInspection.Inspect(coarse.Source!).Count);+ Assert.All(GarmentPatternInspection.Inspect(coarse.Source!), seam => Assert.InRange(seam.Mismatch, 0, 1e-9));+ var compiled = GarmentCompiler.Compile(Dress(), figureBinding: binding);+ var remeshed = GarmentCompiler.Compile(Dress().Replace("meshSize: 55mm", "meshSize: 35mm"), figureBinding: binding);+ Assert.True(compiled.IsSuccess, string.Join("; ", compiled.Diagnostics));+ Assert.True(remeshed.IsSuccess, string.Join("; ", remeshed.Diagnostics));+ Assert.All(compiled.Garment!.Panels, panel => Assert.Equal(panel.Edges.Keys.Order(),+ remeshed.Garment!.Panels.Single(other => other.Identity == panel.Identity).Edges.Keys.Order()));+ Assert.Empty(compiled.Garment.Cloth.Definition.Pins);+ }++ [Fact]+ public void SemanticEditGroupsCannotStitchOverAlreadyConsumedChildren()+ {+ string source = Dress().Replace(" Drape {", " Interface<Stitch> duplicate { a: front.edges.rightCut; b: back.edges.leftCut; }\n Drape {");+ var parsed = GarmentAuthoring.Parse(source, figureBinding: new("Anatolia", BoxBody()));+ Assert.False(parsed.IsSuccess);+ Assert.Contains(parsed.Diagnostics, diagnostic => diagnostic.Code == "garment-stitch-edge-reused");+ }++ [Fact]+ public void PosedDressKeepsTheSameFlatPatternAndExplicitMeasurementPose()+ {+ var binding = new GarmentFigureBinding("Anatolia", BoxBody());+ string Source(string name) => File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath(+ "fixtures/Canonical/Garment/" + name + ".firmament"));+ var baseline = GarmentCompiler.Compile(Source("sundress"), figureBinding: binding);+ var posed = GarmentCompiler.Compile(Source("sundress-posed"), figureBinding: binding);+ Assert.True(baseline.IsSuccess, string.Join("; ", baseline.Diagnostics));+ Assert.True(posed.IsSuccess, string.Join("; ", posed.Diagnostics));+ Assert.Equal(baseline.Garment!.Cloth.ContentKey, posed.Garment!.Cloth.ContentKey);+ Assert.Equal("Rest", Assert.Single(posed.Garment.Source.FigureFits).Pose);+ Assert.Equal("fitting", posed.Garment.Source.Pose);+ Assert.Equal("lowerArms", posed.Garment.Source.Transition);+ var mismatch = GarmentCompiler.Compile(Source("sundress-posed").Replace("pose: fitting;", "pose: wearing;"),+ figureBinding: binding);+ Assert.False(mismatch.IsSuccess);+ Assert.Contains(mismatch.Diagnostics, diagnostic => diagnostic.Code == "garment-pose-transition-binding");+ }++ private static CompiledGarment CompileDress(HumanoidGameplayBody body)+ {+ var result = GarmentCompiler.Compile(Dress(), figureBinding: new("Anatolia", body));+ Assert.True(result.IsSuccess, string.Join("; ", result.Diagnostics));+ return result.Garment!;+ }++ private static string Dress()+ {+ return File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Garment/tshirt-dress.firmament"));+ }++ private static HumanoidGameplayBody BoxBody(double scale = 1, bool open = false)+ {+ Point3D[] positions = [new(-200 * scale, -100 * scale, 800), new(200 * scale, -100 * scale, 800),+ new(200 * scale, 100 * scale, 800), new(-200 * scale, 100 * scale, 800),+ new(-200 * scale, -100 * scale, 1600), new(200 * scale, -100 * scale, 1600),+ new(200 * scale, 100 * scale, 1600), new(-200 * scale, 100 * scale, 1600)];+ int[][] triangles = [[0, 2, 1], [0, 3, 2], [4, 5, 6], [4, 6, 7], [0, 1, 5], [0, 5, 4],+ [1, 2, 6], [1, 6, 5], [2, 3, 7], [2, 7, 6], [3, 0, 4], [3, 4, 7]];+ var vertices = positions.Select((point, index) => new HumanoidVertex("v" + index, point, HumanoidRegionKind.Chest, index)).ToArray();+ var faces = triangles.Select((triangle, index) => new HumanoidFace("f" + index,+ triangle[0], triangle[1], triangle[2], HumanoidRegionKind.Chest, null)).ToArray();+ var surface = new HumanoidSurface("box", "box-bindings", "box-connectivity", vertices, faces, [], null,+ vertices.Select((_, index) => new VertexSkinWeights(index, [new(0, 1)])).ToArray(),+ [new("skin", HumanoidComponentKind.OuterSkin, Enumerable.Range(0, faces.Length).Where(index => !open || index != 4).ToArray(), [])],+ new Dictionary<HumanoidRegionKind, HumanoidRegionKind>());+ var joints = new List<HumanoidJoint>();+ Add(HumanoidJointKind.Root, new(0, 0, 0));+ Add(HumanoidJointKind.Chest, new(0, 0, 1280));+ Add(HumanoidJointKind.Pelvis, new(0, 0, 960));+ Add(HumanoidJointKind.Neck, new(0, 0, 1510));+ Add(HumanoidJointKind.LeftShoulder, new(-150, 0, 1450));+ Add(HumanoidJointKind.RightShoulder, new(150, 0, 1450));+ var skeleton = new HumanoidSkeleton("box-skeleton", "box-rest", "rigid", joints, new Dictionary<HumanoidJointKind, HumanoidJointKind>());+ var provenance = new HumanoidProvenance("test", [], [], "test", "test", "test", "synthetic", []);+ return new(new(HumanoidGameplayBody.Schema, "synthetic-box", surface, skeleton, [], provenance));++ void Add(HumanoidJointKind kind, Point3D point)+ {+ var matrix = Matrix4x4.CreateTranslation((float)point.X, (float)point.Y, (float)point.Z);+ Matrix4x4.Invert(matrix, out var inverse);+ joints.Add(new("joint:" + kind, kind, AnatomicalSide.Center, null,+ HumanoidTransform.FromTranslation(point), matrix, inverse));+ }+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/GarmentSettlingTests.cs b/Aetheris.Kernel.Firmament.Tests/GarmentSettlingTests.csnew file mode 100644index 00000000..b8f3bdf5--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/GarmentSettlingTests.cs@@ -0,0 +1,102 @@+using System.Collections.Immutable;+using System.Numerics;+using Aetheris.Cloth3D;+using Aetheris.Kernel.Firmament.Garment;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class GarmentSettlingTests+{+ [Theory]+ [InlineData(false, 45, "FrameBudget")]+ [InlineData(true, 30, "Settled")]+ public void RealDrapeStopsOnlyAfterStableMotionAndAcceptableResiduals(bool earlyStop, int completed, string reason)+ {+ var garment = SupportedSheet(false);+ var settings = new GarmentDrapeSettings { Substeps = 1, Iterations = 2, StopWhenSettled = earlyStop };+ var result = GarmentDraping.SettleOnSurface(garment, new GroundPlane(), "test", "plane", 45, settings: settings);+ Assert.Equal(completed, result.CompletedSettlingTicks);+ Assert.Equal(reason, result.StopReason);+ Assert.Equal(30 + completed, result.Snapshot.Tick);+ Assert.Equal(settings, result.Settings);+ Assert.True(result.ReplayExact);+ Assert.True(GarmentDrapeLimits.Accept(result.Metrics, result.MaximumSeamGap));+ Assert.Equal(6, result.Samples.Count(sample => sample.Phase == "sewing"));+ Assert.Equal(completed / 5, result.Samples.Count(sample => sample.Phase == "settling"));+ Assert.All(result.Samples, sample =>+ {+ Assert.Equal(0, sample.MaximumSpeed);+ Assert.True(sample.Settled);+ });+ }++ [Fact]+ public void StationaryButStretchedClothCannotTriggerAnEarlySuccess()+ {+ var garment = SupportedSheet(true);+ var result = GarmentDraping.SettleOnSurface(garment, new GroundPlane(), "test", "plane", 40,+ settings: new() { Substeps = 1, Iterations = 2, StopWhenSettled = true });+ Assert.Equal(40, result.CompletedSettlingTicks);+ Assert.Equal("FrameBudget", result.StopReason);+ Assert.InRange(result.Metrics.MaximumStretch, .99f, 1.01f);+ Assert.False(GarmentDrapeLimits.Accept(result.Metrics, result.MaximumSeamGap));+ Assert.All(result.Samples, sample =>+ {+ Assert.Equal(0, sample.MaximumSpeed);+ Assert.False(sample.Settled);+ });+ }++ [Theory]+ [InlineData(0, 24, .01f)]+ [InlineData(65, 24, .01f)]+ [InlineData(8, 0, .01f)]+ [InlineData(8, 65, .01f)]+ [InlineData(8, 24, 0f)]+ [InlineData(8, 24, float.NaN)]+ [InlineData(8, 24, .2f)]+ public void InvalidSettingsStopBeforeSimulation(int substeps, int iterations, float speed)+ {+ var settings = new GarmentDrapeSettings { Substeps = substeps, Iterations = iterations, StationarySpeed = speed };+ Assert.Throws<ArgumentException>(() => GarmentDraping.SettleOnSurface(+ SupportedSheet(false), new GroundPlane(), "test", "plane", settings: settings));+ }++ [Fact]+ public void LimitsKeepTheExistingStrainSeamAndContactThresholds()+ {+ var metrics = new ClothMetrics3D(.15f, 0, .005f, 0, true);+ Assert.True(GarmentDrapeLimits.Accept(metrics, .01f));+ Assert.False(GarmentDrapeLimits.Accept(metrics with { MaximumStretch = .1501f }, .01f));+ Assert.False(GarmentDrapeLimits.Accept(metrics with { MaximumSurfacePenetration = .0051f }, .01f));+ Assert.False(GarmentDrapeLimits.Accept(metrics, .0101f));+ Assert.False(GarmentDrapeLimits.Accept(metrics with { Finite = false }, .01f));+ Assert.False(GarmentDrapeLimits.Accept(metrics, float.NaN));+ }++ private static CompiledGarment SupportedSheet(bool stretch)+ {+ const string source = """+ schema Garment+ Rect2 blank { center: [0mm, 0mm]; size: [100mm, 100mm]; }+ Profile cut { from: blank; }+ Garment test {+ Fabric cotton { thickness: 2mm; arealDensity: 0.2; }+ Panel sheet { profile: cut; origin: [0mm, 0mm, 1000mm]; }+ }+ """;+ var garment = GarmentCompiler.Compile(source).Garment!;+ var definition = garment.Cloth.Definition with+ {+ Pins = Enumerable.Range(0, garment.Cloth.Definition.Positions.Length).ToImmutableArray(),+ InitialPositions = garment.Cloth.Definition.InitialPositions.Select(point =>+ stretch ? new Vector3(point.X * 2, point.Y * 2, point.Z * 2) : point).ToImmutableArray(),+ };+ return garment with { Cloth = definition.Compile() };+ }++ private sealed class GroundPlane : IClothBodySurface3D+ {+ public ClothBodySample3D Query(Vector3 point) => new(new(point.X, point.Y, 0), Vector3.UnitZ, point.Z);+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/HumanoidPoseAuthoringTests.cs b/Aetheris.Kernel.Firmament.Tests/HumanoidPoseAuthoringTests.csnew file mode 100644index 00000000..7c6f29a0--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/HumanoidPoseAuthoringTests.cs@@ -0,0 +1,93 @@+using Aetheris.Humanoid;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Garment;+using Aetheris.Kernel.Firmament.Humanoid;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class HumanoidPoseAuthoringTests+{+ [Fact]+ public void ForwardInheritanceUsesAbsoluteAnglesAndPreservesOriginalBind()+ {+ var document = HumanoidPoseAuthoring.Parse("""+ Pose wearing { figure: Anatolia; from: fitting; Joint LeftShoulder { abduction: 35deg; } }+ Pose fitting { figure: Anatolia; from: TPose; Joint LeftElbow { flexion: 10deg + 5deg; } }+ PoseTransition lowerArms { from: fitting; to: wearing; duration: 0.5s; }+ schema Garment+ """);+ Assert.Contains("schema Garment", document.RemainingSource);+ Assert.DoesNotContain("Pose fitting", document.RemainingSource);+ Assert.Equal(.5, document.Transitions["lowerArms"].DurationSeconds);+ Assert.Equal(15, document.Poses["wearing"].Joints.Single(joint => joint.Joint == HumanoidJointKind.LeftElbow).FlexionDegrees);++ var body = Body();+ string restPoseId = body.Skeleton.RestPoseId;+ var binds = body.Skeleton.Joints.Select(joint => joint.GlobalBind).ToArray();+ var fitting = HumanoidPoseAuthoring.Solve(document.Poses["fitting"], body);+ var wearing = HumanoidPoseAuthoring.Solve(document.Poses["wearing"], body);+ Assert.Equal(restPoseId, body.Skeleton.RestPoseId);+ Assert.Equal(binds, body.Skeleton.Joints.Select(joint => joint.GlobalBind));+ Assert.InRange(Math.Abs(HumanoidPoseSemantics.Measure(body.Skeleton, fitting.GlobalTransforms,+ HumanoidJointKind.LeftShoulder).AbductionDegrees - 90), 0, .01);+ Assert.InRange(Math.Abs(HumanoidPoseSemantics.Measure(body.Skeleton, wearing.GlobalTransforms,+ HumanoidJointKind.LeftShoulder).AbductionDegrees - 35), 0, .01);+ Assert.NotEqual(body.EvaluatePositions(fitting).ToArray(), body.EvaluatePositions(wearing).ToArray());+ }++ [Fact]+ public void PartialRestOverrideKeepsOmittedAnatomicalAngles()+ {+ var body = Body();+ var document = HumanoidPoseAuthoring.Parse("""+ Pose bent { figure: Anatolia; from: Rest; Joint LeftShoulder { flexion: 5deg; } }+ Pose inherited { figure: Anatolia; from: bent; Joint LeftShoulder { twist: 2deg; } }+ """);+ var actualRest = HumanoidPoseSemantics.Measure(body.Skeleton,+ body.Skeleton.Joints.Select(joint => joint.GlobalBind).ToArray(), HumanoidJointKind.LeftShoulder);+ var request = Assert.Single(HumanoidPoseAuthoring.Requests(document.Poses["inherited"], body));+ Assert.Equal(actualRest.AbductionDegrees, request.AbductionDegrees);+ Assert.Equal(5, request.FlexionDegrees);+ Assert.Equal(2, request.TwistDegrees);+ Assert.NotEqual(0, request.AbductionDegrees);+ }++ [Theory]+ [InlineData("Pose a { figure: F; from: b; } Pose b { figure: F; from: a; }", "humanoid-pose-cycle")]+ [InlineData("Pose a { figure: F; from: missing; }", "humanoid-pose-reference")]+ [InlineData("Pose a { figure: F; } Pose b { figure: G; from: a; }", "humanoid-pose-figure-mismatch")]+ [InlineData("Pose a { figure: F; Joint LeftElbow { flexion: 12mm; } }", "humanoid-pose-angle")]+ [InlineData("Pose a { figure: F; Joint Unknown { flexion: 5deg; } }", "humanoid-pose-joint")]+ [InlineData("Pose a { figure: F; } PoseTransition t { from: a; to: a; duration: 0s; }", "humanoid-pose-duration")]+ [InlineData("Pose a { figure: F; } PoseTransition t { from: a; to: missing; duration: 1s; }", "humanoid-pose-transition-binding")]+ public void InvalidPoseProgramsHaveOwnedDiagnostics(string source, string code)+ {+ var error = Assert.Throws<InvalidDataException>(() => HumanoidPoseAuthoring.Parse(source));+ Assert.StartsWith(code + ":", error.Message);+ }++ [Fact]+ public void JointLimitsAreEnforcedByTheExistingSolver()+ {+ var document = HumanoidPoseAuthoring.Parse("Pose a { figure: F; from: APose; Joint LeftElbow { flexion: 999deg; } }");+ var error = Assert.Throws<InvalidDataException>(() => HumanoidPoseAuthoring.Solve(document.Poses["a"], Body()));+ Assert.StartsWith("humanoid-pose-solve:", error.Message);+ }++ [Fact]+ public void PoseFieldsUseTheSharedLanguageServiceAndAngleSchema()+ {+ string source = "Pose fitting { figure: Anatolia; Joint LeftElbow {\n ";+ var completion = FirmamentLanguageService.Complete(source, "pose.firmament", "1", source.Length);+ Assert.Equal("Joint", completion.Context);+ Assert.Contains(completion.Fields, field => field.Name == "Flexion");+ Assert.Equal(FirmamentUnitKind.Angle, FirmamentSemanticSchemas.Get("Joint")!.Fields[0].Unit);+ }++ internal static HumanoidGameplayBody Body()+ {+ var canonical = HumanoidRestPoseNormalizer.Normalize(CanonicalAdultTemplate.Create());+ return new(new(HumanoidGameplayBody.Schema, "pose-test", canonical.Surface,+ canonical.Skeleton, [], canonical.Provenance));+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/ProfileBoundaryAuthoringTests.cs b/Aetheris.Kernel.Firmament.Tests/ProfileBoundaryAuthoringTests.csindex ed56384c..107fd283 100644--- a/Aetheris.Kernel.Firmament.Tests/ProfileBoundaryAuthoringTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/ProfileBoundaryAuthoringTests.cs@@ -5,6 +5,51 @@ namespace Aetheris.Kernel.Firmament.Tests;public sealed class ProfileBoundaryAuthoringTests{+ [Fact]+ public void LinearThroughKeepsAuthoredNamesAndBuildsThroughTheOrdinaryKernel()+ {+ const string source = """+ Model Tab {+ Units: mm+ Rect2 Blank { Center: [0mm,0mm]; Size: [120mm,80mm] }+ Profile Cut {+ From: Blank+ Replace Tab {+ On: Blank.Right+ Range: [20mm,60mm]+ Through: [[80mm,-20mm], [80mm,20mm]]+ Interpolation: Linear+ SpanNames: [lower, end, upper]+ }+ }+ Extrude Body { Profile: Cut From: 0mm To: 3mm }+ }+ """;+ var profile = ProfileAuthoringParser.ResolveNamedProfile(source, "Cut", out var diagnostics);+ Assert.Empty(diagnostics);+ Assert.NotNull(profile);+ Assert.Equal(["lower", "end", "upper"], profile.BoundaryEdits![0].Descendants);+ Assert.All(profile.Loops[0].Segments, segment => Assert.IsType<LineArcLineSegment2D>(segment.Geometry));+ Assert.Equal(10400, ResolvedProfile2DValidator.Validate(profile).SignedArea, 7);+ var build = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(build.IsSuccess, string.Join("; ", build.Diagnostics));+ string retainedSource = source + "\nProfile More { From: Cut; Replace Hem { On: Cut.Bottom; Through: [[0mm,-45mm]] } }";+ var retained = ProfileAuthoringParser.ResolveNamedProfile(retainedSource, "More", out diagnostics);+ Assert.Empty(diagnostics);+ Assert.Equal(["Tab", "Hem"], retained!.BoundaryEdits!.Select(edit => edit.Name));+ string consumedSource = retainedSource + "\nProfile Final { From: More; Replace Lift { On: More.lower; Through: [[70mm,-15mm]] } }";+ var consumed = ProfileAuthoringParser.ResolveNamedProfile(consumedSource, "Final", out diagnostics);+ Assert.Empty(diagnostics);+ Assert.DoesNotContain(consumed!.BoundaryEdits!, edit => edit.Name == "Tab");+ Assert.Contains(consumed.BoundaryEdits!, edit => edit.Name == "Hem");+ var wrongNames = source.Replace("[lower, end, upper]", "[lower, lower]");+ Assert.Null(ProfileAuthoringParser.ResolveNamedProfile(wrongNames, "Cut", out diagnostics));+ Assert.Contains(diagnostics, diagnostic => diagnostic.StartsWith("profile-edit-span-names-invalid"));+ var conflicting = source.Replace("Interpolation: Linear", "Interpolation: Linear; Join: Tangent");+ Assert.Null(ProfileAuthoringParser.ResolveNamedProfile(conflicting, "Cut", out diagnostics));+ Assert.Contains(diagnostics, diagnostic => diagnostic.StartsWith("profile-edit-construction-conflict"));+ }+private const string Panel = """Model Test {Units: mmdiff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.csindex 4ee44f81..71f2919a 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs@@ -353,7 +353,16 @@ internal static class ConceptIrResolverif (close < 0) { diagnostic = InvalidSpatialDerivation; return false; }var name = declaration.Groups["name"].Value;var body = source[(open + 1)..close];- instances[name] = new(name, [], ResolveMembers(name, body, open + 1, "", ParseEnums(source, diagnostics), selections, diagnostics), false, "CompileTimeOnlyErased", new(declaration.Index, close - declaration.Index + 1));+ var resolvedInstance = new ConceptIrStructInstance(name, [], ResolveMembers(name, body, open + 1, "", ParseEnums(source, diagnostics), selections, diagnostics), false, "CompileTimeOnlyErased", new(declaration.Index, close - declaration.Index + 1));+ if (!instances.TryAdd(name, resolvedInstance))+ {+ diagnostics.Add(DuplicateDeclaration);+ }+ }+ if (diagnostics.Count > 0)+ {+ diagnostic = string.Join("; ", diagnostics);+ return false;}if (!instances.TryGetValue(match.Groups["instance"].Value, out var instance) || !instance.Members.TryGetValue(match.Groups["member"].Value, out var value)){ diagnostic = "ConceptPlaneNotFound: " + reference; return false; }@@ -847,9 +856,28 @@ internal static class ConceptIrResolverprivate static bool TryVectorField(string body, string name, out (double X, double Y, double Z) vector){- var match = Regex.Match(body, $@"\b{Regex.Escape(name)}\s*:\s*\[(?<x>[-+.\d]+)(?:mm)?\s*,\s*(?<y>[-+.\d]+)(?:mm)?\s*,\s*(?<z>[-+.\d]+)(?:mm)?\s*\]", RegexOptions.CultureInvariant);- if (match.Success && double.TryParse(match.Groups["x"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var x) && double.TryParse(match.Groups["y"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var y) && double.TryParse(match.Groups["z"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var z) && double.IsFinite(x) && double.IsFinite(y) && double.IsFinite(z)) { vector = (x, y, z); return true; }- vector = default; return false;+ vector = default;+ var match = Regex.Match(body, $@"\b{Regex.Escape(name)}\s*:\s*\[(?<values>[^\]]+)\]", RegexOptions.CultureInvariant);+ if (!match.Success)+ {+ return false;+ }+ var components = FirmamentV2FeatureExpansion.SplitTopLevel(match.Groups["values"].Value);+ if (components.Count != 3)+ {+ return false;+ }+ var values = new double[3];+ for (int index = 0; index < components.Count; index++)+ {+ if (!FirmamentV2FeatureExpansion.TryEvaluateScalar(components[index].Text, out values[index], out string unit)+ || !double.IsFinite(values[index]) || (unit != "" && (name != "Origin" || unit != "mm")))+ {+ return false;+ }+ }+ vector = (values[0], values[1], values[2]);+ return true;}private ConceptIrValue? EvaluateMatch(string expression, ParsedConceptMember target)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBlockReader.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBlockReader.csnew file mode 100644index 00000000..0df772da--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBlockReader.cs@@ -0,0 +1,129 @@+namespace Aetheris.Kernel.Firmament.FirmamentV2;++internal sealed class FirmamentBlockReader+{+ private readonly string source;+ private readonly Action<string, string> Fail;+ private readonly string errorCode;+ private readonly (string Text, string Shape, int Start, int Length)[] tokens;+ private int position;++ public FirmamentBlockReader(string source, Action<string, string> fail, string errorCode = "garment-syntax")+ {+ this.source = source;+ Fail = fail;+ this.errorCode = errorCode;+ tokens = FirmamentLanguageAnalysisService.Lex(source).Where(token => token.Shape != "comment")+ .Select(token => (token.Text, token.Shape, token.Start, token.Length)).ToArray();+ }++ public bool End => position >= tokens.Length;+ public string Peek => End ? "<end>" : tokens[position].Text;+ public string Take()+ {+ if (End)+ {+ Fail(errorCode, "Unexpected end of source block.");+ }+ return tokens[position++].Text;+ }+ public bool Optional(string text)+ {+ if (Peek != text)+ {+ return false;+ }+ position++;+ return true;+ }+ public void Expect(string text)+ {+ if (!Optional(text))+ {+ Fail(errorCode, "Expected '" + text + "', found '" + Peek + "'.");+ }+ }+ public string Identifier()+ {+ if (End || tokens[position].Shape != "identifier")+ {+ Fail(errorCode, "Expected an identifier, found " + Peek);+ }+ return Take();+ }+ public string Block()+ {+ Expect("{");+ int start = tokens[position - 1].Start + 1;+ int depth = 1;+ while (!End)+ {+ var token = tokens[position++];+ if (token.Text == "{")+ {+ depth++;+ }+ if (token.Text == "}")+ {+ depth--;+ }+ if (depth == 0)+ {+ return source[start..token.Start];+ }+ }+ Fail(errorCode, "Unclosed source block.");+ return "";+ }+ public void SkipDeclaration()+ {+ while (!End && Peek != "{")+ {+ Take();+ }+ Block();+ Optional(";");+ }+ public string Value()+ {+ if (End)+ {+ Fail(errorCode, "Missing field value.");+ }+ int start = tokens[position].Start;+ int end = start;+ int depth = 0;+ while (!End)+ {+ var token = tokens[position];+ if (depth == 0 && (token.Text == ";" || (position + 1 < tokens.Length && tokens[position + 1].Text == ":")))+ {+ break;+ }+ if (depth == 0 && end > start && token.Text is "Panel" or "Fabric" or "Interface" or "Drape" or "Fitting")+ {+ break;+ }+ if (token.Text is "[" or "(")+ {+ depth++;+ }+ if (token.Text is "]" or ")")+ {+ depth--;+ }+ if (depth < 0)+ {+ Fail(errorCode, "Unbalanced field value.");+ }+ end = token.Start + token.Length;+ position++;+ }+ if (depth != 0 || end == start)+ {+ Fail(errorCode, "Missing or unbalanced field value.");+ }+ Optional(";");+ return source[start..end].Trim();+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.csindex 4055dec1..ac12ddc8 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs@@ -160,6 +160,28 @@ public static class FirmamentLanguageAnalysisService}}+ private static bool SameFittingGuides(Garment.CompiledGarment before, Garment.CompiledGarment after)+ {+ if (before.FittingGuides.Length != after.FittingGuides.Length)+ {+ return false;+ }+ for (int index = 0; index < before.FittingGuides.Length; index++)+ {+ var original = before.FittingGuides[index];+ var formatted = after.FittingGuides[index];+ if (original.ConceptPlane != formatted.ConceptPlane || original.ReleaseAfter != formatted.ReleaseAfter+ || original.Constraint.Id != formatted.Constraint.Id || original.Constraint.Normal != formatted.Constraint.Normal+ || original.Constraint.Offset != formatted.Constraint.Offset+ || original.Constraint.Compliance != formatted.Constraint.Compliance+ || !original.Constraint.Vertices.SequenceEqual(formatted.Constraint.Vertices))+ {+ return false;+ }+ }+ return true;+ }+public static FirmamentLanguageFormat Format(string source, string document, string revision){if (Garment.GarmentAuthoring.HasRoot(source))@@ -171,7 +193,8 @@ public static class FirmamentLanguageAnalysisService}var garmentFormat = FormatConventions(source, document, revision);var after = Garment.GarmentCompiler.Compile(garmentFormat.Text, document);- if (!after.IsSuccess || before.Garment!.Cloth.ContentKey != after.Garment!.Cloth.ContentKey)+ if (!after.IsSuccess || before.Garment!.Cloth.ContentKey != after.Garment!.Cloth.ContentKey+ || !SameFittingGuides(before.Garment, after.Garment)){throw new InvalidOperationException("Garment formatting changed compilation.");}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.csindex 5c75aa4b..357352b0 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs@@ -139,7 +139,7 @@ public static class FirmamentLanguageService{// Ignore comments/strings and balance nested blocks in incomplete drafts.var prefix = Regex.Replace(source[..offset], @"//[^\r\n]*|/\*[\s\S]*?\*/|""(?:\\.|[^""\\])*""", m => new string(' ', m.Length));- var names = "Scene|Room|Door|Window|Camera|WireRoute|Follow|Section|Points|Linear|Series|Appearance|Material|Placement|FrameTransform|Garment|Panel|Fabric|Drape|Interface";+ var names = "Scene|Room|Door|Window|Camera|WireRoute|Follow|Section|Points|Linear|Series|Appearance|Material|Placement|FrameTransform|Garment|Panel|Fabric|Drape|FigureFit|Fitting|PoseTransition|Pose|Joint|Interface";var matches = Regex.Matches(prefix, $@"\b(?<kind>{names})(?:\s*<(?<family>[^>]+)>)?(?:\s+[A-Za-z_]\w*)?\s*\{{");foreach (Match header in matches.Cast<Match>().Reverse()){diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.csindex 0bc89cf3..5b4609bb 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs@@ -187,7 +187,12 @@ public static class FirmamentSourceSpellingAdd("Panel", "Profile Origin U V Grain Pin PatternIdentity WrapRadius WrapAngle WrapTopRadius WrapTopOrigin WrapTopAngle");Add("Fabric", "ArealDensity Thickness WarpCompliance WeftCompliance DiagonalCompliance BendCompliance");Add("Interface", "A B Orientation Ease Compliance");- Add("Drape", "Figure Pose Clearance");+ Add("Drape", "Figure Pose Clearance Transition");+ Add("Fitting", "On Edges Compliance ReleaseAfter");+ Add("Pose", "Figure From");+ Add("Joint", "Flexion Abduction Twist");+ Add("PoseTransition", "From To Duration Easing");+ Add("FigureFit", "Figure Pose ChestHeight HipHeight");Add("Assembly Subassembly", "Anchor Provenance Appearance");Add("Part Occurrence", "Material Appearance");Add("Plane DatumPlane", "Origin Normal Up From Offset RotateLocal Clocking");@@ -201,7 +206,8 @@ public static class FirmamentSourceSpellingAdd("CubicBezier2", "From Control1 Control2 To");Add("Line2", "From To");Add("Profile", "From");- Add("Replace", "On Through Derivatives");+ Add("Segment", "Trace From To Sweep");+ Add("Replace", "On Range Through Derivatives Join StartTangent EndTangent Interpolation SpanNames");Add("Path", "Start Heading");Add("Line", "Length To");Add("Extrude Base", "Profile From To Role");diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.csindex 11d13a19..e9a01609 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs@@ -466,7 +466,7 @@ internal static class FirmamentV2FeatureExpansionfor (var i = 0; i < text.Length; i++) { switch (text[i]) { case '(': round++; break; case ')': round--; break; case '[': square++; break; case ']': square--; break; case '{': curly++; break; case '}': curly--; break; case ':' when round == 0 && square == 0 && curly == 0: return i; } }return -1;}- private static List<(string Text, int Start)> SplitTopLevel(string text)+ internal static List<(string Text, int Start)> SplitTopLevel(string text){var result = new List<(string, int)>(); var start = 0; var round = 0; var square = 0; var curly = 0;for (var i = 0; i < text.Length; i++)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileBoundaryAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileBoundaryAuthoring.csindex 185881e0..0098ad4e 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileBoundaryAuthoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileBoundaryAuthoring.cs@@ -25,6 +25,26 @@ internal static class ProfileBoundaryAuthoringbool RequireTangentJoin = false);private static string WithoutComments(string text) => Regex.Replace(text, @"/\*.*?\*/|//[^\r\n]*", "", RegexOptions.Singleline);+ private static string[] SpanNames(Dictionary<string, string> fields, string edit, int count, List<string> diagnostics)+ {+ var defaults = Enumerable.Range(0, count).Select(index => $"{edit}_Span{index}").ToArray();+ if (!fields.TryGetValue("SpanNames", out string? text))+ {+ return defaults;+ }+ if (!Regex.IsMatch(text, @"^\[\s*[A-Za-z_]\w*(?:\s*,\s*[A-Za-z_]\w*)*\s*\]$"))+ {+ diagnostics.Add($"profile-edit-span-names-invalid:{edit}");+ return defaults;+ }+ var names = text[1..^1].Split(',', StringSplitOptions.TrimEntries);+ if (names.Length != count || names.Distinct(StringComparer.Ordinal).Count() != count)+ {+ diagnostics.Add($"profile-edit-span-names-invalid:{edit}:expected-{count}");+ return defaults;+ }+ return names;+ }internal static bool IsDerived(string? body) => body is not null && Regex.IsMatch(WithoutComments(body), @"^\s*From\s*:");internal static bool TryResolve(string source, string name, HashSet<string> visiting,@@ -79,7 +99,7 @@ internal static class ProfileBoundaryAuthoringstarts.Add(knots.Count); knots.Add(carrier.Start);foreach (var replacement in replacements){- var replacementFields = Fields(replacement.Body, ["On", "Range", "Through", "Derivatives", "Join", "StartTangent", "EndTangent"], diagnostics, replacement.Name);+ var replacementFields = Fields(replacement.Body, ["On", "Range", "Through", "Derivatives", "Join", "StartTangent", "EndTangent", "Interpolation", "SpanNames"], diagnostics, replacement.Name);if (!replacementFields.TryGetValue("On", out var target) || FindMember(segments, target, owner, localFrom) != i) continue;if (replacementFields.ContainsKey("Range")) diagnostics.Add($"profile-edit-periodic-range-not-qualified:{replacement.Name}");if (replacementFields.TryGetValue("Through", out var value)) knots.AddRange(Vectors(value, "mm", diagnostics, replacement.Name));@@ -98,7 +118,7 @@ internal static class ProfileBoundaryAuthoringforeach (var block in replacements){if (!ids.Add(block.Name)) { diagnostics.Add($"profile-edit-duplicate-name:{name}.{block.Name}"); continue; }- var fields = Fields(block.Body, ["On", "Range", "Through", "Derivatives", "Join", "StartTangent", "EndTangent"], diagnostics, name + "." + block.Name);+ var fields = Fields(block.Body, ["On", "Range", "Through", "Derivatives", "Join", "StartTangent", "EndTangent", "Interpolation", "SpanNames"], diagnostics, name + "." + block.Name);if (!fields.TryGetValue("On", out var on)) { diagnostics.Add($"profile-edit-target-missing:{block.Name}"); continue; }var index = FindMember(segments, on, owner, localFrom);if (index < 0) { diagnostics.Add($"profile-edit-target-missing:{block.Name}:{on}"); continue; }@@ -109,6 +129,37 @@ internal static class ProfileBoundaryAuthoringif (!ValidRange(range, length)) { diagnostics.Add($"profile-edit-range-invalid:{block.Name}"); continue; }if (!fields.TryGetValue("Through", out var through)) { diagnostics.Add($"profile-edit-construction-required:{block.Name}:Through"); continue; }var points = Vectors(through, "mm", diagnostics, block.Name);+ string interpolation = fields.GetValueOrDefault("Interpolation", "Hermite");+ if (interpolation is not ("Hermite" or "Linear"))+ {+ diagnostics.Add($"profile-edit-interpolation-invalid:{block.Name}:{interpolation}");+ continue;+ }+ if (interpolation == "Linear")+ {+ if (fields.Keys.Any(key => key is "Derivatives" or "StartTangent" or "EndTangent")+ || fields.GetValueOrDefault("Join", "Position") != "Position")+ {+ diagnostics.Add($"profile-edit-construction-conflict:{block.Name}:Linear-and-tangents");+ continue;+ }+ var direction = Subtract(line.End, line.Start);+ var knots = new[] { Add(line.Start, Scale(direction, range.Item1 / length)) }+ .Concat(points).Append(Add(line.Start, Scale(direction, range.Item2 / length))).ToArray();+ var linearCurves = new List<(string Name, LineArcProfileCurve2D Curve)>();+ var names = SpanNames(fields, block.Name, knots.Length - 1, diagnostics);+ for (int knot = 0; knot + 1 < knots.Length; knot++)+ {+ if (Distance(knots[knot], knots[knot + 1]) <= Tol)+ {+ diagnostics.Add($"profile-edit-repeated-point:{block.Name}");+ }+ linearCurves.Add((names[knot], new LineArcLineSegment2D(knots[knot], knots[knot + 1])));+ }+ edits.Add(new(block.Name, index, range.Item1 / length, range.Item2 / length,+ linearCurves, "LinearThrough", $"profile:{name}/Replace:{block.Name}"));+ continue;+ }var derivatives = fields.TryGetValue("Derivatives", out var derivativeText)? derivativeText == "Periodic" ? periodic.GetValueOrDefault(index) : Vectors(derivativeText, "mm", diagnostics, block.Name) : null;var join = fields.GetValueOrDefault("Join", "Position");@@ -119,8 +170,9 @@ internal static class ProfileBoundaryAuthoringdiagnostics.Add($"profile-edit-construction-conflict:{block.Name}:Derivatives-and-tangents");var construction = new ProfileThroughConstruction(points, derivatives, startTangent, endTangent, join == "Tangent");var curves = Construct(line, range, construction, diagnostics, block.Name);+ var curveNames = SpanNames(fields, block.Name, curves.Count, diagnostics);edits.Add(new(block.Name, index, range.Item1 / length, range.Item2 / length,- curves.Select((c, i) => ($"{block.Name}_Span{i}", (LineArcProfileCurve2D)c)).ToArray(),+ curves.Select((c, i) => (curveNames[i], (LineArcProfileCurve2D)c)).ToArray(),derivatives is null ? "ChordHermite" : derivativeText == "Periodic" ? "PeriodicHermite" : "ExplicitHermite", $"profile:{name}/Replace:{block.Name}", construction.MatchTangent));}foreach (var apply in applies)@@ -174,9 +226,20 @@ internal static class ProfileBoundaryAuthoringDerivation = FormattableString.Invariant($"RetainedBoundary:{a:R}..{b:R}") }));}}- result = new(name, seed.PlaneFrame, [new("Outer", true, output)], seed.ConstructionPlane,- BoundaryEdits: edits.Select(e => new ProfileBoundaryEditEvidence(e.Name, segments[e.Segment].Name, e.From, e.To,- e.Construction, e.Curves.Select(c => c.Name).ToArray(), e.SourceSpan)).ToArray());+ if (output.Select(segment => segment.Name).Distinct(StringComparer.Ordinal).Count() != output.Count)+ {+ diagnostics.Add($"profile-edit-span-name-duplicate:{name}");+ return true;+ }+ var retainedEdits = (seed.BoundaryEdits ?? []).Where(edit => edit.Descendants.All(descendant => output.Any(segment => segment.Name == descendant)));+ var boundaryEdits = retainedEdits.Concat(edits.Select(e => new ProfileBoundaryEditEvidence(e.Name, segments[e.Segment].Name, e.From, e.To,+ e.Construction, e.Curves.Select(c => c.Name).ToArray(), e.SourceSpan))).ToArray();+ if (boundaryEdits.Select(edit => edit.Name).Distinct(StringComparer.Ordinal).Count() != boundaryEdits.Length)+ {+ diagnostics.Add($"profile-edit-duplicate-name:{name}:retained-edit-name");+ return true;+ }+ result = new(name, seed.PlaneFrame, [new("Outer", true, output)], seed.ConstructionPlane, BoundaryEdits: boundaryEdits);diagnostics.AddRange(ResolvedProfile2DValidator.Validate(result).Diagnostics);if (edits.Count > 0) ValidateSimple(output, diagnostics, name);foreach (var edit in edits.Where(e => e.RequireTangentJoin))diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentAuthoring.cs b/Aetheris.Kernel.Firmament/Garment/GarmentAuthoring.csindex 31cf5bd3..e82eb2ca 100644--- a/Aetheris.Kernel.Firmament/Garment/GarmentAuthoring.cs+++ b/Aetheris.Kernel.Firmament/Garment/GarmentAuthoring.cs@@ -7,6 +7,7 @@ using System.Text.RegularExpressions;using Aetheris.Cloth3D;using Aetheris.Kernel.Firmament.FirmamentV2;using Aetheris.Kernel.Firmament.Materializer;+using Aetheris.Kernel.Firmament.Humanoid;namespace Aetheris.Kernel.Firmament.Garment;@@ -15,11 +16,19 @@ public sealed record GarmentPanel(string Name, string Identity, ResolvedProfile2Vector3 Origin, Vector3 U, Vector3 V, Vector2 Grain, ImmutableArray<string> Pins,float? WrapRadius, float WrapAngle, float? WrapTopRadius, Vector3? WrapTopOrigin, float WrapTopAngle);public sealed record GarmentStitch(string Name, string A, string B, bool Reversed, float Ease, float Compliance);+public sealed record GarmentFittingGuide(string Name, string ConceptPlane, ImmutableArray<string> Edges,+ Vector3 Normal, float Offset, float Compliance, int ReleaseAfter);public sealed record GarmentSource(string Name, string SourceIdentity, string SourceHash,ClothMaterial3D Fabric, float MeshSize, ImmutableArray<GarmentPanel> Panels,ImmutableArray<GarmentStitch> Stitches, string? Figure, string? Pose,IReadOnlyList<FirmamentV2FeatureInvocation> Features,- IReadOnlyList<FirmamentV2CanonicalPatternDecl> Patterns, float BodyClearance);+ IReadOnlyList<FirmamentV2CanonicalPatternDecl> Patterns, float BodyClearance)+{+ public IReadOnlyList<GarmentFigureFitEvidence> FigureFits { get; init; } = [];+ public FirmamentPoseDocument? Posing { get; init; }+ public string? Transition { get; init; }+ public ImmutableArray<GarmentFittingGuide> FittingGuides { get; init; } = [];+}public sealed record GarmentParseResult(GarmentSource? Source, IReadOnlyList<GarmentDiagnostic> Diagnostics){public bool IsSuccess => Source is not null && Diagnostics.Count == 0;@@ -51,23 +60,27 @@ public static class GarmentAuthoringreturn false;}- public static GarmentParseResult Parse(string source, string sourceIdentity = "<memory>")+ public static GarmentParseResult Parse(string source, string sourceIdentity = "<memory>", GarmentFigureBinding? figureBinding = null){try{- return ParseCore(source, sourceIdentity);+ return ParseCore(source, sourceIdentity, figureBinding);}catch (GarmentAuthoringException exception){return new(null, [new(exception.Code, exception.Message, sourceIdentity)]);}+ catch (InvalidDataException exception)+ {+ return new(null, [new(exception.Message.Split(':')[0], exception.Message, sourceIdentity)]);+ }catch (Exception exception) when (exception is FormatException or OverflowException or ArgumentException){return new(null, [new("garment-value-invalid", exception.Message, sourceIdentity)]);}}- private static GarmentParseResult ParseCore(string original, string identity)+ private static GarmentParseResult ParseCore(string original, string identity, GarmentFigureBinding? figureBinding){var selection = FirmamentFrontendSchemas.Select(original);if (!selection.IsSuccess)@@ -86,6 +99,10 @@ public static class GarmentAuthoringArray.Fill(characters, ' ', token.Start, token.Length);}source = new string(characters);+ var posing = HumanoidPoseAuthoring.Parse(source);+ source = posing.RemainingSource;+ var figureFits = new List<GarmentFigureFitEvidence>();+ source = GarmentFigureAuthoring.Expand(source, figureBinding, figureFits, posing);var expansionDiagnostics = new List<string>();var features = FirmamentV2FeatureExpansion.Expand(source, expansionDiagnostics);if (features is null || expansionDiagnostics.Count > 0)@@ -98,13 +115,39 @@ public static class GarmentAuthoringreturn ExpansionFailure(expansionDiagnostics, identity);}source = patterns.Source;- var reader = new Reader(source);+ var reader = new FirmamentBlockReader(source, Fail);while (!reader.End && reader.Peek != "Garment"){if (reader.Optional(";")){continue;}+ if (reader.Peek == "Concept")+ {+ reader.Expect("Concept");+ reader.Expect("Struct");+ reader.SkipDeclaration();+ continue;+ }+ if (reader.Peek is "Use" or "ProfileDelta")+ {+ string kind = reader.Take();+ if (kind == "ProfileDelta")+ {+ reader.Identifier();+ if (reader.Peek == "{")+ {+ reader.Block();+ reader.Optional(";");+ continue;+ }+ }+ while (!reader.End && !reader.Optional(";"))+ {+ reader.Take();+ }+ continue;+ }if (reader.Peek is not ("Point2" or "Line2" or "CubicBezier2" or "Circle2" or "Rect2"or "RoundedRect2" or "Polygon2" or "Profile" or "Curve2" or "Ellipse2Guide")){@@ -120,15 +163,17 @@ public static class GarmentAuthoring{Fail("garment-multiple-roots", "One Garment root is required, with geometry recipes before it.");}- var body = new Reader(bodyText);+ var body = new FirmamentBlockReader(bodyText, Fail);var panels = ImmutableArray.CreateBuilder<GarmentPanel>();var stitches = ImmutableArray.CreateBuilder<GarmentStitch>();+ var guides = ImmutableArray.CreateBuilder<GarmentFittingGuide>();var names = new HashSet<string>(StringComparer.Ordinal);ClothMaterial3D? fabric = null;float meshSize = .06f;bool hasMeshSize = false;string? figure = null;string? pose = null;+ string? transition = null;float bodyClearance = .004f;while (!body.End){@@ -158,7 +203,7 @@ public static class GarmentAuthoring{Fail("garment-duplicate-drape", "Declare only one Drape binding.");}- var fields = Fields(body.Block(), ["Figure", "Pose", "Clearance"]);+ var fields = Fields(body.Block(), ["Figure", "Pose", "Clearance", "Transition"]);figure = Required(fields, "Figure");pose = fields.GetValueOrDefault("Pose", "Rest");bodyClearance = Length(fields.GetValueOrDefault("Clearance", "4mm"));@@ -166,9 +211,12 @@ public static class GarmentAuthoring{Fail("garment-body-clearance", "clearance must be between 0mm and 30mm.");}- if (pose != "Rest")+ posing.Resolve(pose, figure);+ transition = fields.GetValueOrDefault("Transition");+ if (transition is not null && (!posing.Transitions.TryGetValue(transition, out var motion)+ || motion.From != pose || posing.Resolve(motion.To, figure).Figure != figure)){- Fail("garment-pose-unsupported", "This drape milestone admits the loaded figure's Rest pose only.");+ Fail("garment-pose-transition-binding", "Drape transition must start at its named pose and use the same figure.");}continue;}@@ -186,6 +234,30 @@ public static class GarmentAuthoringstring declarationBody = body.Block();switch (kind){+ case "Fitting":+ {+ var fields = Fields(declarationBody, ["On", "Edges", "Compliance", "ReleaseAfter"]);+ string reference = Required(fields, "On");+ if (!ConceptIrResolver.TryResolvePlane(source, reference, out var plane, out var diagnostic))+ {+ Fail("garment-fitting-plane", diagnostic ?? reference);+ }+ Vector3 normal = new((float)plane!.Normal.X, (float)plane.Normal.Y, (float)plane.Normal.Z);+ Vector3 origin = new((float)plane.Origin.X * .001f, (float)plane.Origin.Y * .001f, (float)plane.Origin.Z * .001f);+ float compliance = Scalar(fields.GetValueOrDefault("Compliance", "0.000001"));+ float release = Scalar(Required(fields, "ReleaseAfter"));+ var edges = List(Required(fields, "Edges")).ToImmutableArray();+ float offset = Vector3.Dot(normal, origin);+ if (guides.Count >= 32 || edges.IsEmpty || edges.Length > 64+ || edges.Distinct().Count() != edges.Length || !float.IsFinite(normal.LengthSquared())+ || MathF.Abs(normal.LengthSquared() - 1) > .0001f || !float.IsFinite(offset)+ || compliance < 0 || release is < 0 or > 585 || release != MathF.Floor(release))+ {+ Fail("garment-fitting-properties", "Fitting requires a unit Concept plane, unique edges, nonnegative compliance and an integer releaseAfter of 0..585 settling frames.");+ }+ guides.Add(new(declarationName, reference, edges, normal, offset, compliance, (int)release));+ break;+ }case "Fabric":{if (fabric is not null)@@ -284,8 +356,20 @@ public static class GarmentAuthoringFail("garment-fabric-missing", "Declare one Fabric with explicit authoring properties.");}string hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(original)));- return new(new(name, identity, hash, fabric!, meshSize, panels.ToImmutable(), stitches.ToImmutable(),- figure, pose, features.Invocations, patterns.Document?.Patterns ?? [], bodyClearance), []);+ var garment = new GarmentSource(name, identity, hash, fabric!, meshSize, panels.ToImmutable(), stitches.ToImmutable(),+ figure, pose, features.Invocations, patterns.Document?.Patterns ?? [], bodyClearance)+ {+ FigureFits = figureFits,+ Posing = posing,+ Transition = transition,+ FittingGuides = guides.ToImmutable(),+ };+ if (figureFits.Any(fit => fit.Figure != figure))+ {+ Fail("garment-fit-binding-mismatch", "FigureFit and Drape must refer to the same figure.");+ }+ _ = GarmentPatternInspection.Inspect(garment);+ return new(garment, []);}private static GarmentParseResult ExpansionFailure(IEnumerable<string> diagnostics, string identity)@@ -293,10 +377,10 @@ public static class GarmentAuthoringreturn new(null, diagnostics.Select(message => new GarmentDiagnostic(message.Split(':')[0], message, identity)).ToArray());}- private static Dictionary<string, string> Fields(string text, string[] admitted)+ internal static Dictionary<string, string> Fields(string text, string[] admitted){var result = new Dictionary<string, string>(StringComparer.Ordinal);- var reader = new Reader(text);+ var reader = new FirmamentBlockReader(text, Fail);while (!reader.End){if (reader.Optional(";"))@@ -328,7 +412,11 @@ public static class GarmentAuthoringprivate static float Scalar(string value){- float result = float.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture);+ if (!FirmamentV2FeatureExpansion.TryEvaluateScalar(value, out double evaluated, out string unit) || unit.Length != 0)+ {+ Fail("garment-scalar-invalid", "Expected a dimensionless scalar: " + value);+ }+ float result = (float)evaluated;if (!float.IsFinite(result)){Fail("garment-nonfinite", "All garment values must be finite.");@@ -338,6 +426,14 @@ public static class GarmentAuthoringprivate static float Length(string value){+ if (FirmamentV2FeatureExpansion.TryEvaluateScalar(value, out double evaluated, out string unit) && unit == "mm")+ {+ if (!double.IsFinite(evaluated) || !float.IsFinite((float)evaluated))+ {+ Fail("garment-nonfinite", "All garment values must be finite.");+ }+ return (float)evaluated * .001f;+ }var match = Regex.Match(value, @"^\s*(?<number>[-+\d.eE]+)\s*(?<unit>mm|m)\s*$", RegexOptions.CultureInvariant);if (!match.Success){@@ -380,129 +476,7 @@ public static class GarmentAuthoringinternal static void Fail(string code, string message) => throw new GarmentAuthoringException(code, message);- private sealed class Reader- {- private readonly string source;- private readonly (string Text, string Shape, int Start, int Length)[] tokens;- private int position;-- public Reader(string source)- {- this.source = source;- tokens = FirmamentLanguageAnalysisService.Lex(source).Where(token => token.Shape != "comment")- .Select(token => (token.Text, token.Shape, token.Start, token.Length)).ToArray();- }- public bool End => position >= tokens.Length;- public string Peek => End ? "<end>" : tokens[position].Text;- public string Take()- {- if (End)- {- Fail("garment-syntax", "Unexpected end of garment document.");- }- return tokens[position++].Text;- }- public bool Optional(string text)- {- if (Peek != text)- {- return false;- }- position++;- return true;- }- public void Expect(string text)- {- if (!Optional(text))- {- Fail("garment-syntax", "Expected '" + text + "', found '" + Peek + "'.");- }- }- public string Identifier()- {- if (End || tokens[position].Shape != "identifier")- {- Fail("garment-syntax", "Expected an identifier, found " + Peek);- }- return Take();- }- public string Block()- {- Expect("{");- int start = tokens[position - 1].Start + 1;- int depth = 1;- while (!End)- {- var token = tokens[position++];- if (token.Text == "{")- {- depth++;- }- if (token.Text == "}")- {- depth--;- }- if (depth == 0)- {- return source[start..token.Start];- }- }- Fail("garment-syntax", "Unclosed garment block.");- return "";- }- public void SkipDeclaration()- {- while (!End && Peek != "{")- {- Take();- }- Block();- Optional(";");- }- public string Value()- {- if (End)- {- Fail("garment-syntax", "Missing field value.");- }- int start = tokens[position].Start;- int end = start;- int depth = 0;- while (!End)- {- var token = tokens[position];- if (depth == 0 && (token.Text == ";" || (position + 1 < tokens.Length && tokens[position + 1].Text == ":")))- {- break;- }- if (depth == 0 && end > start && token.Text is "Panel" or "Fabric" or "Interface" or "Drape")- {- break;- }- if (token.Text is "[" or "(")- {- depth++;- }- if (token.Text is "]" or ")")- {- depth--;- }- if (depth < 0)- {- Fail("garment-syntax", "Unbalanced field value.");- }- end = token.Start + token.Length;- position++;- }- if (depth != 0 || end == start)- {- Fail("garment-syntax", "Missing or unbalanced field value.");- }- Optional(";");- return source[start..end].Trim();- }- }}internal sealed class GarmentAuthoringException(string code, string message) : Exception(message)diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentCodeImport.cs b/Aetheris.Kernel.Firmament/Garment/GarmentCodeImport.csnew file mode 100644index 00000000..6388b405--- /dev/null+++ b/Aetheris.Kernel.Firmament/Garment/GarmentCodeImport.cs@@ -0,0 +1,369 @@+using System.Globalization;+using System.Numerics;+using System.Security.Cryptography;+using System.Text;+using System.Text.Json;+using System.Text.RegularExpressions;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.Garment;++public sealed record GarmentCodePanelMapping(string UpstreamName, string PanelName, bool BoundaryReversed, IReadOnlyList<string> Edges);+public sealed record GarmentCodeImportResult(string? Source, string InputHash,+ IReadOnlyList<GarmentCodePanelMapping> Panels, IReadOnlyList<GarmentDiagnostic> Diagnostics)+{+ public bool IsSuccess => Source is not null && Diagnostics.Count == 0;+}++/// <summary>Converts resolved GarmentCode sewing patterns into ordinary editable Firmament.+/// Curve coordinates and stitch conventions follow GarmentCode (MIT, Maria Korosteleva),+/// pygarment/pattern/utils.py and pygarment/meshgen/boxmeshgen.py. See THIRD_PARTY_NOTICES.md.+/// No upstream Python, triangulator or simulator is needed at runtime.</summary>+public static class GarmentCodeImport+{+ public static GarmentCodeImportResult Import(string json, string identity = "<memory>")+ {+ string hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(json)));+ try+ {+ if (json.Length > 16 * 1024 * 1024)+ {+ Fail("garmentcode-input-budget", "Pattern JSON exceeds the 16 MiB import budget.");+ }+ return ImportCore(json, hash, identity);+ }+ catch (Exception exception) when (exception is JsonException or InvalidDataException+ or KeyNotFoundException or InvalidOperationException or FormatException or OverflowException+ or IndexOutOfRangeException or ArgumentException)+ {+ string code = exception is InvalidDataException ? exception.Message.Split(':')[0] : "garmentcode-json-invalid";+ return new(null, hash, [], [new(code, exception.Message, identity)]);+ }+ }++ private static GarmentCodeImportResult ImportCore(string json, string hash, string identity)+ {+ using var document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 64 });+ var root = document.RootElement;+ if ((root.TryGetProperty("parameters", out var parameters) && parameters.EnumerateObject().Any())+ || (root.TryGetProperty("parameter_order", out var order) && order.GetArrayLength() != 0))+ {+ Fail("garmentcode-parameters-unresolved", "Evaluate the upstream design program before importing its resolved pattern.");+ }+ var properties = root.GetProperty("properties");+ if (properties.GetProperty("curvature_coords").GetString() != "relative"+ || properties.GetProperty("normalize_panel_translation").GetBoolean())+ {+ Fail("garmentcode-normalization-required", "Export resolved relative curves and explicit panel translations first.");+ }+ double units = Number(properties.GetProperty("units_in_meter"));+ if (units <= 0)+ {+ Fail("garmentcode-units-invalid", "units_in_meter must be positive.");+ }+ double millimeters = 1000 / units;+ var pattern = root.GetProperty("pattern");+ var panels = new List<ImportedPanel>();+ var names = new HashSet<string>(StringComparer.Ordinal);+ var text = new StringBuilder();+ text.AppendLine("schema Garment");+ text.AppendLine("// Imported from GarmentCode; MIT, copyright (c) 2024 Maria Korosteleva.");+ text.AppendLine("// Keep the source specification and its applicable license with this derivative.");+ text.AppendLine("// Input SHA-256: " + hash);+ text.AppendLine("// Local XY remains the flat rest pattern. Placement maps upstream Y-up to Aetheris Z-up.");+ foreach (var entry in pattern.GetProperty("panels").EnumerateObject())+ {+ string name = Identifier(entry.Name);+ if (!names.Add(name))+ {+ Fail("garmentcode-name-collision", entry.Name);+ }+ var vertices = entry.Value.GetProperty("vertices").EnumerateArray()+ .Select(value => Point(value, millimeters)).ToArray();+ if (vertices.Length is < 3 or > 4096)+ {+ Fail("garmentcode-vertex-budget", "A panel requires between 3 and 4096 cut vertices.");+ }+ var edges = new List<ImportedEdge>();+ foreach (var edge in entry.Value.GetProperty("edges").EnumerateArray())+ {+ var endpoints = edge.GetProperty("endpoints").EnumerateArray().Select(value => value.GetInt32()).ToArray();+ if (endpoints.Length != 2 || endpoints.Any(index => index < 0 || index >= vertices.Length))+ {+ Fail("garmentcode-endpoint-invalid", entry.Name);+ }+ string edgeName = "edge" + edges.Count;+ if (edge.TryGetProperty("label", out var label) && !string.IsNullOrEmpty(label.GetString()))+ {+ edgeName += "_" + Identifier(label.GetString()!);+ }+ edges.Add(new(edges.Count, edgeName, endpoints[0], endpoints[1], Curve(edge, vertices[endpoints[0]], vertices[endpoints[1]], millimeters)));+ }+ if (edges.Count < 3 || edges.Where((edge, index) => edge.To != edges[(index + 1) % edges.Count].From).Any())+ {+ Fail("garmentcode-loop-invalid", entry.Name + " must contain one ordered closed edge loop.");+ }+ bool reversed = edges.Sum(edge => ResolvedProfile2DValidator.SignedAreaContribution(edge.Curve)) < 0;+ if (reversed)+ {+ edges = edges.AsEnumerable().Reverse().Select(edge => edge with+ {+ From = edge.To,+ To = edge.From,+ Curve = Reverse(edge.Curve),+ }).ToList();+ }+ var translation = Triple(entry.Value.GetProperty("translation"));+ var rotation = Triple(entry.Value.GetProperty("rotation"));+ var panel = new ImportedPanel(entry.Name, name, vertices, edges, translation, rotation, reversed);+ panels.Add(panel);+ EmitFeature(text, panel);+ }+ if (panels.Count is < 1 or > 128)+ {+ Fail("garmentcode-panel-budget", "Import between 1 and 128 panels.");+ }+ text.AppendLine("Garment ImportedGarment {");+ text.AppendLine(" meshSize: 60mm;");+ text.AppendLine(" // Aetheris cotton defaults; upstream JSON does not specify fabric physics.");+ text.AppendLine(" Fabric cotton {");+ text.AppendLine(" thickness: 2mm;");+ text.AppendLine(" arealDensity: 0.2;");+ text.AppendLine(" warpCompliance: 0.00000001;");+ text.AppendLine(" weftCompliance: 0.00000001;");+ text.AppendLine(" diagonalCompliance: 0.00000004;");+ text.AppendLine(" }");+ foreach (var panel in panels)+ {+ text.AppendLine($" Panel {panel.Name} {{");+ text.AppendLine($" profile: {panel.Name}Cut;");+ var origin = panel.Translation.Select(value => value * millimeters).ToArray();+ text.AppendLine($" origin: [{Length(origin[0])}, {Length(origin[2])}, {Length(origin[1])}];");+ text.AppendLine(" u: " + Direction(Rotate(Vector3.UnitX, panel.Rotation)) + ";");+ text.AppendLine(" v: " + Direction(Rotate(Vector3.UnitY, panel.Rotation)) + ";");+ text.AppendLine(" grain: [0, 1];");+ text.AppendLine(" }");+ }+ int seamIndex = 0;+ foreach (var pair in pattern.GetProperty("stitches").EnumerateArray())+ {+ var values = pair.EnumerateArray().ToArray();+ if (values.Length is < 2 or > 3 || (values.Length == 3 && values[2].GetString() != "right_wrong"))+ {+ Fail("garmentcode-stitch-invalid", "Expected two edge references and an optional right_wrong flag.");+ }+ var a = Reference(values[0], panels);+ var b = Reference(values[1], panels);+ double lengthA = GarmentPatternInspection.CurveLength(a.Edge.Curve);+ double lengthB = GarmentPatternInspection.CurveLength(b.Edge.Curve);+ double mismatch = Math.Abs(lengthA - lengthB) / Math.Max(lengthA, lengthB);+ if (mismatch > .25)+ {+ Fail("garmentcode-ease-unsupported", "Seam " + seamIndex + " exceeds the admitted 25% ease budget.");+ }+ text.AppendLine($" Interface<Stitch> seam{seamIndex++} {{");+ text.AppendLine($" a: {a.Panel.Name}.edges.{a.Edge.Name};");+ text.AppendLine($" b: {b.Panel.Name}.edges.{b.Edge.Name};");+ bool reversedSeam = (values.Length != 3) ^ a.Panel.BoundaryReversed ^ b.Panel.BoundaryReversed;+ text.AppendLine(" orientation: " + (reversedSeam ? "Reversed" : "Same") + ";");+ text.AppendLine(" // Measured mismatch in the upstream pattern, explicitly retained as ease.");+ text.AppendLine(" ease: " + Scalar(mismatch) + ";");+ text.AppendLine(" }");+ }+ text.AppendLine("}");+ string source = text.ToString();+ var parsed = GarmentAuthoring.Parse(source, identity);+ if (!parsed.IsSuccess)+ {+ return new(null, hash, [], parsed.Diagnostics);+ }+ return new(source, hash, panels.Select(panel => new GarmentCodePanelMapping(panel.UpstreamName,+ panel.Name, panel.BoundaryReversed, panel.Edges.OrderBy(edge => edge.Index).Select(edge => edge.Name).ToArray())).ToArray(), []);+ }++ private static void EmitFeature(StringBuilder text, ImportedPanel panel)+ {+ text.AppendLine();+ text.AppendLine($"Feature {panel.Name}Pattern() -> Profile {{");+ for (int i = 0; i < panel.Vertices.Length; i++)+ {+ EmitPoint(text, "vertex" + i, panel.Vertices[i]);+ }+ foreach (var edge in panel.Edges)+ {+ string guide = edge.Name + "Guide";+ switch (edge.Curve)+ {+ case LineArcLineSegment2D:+ text.AppendLine($" Line2 {guide} {{ from: vertex{edge.From}; to: vertex{edge.To} }}");+ break;+ case LineArcCubicBezier2D cubic:+ EmitPoint(text, edge.Name + "Control1", cubic.Control1);+ EmitPoint(text, edge.Name + "Control2", cubic.Control2);+ text.AppendLine($" CubicBezier2 {guide} {{ from: vertex{edge.From}; control1: {edge.Name}Control1; control2: {edge.Name}Control2; to: vertex{edge.To} }}");+ break;+ case LineArcCircularArc2D arc:+ EmitPoint(text, edge.Name + "Center", arc.Center);+ text.AppendLine($" Circle2 {guide} {{ center: {edge.Name}Center; radius: {Length(arc.Radius)} }}");+ break;+ }+ }+ text.AppendLine(" return Profile {");+ text.AppendLine(" Loop Outer {");+ foreach (var edge in panel.Edges)+ {+ string sweep = "";+ if (edge.Curve is LineArcCircularArc2D arc)+ {+ sweep = "; sweep: " + (arc.SweepAngleRadians > 0 ? "CounterClockwise" : "Clockwise");+ }+ text.AppendLine($" Segment {edge.Name} {{ trace: {edge.Name}Guide; from: vertex{edge.From}; to: vertex{edge.To}{sweep} }}");+ }+ text.AppendLine(" }");+ text.AppendLine(" }");+ text.AppendLine("}");+ text.AppendLine($"Feature {panel.Name}Cut = {panel.Name}Pattern();");+ }++ private static LineArcProfileCurve2D Curve(JsonElement edge, (double X, double Y) start,+ (double X, double Y) end, double scale)+ {+ if (!edge.TryGetProperty("curvature", out var curvature))+ {+ return new LineArcLineSegment2D(start, end);+ }+ string? type = curvature.ValueKind == JsonValueKind.Array ? "quadratic" : curvature.GetProperty("type").GetString();+ var parameters = curvature.ValueKind == JsonValueKind.Array ? curvature : curvature.GetProperty("params");+ if (type == "quadratic")+ {+ var control = Relative(start, end, curvature.ValueKind == JsonValueKind.Array ? parameters : parameters[0]);+ return new LineArcCubicBezier2D(start, Lerp(start, control, 2d / 3), Lerp(end, control, 2d / 3), end);+ }+ if (type == "cubic" && parameters.GetArrayLength() == 2)+ {+ return new LineArcCubicBezier2D(start, Relative(start, end, parameters[0]), Relative(start, end, parameters[1]), end);+ }+ if (type == "circle" && parameters.GetArrayLength() == 3)+ {+ double radius = Number(parameters[0]) * scale;+ bool large = Flag(parameters[1]);+ bool ccw = Flag(parameters[2]);+ double dx = end.X - start.X;+ double dy = end.Y - start.Y;+ double chord = Math.Sqrt(dx * dx + dy * dy);+ if (chord <= 1e-8 || radius <= 0 || radius < chord / 2 - 1e-7)+ {+ Fail("garmentcode-circle-invalid", "Circular edge requires a positive radius >= half its chord.");+ }+ double distance = Math.Sqrt(Math.Max(0, radius * radius - chord * chord / 4));+ double sign = ccw != large ? 1 : -1;+ var center = (X: (start.X + end.X) / 2 - sign * distance * dy / chord,+ Y: (start.Y + end.Y) / 2 + sign * distance * dx / chord);+ double angle = Math.Atan2(start.Y - center.Y, start.X - center.X);+ double sweep = Math.Atan2(end.Y - center.Y, end.X - center.X) - angle;+ if (ccw && sweep <= 0)+ {+ sweep += 2 * Math.PI;+ }+ if (!ccw && sweep >= 0)+ {+ sweep -= 2 * Math.PI;+ }+ return new LineArcCircularArc2D(center, radius, angle, sweep);+ }+ Fail("garmentcode-curve-unsupported", "Admitted curves: line, quadratic, cubic, circle; found " + type);+ return null!;+ }++ private static (ImportedPanel Panel, ImportedEdge Edge) Reference(JsonElement reference, IReadOnlyList<ImportedPanel> panels)+ {+ string? name = reference.GetProperty("panel").GetString();+ int index = reference.GetProperty("edge").GetInt32();+ var panel = panels.SingleOrDefault(panel => panel.UpstreamName == name);+ if (panel is null || index < 0 || index >= panel.Edges.Count)+ {+ Fail("garmentcode-stitch-reference", name + "/" + index);+ }+ return (panel!, panel!.Edges.Single(edge => edge.Index == index));+ }++ private static LineArcProfileCurve2D Reverse(LineArcProfileCurve2D curve) => curve switch+ {+ LineArcLineSegment2D line => new LineArcLineSegment2D(line.End, line.Start),+ LineArcCubicBezier2D cubic => new LineArcCubicBezier2D(cubic.End, cubic.Control2, cubic.Control1, cubic.Start),+ LineArcCircularArc2D arc => new LineArcCircularArc2D(arc.Center, arc.Radius,+ arc.StartAngleRadians + arc.SweepAngleRadians, -arc.SweepAngleRadians),+ _ => throw new NotSupportedException("Unsupported imported curve."),+ };++ private static Vector3 Rotate(Vector3 value, double[] degrees)+ {+ // GarmentCode uses Rz * Ry * Rx on column vectors; System.Numerics uses row vectors.+ value = Vector3.Transform(value, Matrix4x4.CreateRotationX((float)(degrees[0] * Math.PI / 180)));+ value = Vector3.Transform(value, Matrix4x4.CreateRotationY((float)(degrees[1] * Math.PI / 180)));+ return Vector3.Transform(value, Matrix4x4.CreateRotationZ((float)(degrees[2] * Math.PI / 180)));+ }++ private static string Direction(Vector3 value) => $"[{Scalar(value.X)}, {Scalar(value.Z)}, {Scalar(value.Y)}]";+ private static void EmitPoint(StringBuilder text, string name, (double X, double Y) point) =>+ text.AppendLine($" Point2 {name} {{ position: [{Length(point.X)}, {Length(point.Y)}] }}");+ private static string Length(double value) => Scalar(value) + "mm";+ private static string Scalar(double value) => value.ToString("0.############", CultureInfo.InvariantCulture);+ private static double Number(JsonElement value)+ {+ double result = value.GetDouble();+ if (!double.IsFinite(result))+ {+ Fail("garmentcode-number-invalid", "All coordinates must be finite.");+ }+ return result;+ }+ private static double[] Triple(JsonElement value)+ {+ var result = value.EnumerateArray().Select(Number).ToArray();+ if (result.Length != 3)+ {+ Fail("garmentcode-frame-invalid", "Expected three translation or Euler components.");+ }+ return result;+ }+ private static bool Flag(JsonElement value)+ {+ int result = value.GetInt32();+ if (result is not (0 or 1))+ {+ Fail("garmentcode-circle-flag-invalid", "Arc flags must be 0 or 1.");+ }+ return result == 1;+ }+ private static (double X, double Y) Point(JsonElement value, double scale)+ {+ if (value.GetArrayLength() != 2)+ {+ Fail("garmentcode-point-invalid", "Expected two coordinates.");+ }+ return (Number(value[0]) * scale, Number(value[1]) * scale);+ }+ private static (double X, double Y) Relative((double X, double Y) start, (double X, double Y) end, JsonElement value)+ {+ var point = Point(value, 1);+ double dx = end.X - start.X;+ double dy = end.Y - start.Y;+ return (start.X + point.X * dx - point.Y * dy, start.Y + point.X * dy + point.Y * dx);+ }+ private static (double X, double Y) Lerp((double X, double Y) a, (double X, double Y) b, double t) =>+ (a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t);+ private static string Identifier(string name)+ {+ string result = Regex.Replace(name, "[^A-Za-z0-9_]", "_");+ if (result.Length == 0 || char.IsDigit(result[0]))+ {+ result = "panel_" + result;+ }+ return result;+ }+ private static void Fail(string code, string detail) => throw new InvalidDataException(code + ": " + detail);+ private sealed record ImportedEdge(int Index, string Name, int From, int To, LineArcProfileCurve2D Curve);+ private sealed record ImportedPanel(string UpstreamName, string Name, (double X, double Y)[] Vertices,+ IReadOnlyList<ImportedEdge> Edges, double[] Translation, double[] Rotation, bool BoundaryReversed);+}diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentCompiler.cs b/Aetheris.Kernel.Firmament/Garment/GarmentCompiler.csindex 74921908..e9540e34 100644--- a/Aetheris.Kernel.Firmament/Garment/GarmentCompiler.cs+++ b/Aetheris.Kernel.Firmament/Garment/GarmentCompiler.cs@@ -6,6 +6,7 @@ namespace Aetheris.Kernel.Firmament.Garment;public sealed record CompiledGarment(GarmentSource Source, CompiledCloth3D Cloth, ImmutableArray<GarmentMeshPanel> Panels){+ public ImmutableArray<CompiledGarmentFittingGuide> FittingGuides { get; init; } = [];public float MaximumSeamGap(ClothSnapshot3D snapshot){ClothState3D.ValidateSnapshot(Cloth, snapshot);@@ -23,6 +24,8 @@ public sealed record CompiledGarment(GarmentSource Source, CompiledCloth3D Cloth}}+public sealed record CompiledGarmentFittingGuide(string ConceptPlane, ClothHalfSpaceGuide3D Constraint, int ReleaseAfter);+public sealed record GarmentCompilationResult(CompiledGarment? Garment, IReadOnlyList<GarmentDiagnostic> Diagnostics){public bool IsSuccess => Garment is not null && Diagnostics.Count == 0;@@ -30,9 +33,9 @@ public sealed record GarmentCompilationResult(CompiledGarment? Garment, IReadOnlpublic static class GarmentCompiler{- public static GarmentCompilationResult Compile(string source, string sourceIdentity = "<memory>")+ public static GarmentCompilationResult Compile(string source, string sourceIdentity = "<memory>", GarmentFigureBinding? figureBinding = null){- var parsed = GarmentAuthoring.Parse(source, sourceIdentity);+ var parsed = GarmentAuthoring.Parse(source, sourceIdentity, figureBinding);if (!parsed.IsSuccess){return new(null, parsed.Diagnostics);@@ -53,6 +56,7 @@ public static class GarmentCompilerprivate static CompiledGarment Compile(GarmentSource source){+ _ = GarmentPatternInspection.Inspect(source);var rest = new List<Vector3>();var initial = new List<Vector3>();var coordinates = new List<Vector2>();@@ -113,11 +117,9 @@ public static class GarmentCompilerfloat[] distancesB = Distances(b);float lengthA = distancesA[^1];float lengthB = distancesB[^1];- float mismatch = MathF.Abs(lengthA - lengthB) / MathF.Max(lengthA, lengthB);- if (mismatch > seam.Ease + .001f)- {- GarmentAuthoring.Fail("garment-stitch-length-mismatch", seam.Name + $": edge lengths {lengthA:R}m and {lengthB:R}m require explicit ease >= {mismatch:R}.");- }+ // PatternInspection already validates the analytic cut lengths and authored ease.+ // Different curved edges acquire different chord errors during meshing; those+ // errors must not redefine the sewing pattern's physical ease allowance.var samples = distancesA.Select(distance => distance / lengthA).Concat(distancesB.Select(distance => seam.Reversed ? 1 - distance / lengthB : distance / lengthB)).Order().Aggregate(new List<float>(), (list, value) =>@@ -145,24 +147,29 @@ public static class GarmentCompilerPins = pins.Order().ToImmutableArray(),Material = source.Fabric,};- return new(source, definition.Compile(), compiledPanels);+ var guides = source.FittingGuides.Select(guide => new CompiledGarmentFittingGuide(guide.ConceptPlane,+ new(guide.Name, guide.Edges.SelectMany(reference => Boundary(reference, false)).Distinct().Order().ToImmutableArray(),+ guide.Normal, guide.Offset, guide.Compliance), guide.ReleaseAfter)).ToImmutableArray();+ var cloth = definition.Compile();+ ClothState3D.ValidateStep(cloth, new(), new() { Guides = guides.Select(guide => guide.Constraint).ToImmutableArray() });+ return new(source, cloth, compiledPanels) { FittingGuides = guides };- ImmutableArray<int> Boundary(string reference)+ ImmutableArray<int> Boundary(string reference, bool seam = true){int separator = reference.IndexOf(".edges.", StringComparison.Ordinal);if (separator < 1){- GarmentAuthoring.Fail("garment-stitch-reference", "Use panel.edges.namedSpan: " + reference);+ GarmentAuthoring.Fail(seam ? "garment-stitch-reference" : "garment-fitting-reference", "Use panel.edges.namedSpan: " + reference);}string panelName = reference[..separator];string edgeName = reference[(separator + 7)..];var panel = compiledPanels.SingleOrDefault(panel => panel.Name == panelName || panel.Identity == panelName);if (panel is null || !panel.Edges.ContainsKey(edgeName)){- GarmentAuthoring.Fail("garment-stitch-edge-unknown", reference);+ GarmentAuthoring.Fail(seam ? "garment-stitch-edge-unknown" : "garment-fitting-edge-unknown", reference);}string canonical = panel!.Identity + ".edges." + edgeName;- if (!usedEdges.Add(canonical))+ if (seam && !usedEdges.Add(canonical)){GarmentAuthoring.Fail("garment-stitch-edge-reused", canonical + " already has a seam.");}diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentDraping.cs b/Aetheris.Kernel.Firmament/Garment/GarmentDraping.csindex 0d5f5a9a..555a9c49 100644--- a/Aetheris.Kernel.Firmament/Garment/GarmentDraping.cs+++ b/Aetheris.Kernel.Firmament/Garment/GarmentDraping.cs@@ -1,24 +1,92 @@using System.Collections.Immutable;+using System.Diagnostics;using System.Numerics;using Aetheris.Cloth3D;using Aetheris.Humanoid;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament.Humanoid;namespace Aetheris.Kernel.Firmament.Garment;+public sealed record GarmentDrapeSettings+{+ public int Substeps { get; init; } = 8;+ public int Iterations { get; init; } = 24;+ public bool StopWhenSettled { get; init; }+ public float StationarySpeed { get; init; } = .01f;++ public void Validate()+ {+ if (Substeps is < 1 or > 64 || Iterations is < 1 or > 64+ || !float.IsFinite(StationarySpeed) || StationarySpeed <= 0 || StationarySpeed > .1f)+ {+ throw new ArgumentException("Invalid bounded garment drape settings.");+ }+ }+}++public static class GarmentDrapeLimits+{+ public const float MaximumStretch = .15f;+ public const float MaximumSeamGap = .01f;+ public const float MaximumPenetration = .005f;++ public static bool Accept(ClothMetrics3D metrics, float seamGap)+ {+ return metrics.Finite && metrics.MaximumStretch <= MaximumStretch+ && metrics.MaximumSurfacePenetration <= MaximumPenetration && seamGap <= MaximumSeamGap;+ }+}++public sealed record GarmentDrapeSample(string Phase, int Frame, float MaximumSpeed,+ ClothMetrics3D Metrics, float MaximumSeamGap, bool Settled)+{+ public IReadOnlyList<GarmentGuideResidual> Guides { get; init; } = [];+}++public sealed record GarmentGuideResidual(string Name, string ConceptPlane, int ReleaseAfter,+ bool Active, float MaximumViolation);+public sealed record GarmentFittingCheckpoint(string Name, ClothSnapshot3D Snapshot, IReadOnlyList<Point3D> BodyPositions);+public sealed record GarmentDrapeResult(ClothSnapshot3D Snapshot, ClothMetrics3D Metrics,float MaximumSeamGap, float InitialSeamGap, bool ReplayExact, string BodyId, string BodyTopology,- IReadOnlyList<GarmentContactOutlier> ContactOutliers, IReadOnlyList<GarmentStretchOutlier> StretchOutliers);+ IReadOnlyList<GarmentContactOutlier> ContactOutliers, IReadOnlyList<GarmentStretchOutlier> StretchOutliers)+{+ public IReadOnlyList<GarmentSurfaceContactOutlier> SurfaceContactOutliers { get; init; } = [];+ public IReadOnlyList<GarmentDrapeFrame> Frames { get; init; } = [];+ public IReadOnlyList<Point3D> BodyPositions { get; init; } = [];+ public bool TransitionReplayExact { get; init; } = true;+ public float MaximumBodySubstepTravel { get; init; }+ public GarmentDrapeSettings Settings { get; init; } = new();+ public IReadOnlyList<GarmentDrapeSample> Samples { get; init; } = [];+ public int CompletedSettlingTicks { get; init; }+ public string StopReason { get; init; } = "FrameBudget";+ public bool GuidesReleased { get; init; } = true;+ public IReadOnlyList<GarmentFittingCheckpoint> FittingCheckpoints { get; init; } = [];+}++public sealed record GarmentDrapeFrame(string Name, double MotionSeconds, ClothSnapshot3D Snapshot,+ IReadOnlyList<Point3D> BodyPositions, ClothMetrics3D Metrics, float MaximumSeamGap,+ ConstrainedSurfaceEvidence BodyEvidence, IReadOnlyList<AnatomicalJointRequest> Joints);public sealed record GarmentContactOutlier(int Vertex, string Panel, bool Pinned, float Penetration, float[] Position);-public sealed record GarmentStretchOutlier(int A, int B, float Stretch, float RestLength);+public sealed record GarmentStretchOutlier(int A, int B, float Stretch, float RestLength)+{+ public string Panel { get; init; } = "";+ public string Kind { get; init; } = "";+ public float[] MaterialA { get; init; } = [];+ public float[] MaterialB { get; init; } = [];+}+public sealed record GarmentSurfaceContactOutlier(int Triangle, string Panel, float Penetration, float[] Position);+public sealed record GarmentDrapeProgress(string Phase, int Completed, int Total, double ElapsedSeconds);public static class GarmentDraping{- public static ClothTriangleBody3D BodySurface(HumanoidGameplayBody body)+ public static ClothTriangleBody3D BodySurface(HumanoidGameplayBody body, IReadOnlyList<Point3D>? posed = null){ArgumentNullException.ThrowIfNull(body);- var positions = body.Surface.Vertices.Select(vertex => new Vector3(- (float)vertex.Position.X, (float)vertex.Position.Y, (float)vertex.Position.Z) * .001f).ToImmutableArray();+ var positions = (posed ?? body.Surface.Vertices.Select(vertex => vertex.Position).ToArray())+ .Select(point => new Vector3((float)point.X, (float)point.Y, (float)point.Z) * .001f).ToImmutableArray();var outer = body.Surface.Components.Where(component => component.Kind == HumanoidComponentKind.OuterSkin).SelectMany(component => component.FaceIndices).Distinct().Order().ToArray();if (outer.Length == 0)@@ -33,40 +101,172 @@ public static class GarmentDrapingreturn new(positions, indices);}- /// <summary>Static Rest-pose authoring qualification on the shared CPU solver.- /// Explicit pins are retained garment supports. No animation, friction, CCD or self-contact claim.</summary>- public static GarmentDrapeResult Settle(CompiledGarment garment, HumanoidGameplayBody body, int ticks = 60)+ /// <summary>Sew and settle on an authored figure pose, optionally following an explicit kinematic transition.+ /// This remains a one-way CPU contact experiment without friction, CCD or self-contact.</summary>+ public static GarmentDrapeResult Settle(CompiledGarment garment, HumanoidGameplayBody body, int ticks = 60,+ Action<GarmentDrapeProgress>? progress = null, GarmentDrapeSettings? settings = null){if (ticks is < 1 or > 600){throw new ArgumentOutOfRangeException(nameof(ticks));}- if (garment.Source.Figure is null || garment.Source.Pose != "Rest")+ if (garment.Source.Figure is null || garment.Source.Pose is null)+ {+ throw new InvalidOperationException("garment-drape-binding-required: Declare a Drape figure and pose, and supply its body artifact.");+ }+ if (garment.Source.FigureFits.Count > 0){- throw new InvalidOperationException("garment-drape-binding-required: Declare Drape { figure: Anatolia; pose: Rest; } and supply its body artifact.");+ string surfaceHash = HumanoidFigureFitting.SurfaceHash(body);+ if (garment.Source.FigureFits.Any(fit => fit.Measurements.BodyId != body.Id+ || fit.Measurements.RestSurfaceHash != surfaceHash+ || fit.Measurements.SkeletonId != body.Skeleton.SkeletonId+ || fit.Measurements.RestPoseId != body.Skeleton.RestPoseId))+ {+ throw new InvalidOperationException("garment-fit-body-changed: Recompile the pattern for the supplied body before draping.");+ }}- var contacts = new ClothContacts3D { BodySurface = BodySurface(body), BodyClearance = garment.Source.BodyClearance };+ HumanoidClothMotion? motion = null;+ if (garment.Source.Pose != "Rest" || garment.Source.Transition is not null)+ {+ var posing = garment.Source.Posing ?? throw new InvalidOperationException(+ "garment-pose-program-required: Compile the authored pose declarations before draping.");+ motion = new(body, posing, garment.Source.Figure, garment.Source.Pose, garment.Source.Transition);+ }+ return SettleCore(garment, motion?.Surface ?? BodySurface(body), body.Id, body.Surface.ConnectivityHash,+ body.Surface.Vertices.Select(vertex => vertex.Position).ToArray(), motion, ticks, progress, settings ?? new());+ }++ /// <summary>Static reference-body experiment using the same sewing, settling and replay path.+ /// This accepts an existing collider without inventing a humanoid rig for an unrigged reference mesh.</summary>+ public static GarmentDrapeResult SettleOnSurface(CompiledGarment garment, IClothBodySurface3D surface,+ string bodyId, string topologyId, int ticks = 60, Action<GarmentDrapeProgress>? progress = null,+ GarmentDrapeSettings? settings = null)+ {+ ArgumentNullException.ThrowIfNull(surface);+ if (ticks is < 1 or > 600)+ {+ throw new ArgumentOutOfRangeException(nameof(ticks));+ }+ if (string.IsNullOrWhiteSpace(bodyId) || string.IsNullOrWhiteSpace(topologyId))+ {+ throw new ArgumentException("A reference surface requires explicit body and topology identities.");+ }+ if (garment.Source.Figure is not null || garment.Source.FigureFits.Count > 0 || garment.Source.Pose is not (null or "Rest")+ || garment.Source.Transition is not null || surface is IClothKinematicBodySurface3D)+ {+ throw new InvalidOperationException("garment-reference-surface-static: Measured fits and poses require their actual humanoid binding.");+ }+ return SettleCore(garment, surface, bodyId, topologyId, [], null, ticks, progress, settings ?? new());+ }++ private static GarmentDrapeResult SettleCore(CompiledGarment garment, IClothBodySurface3D surface,+ string bodyId, string topologyId, IReadOnlyList<Point3D> bodyPositions, HumanoidClothMotion? motion,+ int ticks, Action<GarmentDrapeProgress>? progress, GarmentDrapeSettings settings)+ {+ settings.Validate();+ int releaseFrame = garment.FittingGuides.IsEmpty ? 0 : garment.FittingGuides.Max(guide => guide.ReleaseAfter);+ if (!garment.FittingGuides.IsEmpty && ticks < releaseFrame + 15)+ {+ throw new InvalidOperationException("garment-fitting-release-budget: Provide at least 15 unsupported settling frames after the last guide release.");+ }+ var contacts = new ClothContacts3D+ {+ BodySurface = surface,+ BodyClearance = garment.Source.BodyClearance,+ Guides = garment.FittingGuides.Select(guide => guide.Constraint).ToImmutableArray(),+ };var options = new ClothStepOptions3D{Gravity = new(0, 0, -9.81f),- Substeps = 8,- Iterations = 24,+ Substeps = settings.Substeps,+ Iterations = settings.Iterations,ContactIterations = 1,VelocityDamping = 8,};using var solver = new ClothSolver3D(garment.Cloth);+ var watch = Stopwatch.StartNew();var initial = solver.Capture();float initialGap = garment.MaximumSeamGap(initial);+ var frames = new List<GarmentDrapeFrame>();+ var samples = new List<GarmentDrapeSample>();+ var fittingCheckpoints = new List<GarmentFittingCheckpoint>();+ int completedSettlingTicks = 0;+ int consecutiveSettled = 0;+ string stopReason = "FrameBudget";+ bool transitionReplay = true;// Sew with gravity disabled and a decreasing compliance, then settle.// This keeps the initial closing impulse from dominating garment motion.for (int stage = 0; stage < 30; stage++){float scale = MathF.Pow(10, 6 * (1 - stage / 29f));solver.Step(options with { Gravity = Vector3.Zero, StitchComplianceScale = scale }, contacts);+ if ((stage + 1) % 5 == 0)+ {+ Sample("sewing", stage + 1);+ progress?.Invoke(new("sewing", stage + 1, 30, watch.Elapsed.TotalSeconds));+ }}for (int tick = 0; tick < ticks; tick++){+ if (!contacts.Guides.IsEmpty && tick == releaseFrame)+ {+ fittingCheckpoints.Add(new("guided", solver.Capture(), motion?.Positions.ToArray() ?? bodyPositions));+ }+ contacts = contacts with+ {+ Guides = garment.FittingGuides.Where(guide => tick < guide.ReleaseAfter)+ .Select(guide => guide.Constraint).ToImmutableArray(),+ };solver.Step(options, contacts);+ completedSettlingTicks = tick + 1;+ if ((tick + 1) % 5 == 0 || tick + 1 == ticks)+ {+ bool settled = Sample("settling", tick + 1);+ progress?.Invoke(new("settling", tick + 1, ticks, watch.Elapsed.TotalSeconds));+ consecutiveSettled = settled ? consecutiveSettled + 1 : 0;+ if (settings.StopWhenSettled && tick + 1 >= 30 && consecutiveSettled >= 3)+ {+ stopReason = "Settled";+ break;+ }+ }+ }+ if (motion is not null)+ {+ RecordFrame("fitting", 0);+ int transitionTicks = (int)Math.Ceiling(motion.DurationSeconds / options.DeltaSeconds);+ for (int tick = 0; tick < transitionTicks; tick++)+ {+ var movingContacts = contacts with { BodySurface = motion, BodyTimeSeconds = tick * (double)options.DeltaSeconds };+ bool midpoint = tick + 1 == Math.Max(1, transitionTicks / 2);+ var before = midpoint ? solver.Capture() : null;+ solver.Step(options, movingContacts);+ if (midpoint)+ {+ var expectedMoving = solver.Capture();+ solver.Restore(before!);+ solver.Step(options, movingContacts);+ transitionReplay = SameSnapshot(expectedMoving, solver.Capture());+ RecordFrame("midway", Math.Min(motion.DurationSeconds, (tick + 1d) * options.DeltaSeconds));+ }+ if ((tick + 1) % 5 == 0 || tick + 1 == transitionTicks)+ {+ progress?.Invoke(new("transition", tick + 1, transitionTicks, watch.Elapsed.TotalSeconds));+ }+ }+ if (transitionTicks > 0)+ {+ for (int tick = 0; tick < ticks; tick++)+ {+ solver.Step(options, contacts);+ if ((tick + 1) % 5 == 0 || tick + 1 == ticks)+ {+ Sample("wearing", tick + 1);+ progress?.Invoke(new("wearing", tick + 1, ticks, watch.Elapsed.TotalSeconds));+ }+ }+ RecordFrame("wearing", motion.DurationSeconds);+ }}var final = solver.Capture();var beforeReplay = final;@@ -75,8 +275,7 @@ public static class GarmentDrapingsolver.Restore(beforeReplay);solver.Step(options, contacts);var replayed = solver.Capture();- bool replay = expected.Positions.SequenceEqual(replayed.Positions)- && expected.Velocities.SequenceEqual(replayed.Velocities) && expected.Tick == replayed.Tick;+ bool replay = SameSnapshot(expected, replayed);var pins = garment.Cloth.Definition.Pins.ToHashSet();var contactOutliers = final.Positions.Select((position, index) => new GarmentContactOutlier(index,garment.Panels.Single(panel => index >= panel.VertexStart && index < panel.VertexStart + panel.VertexCount).Identity,@@ -86,8 +285,87 @@ public static class GarmentDrapingvar stretchOutliers = garment.Cloth.Constraints.Where(constraint => constraint.Vertices.Length == 2&& constraint.Weights.IsEmpty).Select(constraint => new GarmentStretchOutlier(constraint.Vertices[0], constraint.Vertices[1],Vector3.Distance(final.Positions[constraint.Vertices[0]], final.Positions[constraint.Vertices[1]]) / constraint.RestLength - 1,- constraint.RestLength)).OrderByDescending(item => item.Stretch).Take(8).ToArray();+ constraint.RestLength)+ {+ Panel = PanelOfVertex(constraint.Vertices[0]),+ Kind = constraint.Kind.ToString(),+ MaterialA = MaterialPoint(constraint.Vertices[0]),+ MaterialB = MaterialPoint(constraint.Vertices[1]),+ }).OrderByDescending(item => item.Stretch).Take(8).ToArray();+ var surfaceOutliers = new List<GarmentSurfaceContactOutlier>();+ var indices = garment.Cloth.Definition.Indices;+ for (int face = 0; face < indices.Length; face += 3)+ {+ foreach (var barycentric in ClothBodyContact3D.Samples)+ {+ Vector3 point = final.Positions[indices[face]] * barycentric.X+ + final.Positions[indices[face + 1]] * barycentric.Y+ + final.Positions[indices[face + 2]] * barycentric.Z;+ float penetration = garment.Cloth.Definition.Material.Thickness * .5f + contacts.BodyClearance+ - contacts.BodySurface!.Query(point).SignedDistance;+ if (penetration > .001f)+ {+ surfaceOutliers.Add(new(face / 3, PanelOfVertex(indices[face]), penetration, [point.X, point.Y, point.Z]));+ }+ }+ }return new(final, ClothState3D.Measure(garment.Cloth, final, contacts), garment.MaximumSeamGap(final),- initialGap, replay, body.Id, body.Surface.ConnectivityHash, contactOutliers, stretchOutliers);+ initialGap, replay, bodyId, topologyId, contactOutliers, stretchOutliers)+ {+ SurfaceContactOutliers = surfaceOutliers.OrderByDescending(outlier => outlier.Penetration).Take(8).ToArray(),+ Frames = frames,+ BodyPositions = motion?.Positions.ToArray() ?? bodyPositions,+ TransitionReplayExact = transitionReplay,+ MaximumBodySubstepTravel = motion?.MaximumSubstepTravel ?? 0,+ Settings = settings,+ Samples = samples,+ CompletedSettlingTicks = completedSettlingTicks,+ StopReason = stopReason,+ GuidesReleased = contacts.Guides.IsEmpty,+ FittingCheckpoints = fittingCheckpoints,+ };++ bool Sample(string phase, int frame)+ {+ var snapshot = solver.Capture();+ var metrics = ClothState3D.Measure(garment.Cloth, snapshot, contacts);+ float gap = garment.MaximumSeamGap(snapshot);+ float speed = snapshot.Velocities.Max(velocity => velocity.Length());+ bool settled = float.IsFinite(speed) && speed <= settings.StationarySpeed+ && GarmentDrapeLimits.Accept(metrics, gap)+ && contacts.Guides.IsEmpty+ && (garment.FittingGuides.IsEmpty || (phase != "sewing" && frame >= releaseFrame + 15));+ var guideResiduals = garment.FittingGuides.Select(guide => new GarmentGuideResidual(+ guide.Constraint.Id, guide.ConceptPlane, guide.ReleaseAfter,+ contacts.Guides.Any(active => active.Id == guide.Constraint.Id),+ guide.Constraint.Vertices.Max(vertex => MathF.Max(0,+ guide.Constraint.Offset - Vector3.Dot(guide.Constraint.Normal, snapshot.Positions[vertex]))))).ToArray();+ samples.Add(new(phase, frame, speed, metrics, gap, settled) { Guides = guideResiduals });+ return settled;+ }++ void RecordFrame(string name, double seconds)+ {+ var snapshot = solver.Capture();+ frames.Add(new(name, seconds, snapshot, motion!.Positions.ToArray(), ClothState3D.Measure(garment.Cloth, snapshot, contacts),+ garment.MaximumSeamGap(snapshot), motion.Inspect(), motion.CurrentPose.Joints));+ }++ string PanelOfVertex(int vertex)+ {+ return garment.Panels.Single(panel => vertex >= panel.VertexStart && vertex < panel.VertexStart + panel.VertexCount).Identity;+ }+ float[] MaterialPoint(int vertex)+ {+ var point = garment.Cloth.Definition.Positions[vertex];+ return [point.X, point.Y];+ }+ }++ private static bool SameSnapshot(ClothSnapshot3D expected, ClothSnapshot3D actual)+ {+ return expected.Tick == actual.Tick && expected.ContentKey == actual.ContentKey+ && expected.Positions.SequenceEqual(actual.Positions) && expected.Velocities.SequenceEqual(actual.Velocities)+ && expected.PinTargets.SequenceEqual(actual.PinTargets);}}diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentExport.cs b/Aetheris.Kernel.Firmament/Garment/GarmentExport.csindex 3eafc4ae..2abdd4ba 100644--- a/Aetheris.Kernel.Firmament/Garment/GarmentExport.cs+++ b/Aetheris.Kernel.Firmament/Garment/GarmentExport.cs@@ -29,6 +29,9 @@ public static class GarmentExportupAxis = "Z",sourceHash = garment.Source.SourceHash,sourceIdentity = garment.Source.SourceIdentity,+ figureFits = garment.Source.FigureFits,+ posing = garment.Source.Posing,+ transition = garment.Source.Transition,contentKey = garment.Cloth.ContentKey,definition = garment.Cloth.Definition,panels = garment.Panels,@@ -67,12 +70,12 @@ public static class GarmentExportreturn result.ToString();}- public static string BodyObj(HumanoidGameplayBody body)+ public static string BodyObj(HumanoidGameplayBody body,+ IReadOnlyList<Aetheris.Kernel.Core.Math.Point3D>? positions = null){var result = new StringBuilder("# Antonia gameplay body; metres; Z up. Preserve its source attribution.\n");- foreach (var vertex in body.Surface.Vertices)+ foreach (var point in positions ?? body.Surface.Vertices.Select(vertex => vertex.Position).ToArray()){- var point = vertex.Position;result.AppendLine(FormattableString.Invariant($"v {point.X / 1000:R} {point.Y / 1000:R} {point.Z / 1000:R}"));}foreach (var face in body.Surface.Faces)@@ -84,40 +87,7 @@ public static class GarmentExportpublic static string PatternsSvg(CompiledGarment garment){- var result = new StringBuilder("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1200\" height=\"900\" viewBox=\"0 0 1200 900\">\n");- result.AppendLine("<rect width=\"1200\" height=\"900\" fill=\"#f5f3ee\"/><g font-family=\"sans-serif\" fill=\"#24344c\">");- result.AppendLine("<text x=\"24\" y=\"36\" font-size=\"24\">" + Escape(garment.Source.Name) + " — material patterns (mm)</text>");- result.AppendLine("<text x=\"24\" y=\"64\" font-size=\"14\">Blue: open edge · orange: stitch · green: explicit support. Cut boundary; no seam allowance added.</text>");- int panelNumber = 0;- foreach (var panel in garment.Panels)- {- var points = garment.Cloth.Definition.Positions.Skip(panel.VertexStart).Take(panel.VertexCount).ToArray();- float minX = points.Min(point => point.X);- float minY = points.Min(point => point.Y);- float width = points.Max(point => point.X) - minX;- float height = points.Max(point => point.Y) - minY;- float scale = MathF.Min(490 / width, 300 / height);- float originX = 40 + panelNumber % 2 * 590;- float originY = 140 + panelNumber / 2 * 370;- panelNumber++;- result.AppendLine(FormattableString.Invariant($"<text x=\"{originX}\" y=\"{originY - 30}\" font-size=\"18\">{Escape(panel.Identity)}</text>"));- foreach (var edge in panel.Edges)- {- string reference = panel.Identity + ".edges." + edge.Key;- var seam = garment.Source.Stitches.FirstOrDefault(stitch => stitch.A == reference || stitch.B == reference- || stitch.A == panel.Name + ".edges." + edge.Key || stitch.B == panel.Name + ".edges." + edge.Key);- bool pinned = garment.Source.Panels.Single(source => source.Name == panel.Name).Pins.Contains(edge.Key);- string color = pinned ? "#16835b" : seam is null ? "#3274a0" : "#c76925";- var line = edge.Value.Select(index => garment.Cloth.Definition.Positions[index]).ToArray();- string coordinates = string.Join(" ", line.Select(point => FormattableString.Invariant($"{originX + (point.X - minX) * scale},{originY + (height - point.Y + minY) * scale}")));- result.AppendLine($"<polyline points=\"{coordinates}\" fill=\"none\" stroke=\"{color}\" stroke-width=\"2\"/>");- var middle = line[line.Length / 2];- string label = edge.Key + (seam is null ? "" : " / " + seam.Name);- result.AppendLine(FormattableString.Invariant($"<text x=\"{originX + (middle.X - minX) * scale + 3}\" y=\"{originY + (height - middle.Y + minY) * scale - 4}\" font-size=\"10\">{Escape(label)}</text>"));- }- }- result.AppendLine("</g></svg>");- return result.ToString();+ return GarmentPatternPreview.Svg(garment.Source);}public static string Usd(CompiledGarment garment, ClothSnapshot3D? settled = null)diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentFigureAuthoring.cs b/Aetheris.Kernel.Firmament/Garment/GarmentFigureAuthoring.csnew file mode 100644index 00000000..f3bccf57--- /dev/null+++ b/Aetheris.Kernel.Firmament/Garment/GarmentFigureAuthoring.cs@@ -0,0 +1,160 @@+using System.Globalization;+using System.Text.RegularExpressions;+using Aetheris.Humanoid;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Humanoid;++namespace Aetheris.Kernel.Firmament.Garment;++public sealed record GarmentFigureBinding(string Figure, HumanoidGameplayBody Body, string? ArtifactHash = null);+public sealed record GarmentFigureFitEvidence(string Identity, string Figure, string? ArtifactHash,+ HumanoidFigureFit Measurements)+{+ public string Pose { get; init; } = "Rest";+}++/// <summary>A figure-bound Concept publication. Values are measured once at authoring time,+/// then consumed by the ordinary Feature, point, Profile and placement authorities.</summary>+internal static class GarmentFigureAuthoring+{+ public static string Expand(string source, GarmentFigureBinding? binding, List<GarmentFigureFitEvidence> evidence,+ FirmamentPoseDocument posing)+ {+ var tokens = FirmamentLanguageAnalysisService.Lex(source).Where(token => token.Shape != "comment").ToArray();+ var changes = new List<(int Start, int Length)>();+ var publications = new Dictionary<string, string>(StringComparer.Ordinal);+ for (int index = 0; index + 3 < tokens.Length; index++)+ {+ if (tokens[index].Text != "Concept" || tokens[index + 1].Text != "Struct")+ {+ continue;+ }+ string owner = tokens[index + 2].Text;+ int open = index + 3;+ while (open < tokens.Length && tokens[open].Text != "{")+ {+ open++;+ }+ int close = Closing(open);+ int depth = 1;+ for (int child = open + 1; child < close; child++)+ {+ if (tokens[child].Text == "{")+ {+ depth++;+ }+ if (tokens[child].Text == "}")+ {+ depth--;+ }+ if (depth != 1 || tokens[child].Text != "FigureFit")+ {+ continue;+ }+ if (binding is null)+ {+ GarmentAuthoring.Fail("garment-fit-body-required", "Bind FigureFit with --body gameplay-body.json, or supply a GarmentFigureBinding.");+ }+ if (child + 2 >= close || tokens[child + 1].Shape != "identifier" || tokens[child + 2].Text != "{")+ {+ GarmentAuthoring.Fail("garment-fit-syntax", "Expected FigureFit name { ... } inside Concept Struct.");+ }+ int end = Closing(child + 2);+ string identity = owner + "." + tokens[child + 1].Text;+ string body = source[(tokens[child + 2].Start + 1)..tokens[end].Start];+ var fields = GarmentAuthoring.Fields(body, ["Figure", "Pose", "ChestHeight", "HipHeight"]);+ if (fields.GetValueOrDefault("Figure") != binding!.Figure)+ {+ GarmentAuthoring.Fail("garment-fit-binding-mismatch", identity + " must name the supplied figure.");+ }+ double? chest = fields.TryGetValue("ChestHeight", out string? chestText) ? Length(chestText) : null;+ double? hip = fields.TryGetValue("HipHeight", out string? hipText) ? Length(hipText) : null;+ HumanoidFigureFit fit;+ string poseName = fields.GetValueOrDefault("Pose", "Rest");+ var recipe = posing.Resolve(poseName, binding.Figure);+ try+ {+ SolvedHumanoidPose? pose = recipe.Joints.Count == 0 && recipe.RestOverrides.Count == 0+ ? null : HumanoidPoseAuthoring.Solve(recipe, binding.Body);+ fit = HumanoidFigureFitting.Measure(binding.Body, chest, hip, pose);+ }+ catch (Exception exception) when (exception is ArgumentException or InvalidOperationException)+ {+ GarmentAuthoring.Fail("garment-fit-measurement-invalid", exception.Message);+ return source;+ }+ evidence.Add(new(identity, binding.Figure, binding.ArtifactHash, fit) { Pose = poseName });+ Publish("shoulderWidth", Math.Abs(fit.RightShoulder.X - fit.LeftShoulder.X));+ Publish("shoulderHeight", (fit.LeftShoulder.Z + fit.RightShoulder.Z) / 2);+ Publish("neckHeight", fit.Neck.Z);+ Publish("centerX", fit.Neck.X);+ Publish("centerY", fit.Neck.Y);+ Publish("chestHeight", fit.Chest.HeightMm);+ Publish("hipHeight", fit.Hip.HeightMm);+ Publish("chestCircumference", fit.Chest.CircumferenceMm);+ Publish("hipCircumference", fit.Hip.CircumferenceMm);+ Publish("torsoCircumference", Math.Max(fit.Chest.CircumferenceMm, fit.Hip.CircumferenceMm));+ Publish("frontY", Math.Max(fit.Chest.MaximumY, fit.Hip.MaximumY));+ Publish("backY", Math.Min(fit.Chest.MinimumY, fit.Hip.MinimumY));+ changes.Add((tokens[child].Start, tokens[end].Start + tokens[end].Length - tokens[child].Start));+ child = end;++ void Publish(string name, double value)+ {+ if (!publications.TryAdd(identity + "." + name, value.ToString("R", CultureInfo.InvariantCulture) + "mm"))+ {+ GarmentAuthoring.Fail("garment-fit-name-duplicate", identity);+ }+ }+ }+ index = close;+ }+ foreach (var change in changes.OrderByDescending(change => change.Start))+ {+ source = source.Remove(change.Start, change.Length);+ }+ foreach (var publication in publications)+ {+ source = Regex.Replace(source, $@"(?<![\w.]){Regex.Escape(publication.Key)}(?![\w.])", publication.Value);+ }+ foreach (var fit in evidence)+ {+ if (Regex.IsMatch(source, $@"\b{Regex.Escape(fit.Identity)}\."))+ {+ GarmentAuthoring.Fail("garment-fit-member-unknown", fit.Identity);+ }+ }+ return source;++ int Closing(int open)+ {+ int depth = 0;+ for (int token = open; token < tokens.Length; token++)+ {+ if (tokens[token].Text == "{")+ {+ depth++;+ }+ if (tokens[token].Text == "}")+ {+ depth--;+ if (depth == 0)+ {+ return token;+ }+ }+ }+ GarmentAuthoring.Fail("garment-fit-syntax", "Unclosed Concept block.");+ return tokens.Length;+ }+ }++ private static double Length(string text)+ {+ if (!FirmamentV2FeatureExpansion.TryEvaluateScalar(text, out double value, out string unit) || unit != "mm")+ {+ GarmentAuthoring.Fail("garment-fit-unit-invalid", "Section height must be a Length: " + text);+ }+ return value;+ }+}diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentMeshInspection.cs b/Aetheris.Kernel.Firmament/Garment/GarmentMeshInspection.csnew file mode 100644index 00000000..56e93859--- /dev/null+++ b/Aetheris.Kernel.Firmament/Garment/GarmentMeshInspection.cs@@ -0,0 +1,57 @@+using System.Numerics;++namespace Aetheris.Kernel.Firmament.Garment;++/// <summary>Rest-pattern diagnostics. Lengths are metres, angles are degrees.+/// Lumped area includes pinned vertices; it does not infer mass from their zero inverse mass.</summary>+public sealed record GarmentMeshQuality(int UniqueEdges, double MinimumEdgeLength,+ double MedianEdgeLength, double MaximumEdgeLength, double MinimumTriangleAngleDegrees,+ int TrianglesBelowTenDegrees, double MaximumLumpedAreaRatio, int UnreferencedVertices);++public static class GarmentMeshInspection+{+ public static GarmentMeshQuality Measure(CompiledGarment garment)+ {+ ArgumentNullException.ThrowIfNull(garment);+ var definition = garment.Cloth.Definition;+ var edges = new HashSet<(int A, int B)>();+ var lumpedAreas = new double[definition.Positions.Length];+ double minimumAngle = 180;+ int thinTriangles = 0;+ for (int face = 0; face < definition.Indices.Length; face += 3)+ {+ int[] triangle = [definition.Indices[face], definition.Indices[face + 1], definition.Indices[face + 2]];+ var a = definition.Positions[triangle[0]];+ var b = definition.Positions[triangle[1]];+ var c = definition.Positions[triangle[2]];+ double area = Vector3.Cross(b - a, c - a).Length() * .5;+ double triangleAngle = 180;+ for (int corner = 0; corner < 3; corner++)+ {+ int vertex = triangle[corner];+ int next = triangle[(corner + 1) % 3];+ int previous = triangle[(corner + 2) % 3];+ edges.Add((Math.Min(vertex, next), Math.Max(vertex, next)));+ lumpedAreas[vertex] += area / 3;+ Vector3 first = definition.Positions[next] - definition.Positions[vertex];+ Vector3 second = definition.Positions[previous] - definition.Positions[vertex];+ double cosine = Vector3.Dot(first, second) / ((double)first.Length() * second.Length());+ double angle = Math.Acos(Math.Clamp(cosine, -1, 1)) * 180 / Math.PI;+ triangleAngle = Math.Min(triangleAngle, angle);+ }+ minimumAngle = Math.Min(minimumAngle, triangleAngle);+ if (triangleAngle < 10)+ {+ thinTriangles++;+ }+ }+ double[] lengths = edges.Select(edge => (double)Vector3.Distance(+ definition.Positions[edge.A], definition.Positions[edge.B])).Order().ToArray();+ double median = lengths.Length % 2 == 0+ ? (lengths[lengths.Length / 2 - 1] + lengths[lengths.Length / 2]) * .5+ : lengths[lengths.Length / 2];+ double[] positiveAreas = lumpedAreas.Where(area => area > 0).ToArray();+ return new(lengths.Length, lengths[0], median, lengths[^1], minimumAngle, thinTriangles,+ positiveAreas.Max() / positiveAreas.Min(), lumpedAreas.Count(area => area == 0));+ }+}diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentPanelMesher.cs b/Aetheris.Kernel.Firmament/Garment/GarmentPanelMesher.csindex 8da03a8b..a671d96a 100644--- a/Aetheris.Kernel.Firmament/Garment/GarmentPanelMesher.cs+++ b/Aetheris.Kernel.Firmament/Garment/GarmentPanelMesher.cs@@ -16,6 +16,18 @@ internal sealed record PanelMesh(List<Vector2> Points, List<int> Indices, Dictiointernal static class GarmentPanelMesher{public static PanelMesh Mesh(GarmentPanel panel, float meshSize)+ {+ try+ {+ return MeshCore(panel, meshSize);+ }+ catch (InvalidOperationException exception) when (exception.Message.StartsWith("planar-mesh-", StringComparison.Ordinal))+ {+ throw new GarmentAuthoringException("garment-mesh-budget", panel.Name + ": " + exception.Message);+ }+ }++ private static PanelMesh MeshCore(GarmentPanel panel, float meshSize){if (panel.Profile.Loops.Count != 1){@@ -29,6 +41,10 @@ internal static class GarmentPanelMeshervar boundary = new List<int>();for (int sample = 0; sample < sampled.Count - 1; sample++){+ if (points.Count >= 8192)+ {+ GarmentAuthoring.Fail("garment-mesh-budget", panel.Name + " exceeds 8192 boundary vertices; increase meshSize.");+ }boundary.Add(points.Count);points.Add(sampled[sample]);}@@ -44,6 +60,7 @@ internal static class GarmentPanelMesher}}var polygon = points.Select(point => new Point3D(point.X * 1000d, point.Y * 1000d, 0)).ToArray();+ PlanarMeshQuality.ValidateFillBudget(polygon, meshSize * 800d);if (!PlanarPolygonTriangulator.TryTriangulate(polygon, new Vector3D(0, 0, 1), out var seed, out var failure)){GarmentAuthoring.Fail("garment-triangulation-failed", panel.Name + ": " + failure);@@ -58,6 +75,9 @@ internal static class GarmentPanelMesherInsertBoundaryPoint(point, points, indices);}}+ var filled = PlanarMeshQuality.FillInterior(polygon, indices, meshSize * 800d);+ points = filled.Points.Select(point => new Vector2((float)(point.X * .001), (float)(point.Y * .001))).ToList();+ indices = filled.Indices.ToList();for (int pass = 0; pass < 12; pass++){indices = PlanarMeshQuality.Improve(points.Select(point =>@@ -71,6 +91,23 @@ internal static class GarmentPanelMesher}if (split.Count == 0){+ foreach (var edit in panel.Profile.BoundaryEdits ?? [])+ {+ var boundary = new List<int>();+ foreach (string descendant in edit.Descendants)+ {+ var next = edges[descendant];+ if (boundary.Count > 0 && boundary[^1] != next[0])+ {+ GarmentAuthoring.Fail("garment-boundary-disconnected", panel.Identity + ".edges." + edit.Name);+ }+ boundary.AddRange(boundary.Count == 0 ? next : next.Skip(1));+ }+ if (!edges.TryAdd(edit.Name, boundary) && !edges[edit.Name].SequenceEqual(boundary))+ {+ GarmentAuthoring.Fail("garment-boundary-name-ambiguous", panel.Identity + ".edges." + edit.Name);+ }+ }return new(points, indices, edges);}if (points.Count > 8192)@@ -149,6 +186,10 @@ internal static class GarmentPanelMeshervar key = Key(a, b);if (!split.ContainsKey(key) && Vector2.Distance(points[a], points[b]) > meshSize * 1.001f){+ if (points.Count >= 8192)+ {+ GarmentAuthoring.Fail("garment-mesh-budget", panel.Name + " exceeds 8192 vertices; increase meshSize.");+ }split.Add(key, points.Count);points.Add((points[a] + points[b]) * .5f);}@@ -164,10 +205,16 @@ internal static class GarmentPanelMesherswitch (curve){case LineArcLineSegment2D line:- return [Point(line.Start), Point(line.End)];+ {+ int count = SegmentCount(GarmentPatternInspection.CurveLength(line) / (meshSize * 800d));+ return Enumerable.Range(0, count + 1).Select(i => Vector2.Lerp(Point(line.Start), Point(line.End), (float)i / count)).ToList();+ }case LineArcCircularArc2D arc:{- int count = Math.Clamp((int)Math.Ceiling(Math.Abs(arc.SweepAngleRadians) * arc.Radius / (meshSize * 1000)), 4, 128);+ double tolerance = Math.Min(1, meshSize * 20d);+ double maximumAngle = 2 * Math.Acos(Math.Clamp(1 - tolerance / arc.Radius, -1, 1));+ int count = SegmentCount(Math.Max(Math.Abs(arc.SweepAngleRadians) * arc.Radius / (meshSize * 800),+ Math.Abs(arc.SweepAngleRadians) / maximumAngle));return Enumerable.Range(0, count + 1).Select(i =>{double angle = arc.StartAngleRadians + arc.SweepAngleRadians * i / count;@@ -176,17 +223,43 @@ internal static class GarmentPanelMesher}case LineArcCubicBezier2D cubic:{- float length = Vector2.Distance(Point(cubic.Start), Point(cubic.Control1))- + Vector2.Distance(Point(cubic.Control1), Point(cubic.Control2))- + Vector2.Distance(Point(cubic.Control2), Point(cubic.End));- int count = Math.Clamp((int)Math.Ceiling(length / meshSize), 8, 128);- return Enumerable.Range(0, count + 1).Select(i =>+ var sampled = new List<Vector2> { Point(cubic.Start) };+ Subdivide(cubic, 0);+ return sampled;++ void Subdivide(LineArcCubicBezier2D section, int depth){- float t = (float)i / count;- float u = 1 - t;- return Point(cubic.Start) * (u * u * u) + Point(cubic.Control1) * (3 * u * u * t)- + Point(cubic.Control2) * (3 * u * t * t) + Point(cubic.End) * (t * t * t);- }).ToList();+ Vector2 start = Point(section.Start);+ Vector2 end = Point(section.End);+ Vector2 direction = end - start;+ float length = direction.Length();+ float deviation = Math.Max(DistanceToChord(Point(section.Control1)), DistanceToChord(Point(section.Control2)));+ if (length <= meshSize * .8f && deviation <= Math.Min(.001f, meshSize * .02f))+ {+ if (sampled.Count >= 4097)+ {+ GarmentAuthoring.Fail("garment-curve-sampling-budget", "Cubic sampling exceeds 4096 segments.");+ }+ sampled.Add(end);+ return;+ }+ if (depth == 16)+ {+ GarmentAuthoring.Fail("garment-curve-sampling-budget", "Cubic sampling did not converge within its bounded error/size budget.");+ }+ Subdivide(BezierSectionCurve2D.Trim(section, 0, .5), depth + 1);+ Subdivide(BezierSectionCurve2D.Trim(section, .5, 1), depth + 1);++ float DistanceToChord(Vector2 point)+ {+ if (length < 1e-10f)+ {+ return Vector2.Distance(point, start);+ }+ float t = Math.Clamp(Vector2.Dot(point - start, direction) / (length * length), 0, 1);+ return Vector2.Distance(point, start + direction * t);+ }+ }}default:GarmentAuthoring.Fail("garment-curve-unsupported", "Panels currently admit directed lines, circular arcs and cubic Beziers.");@@ -194,6 +267,16 @@ internal static class GarmentPanelMesher}}+ private static int SegmentCount(double required)+ {+ double count = Math.Max(1, Math.Ceiling(required));+ if (!double.IsFinite(count) || count > 4096)+ {+ GarmentAuthoring.Fail("garment-curve-sampling-budget", "Boundary sampling exceeds 4096 segments; increase meshSize.");+ }+ return (int)count;+ }+private static void InsertBoundaryPoint(int vertex, List<Vector2> points, List<int> indices){Vector2 point = points[vertex];diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentPatternInspection.cs b/Aetheris.Kernel.Firmament/Garment/GarmentPatternInspection.csnew file mode 100644index 00000000..7b55405e--- /dev/null+++ b/Aetheris.Kernel.Firmament/Garment/GarmentPatternInspection.cs@@ -0,0 +1,149 @@+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.Garment;++public sealed record GarmentPatternBoundary(string Name, IReadOnlyList<ResolvedProfileSegment2D> Segments,+ double LengthMm);+public sealed record GarmentPatternSeam(string Name, string A, string B, bool Reversed,+ double LengthAMm, double LengthBMm, double Mismatch, double AllowedEase);++/// <summary>Pattern inspection precedes meshing. Named edits select their ordered descendants;+/// consumed carrier names are never silently rebound to a child.</summary>+public static class GarmentPatternInspection+{+ public static IReadOnlyDictionary<string, GarmentPatternBoundary> Boundaries(GarmentPanel panel)+ {+ var segments = panel.Profile.Loops.Single().Segments;+ var result = new Dictionary<string, GarmentPatternBoundary>(StringComparer.Ordinal);+ foreach (var segment in segments)+ {+ result.Add(segment.Name, new(segment.Name, [segment], CurveLength(segment.Geometry)));+ }+ foreach (var edit in panel.Profile.BoundaryEdits ?? [])+ {+ var descendants = edit.Descendants.Select(name => segments.Single(segment => segment.Name == name)).ToArray();+ if (!result.TryAdd(edit.Name, new(edit.Name, descendants,+ descendants.Sum(segment => CurveLength(segment.Geometry))))+ && !result[edit.Name].Segments.SequenceEqual(descendants))+ {+ GarmentAuthoring.Fail("garment-boundary-name-ambiguous", panel.Identity + ".edges." + edit.Name);+ }+ }+ return result;+ }++ public static IReadOnlyList<GarmentPatternSeam> Inspect(GarmentSource source)+ {+ var used = new HashSet<string>(StringComparer.Ordinal);+ var result = new List<GarmentPatternSeam>();+ foreach (var panel in source.Panels)+ {+ if (panel.Profile.Loops.Count != 1 || !panel.Profile.Loops[0].IsOuter)+ {+ GarmentAuthoring.Fail("garment-profile-holes-unsupported", panel.Identity);+ }+ var boundaries = Boundaries(panel);+ foreach (var pin in panel.Pins)+ {+ if (!boundaries.ContainsKey(pin))+ {+ GarmentAuthoring.Fail("garment-pin-edge-unknown", panel.Identity + ".edges." + pin);+ }+ }+ }+ foreach (var seam in source.Stitches)+ {+ var a = Resolve(seam.A);+ var b = Resolve(seam.B);+ double mismatch = Math.Abs(a.LengthMm - b.LengthMm) / Math.Max(a.LengthMm, b.LengthMm);+ if (mismatch > seam.Ease + .001)+ {+ GarmentAuthoring.Fail("garment-stitch-length-mismatch",+ FormattableString.Invariant($"{seam.Name}: {a.LengthMm:F3}mm / {b.LengthMm:F3}mm; explicit ease >= {mismatch:R} required."));+ }+ result.Add(new(seam.Name, seam.A, seam.B, seam.Reversed, a.LengthMm, b.LengthMm, mismatch, seam.Ease));+ }+ return result;++ GarmentPatternBoundary Resolve(string reference)+ {+ int separator = reference.IndexOf(".edges.", StringComparison.Ordinal);+ if (separator < 1)+ {+ GarmentAuthoring.Fail("garment-stitch-reference", reference);+ }+ string identity = reference[..separator];+ string name = reference[(separator + 7)..];+ var panel = source.Panels.SingleOrDefault(panel => panel.Name == identity || panel.Identity == identity);+ if (panel is null || !Boundaries(panel).TryGetValue(name, out var boundary))+ {+ GarmentAuthoring.Fail("garment-stitch-edge-unknown", reference);+ return null!;+ }+ foreach (var segment in boundary.Segments)+ {+ if (!used.Add(panel.Identity + ".edges." + segment.Name))+ {+ GarmentAuthoring.Fail("garment-stitch-edge-reused", reference + " overlaps an already stitched span.");+ }+ }+ return boundary;+ }+ }++ internal static double CurveLength(LineArcProfileCurve2D curve)+ {+ switch (curve)+ {+ case LineArcLineSegment2D line:+ return Distance(line.Start, line.End);+ case LineArcCircularArc2D arc:+ return arc.Radius * Math.Abs(arc.SweepAngleRadians);+ case LineArcCubicBezier2D cubic:+ return Integrate(0, 1, Speed(0), Speed(.5), Speed(1), 0);++ double Speed(double t)+ {+ double u = 1 - t;+ double x = 3 * (u * u * (cubic.Control1.X - cubic.Start.X)+ + 2 * u * t * (cubic.Control2.X - cubic.Control1.X) + t * t * (cubic.End.X - cubic.Control2.X));+ double y = 3 * (u * u * (cubic.Control1.Y - cubic.Start.Y)+ + 2 * u * t * (cubic.Control2.Y - cubic.Control1.Y) + t * t * (cubic.End.Y - cubic.Control2.Y));+ return Math.Sqrt(x * x + y * y);+ }+ double Integrate(double a, double b, double fa, double fm, double fb, int depth)+ {+ double middle = (a + b) / 2;+ double left = Speed((a + middle) / 2);+ double right = Speed((middle + b) / 2);+ double whole = (b - a) * (fa + 4 * fm + fb) / 6;+ double halves = (b - a) * (fa + 4 * left + 2 * fm + 4 * right + fb) / 12;+ if (depth >= 12 || Math.Abs(halves - whole) < 1e-5)+ {+ return halves + (halves - whole) / 15;+ }+ return Integrate(a, middle, fa, left, fm, depth + 1)+ + Integrate(middle, b, fm, right, fb, depth + 1);+ }+ default:+ GarmentAuthoring.Fail("garment-curve-unsupported", "Patterns admit lines, circular arcs and cubic Beziers.");+ return 0;+ }+ }++ internal static (double X, double Y) Start(LineArcProfileCurve2D curve) => curve switch+ {+ LineArcLineSegment2D line => line.Start,+ LineArcCubicBezier2D cubic => cubic.Start,+ LineArcCircularArc2D arc => (arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians),+ arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians)),+ _ => throw new NotSupportedException("Unsupported pattern curve."),+ };++ private static double Distance((double X, double Y) a, (double X, double Y) b)+ {+ double x = b.X - a.X;+ double y = b.Y - a.Y;+ return Math.Sqrt(x * x + y * y);+ }+}diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentPatternPreview.cs b/Aetheris.Kernel.Firmament/Garment/GarmentPatternPreview.csnew file mode 100644index 00000000..22484702--- /dev/null+++ b/Aetheris.Kernel.Firmament/Garment/GarmentPatternPreview.cs@@ -0,0 +1,140 @@+using System.Globalization;+using System.Security;+using System.Text;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.Garment;++/// <summary>Projects resolved analytic curves directly to SVG. No mesh or simulation dependency.</summary>+public static class GarmentPatternPreview+{+ private static readonly string[] SeamColors = ["#c45d21", "#933c83", "#177b66", "#3758b1", "#ac7022", "#b7384a"];++ public static string Svg(GarmentSource source)+ {+ var seams = GarmentPatternInspection.Inspect(source);+ int rows = (source.Panels.Length + 1) / 2;+ int height = 130 + rows * 650;+ var svg = new StringBuilder($"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"1600\" height=\"{height}\" viewBox=\"0 0 1600 {height}\">\n");+ svg.AppendLine($"<rect width=\"1600\" height=\"{height}\" fill=\"#f5f3ee\"/>");+ svg.AppendLine("<g font-family=\"sans-serif\" fill=\"#24344c\">");+ svg.AppendLine($"<text x=\"30\" y=\"38\" font-size=\"26\">{Escape(source.Name)} — resolved material patterns (mm)</text>");+ svg.AppendLine("<text x=\"30\" y=\"68\" font-size=\"15\">Matching seam colors · blue open boundaries · green supports · arrows indicate seam correspondence</text>");+ svg.AppendLine("<text x=\"30\" y=\"92\" font-size=\"15\">Analytic profiles before meshing. Cut boundary; no seam allowance added.</text>");+ for (int ordinal = 0; ordinal < source.Panels.Length; ordinal++)+ {+ var panel = source.Panels[ordinal];+ var segments = panel.Profile.Loops.Single().Segments;+ var bounds = segments.SelectMany(segment => Bounds(segment.Geometry)).ToArray();+ var boundaries = GarmentPatternInspection.Boundaries(panel);+ double minX = bounds.Min(point => point.X);+ double minY = bounds.Min(point => point.Y);+ double maxX = bounds.Max(point => point.X);+ double maxY = bounds.Max(point => point.Y);+ double scale = Math.Min(430 / (maxX - minX), 450 / (maxY - minY));+ double left = 35 + ordinal % 2 * 800;+ double top = 155 + ordinal / 2 * 650;+ svg.AppendLine($"<text x=\"{Number(left)}\" y=\"{Number(top)}\" font-size=\"21\">{Escape(panel.Identity)}</text>");+ svg.AppendLine($"<text x=\"{Number(left)}\" y=\"{Number(top + 25)}\" font-size=\"13\">Envelope {Number(maxX - minX)} × {Number(maxY - minY)} mm</text>");+ svg.AppendLine($"<g transform=\"translate({Number(left - minX * scale)},{Number(top + 50 + maxY * scale)}) scale({Number(scale)},-{Number(scale)})\">");+ foreach (var segment in segments)+ {+ var boundaryNames = boundaries.Values+ .Where(boundary => boundary.Segments.Any(child => child.Name == segment.Name))+ .Select(boundary => boundary.Name).ToArray();+ int seamIndex = FindSeam(seams, panel, boundaryNames);+ bool pinned = panel.Pins.Any(boundaryNames.Contains);+ string color = BoundaryColor(seamIndex, pinned);+ svg.AppendLine($"<path data-boundary=\"{Escape(segment.Name)}\" d=\"{Path(segment.Geometry)}\" fill=\"none\" stroke=\"{color}\" stroke-width=\"2\" vector-effect=\"non-scaling-stroke\"/>");+ }+ double cx = (minX + maxX) / 2;+ double cy = (minY + maxY) / 2;+ double arrow = Math.Min(maxX - minX, maxY - minY) * .13;+ double gx = panel.Grain.X * arrow;+ double gy = panel.Grain.Y * arrow;+ svg.AppendLine($"<path d=\"M {Number(cx - gx)} {Number(cy - gy)} L {Number(cx + gx)} {Number(cy + gy)} M {Number(cx + gx - gx * .2 - gy * .1)} {Number(cy + gy - gy * .2 + gx * .1)} L {Number(cx + gx)} {Number(cy + gy)} L {Number(cx + gx - gx * .2 + gy * .1)} {Number(cy + gy - gy * .2 - gx * .1)}\" fill=\"none\" stroke=\"#24344c\" stroke-width=\"1.5\" vector-effect=\"non-scaling-stroke\"/>");+ svg.AppendLine("</g>");+ double lineY = top + 62;+ foreach (var boundary in boundaries.Values)+ {+ bool unnamedChild = (panel.Profile.BoundaryEdits ?? []).Any(edit => edit.Descendants.Contains(boundary.Name)+ && boundary.Name.StartsWith(edit.Name + "_Span", StringComparison.Ordinal));+ bool unselectedGroup = (panel.Profile.BoundaryEdits ?? []).Any(edit => edit.Name == boundary.Name)+ && FindSeam(seams, panel, [boundary.Name]) < 0 && !panel.Pins.Contains(boundary.Name)+ && !(panel.Profile.BoundaryEdits ?? []).Any(edit => edit.Name == boundary.Name+ && edit.Descendants.All(name => name.StartsWith(edit.Name + "_Span", StringComparison.Ordinal)));+ if (unnamedChild || unselectedGroup)+ {+ continue;+ }+ int seamIndex = FindSeam(seams, panel, [boundary.Name]);+ bool pinned = panel.Pins.Contains(boundary.Name);+ string color = BoundaryColor(seamIndex, pinned);+ string correspondence = pinned ? "support" : "open";+ if (seamIndex >= 0)+ {+ string direction = seams[seamIndex].Reversed ? " ↔ reversed" : " → same";+ correspondence = seams[seamIndex].Name + direction;+ }+ svg.AppendLine($"<text x=\"{Number(left + 455)}\" y=\"{Number(lineY)}\" font-size=\"12\" fill=\"{color}\">{Escape(boundary.Name)} · {Number(boundary.LengthMm)}mm</text>");+ svg.AppendLine($"<text x=\"{Number(left + 455)}\" y=\"{Number(lineY + 16)}\" font-size=\"11\">{Escape(correspondence)}</text>");+ lineY += 38;+ }+ }+ svg.AppendLine("</g></svg>");+ return svg.ToString();+ }++ private static int FindSeam(IReadOnlyList<GarmentPatternSeam> seams, GarmentPanel panel, string[] names)+ {+ for (int index = 0; index < seams.Count; index++)+ {+ foreach (string name in names)+ {+ string identity = panel.Identity + ".edges." + name;+ string local = panel.Name + ".edges." + name;+ if (seams[index].A == identity || seams[index].B == identity || seams[index].A == local || seams[index].B == local)+ {+ return index;+ }+ }+ }+ return -1;+ }++ private static string BoundaryColor(int seamIndex, bool pinned)+ {+ if (pinned)+ {+ return "#16835b";+ }+ if (seamIndex < 0)+ {+ return "#3274a0";+ }+ return SeamColors[seamIndex % SeamColors.Length];+ }++ private static IEnumerable<(double X, double Y)> Bounds(LineArcProfileCurve2D curve)+ {+ // Reuse profile curve bounds. An arc's unused circle must not enlarge the panel preview.+ var bounds = BezierSectionCurve2D.Bounds(curve, 0, 1);+ return [(bounds.MinX, bounds.MinY), (bounds.MaxX, bounds.MaxY)];+ }++ private static string Path(LineArcProfileCurve2D curve)+ {+ var start = GarmentPatternInspection.Start(curve);+ string path = $"M {Number(start.X)} {Number(start.Y)} ";+ return curve switch+ {+ LineArcLineSegment2D line => path + $"L {Number(line.End.X)} {Number(line.End.Y)}",+ LineArcCubicBezier2D cubic => path + $"C {Number(cubic.Control1.X)} {Number(cubic.Control1.Y)} {Number(cubic.Control2.X)} {Number(cubic.Control2.Y)} {Number(cubic.End.X)} {Number(cubic.End.Y)}",+ LineArcCircularArc2D arc => path + $"A {Number(arc.Radius)} {Number(arc.Radius)} 0 {(Math.Abs(arc.SweepAngleRadians) > Math.PI ? 1 : 0)} {(arc.SweepAngleRadians > 0 ? 1 : 0)} {Number(arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians + arc.SweepAngleRadians))} {Number(arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians + arc.SweepAngleRadians))}",+ _ => throw new NotSupportedException("Unsupported pattern curve."),+ };+ }++ private static string Number(double value) => value.ToString("0.######", CultureInfo.InvariantCulture);+ private static string Escape(string value) => SecurityElement.Escape(value) ?? "";+}diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentSchema.cs b/Aetheris.Kernel.Firmament/Garment/GarmentSchema.csindex edb29a3c..ef507522 100644--- a/Aetheris.Kernel.Firmament/Garment/GarmentSchema.cs+++ b/Aetheris.Kernel.Firmament/Garment/GarmentSchema.cs@@ -37,8 +37,23 @@ public static class GarmentStitchDeclaration { }[FirmamentField("BendCompliance", "BendCompliance", FirmamentSchemaValueKind.Scalar)]public static class GarmentFabricDeclaration { }-[FirmamentConstruct("Drape", "Drape", Context = "Garment", Entry = "Drape { figure: Anatolia; pose: Rest; clearance: 4mm; }", Description = "A named figure binding supplied by the host. The first lane sews and settles on the loaded static Rest-pose body.")]+[FirmamentConstruct("Drape", "Drape", Context = "Garment", Entry = "Drape { figure: Anatolia; pose: Rest; clearance: 4mm; }", Description = "A figure and authored pose binding, with an optional finite transition sampled during cloth simulation.")][FirmamentField("Figure", "Figure", FirmamentSchemaValueKind.ConstructReference, Required = true)]-[FirmamentField("Pose", "Pose", FirmamentSchemaValueKind.Choice, Choices = ["Rest"])]+[FirmamentField("Pose", "Pose", FirmamentSchemaValueKind.ConstructReference, Default = "Rest")][FirmamentField("Clearance", "Clearance", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length)]+[FirmamentField("Transition", "Transition", FirmamentSchemaValueKind.ConstructReference)]public static class GarmentDrapeDeclaration { }++[FirmamentConstruct("FigureFit", "FigureFit", Context = "Concept Struct", Entry = "FigureFit body { figure: Anatolia; pose: Rest; }", Description = "Checked surface sections and joint guides of an explicitly supplied gameplay body and measurement pose. Publishes Length values for ordinary Features and Concept placement.")]+[FirmamentField("Figure", "Figure", FirmamentSchemaValueKind.ConstructReference, Required = true)]+[FirmamentField("Pose", "Pose", FirmamentSchemaValueKind.ConstructReference, Default = "Rest")]+[FirmamentField("ChestHeight", "ChestHeight", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length)]+[FirmamentField("HipHeight", "HipHeight", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length)]+public static class GarmentFigureFitDeclaration { }++[FirmamentConstruct("Fitting", "Fitting", Context = "Garment", Entry = "Fitting collar { on: guides.collarFloor; edges: [front.edges.collar]; compliance: 0.000001; releaseAfter: 20; }", Description = "Temporary named-edge half-space constraints compiled from an erased Concept plane. Released after the declared number of settling frames, with at least 15 unsupported frames before qualification.")]+[FirmamentField("On", "On", FirmamentSchemaValueKind.ConstructReference, Required = true)]+[FirmamentField("Edges", "Edges", FirmamentSchemaValueKind.ConstructReference, Required = true)]+[FirmamentField("Compliance", "Compliance", FirmamentSchemaValueKind.Scalar, Default = "0.000001")]+[FirmamentField("ReleaseAfter", "ReleaseAfter", FirmamentSchemaValueKind.Scalar, Required = true)]+public static class GarmentFittingDeclaration { }diff --git a/Aetheris.Kernel.Firmament/Humanoid/HumanoidClothMotion.cs b/Aetheris.Kernel.Firmament/Humanoid/HumanoidClothMotion.csnew file mode 100644index 00000000..d3590bf1--- /dev/null+++ b/Aetheris.Kernel.Firmament/Humanoid/HumanoidClothMotion.cs@@ -0,0 +1,93 @@+using System.Numerics;+using Aetheris.Cloth3D;+using Aetheris.Humanoid;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament.Garment;++namespace Aetheris.Kernel.Firmament.Humanoid;++/// <summary>One-way authored motion. Skinning preserves the bind skeleton; only collision positions are refitted.</summary>+internal sealed class HumanoidClothMotion : IClothKinematicBodySurface3D+{+ private readonly HumanoidGameplayBody body;+ private readonly FirmamentHumanoidPose from;+ private readonly FirmamentHumanoidPose to;+ private readonly FirmamentPoseTransition? transition;+ private readonly IReadOnlyList<AnatomicalJointRequest> fromRequests;+ private readonly IReadOnlyList<AnatomicalJointRequest> toRequests;+ private double previousTime;+ private double previousFraction = -1;++ public HumanoidClothMotion(HumanoidGameplayBody body, FirmamentPoseDocument document,+ string figure, string pose, string? transitionName)+ {+ this.body = body;+ from = document.Resolve(pose, figure);+ to = from;+ if (transitionName is not null)+ {+ transition = document.Transitions[transitionName];+ to = document.Resolve(transition.To, figure);+ }+ CurrentPose = HumanoidPoseAuthoring.Solve(from, body);+ fromRequests = HumanoidPoseAuthoring.Requests(from, body);+ toRequests = HumanoidPoseAuthoring.Requests(to, body);+ Positions = body.EvaluatePositions(CurrentPose);+ Surface = GarmentDraping.BodySurface(body, Positions);+ previousFraction = 0;+ }++ public ClothTriangleBody3D Surface { get; }+ public SolvedHumanoidPose CurrentPose { get; private set; }+ public IReadOnlyList<Point3D> Positions { get; private set; }+ public double DurationSeconds => transition?.DurationSeconds ?? 0;+ public float MaximumSubstepTravel { get; private set; }++ public ClothBodySample3D Query(Vector3 position)+ {+ return Surface.Query(position);+ }++ public void Sample(double seconds)+ {+ if (!double.IsFinite(seconds) || seconds < 0)+ {+ throw new ArgumentOutOfRangeException(nameof(seconds));+ }+ double fraction = DurationSeconds == 0 ? 0 : Math.Clamp(seconds / DurationSeconds, 0, 1);+ if (fraction == previousFraction)+ {+ previousTime = seconds;+ return;+ }+ double eased = fraction;+ if (transition?.Easing == "SmoothStep")+ {+ eased = fraction * fraction * (3 - 2 * fraction);+ }+ var requests = HumanoidPoseRecipes.Blend(body, fromRequests, toRequests, eased);+ var recipe = new FirmamentHumanoidPose(transition!.Name, from.Figure, requests);+ var solved = HumanoidPoseAuthoring.Solve(recipe, body);+ var updated = body.EvaluatePositions(solved);+ var collisionPositions = updated.Select(point => new Vector3((float)point.X, (float)point.Y, (float)point.Z) * .001f).ToArray();+ Surface.Refit(collisionPositions);+ // Backward samples are legal for replay; only forward substep travel is measured.+ if (seconds > previousTime && seconds - previousTime <= .1)+ {+ for (int vertex = 0; vertex < updated.Count; vertex++)+ {+ float distance = (float)(updated[vertex] - Positions[vertex]).Length * .001f;+ MaximumSubstepTravel = MathF.Max(MaximumSubstepTravel, distance);+ }+ }+ Positions = updated;+ CurrentPose = solved;+ previousFraction = fraction;+ previousTime = seconds;+ }++ public ConstrainedSurfaceEvidence Inspect()+ {+ return HumanoidConstrainedSurface.Inspect(body.Surface, body.Skeleton, CurrentPose.GlobalTransforms, Positions);+ }+}diff --git a/Aetheris.Kernel.Firmament/Humanoid/HumanoidPoseAuthoring.cs b/Aetheris.Kernel.Firmament/Humanoid/HumanoidPoseAuthoring.csnew file mode 100644index 00000000..b26d0af7--- /dev/null+++ b/Aetheris.Kernel.Firmament/Humanoid/HumanoidPoseAuthoring.cs@@ -0,0 +1,301 @@+using System.Globalization;+using System.Text.RegularExpressions;+using Aetheris.Humanoid;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Humanoid;++public sealed record FirmamentHumanoidPose(string Name, string Figure,+ IReadOnlyList<AnatomicalJointRequest> Joints)+{+ public IReadOnlyList<FirmamentJointOverride> RestOverrides { get; init; } = [];+}+public sealed record FirmamentJointOverride(HumanoidJointKind Joint, double? Flexion, double? Abduction, double? Twist);+public sealed record FirmamentPoseTransition(string Name, string From, string To,+ double DurationSeconds, string Easing);+public sealed record FirmamentPoseDocument([property: System.Text.Json.Serialization.JsonIgnore] string RemainingSource,+ IReadOnlyDictionary<string, FirmamentHumanoidPose> Poses,+ IReadOnlyDictionary<string, FirmamentPoseTransition> Transitions)+{+ public FirmamentHumanoidPose Resolve(string name, string figure)+ {+ if (Enum.TryParse<HumanoidPosePreset>(name, out var preset) && Enum.IsDefined(preset))+ {+ return new(name, figure, HumanoidPoseRecipes.Preset(preset));+ }+ if (!Poses.TryGetValue(name, out var pose) || pose.Figure != figure)+ {+ throw new InvalidDataException("humanoid-pose-reference: Unknown pose or mismatched figure: " + name);+ }+ return pose;+ }+}++/// <summary>Finite named pose recipes lowered to the existing anatomical solver. No second skeleton or skinning path.</summary>+public static class HumanoidPoseAuthoring+{+ private sealed record Declaration(string Name, string Figure, string From,+ IReadOnlyDictionary<HumanoidJointKind, IReadOnlyDictionary<string, double>> Overrides);++ public static FirmamentPoseDocument Parse(string original)+ {+ string source = FirmamentSourceSpelling.Normalize(original);+ var tokens = FirmamentLanguageAnalysisService.Lex(source).Where(token => token.Shape != "comment").ToArray();+ var poses = new Dictionary<string, Declaration>(StringComparer.Ordinal);+ var transitions = new Dictionary<string, FirmamentPoseTransition>(StringComparer.Ordinal);+ var removals = new List<(int Start, int Length)>();+ int depth = 0;+ for (int index = 0; index < tokens.Length; index++)+ {+ string kind = tokens[index].Text;+ if (depth == 0 && kind is "Pose" or "PoseTransition")+ {+ if (index + 2 >= tokens.Length || tokens[index + 1].Shape != "identifier" || tokens[index + 2].Text != "{")+ {+ Fail("humanoid-pose-syntax", "Expected " + kind + " name { ... }.");+ }+ string name = tokens[index + 1].Text;+ int end = index + 3;+ int blockDepth = 1;+ for (; end < tokens.Length; end++)+ {+ if (tokens[end].Text == "{")+ {+ blockDepth++;+ }+ if (tokens[end].Text == "}" && --blockDepth == 0)+ {+ break;+ }+ }+ if (end == tokens.Length)+ {+ Fail("humanoid-pose-syntax", "Unclosed " + name);+ }+ string body = source[(tokens[index + 2].Start + 1)..tokens[end].Start];+ if (poses.ContainsKey(name) || transitions.ContainsKey(name) || Enum.TryParse<HumanoidPosePreset>(name, out _))+ {+ Fail("humanoid-pose-name-duplicate", name);+ }+ if (kind == "Pose")+ {+ poses.Add(name, ReadPose(name, body));+ }+ else+ {+ var fields = Fields(body, ["From", "To", "Duration", "Easing"]);+ string easing = fields.GetValueOrDefault("Easing", "SmoothStep");+ if (easing is not ("SmoothStep" or "Linear"))+ {+ Fail("humanoid-pose-easing", easing);+ }+ var duration = Regex.Match(Required(fields, "Duration"), @"^([0-9]+(?:\.[0-9]+)?)\s*s$");+ double seconds = 0;+ if (!duration.Success || !double.TryParse(duration.Groups[1].Value, CultureInfo.InvariantCulture, out seconds)+ || seconds is < .016666 or > 10)+ {+ Fail("humanoid-pose-duration", "Duration requires 1/60..10 seconds with an explicit s suffix.");+ }+ transitions.Add(name, new(name, Required(fields, "From"), Required(fields, "To"), seconds, easing));+ }+ removals.Add((tokens[index].Start, tokens[end].Start + tokens[end].Length - tokens[index].Start));+ index = end;+ continue;+ }+ if (kind == "{")+ {+ depth++;+ }+ if (kind == "}")+ {+ depth--;+ }+ }+ var resolved = new Dictionary<string, FirmamentHumanoidPose>(StringComparer.Ordinal);+ var visiting = new HashSet<string>(StringComparer.Ordinal);+ foreach (string name in poses.Keys)+ {+ Resolve(name);+ }+ foreach (var transition in transitions.Values)+ {+ if (!resolved.TryGetValue(transition.From, out var from) || !resolved.TryGetValue(transition.To, out var to)+ || from.Figure != to.Figure)+ {+ Fail("humanoid-pose-transition-binding", "Transition endpoints must be named poses of the same figure.");+ }+ }+ foreach (var removal in removals.OrderByDescending(removal => removal.Start))+ {+ source = source.Remove(removal.Start, removal.Length);+ }+ return new(source, new System.Collections.ObjectModel.ReadOnlyDictionary<string, FirmamentHumanoidPose>(resolved),+ new System.Collections.ObjectModel.ReadOnlyDictionary<string, FirmamentPoseTransition>(transitions));++ FirmamentHumanoidPose Resolve(string name)+ {+ if (resolved.TryGetValue(name, out var existing))+ {+ return existing;+ }+ if (!visiting.Add(name) || visiting.Count > 32)+ {+ Fail("humanoid-pose-cycle", "Pose inheritance must be acyclic and at most 32 levels deep.");+ }+ var declaration = poses[name];+ IReadOnlyList<AnatomicalJointRequest> inherited;+ IReadOnlyList<FirmamentJointOverride> inheritedRest = [];+ if (Enum.TryParse<HumanoidPosePreset>(declaration.From, out var preset) && Enum.IsDefined(preset))+ {+ inherited = HumanoidPoseRecipes.Preset(preset);+ }+ else+ {+ if (!poses.ContainsKey(declaration.From))+ {+ Fail("humanoid-pose-reference", declaration.From);+ }+ var parent = Resolve(declaration.From);+ if (parent.Figure != declaration.Figure)+ {+ Fail("humanoid-pose-figure-mismatch", name);+ }+ inherited = parent.Joints;+ inheritedRest = parent.RestOverrides;+ }+ var joints = inherited.ToDictionary(joint => joint.Joint);+ var restOverrides = inheritedRest.ToDictionary(joint => joint.Joint);+ foreach (var joint in declaration.Overrides)+ {+ if (joints.TryGetValue(joint.Key, out var basis))+ {+ joints[joint.Key] = new(joint.Key,+ joint.Value.GetValueOrDefault("Flexion", basis.FlexionDegrees),+ joint.Value.GetValueOrDefault("Abduction", basis.AbductionDegrees),+ joint.Value.GetValueOrDefault("Twist", basis.TwistDegrees));+ }+ else+ {+ var prior = restOverrides.GetValueOrDefault(joint.Key) ?? new FirmamentJointOverride(joint.Key, null, null, null);+ restOverrides[joint.Key] = new(joint.Key,+ Override("Flexion", prior.Flexion), Override("Abduction", prior.Abduction), Override("Twist", prior.Twist));++ double? Override(string field, double? previous)+ {+ return joint.Value.TryGetValue(field, out double value) ? value : previous;+ }+ }+ }+ var result = new FirmamentHumanoidPose(name, declaration.Figure, Array.AsReadOnly(joints.Values.OrderBy(joint => joint.Joint).ToArray()))+ {+ RestOverrides = Array.AsReadOnly(restOverrides.Values.OrderBy(joint => joint.Joint).ToArray()),+ };+ visiting.Remove(name);+ resolved.Add(name, result);+ return result;+ }+ }++ public static SolvedHumanoidPose Solve(FirmamentHumanoidPose pose, HumanoidGameplayBody body)+ {+ var solved = body.Solve(pose.Name, Requests(pose, body));+ if (!solved.IsSolved)+ {+ Fail("humanoid-pose-solve", string.Join("; ", solved.Diagnostics.Select(diagnostic => diagnostic.Code + ": " + diagnostic.Message)));+ }+ return solved.Pose!;+ }++ public static IReadOnlyList<AnatomicalJointRequest> Requests(FirmamentHumanoidPose pose, HumanoidGameplayBody body)+ {+ var result = pose.Joints.ToList();+ var globals = body.Skeleton.Joints.Select(joint => joint.GlobalBind).ToArray();+ foreach (var joint in pose.RestOverrides)+ {+ var rest = HumanoidPoseSemantics.Measure(body.Skeleton, globals, joint.Joint);+ result.Add(new(joint.Joint, joint.Flexion ?? rest.FlexionDegrees,+ joint.Abduction ?? rest.AbductionDegrees, joint.Twist ?? rest.TwistDegrees));+ }+ return Array.AsReadOnly(result.OrderBy(joint => joint.Joint).ToArray());+ }++ private static Declaration ReadPose(string name, string body)+ {+ var reader = new FirmamentBlockReader(body, Fail, "humanoid-pose-syntax");+ var fields = new Dictionary<string, string>(StringComparer.Ordinal);+ var joints = new Dictionary<HumanoidJointKind, IReadOnlyDictionary<string, double>>();+ while (!reader.End)+ {+ if (reader.Optional(";"))+ {+ continue;+ }+ if (reader.Optional("Joint"))+ {+ string jointName = reader.Identifier();+ if (!Enum.TryParse<HumanoidJointKind>(jointName, out var joint) || !Enum.IsDefined(joint))+ {+ Fail("humanoid-pose-joint", jointName);+ }+ var angles = Fields(reader.Block(), ["Flexion", "Abduction", "Twist"]);+ var values = angles.ToDictionary(pair => pair.Key, pair => Angle(pair.Value));+ if (values.Count == 0 || !joints.TryAdd(joint, values))+ {+ Fail("humanoid-pose-joint-duplicate", jointName);+ }+ continue;+ }+ string field = reader.Identifier();+ reader.Expect(":");+ if (field is not ("Figure" or "From") || !fields.TryAdd(field, reader.Value()))+ {+ Fail("humanoid-pose-field", field);+ }+ }+ return new(name, Required(fields, "Figure"), fields.GetValueOrDefault("From", "Rest"), joints);+ }++ private static Dictionary<string, string> Fields(string body, string[] admitted)+ {+ var reader = new FirmamentBlockReader(body, Fail, "humanoid-pose-syntax");+ var fields = new Dictionary<string, string>(StringComparer.Ordinal);+ while (!reader.End)+ {+ if (reader.Optional(";"))+ {+ continue;+ }+ string name = reader.Identifier();+ reader.Expect(":");+ if (!admitted.Contains(name) || !fields.TryAdd(name, reader.Value()))+ {+ Fail("humanoid-pose-field", name);+ }+ }+ return fields;+ }++ private static double Angle(string text)+ {+ if (!FirmamentV2FeatureExpansion.TryEvaluateScalar(text, out double value, out string unit)+ || unit != "deg" || !double.IsFinite(value))+ {+ Fail("humanoid-pose-angle", "Anatomical angles require finite degree-valued expressions: " + text);+ }+ return value;+ }++ private static string Required(Dictionary<string, string> fields, string field)+ {+ if (!fields.TryGetValue(field, out string? value))+ {+ Fail("humanoid-pose-field-required", field);+ }+ return value!;+ }++ private static void Fail(string code, string message)+ {+ throw new InvalidDataException(code + ": " + message);+ }+}diff --git a/Aetheris.Kernel.Firmament/Humanoid/HumanoidPoseSchema.cs b/Aetheris.Kernel.Firmament/Humanoid/HumanoidPoseSchema.csnew file mode 100644index 00000000..9b140954--- /dev/null+++ b/Aetheris.Kernel.Firmament/Humanoid/HumanoidPoseSchema.cs@@ -0,0 +1,21 @@+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Humanoid;++[FirmamentConstruct("Pose", "Pose", Context = "Document", Entry = "Pose fitting { figure: Anatolia; from: TPose; }", Description = "Finite named anatomical pose recipe using the original figure skeleton.")]+[FirmamentField("Figure", "Figure", FirmamentSchemaValueKind.ConstructReference, Required = true)]+[FirmamentField("From", "From", FirmamentSchemaValueKind.ConstructReference, Default = "Rest")]+public static class HumanoidPoseDeclaration { }++[FirmamentConstruct("Joint", "Joint", Context = "Pose", Entry = "Joint LeftElbow { flexion: 15deg; }", Description = "Absolute anatomical joint overrides, validated by the shared humanoid solver.")]+[FirmamentField("Flexion", "Flexion", FirmamentSchemaValueKind.Angle, Unit = FirmamentUnitKind.Angle)]+[FirmamentField("Abduction", "Abduction", FirmamentSchemaValueKind.Angle, Unit = FirmamentUnitKind.Angle)]+[FirmamentField("Twist", "Twist", FirmamentSchemaValueKind.Angle, Unit = FirmamentUnitKind.Angle)]+public static class HumanoidPoseJointDeclaration { }++[FirmamentConstruct("PoseTransition", "PoseTransition", Context = "Document", Entry = "PoseTransition lowerArms { from: fitting; to: wearing; duration: 2s; easing: SmoothStep; }", Description = "Explicit finite anatomical transition, sampled at cloth substep times without rebinding the skeleton.")]+[FirmamentField("From", "From", FirmamentSchemaValueKind.ConstructReference, Required = true)]+[FirmamentField("To", "To", FirmamentSchemaValueKind.ConstructReference, Required = true)]+[FirmamentField("Duration", "Duration", FirmamentSchemaValueKind.Scalar, Required = true)]+[FirmamentField("Easing", "Easing", FirmamentSchemaValueKind.Choice, Choices = ["SmoothStep", "Linear"], Default = "SmoothStep")]+public static class HumanoidPoseTransitionDeclaration { }diff --git a/Aetheris.Kernel.Firmament/Materializer/BezierSectionCurve2D.cs b/Aetheris.Kernel.Firmament/Materializer/BezierSectionCurve2D.csindex 53a0ed31..12162d29 100644--- a/Aetheris.Kernel.Firmament/Materializer/BezierSectionCurve2D.cs+++ b/Aetheris.Kernel.Firmament/Materializer/BezierSectionCurve2D.cs@@ -107,7 +107,7 @@ internal static class BezierSectionCurve2D_ => throw new NotSupportedException($"Unsupported section boundary: {c.GetType().Name}")};- private static (double MinX,double MaxX,double MinY,double MaxY) Bounds(LineArcProfileCurve2D c,double from,double to)+ internal static (double MinX,double MaxX,double MinY,double MaxY) Bounds(LineArcProfileCurve2D c,double from,double to){(double X,double Y)[] points;if (c is LineArcCubicBezier2D b)diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 6f097c5a..1d6f904a 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -82,6 +82,34 @@ Institute of Standards and Technology. NIST does not endorse Aetheris, no NISTcode is represented as part of Aetheris, and the models are not represented asAGPL-licensed or authored by Aetheris.+## GarmentCode sewing-pattern reference and interchange++The GarmentCode curve-coordinate and stitch conventions used by+`Aetheris.Kernel.Firmament/Garment/GarmentCodeImport.cs`, and the generated+shirt/dress reference patterns under `fixtures/Canonical/Garment/GarmentCode/`,+derive from Maria Korosteleva's MIT-licensed GarmentCode:+https://github.com/maria-korosteleva/GarmentCode/tree/d449629979028123a5c4dc9e732a2ec19b7fce31.+Copyright (c) 2024 Maria Korosteleva. The complete unmodified MIT license is+preserved in `fixtures/Canonical/Garment/GarmentCode/LICENSE.txt` and must+accompany copies or substantial portions of these derivatives.++Reference recipes: `assets/garment_programs/bodice.py` (`Shirt`, non-fitted),+`tee.py`, `sleeves.py`, `collars.py`; conventions: `pygarment/pattern/utils.py`+and `pygarment/meshgen/boxmeshgen.py`. `provenance.json`, design presets and+body measurements identify the exact upstream experiment. The two Firmament+dress fixtures are Aetheris translations/adaptations of this reference, not+independently invented sewing patterns.++Credit the research: Maria Korosteleva and Olga Sorkine-Hornung,+*GarmentCode: Programming Parametric Sewing Patterns*, SIGGRAPH Asia 2023.+https://igl.ethz.ch/projects/garmentcode/.++No upstream simulator, Python runtime, body mesh, SMPL/CAESAR data or+GarmentCodeData dataset is bundled by this adoption. The upstream body README+describes body-asset provenance separately; dataset/body terms are not+replaced by the code's MIT license. External body meshes used for local+research remain external inputs and their original terms still apply.+## Other dependenciesCadmata's managed WGSL compilation graph includes Copeland.Markdown,diff --git a/docs/public/firmament/garment-armhole-experiment.md b/docs/public/firmament/garment-armhole-experiment.mdnew file mode 100644index 00000000..40340d87--- /dev/null+++ b/docs/public/firmament/garment-armhole-experiment.md@@ -0,0 +1,150 @@+# Garment armhole experiment++Date: 2026-10-11. This follows [temporary Concept fitting](garment-temporary-fitting.md).+**The final A-pose drape improves from 87.12% to 9.23% peak strain. The complete+dressing sequence remains unqualified because fitting and midpoint checkpoints+still exceed the unchanged 15% strain limit.**++## Controlled inputs++All trials retain the imported GarmentCode cut, raised flat arrangement, 611+vertices, 992 triangles, six seams and zero permanent pins. The control uses+Rest-pose sewing and a collar guide at measured shoulder height plus 45mm,+compliance 1e-8, released after 20 settling frames. Each run has 30 gravity-free+sewing frames, 60 fitting frames, eight substeps and 24 structural iterations.+The transition adds 30 motion frames and 60 wearing frames.++Body SHA-256:+`0a0ad03e86447fc56448940c7aa56b54ea6683e8a874f833e01fd56a65a2d0e5`.+Cloth content key, including arrangement and fabric:+`42C204F0BE495216B6CB3C2C3087EC8C786135D3EE71FE2D465BCFB4D468BA8B`.+Warp/weft compliance remains 1e-8 and diagonal compliance 4e-8. These are+authoring values, not calibrated textile measurements. No pattern dimension,+clearance, acceptance gate or body skin weight was adjusted.++## Contact isolation++`scripts/inspect-garment-strain.cs` recompiles the actual source, checks its hash+against the retained `garment.json`, verifies FigureFit body artifact hashes+and validates snapshot topology/material identity. It reconstructs the authored+final body pose through the existing humanoid solver. It reports semantic edge+membership, material coordinates and body samples for the eight worst links.+It runs five replay frames through `ClothSolver3D` with zero initial velocity+and zero gravity, varying contact and substeps with 24 iterations.++The original final snapshot has 87.119% strain and 0.00872mm sampled penetration.+Its worst link is right-back armhole 336/337, rest length 14.275mm. Its endpoints+are 6.002mm and 7.792mm from the body. Interior triangle samples and connected+constraints also act on them; endpoint distance alone cannot justify disabling+contact.++| Contact | Substeps | Peak strain after five frames | Penetration against original body | Seam gap |+| --- | ---: | ---: | ---: | ---: |+| Enabled | 8 | 80.663% | 0.748mm | 1.968mm |+| Enabled | 32 | 85.598% | 0.766mm | 1.734mm |+| Disabled | 8 | 12.490% | 61.136mm | 0.548mm |+| Disabled | 32 | 0.925% | 95.169mm | 0.064mm |++The sewn material can relax when contact is removed, but then enters the body.+More substeps with contact enabled do not repair this control. This implicates+the fitted arrangement and contact/structural conflict; it does not establish+pattern sizing or the discrete contact algorithm as the sole root cause.+Contact-disabled snapshots are diagnostic failures, never accepted fits.++## Declarative fitting and motion++Changing only the fitting pose to TPose reduces final strain to 22.309%, seam+gap to 0.820mm and sampled penetration to 0.000128mm. The guide is released,+with 40 unsupported fitting frames. The worst remaining edge is right-back+armhole 331/332, rest length 10.770mm; the next reported outlier is 9.614%.++Then the same fitted garment follows the existing half-second SmoothStep+transition from TPose to APose, followed by 60 wearing frames:++| Checkpoint | Peak strain | Seam gap | Sampled penetration | Body surface admissible |+| --- | ---: | ---: | ---: | --- |+| Fitting | 22.309% | 0.820mm | 0.000128mm | Yes |+| Midpoint | 22.372% | 1.111mm | 0.000118mm | Yes |+| Wearing | 9.228% | 1.132mm | 0.0000247mm | Yes |++The final garment has no permanent pins or active guides. Final and midpoint+replay checks are exact. Maximum measured body travel per substep is 4.088mm;+this is a diagnostic, not CCD certification. The final wearing snapshot passes+the existing strain/seam/contact gates. **The CLI correctly reports the whole+sequence as failed** because its fitting and midpoint strain still exceeds 15%.+No checkpoint is exempted and no limit is weakened.+The final three wearing samples also satisfy the existing stationary/gate+predicate, with final maximum speed 0.000799m/s. This is bounded settling+evidence, not proof for arbitrary motion.++This isolates the remaining blocker to startup fitting near the right-back+armhole, rather than final A-pose equilibrium or collar retention. A further+startup-arrangement/contact investigation is required before qualifying the+complete sequence. Adding a strain cap that merely transfers the error into+penetration or seam gaps would not resolve it.++The actual front/side/back renders show less armhole bunching than the Rest-pose+control. They still show a coarse, somewhat stiff silhouette and a projecting+neckline; this is a foundation specimen, not a finished textile model. Blender+only presents exported solver meshes, with no fitting, subdivision or cloth sim.++## Reusable source and evidence++`fixtures/Canonical/Garment/garmentcode-dress-guided.firmament` composes existing+Concept measurements, an erased collar plane, named boundary guides, release,+and declarative poses. The original bind skeleton and cut are preserved. A+source regression checks this composition. CLI compilation with the actual+body also confirms the same cloth key, guide command and motion program.++The checked-in specimen SHA-256 is+`6c672fced4ad4a1c210466ed9c5bc8402068ccfbdc13ec812579343bd5f55d9a`.+Experimental source files have different comments; each retained artifact+records its own source hash. Outputs live in+`artifacts/local/garment/armhole-round/`: `strain-inspection.json`,+`wearing-inspection.json`, `tpose-60/`, `transition-60/`, and `specimen/`.+Renders are under `artifacts/local/garment/renders/armhole-round-wearing/wearing/`.++```powershell+dotnet run -c Release scripts/inspect-garment-strain.cs -- `+ artifacts/local/garment/fitting-round/anatolia-guided-high.firmament `+ artifacts/local/humanoid-production/antonia.gameplay-body.json `+ artifacts/local/garment/fitting-round/high-60/garment.json `+ artifacts/local/garment/armhole-round/strain-inspection.json++dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll garment drape `+ fixtures/Canonical/Garment/garmentcode-dress-guided.firmament `+ --body artifacts/local/humanoid-production/antonia.gameplay-body.json `+ --ticks 60 --substeps 8 --iterations 24 `+ --out-dir artifacts/local/garment/armhole-round/reproduced --json+```++Use Release for replay probes; Debug is substantially slower. The helper accepts+a retained final snapshot with a FigureFit binding, not an intermediate OBJ.+Guides/body contact remain CPU capabilities. This does not qualify GPU draping,+friction, garment self-contact or continuous collision safety. No new dependency+or third-party solver was adopted. GarmentCode remains MIT-credited to Maria+Korosteleva; see pinned licenses and [import provenance](garmentcode.md).++## Validation++The idle serial Release Aetheris solution build passed with zero errors and+five existing WebAssembly SQLite interop warnings. The complete solution test+lane passed 4,518 tests, including 2,109 Firmament tests and 1,195 kernel tests.+The new source regression composes the known cut, temporary guides and pose+motion without changing cloth identity or the original bind skeleton. The+generated STEP test output was restored after the lane.++The inspection helper ran against both the original Rest snapshot and the+authored final A-pose snapshot; its recomputed metrics match the retained drape.+An equivalent UTF-8 BOM source produced identical compiler identity and replay+results. A mismatched source and attempted input overwrite were rejected, with+no diagnostic report written. Logs and probe reports are retained under+`artifacts/local/garment/armhole-round/`.++The Release Aurelian consumer solution built with zero warnings/errors and its+complete serial test lane passed 1,218 tests, with the installed Naga selected+through `AURELIAN_NAGA`. Copeland logs are+`artifacts/aurelian-beacon3d/garment-armhole-{build,tests}.log`.+This proves consumer regression compatibility, not GPU body-contact support or+native game presentation of this garment. No Copeland source was changed in+this round.diff --git a/docs/public/firmament/garment-draping-research.md b/docs/public/firmament/garment-draping-research.mdnew file mode 100644index 00000000..a424f8ba--- /dev/null+++ b/docs/public/firmament/garment-draping-research.md@@ -0,0 +1,220 @@+# Garment draping research: improving the known-pattern baseline++Research date: 2026-10-10. This report compares current source and retained drapes+with primary research. It proposes experiments; it does not qualify a new solver+or a production garment. No runtime, material, source cut or acceptance threshold+was changed during this research turn.++Implementation follow-up (2026-10-11):+[panel meshing and settling experiment](garment-meshing-settling-experiment.md)+implements the mesh and convergence instrumentation, retains the failed drapes,+and isolates the sewing/contact initialization conflict. The measurements below+describe the original research baseline, not the new mesh.++## Findings from the actual artifacts++The [GarmentCode workflow](garmentcode.md) removed uncertainty about the reference+cut and curve interchange. A read-only audit of the two Anatolia controls gives+the following measurements. Both contain the same rest mesh: 1,234 vertices,+2,244 triangles and 3,474 unique triangle edges.++| Measurement | Original arrangement | Arrangement raised 100mm |+| --- | ---: | ---: |+| Maximum edge tensile strain | 42.351% | 50.823% |+| 95th percentile edge tensile strain | 3.939% | 1.451% |+| Number of edges above 15% | 23 | 11 |+| Maximum triangle principal tensile strain | 46.240% | 51.364% |+| Rest-area fraction above 15% principal tensile strain | 1.407% | 0.145% |++The raised control's worst link is vertices 1210/1214: 1.775mm rest length and+0.902mm extension. The original control's worst link is much longer, 31.646mm,+so short links are not a complete explanation of both failures. The improvement+in the bulk distribution also does not override the failed peak-strain gate.++Rest-mesh quality is poor in more than one location:++- Minimum edge length: 1.409mm; median: 41.434mm; maximum: 56.916mm.+- Minimum triangle angle: 1.790 degrees. 332 triangles (14.8%) have an angle+ below 5 degrees; 554 (24.7%) are below 10 degrees.+- Maximum/minimum area-lumped vertex mass ratio: 110.74.+- Under the current edge classifier: 208 warp links, 336 weft links and+ 2,930 diagonal links (84.3%).++`GarmentPanelMesher` already calls the shared `PlanarMeshQuality.Improve` for+Delaunay edge flips. It then bisects overlong edges. That controls maximum edge+length, but does not provide shape refinement, a minimum angle or a controlled+minimum feature size. Merely adding another edge-flip pass is not the proposed fix.++`ClothCompiler3D` assigns warp/weft stiffness only to almost exactly axis-aligned+material edges; all other directions receive diagonal stiffness. These are+authoring compliances, not a calibrated continuum textile model. Improving+triangulation without checking this dependency could change the apparent fabric.++The current drape uses eight substeps and 24 structural iterations per frame,+one contact pass per iteration, 30 gravity-free sewing frames and a fixed number+of settling frames. The retained controls used 30 settling frames: 0.5 seconds+at 60Hz. There is no equilibrium stopping test in this path. Body contacts use+nearest-surface vertex and triangle-sample projections without friction or CCD.+The default bending model is already boundary-corrected vertex bending; it is+not necessary to reintroduce the earlier Better Bending foundation.++## Research that maps to these gaps++**GarmentCodeData, ECCV 2024.** Their pipeline uses a connected box mesh, matched+samples on paired sewing boundaries, constrained Delaunay panel meshing and+gravity-free initialization. It adds semantic body-part handling, temporary+half-space attachments and a static-equilibrium check. Collar guides are released+before the final drape. This supports treating dressing initialization as an+explicit stage rather than expecting unconstrained gravity to find the intended+placement. [Paper, sections 3.4 and appendix C](https://arxiv.org/html/2405.17609v2).+The pinned MIT wrapper also enables body/fabric friction and schedules attachment+release; its parameters are not portable fabric units for Aetheris.++**Quality triangulation.** Shape and size criteria are distinct. Delaunay+refinement inserts vertices to improve triangle shape; flips alone cannot always+repair a bad point distribution. Acute authored boundaries constrain achievable+angles, so a global minimum-angle promise would be incorrect.+[CGAL Mesh_2 documentation](https://doc.cgal.org/latest/Mesh_2/index.html).++**Physics-inspired Estimation of Optimal Cloth Mesh Resolution, SIGGRAPH 2025.**+Uses material properties and boundary conditions to choose spatially varying+resolution, with smooth transitions between fine and coarse regions. Useful+later for collar/seam/contact sizing maps. We first need a sound material model+and a quality mesher; globally shrinking `meshSize` is not an equivalent method.+[Author's project](https://wanghmin.github.io/publication/zhang-2025-pie/).++**Small Steps in Physics Simulation, SCA 2019.** Shows advantages of spending an+XPBD budget on smaller steps rather than many iterations in a larger step. We+already substep, but have not measured the appropriate split for sewn garments.+This is a cheap controlled convergence experiment, not a claimed cure for+invalid initialization. [Author's paper](https://mmacklin.com/smallsteps.pdf).++**Strain Based Dynamics, SCA 2014.** Controls material strain directions+independently of mesh edge directions and separates stretch from shear. It is a+particularly direct match to the present warp/weft/diagonal classification gap.+Adapting its constraints to XPBD still requires area/energy normalization and+verification; the original PBD stiffness parameters are not physical moduli.+[Author's paper](https://matthias-research.github.io/pages/publications/strainBasedDynamics.pdf).++**Automatic Digital Garment Initialization, SIGGRAPH 2024.** Treats panel+arrangement as its own phased selection/placement problem. Its hybrid classifier+and optimizer need not become a dependency: Firmament can supply the panel roles,+body landmarks and target frames explicitly, reducing ambiguity at authoring time.+That is our proposed adaptation, not a reproduction of their method.+[Author's project](https://wanghmin.github.io/publication/liu-2024-adg/).++**OGC, AVBD and C-IPC.** OGC's local contact and movement bounds are attractive+for Vulkan. Aetheris already has an OGC-inspired foundation, but its exhaustive+candidate admission stops at 128 vertices; the 1,234-vertex dress has offset+self-contact disabled. We need a conservative accelerated candidate search and+seam-aware exclusions before garment-scale use. Initial collision recovery is+distinct from preventing new collisions.+[OGC project](https://ankachan.github.io/Projects/OGC/).+AVBD addresses hard constraints and stiffness ratios, but the existing scalar+probe does not demonstrate a garment advantage over XPBD. Keep it as a later+comparison on identical energies and contacts. [AVBD project](https://graphics.cs.utah.edu/research/projects/avbd/).+C-IPC offers coupled strain limits, thickness and friction with strong contact+handling; use it as a reference for validation and possible offline comparison,+rather than adding its global solve to the current small milestone.+[C-IPC project](https://ipc-sim.github.io/C-IPC/).++**Better Bending, SIGGRAPH 2026.** Retain analytic, refinement and rotated-mesh+tests when changing meshing or materials; a convincing dress render cannot+establish convergence. The existing boundary-corrected bending implementation+does not qualify sharp folds, shaped rest states or every irregular mesh.+[Author's project](https://zhenchen-jay.github.io/publication/betterbending/).++## Recommended experiment order++Each experiment starts from the same retained cut, body and explicitly named+arrangement. Change one variable group at a time. Preserve failed runs and the+existing 15% peak strain, 10mm seam-gap and 5mm sampled-penetration limits.++1. **Quality panel meshing in the existing owner.** Keep analytic profiles and+ named spans authoritative. Use bounded shape refinement/interior point+ distribution plus size control. Improve curve sampling with arc-length and+ geometric-error criteria instead of unconditional minimum sample counts.+ Preserve authored endpoints, seam direction and ease. Compare triangle+ angles, area/mass ratios, vertex count, pattern area and actual drape residuals.+ Do not delete a legitimate short authored feature to improve a statistic.+ Target roughly 20-degree angles where the boundary permits, with explicit+ exceptions and failure diagnostics rather than an unconditional guarantee.+2. **Establish settling convergence.** Compare 30, 120 and 600 settling frames+ on the current owner before selecting a new default. Record residual and+ velocity histories. Then compare substep/iteration splits `(8,24)`, `(16,12)`,+ `(32,6)` and `(64,3)`: all have 192 structural passes per frame. Contact work+ and total wall time still need measurement; equal pass counts are not equal+ cost. A bounded equilibrium check should include seam/strain/contact residuals+ and motion, since high damping can make a wrong solution appear stationary.+3. **Explicit temporary fitting guides.** Use existing figure landmarks and+ collar edge identities to author soft half-space guides. Release them during+ the settling phase, then require an unsupported final equilibrium. Avoid+ permanently fixing collar vertices in world space. Retain guide identity,+ active duration, force/residual and release evidence. Drive the existing+ T-to-A pose transition only after the static control qualifies.+4. **Material-space triangle strain.** Compile rest inverses, area weights,+ grain directions and conflict-free rows once. Project warp, weft and shear+ through the existing XPBD schedule. Verify flat-patch stretch/shear, rotation+ of triangulation relative to grain, rigid-motion invariance and mesh refinement.+ Keep edge springs as a named experimental control; do not call their settings+ measured fabric constants. A strain limiter must report residuals and contact+ conflicts rather than silently clamping positions after contact.+5. **Friction and scalable self-contact.** Add controlled tangential response+ with static/sliding tests and moving-body-relative velocities. Do not use high+ friction to hold an incorrectly placed dress. Extend the existing offset+ narrowphase with conservative candidates and seam-aware neighborhoods; compare+ candidate coverage against exhaustive small cases. GPU bounds, reductions and+ projections belong in real `.v.ts`; retain CPU reference agreement and replay.++Shared seam sampling is a useful companion to meshing: derive paired stations+from both analytic lengths, ease and landmarks before triangulation. Keep+weighted constraints for unequal discretizations. Do not naively weld vertices+and replace the flat material charts with their 3D arrangement. If introducing+joined simulation topology, preserve per-triangle rest charts and explicit seam+behavior, including contact exclusions and bending across the join.++The first implementation milestone should cover steps 1-3 on this one dress.+Step 4 is the next material-model milestone; step 5 is needed before layered+outfits and demanding animation. These priorities are engineering inferences+from the measured failures, not demonstrated improvements from new simulations.++## Evidence, reproduction and licensing++Local audit outputs are ignored under `artifacts/local/garment/research/`:+`audit-garment-mesh.py`, `mesh-audit.json` and `mesh-audit.png`. The audit reads+retained `garment.json`; it does not step, remesh, pin or modify either garment.+It computes unique-edge strain, minimum triangle angles, area-lumped masses and+the singular values of each triangle's 3-by-2 deformation gradient. Principal+strain is an additional diagnostic, not a replacement acceptance metric.+The panel plot separates each material chart; chart locations are not drape+placements. Largest edge-strain differences from the runtime reports are below+0.00001 in strain, consistent with serialized float precision.+Analytic checks also passed: translating/rotating the rest mesh produces zero+edge and principal tensile strain within 1e-9; applying uniform scale 1.1 gives+0.1 for both. These validate the audit calculation, not the garment solver.++```powershell+& artifacts/local/garment/research/venv/Scripts/python.exe `+ artifacts/local/garment/research/audit-garment-mesh.py `+ artifacts/local/garment/garmentcode-dress/antonia-reference-sizing/garment.json `+ artifacts/local/garment/garmentcode-dress/anatolia-raised/garment.json `+ --output artifacts/local/garment/research/mesh-audit.json `+ --plot artifacts/local/garment/research/mesh-audit.png+```++The script uses the existing research venv's NumPy/Matplotlib. No packages or+tools were installed this turn. Artifact hashes are retained in `mesh-audit.json`:+original `24f0a427d2cbf270628ad4fdb1e556e8ecb1c0e6d85a81cfd976664039e4de8a`,+raised `55419de373c21bd0e1d2246e459755504a9350ab0b7486e177729dd0cda3dd87`.+GarmentCode source inspected is pinned to+`d449629979028123a5c4dc9e732a2ec19b7fce31`. No new simulator was executed;+the existing drapes remain failed and no new build/test qualification is claimed.++GarmentCode's MIT license does not cover every associated project. The separate+[NvidiaWarp-GarmentCode license](https://github.com/maria-korosteleva/NvidiaWarp-GarmentCode/blob/main/LICENSE.md)+contains a research/evaluation-only use limitation in section 3.3. Do not copy+that fork into the production runtime under the assumption that it is MIT.+This review adopted no fork code or new dependency. Paper-inspired changes+should remain in the existing Aetheris/Aurelian owners with attribution and+independent validation; any future source reuse needs that source's own license+and notices. Existing MIT pattern fixtures and notices remain unchanged.diff --git a/docs/public/firmament/garment-meshing-settling-experiment.md b/docs/public/firmament/garment-meshing-settling-experiment.mdnew file mode 100644index 00000000..74b554b8--- /dev/null+++ b/docs/public/firmament/garment-meshing-settling-experiment.md@@ -0,0 +1,163 @@+# Panel meshing and settling experiment++Experiment date: 2026-10-11. This implements the first two experiments from+[the draping research plan](garment-draping-research.md), using the unchanged+GarmentCode dress cut and retained raised Anatolia arrangement. Mesh quality and+inspection improve; the dress still fails qualification. Temporary fitting+guides, material-space strain and friction are not implemented in this round.++## Reusable capabilities++`PlanarMeshQuality.FillInterior` inserts a bounded triangular lattice inside an+existing constrained XY triangulation, then uses the existing Lawson flips.+Original boundary points, directed segments and the polygon domain are retained.+The garment mesher uses this shared kernel path before its existing conforming+maximum-edge refinement. It does not replace analytic Profiles or stitch truth.++Boundary sampling uses length plus geometric error: lines are subdivided by+length, arcs by length and sagitta, and cubics by bounded de Casteljau subdivision.+The error target is the smaller of 1mm and 2% of `meshSize`. There is no+unconditional minimum sample count on short curves. Authored endpoints remain;+legitimate short features are not discarded. Named boundary, fill, flip and+vertex budgets stop with garment diagnostics before excessive allocation.++This is deterministic point-distribution and size control, **not a general+minimum-angle guarantee**. Acute authored features can still produce thin faces.+The known-dress test checks its observed quality separately from the general+concave-domain, boundary, area, determinism and budget tests.++`GarmentMeshInspection.Measure` reports unique-edge length statistics, minimum+triangle angle, triangles below 10 degrees, unreferenced vertices and the+maximum/minimum area-lumped vertex ratio. CLI `inspect`, `build` and `drape`+include `meshQuality` in their evidence. These measure the undeformed material+mesh, including pinned vertices, rather than the posed arrangement.++`GarmentDrapeSettings` exposes bounded substeps and structural iterations.+Defaults remain `(8,24)`, with the existing sewing schedule and materials.+`--until-settled` requires all of the following at three consecutive sampled+checkpoints, after at least 30 settling frames:++- Maximum vertex speed at most 0.01m/s.+- Finite state and maximum edge tensile strain at most 15%.+- Maximum seam gap at most 10mm.+- Maximum sampled body penetration at most 5mm.++Samples are retained every five sewing/settling frames and at the final frame.+Evidence records requested budget, completed settling ticks, settings and stop+reason. Low velocity with excessive residuals cannot produce an early success.+`GarmentDrapeLimits` centralizes the unchanged CLI checkpoint thresholds.+Pinned analytic controls test both accepted and stationary-but-stretched cases;+these do not qualify an unsupported garment or every intermediate surface.++## Measured controls++The cut, seam orientation/ease, fabric and 60mm mesh request are unchanged.+Only mesh construction changes in the first comparison. All new drapes share+cloth content key+`42C204F0BE495216B6CB3C2C3087EC8C786135D3EE71FE2D465BCFB4D468BA8B`.+The body artifact SHA-256 is+`0a0ad03e86447fc56448940c7aa56b54ea6683e8a874f833e01fd56a65a2d0e5`.++| Rest mesh measurement | Previous mesh | Interior-fill mesh |+| --- | ---: | ---: |+| Vertices / triangles | 1,234 / 2,244 | 611 / 992 |+| Minimum edge length | 1.409mm | 6.135mm |+| Median edge length | 41.434mm | 48.000mm |+| Minimum triangle angle | 1.790° | 10.328° |+| Triangles below 10° | 554 | 0 |+| Maximum/minimum lumped area | 110.74 | 26.32 |++The independent analytic curve oracles and seam tests still pass. Per-panel+mesh areas remain within 250mm² of the exact cut area; approximation error is+from the sampled curved boundary, not interior fill changing the domain.++All controls below use 30 gravity-free sewing frames. The previous control's+metrics are retained historical evidence; new runs use the real CLI and body+contact solver. Blender only presents their exported OBJ meshes.++| Mesh / solver budget | Settling frames | Peak strain | Seam gap | Sampled penetration | Replay |+| --- | ---: | ---: | ---: | ---: | --- |+| Previous mesh, 8 × 24 | 30 | 50.82% | 1.28mm | <0.001mm | Exact |+| Interior fill, 8 × 24 | 30 | 111.18% | 5.60mm | <0.001mm | Exact |+| Interior fill, 8 × 24 | 120 | 111.24% | 5.62mm | <0.001mm | Exact |+| Interior fill, 32 × 6 | 30 | 41.67% | 3.18mm | <0.001mm | Exact |++The longer `(8,24)` trace already has 111.33% strain at sewing frame 5. After+60 settling frames maximum speed is 0.00259m/s; after 120 it is 0.000294m/s,+while strain stays near 111%. It correctly exhausts its budget rather than+reporting settled. The worst link is a 27.856mm front-neckline link, so the new+failure is not explained by the previous tiny-edge outlier. Longer settling+does not resolve this sewing/contact conflict; a 600-frame repetition is not+justified by this stationary plateau.++Smaller steps reduce peak strain at the same 192 structural passes per frame,+but the garment drops farther down the body. This is **not improved fit**, and+does not justify changing the default budget. Both meshes expose an initialization+problem: the collar/shoulder placement is not retained during sewing. Temporary+semantic fitting guides, released before unsupported qualification, are the next+controlled experiment. Their benefit remains unproven; neither permanent pins+nor a strain-threshold relaxation is substituted for that missing capability.++Observed total CLI times were 99.24s for the new 30-frame `(8,24)` control,+241.02s for 120 frames, and 105.00s for `(32,6)`. These are local observations,+not a controlled performance benchmark; the split run overlapped regression+tests. Equal structural pass counts do not imply equal contact cost.++## Reproduction and retained evidence++Run from the repository root with the actual gameplay body artifact. Recreate+the previously retained raised arrangement without changing the cut:++```powershell+$output = 'artifacts/local/garment/mesh-round'+New-Item -ItemType Directory -Force $output | Out-Null+$pattern = Get-Content fixtures/Canonical/Garment/garmentcode-dress.firmament -Raw+$pattern = $pattern.Replace('545.535950181744mm', '645.535950181744mm')+$pattern = $pattern.Replace('545.089908235091mm', '645.089908235091mm').TrimEnd()+$pattern = $pattern.Substring(0, $pattern.Length - 1) + "`n Drape { figure: Anatolia; pose: Rest; }`n}"+$source = Join-Path $output 'anatolia-raised.firmament'+Set-Content -LiteralPath $source -Value $pattern -Encoding utf8+$body = 'artifacts/local/humanoid-production/antonia.gameplay-body.json'++dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll garment build $source `+ --out-dir "$output/build" --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll garment drape $source `+ --body $body --ticks 30 --out-dir "$output/drape-30" --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll garment drape $source `+ --body $body --ticks 120 --until-settled --out-dir "$output/drape-120" --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll garment drape $source `+ --body $body --ticks 30 --substeps 32 --iterations 6 `+ --out-dir "$output/drape-32x6" --json+```++Retain the JSON report even when a drape fails. The CLI qualification exit code+is 2 (the experiment log's PowerShell host may return 1); runtime exceptions+return 1. The three drapes remain under the ignored output directories above,+with source/body identities, actual solver snapshots, OBJ, USDA and SVG.+Front/side/back renders are under+`artifacts/local/garment/renders/mesh-round-{30,120,32x6}/`, with input hashes.+The read-only rest-mesh comparison is+`artifacts/local/garment/mesh-round/mesh-comparison.png`. Final CLI inspection+reproduces the same content key and is retained as `final-inspection.json`.++The Release Aetheris solution build passed. Its complete idle/serial test lane+passed 4,498 tests, including 1,195 kernel and 2,093 Firmament tests. An earlier+overlapping run was stopped: two CAD display tests hit their five-second display+budget, and the new oversized-panel test exposed late fill-budget admission.+Admission now occurs before seed triangulation; its focused test passes. Both+display cases passed in isolation and in the final complete idle run. The+generated STEP test output was restored after validation.+The Release Aurelian consumer solution also built with no warnings or errors;+all 1,217 consumer tests passed with the installed Naga selected through+`AURELIAN_NAGA`. This is consumer compatibility evidence, not a new native+garment animation or GPU body-contact qualification.++Validation logs are retained as+`artifacts/local/garment/mesh-round-final-build.log` and+`mesh-round-full-tests-idle.log`; the Copeland checkout retains+`artifacts/aurelian-beacon3d/garment-mesh-round-{build,tests}.log`.++The existing one-way CPU body contact limitations still apply: no friction,+CCD or garment self-contact. No NVIDIA research-only solver was copied, no new+third-party package was installed, and this experiment does not qualify GPU+body contacts, garment animation or production fit.diff --git a/docs/public/firmament/garment-temporary-fitting.md b/docs/public/firmament/garment-temporary-fitting.mdnew file mode 100644index 00000000..ee85a89a--- /dev/null+++ b/docs/public/firmament/garment-temporary-fitting.md@@ -0,0 +1,167 @@+# Temporary fitting from Concept geometry++Follow-up: the [armhole investigation](garment-armhole-experiment.md) combines+these guides with T-pose sewing and A-pose wearing. Final strain improves to+9.23%, while startup checkpoint strain remains an explicit failed gate.++A fitting plane belongs to an ordinary Concept Struct. It is construction+geometry, erased from the garment mesh and material scene. A `Fitting` binding+selects named material boundaries and compiles the plane to a bounded, explicit+solver command. It does not add permanent pins, alter the flat pattern, weld+seams or change the cloth content key.++```firmament+Concept Struct fitting {+ FigureFit body {+ figure: Anatolia;+ pose: Rest;+ chestHeight: 1280mm;+ hipHeight: 960mm;+ }+ collarFloor: Plane {+ origin: [fitting.body.centerX, fitting.body.centerY,+ fitting.body.shoulderHeight + 45mm]+ normal: [0, 0, 1]+ }+}++// Inside the Garment, alongside Panels, stitch Interfaces and Drape:+Fitting collar {+ on: fitting.collarFloor;+ edges: [front.edges.collar, back.edges.collar];+ compliance: 0.00000001;+ releaseAfter: 20;+}+```++The body measurement pass and existing Concept plane resolver own construction+geometry. Coordinates use the existing compile-time scalar evaluator, including+dimensional arithmetic; origins are in Firmament millimetres and compile to+metres. Normals must be finite unit vectors. Selected vertices obey+`dot(normal, position) >= offset`, with unilateral XPBD multipliers reset per+substep and accumulated across iterations. Compliance is an authoring parameter,+not a calibrated textile modulus. Body contact runs after guide projection so+a conflicting guide cannot override body clearance; its residual stays visible.++`releaseAfter` counts gravity-driven settling frames **after** the 30 sewing+frames. Zero supports sewing only. Every guide requires an explicit integer+release frame, from 0 through 585. There are at most 32 guides, 64 edge references+per binding and 32,768 total selected vertex entries. A drape budget leaving+fewer than 15 frames after the final release fails before stepping with+`garment-fitting-release-budget`. Early settling cannot succeed while a guide+is active or during those first 15 unsupported frames. The existing 15% strain,+10mm seam gap and 5mm sampled penetration limits stay unchanged.++CLI evidence retains the Concept reference, compiled vertex IDs, numeric plane,+compliance, release frame and per-sample active status/residual. It writes the+last supported snapshot as `guided-garment.obj` and `guided-body.obj`; the usual+`garment.obj` is the unsupported final snapshot. Neither OBJ nor USDA exports+the construction plane. A `build` success establishes compilation only, not a+supported or unsupported body fit.++This uses the existing CPU cloth solver. The Vulkan solver and shared GPU header+builder reject guides with `AUR-CLOTH-005` before GPU work; they must not silently+drop constraints. There is no new GPU fitting, friction, CCD or self-contact+qualification.++## Analytic witness++`fixtures/Canonical/Garment/temporary-fitting.firmament` uses the same mechanism+on a small horizontal sheet. Real draping supports its boundaries at one metre,+releases them after five settling frames and shows downward motion during 15+unsupported frames with exact snapshot replay. Tests also check XPBD compliance+without artificial iteration stiffening, contact conflicts, unchanged material+topology, invalid bindings, unit errors and atomic invalid-command rejection.++## Anatolia experiment++The known raised GarmentCode dress is reused without changing its flat cut,+material, stitches, initial placement or body. Only measured Concept geometry+and the fitting binding are added. The retained source and CLI evidence live+under `artifacts/local/garment/fitting-round/`.++Both trials use the same cloth key+`42C204F0BE495216B6CB3C2C3087EC8C786135D3EE71FE2D465BCFB4D468BA8B`,+611 vertices, 992 triangles and zero permanent pins. The body is+`antonia.gameplay-candidate.v1`, artifact SHA-256+`0a0ad03e86447fc56448940c7aa56b54ea6683e8a874f833e01fd56a65a2d0e5`.+Only the four named front/back collar boundaries are selected. Each run uses+30 sewing frames, 60 settling frames, eight substeps and 24 iterations. Guides+release after settling frame 20, leaving 40 unsupported frames.++The matching no-guide control (`control-60/`) uses the same 30+60 frame budget,+cloth, body and solver settings. It slips below the shoulders, with 111.24% peak+strain and 5.618mm seam gap. All three runs have exact replay, finite metrics+and no guides active in their final snapshot. Comparison values and matching+cloth/body hashes are retained in `comparison.json`:++| Trial | Final strain | Seam gap | Sampled penetration | Appearance |+|---|---:|---:|---:|---|+| No guide | 111.24% | 5.618mm | 0.0000964mm | Slips below shoulders |+| Low, soft guide | 48.50% | 5.658mm | 0.858mm | Still strapless |+| Higher, firmer guide | 87.12% | 3.144mm | 0.00872mm | Remains around shoulders |++None passes the strain gate. The higher guide improves retention without+permanent support; the low guide demonstrates why optimizing peak strain in+isolation would choose the wrong visual result.++The first trial (`anatolia-guided.firmament`, `guided-60/`) sets the plane 30mm+below the measured shoulder height, at 1.3848487m, with compliance 1e-6. Its final+strain is 48.50%, seam gap 5.658mm and sampled penetration 0.858mm. It still looks+strapless while supported and after release. A lower strain alone is not a+better fit.++The second (`anatolia-guided-high.firmament`, `high-60/`) uses shoulder height+plus 45mm, at 1.4598488m, with compliance 1e-8. Source SHA-256 is+`9b912b0e7e30de828d854d44a111c83bda95daa43a4977c756af6767384f014a`.+The collar remains around the shoulders after release; the guide violation is+zero in the last supported sample. Final seam gap is 3.144mm and sampled+penetration is 0.00872mm, with exact replay and all guides removed. However,+peak strain is 84.46% already at the last supported sample and 87.12% after+release: **the dress still fails the unchanged 15% strain limit**.++The worst final constraint is the right-back armhole diagonal 336/337, rest+length 14.275mm. Its material coordinates are retained in `stretchOutliers`.+This isolates the next investigation to sewing/contact/material strain at the+armhole rather than simply keeping the collar from falling. It does not prove+that pattern sizing alone, contact alone or a particular textile parameter is+the root cause. No acceptance threshold or pattern dimension was adjusted to+make the trial pass.++```powershell+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll garment drape `+ artifacts/local/garment/fitting-round/anatolia-guided-high.firmament `+ --body artifacts/local/humanoid-production/antonia.gameplay-body.json `+ --ticks 60 --substeps 8 --iterations 24 `+ --out-dir artifacts/local/garment/fitting-round/high-60 --json++& 'C:/Program Files/Blender Foundation/Blender 5.2/blender.exe' `+ --background --python scripts/render-garment.py -- `+ --garment fitting-round-high-supported `+ --input-dir artifacts/local/garment/fitting-round/high-60 --frame guided --samples 12+```++Render the unsupported result by omitting `--frame guided` and choosing a+different `--garment` output name. All three views use the actual solver OBJ+meshes, with no Blender fitting, subdivision or cloth simulation. Each render+records its input hashes. The first trial preceded the dedicated checkpoint-body+export; its Rest body OBJ was copied to `guided-body.obj` for presentation only.+The second trial exports both checkpoint meshes directly through the CLI.++## Validation++The Release Aetheris solution build passed with the existing nullable/obsolete+and WebAssembly SQLite interop warnings. Its complete idle, serial solution+lane passed 4,517 tests, including 1,195 kernel and 2,108 Firmament tests. The+15 fitting tests also passed after making the scalar-expression test input+independent of checkout line endings. The generated STEP test output was+restored after validation. Logs are retained as+`artifacts/local/garment/fitting-round/{build-final,tests-full,tests-focused-final}.log`.++The Release Aurelian consumer solution built with zero warnings and errors.+Its full serial test lane passed 1,218 tests with the installed Naga selected+through `AURELIAN_NAGA`. Copeland logs are+`artifacts/aurelian-beacon3d/garment-fitting-{build,tests}.log`. This establishes+consumer compatibility and explicit GPU refusal, not GPU fitting support or a+new native garment animation qualification. No dependency was downloaded and+no third-party solver code was adopted.diff --git a/docs/public/firmament/garmentcode.md b/docs/public/firmament/garmentcode.mdnew file mode 100644index 00000000..9f309d37--- /dev/null+++ b/docs/public/firmament/garmentcode.md@@ -0,0 +1,154 @@+# Starting from GarmentCode sewing patterns++Garment authoring can begin with an actual programmed sewing pattern rather+than an approximate garment silhouette. Aetheris imports resolved GarmentCode+JSON into ordinary `schema Garment` source: pure profile `Feature`s, arranged+`Panel`s and explicit `Interface<Stitch>` declarations. The existing profile+resolver, analytic seam inspector, panel mesher and cloth solver retain authority.+There is no Python dependency in the application runtime.++Credit: Maria Korosteleva and Olga Sorkine-Hornung,+[*GarmentCode: Programming Parametric Sewing Patterns*](https://igl.ethz.ch/projects/garmentcode/),+SIGGRAPH Asia 2023. The [upstream code](https://github.com/maria-korosteleva/GarmentCode)+is MIT licensed. See `THIRD_PARTY_NOTICES.md` and the complete preserved license+in `fixtures/Canonical/Garment/GarmentCode/LICENSE.txt`.++## Import, inspect, modify++```powershell+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll garment import-garmentcode `+ fixtures/Canonical/Garment/GarmentCode/dress.json `+ --out-dir artifacts/local/garment/imported-dress --json++dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll garment build `+ artifacts/local/garment/imported-dress/garment.firmament `+ --out-dir artifacts/local/garment/imported-dress/build --json+```++Import emits `garment.firmament`, the retained `specification.json`, an analytic+`patterns.svg` preview and `import-evidence.json`. It does **not** claim to mesh,+simulate or fit a new figure. Evidence records the input hash, original panel+names, edge-index mapping, boundary reversals and measured seam lengths.+Keep the original specification's license with imported derivatives.++The importer admits resolved relative curves, explicit units and panel transforms,+one closed loop per panel, line/circular/quadratic/cubic edges and two-sided+stitches. Quadratic curves are elevated exactly to cubic Beziers. Circular+arcs retain radius, side and major/minor selection. Unsupported curves, unresolved+parameter programs, invalid references and reused seam spans stop with diagnostics.++The source's local XY coordinates remain the flat material pattern. Upstream+Y-up placement maps to Aetheris Z-up; Euler rotation order is retained. Clockwise+loops are normalized to Firmament's counterclockwise outer boundary and seam+correspondence is adjusted by the same reversal parity. `right_wrong` stitches+retain their upstream same-direction pairing. Numeric edge IDs remain in the+names even when semantic armhole/collar labels are present.++Upstream JSON does not carry Aetheris fabric properties or a material grain+direction. The generated source exposes **Aetheris defaults** explicitly for+review and replacement. Upstream unequal seam lengths become an explicit+measured `ease` value; mismatches above Aetheris's 25% budget are rejected.+Analytic cut lengths govern admission. Polygonal chord errors during meshing+do not redefine authored ease.++## Known templates++`fixtures/Canonical/Garment/garmentcode-dress.firmament` is the imported+non-fitted `Shirt` block with sleeves disabled and upstream length multiplier+2.2. It has four half-torso panels and six seams, with real curved armholes+and different front/back collar cuts. `GarmentCode/shirt.json` retains the+original sleeved shirt control with eight panels and sixteen seams.++`garmentcode-dress-template.firmament` adds a native `hemDrop: Length` parameter+to those same pure profile recipes:++```firmament+Feature left_ftorsoCut = left_ftorsoPattern(hemDrop: 100mm);+```++Apply the same adjustment to all four cuts. Zero produces the same compiled+cloth as the reference import; a positive value lowers the hem without changing+armhole, collar or shoulder construction. Existing profile deltas remain the+owner for other named-span edits. This is a resolved starter block, **not** a+port of the entire upstream measurement-driven configurator.++## Reproduce the research controls++The external checkout is pinned to+`d449629979028123a5c4dc9e732a2ec19b7fce31`.+`scripts/research-garmentcode.py --upstream <checkout> --out-dir <ignored-directory>`+calls the real upstream `Shirt` program and its SVG/JSON exporter. The checked-in+designs, measurement YAML, provenance and independently sampled curve oracles+document the inputs. Canonical presentation ordering makes generated JSON repeat+byte-for-byte despite upstream component discovery using a Python set.++Pattern-only Python dependencies used in the isolated research venv:+`numpy<2`, `pyyaml`, `scipy`, `svgwrite`, `svgpathtools`, `psutil`, `matplotlib`,+`CairoSVG`. The venv and checkout remain under `artifacts/local/garment/research/`.++For a matching **external** unrigged reference mesh, the shared+`GarmentDraping.SettleOnSurface` API runs the same sewing/settling/replay path+using `IClothBodySurface3D`, without inventing skeletons or skin weights.+It rejects named figure/pose bindings and measured fits; those must use their+actual humanoid binding. The bounded research harness accepts upstream Y-up,+metre, triangle-only OBJ input:++```powershell+dotnet run --file scripts/qualify-garmentcode-reference.cs -c Release -- `+ artifacts/local/garment/imported-dress/garment.firmament `+ <external-checkout>/assets/bodies/mean_all.obj `+ artifacts/local/garment/reference-body+```++The harness retains body/specification hashes, actual solver metrics, replay,+contact/stretch outliers and OBJ artifacts. A failure returns code 2. These are+discrete one-way CPU contact experiments without friction, CCD or self-contact;+they do not qualify animation or production cloth. Body meshes and the separate+GarmentCodeData dataset are not included or relicensed by this source adoption.++## Current experiment results++Follow-up: [garment draping research](garment-draping-research.md) audits the+retained mesh and strain distribution, compares primary research, and defines+the next controlled experiments. It does not relax these qualification gates.+The [mesh and settling implementation](garment-meshing-settling-experiment.md)+records the new mesh, residual histories and solver split experiment separately+from these historical controls. The dress still fails qualification.++The real upstream shirt and dress patterns match their independently generated+curve oracles (five samples and length per edge, 0.00001mm tolerance), then build+through the normal CLI mesher. A 100mm native hem extension keeps collar and+armhole geometry unchanged; zero reproduces the reference compiled cloth.++The first drape controls use the same 60mm mesh request, cotton defaults,+30 sewing ticks and 30 gravity ticks. Blender renders only the retained solver+OBJ output. These controls **fail** the existing 15% peak strain budget:++| Control | Peak stretch | Maximum seam gap | Maximum surface penetration | Replay |+|---|---:|---:|---:|---|+| Original upstream sizing/arrangement on Anatolia | 42.35% | 3.51mm | <0.001mm | Exact |+| Original cut on matching upstream `mean_all` reference body | 85.62% | 11.30mm | <0.001mm | Exact |+| Matching reference body, arrangement raised 100mm, cut unchanged | 154.72% | 4.20mm | 1.49mm | Exact |+| Anatolia, same raised arrangement and unchanged cut | 50.82% | 1.28mm | <0.001mm | Exact |++The unraised dress slips below the shoulders on both bodies. Raising arrangement+improves seam closure but worsens peak strain, so an arrangement offset alone is+not a qualified fix. The raised control's largest outlier is a 1.48mm rest link+near the front neckline, despite the 60mm mesh request. This isolates mesh quality+and sewing/body-contact convergence as the next investigation; it does not prove+that short links alone caused the failure. Neither changing the reference cut+nor relaxing the acceptance budget is justified by these results.++Retained evidence: `artifacts/local/garment/garmentcode-dress/` contains imports,+sources, `antonia-reference-sizing/`, `reference-body/`, `raised-reference-body/`+and their metric/outlier reports. The upstream simulator was not run. No+production garment fit, animation or new-body automatic measurement mapping is+claimed by these pattern/interchange controls.++The raised arrangement stays on the shoulders in the reference-body render;+its improved silhouette does not override the failed strain check. The same+arrangement is retained as `anatolia-raised.firmament` and `anatolia-raised/`,+with an unchanged flat cut and no hidden supports. Both still need solver/mesh+convergence work. Both Release solution builds passed; the full Aetheris suite+passed 4,479 tests, and the Aurelian consumer suite passed 1,217 with its installed+Naga selected through `AURELIAN_NAGA`.diff --git a/docs/public/firmament/garments.md b/docs/public/firmament/garments.mdindex ddcedd60..739b9dab 100644--- a/docs/public/firmament/garments.md+++ b/docs/public/firmament/garments.md@@ -1,5 +1,11 @@# Garment authoring foundation+Temporary construction guides can now be bound to named panel boundaries with+an explicit release schedule. See [Concept fitting](garment-temporary-fitting.md)+for syntax, unsupported settling checks and the Anatolia experiment.+The [armhole follow-up](garment-armhole-experiment.md) composes these guides with+declarative pose motion and retains contact-isolation diagnostics.+`schema Garment` composes resolved 2D Profiles into material panels, distributedstitches and an initial arrangement. Firmament owns the pattern and seam truth;the shared `Aetheris.Cloth3D` runtime owns constraints and simulation. Blender is@@ -7,10 +13,14 @@ an optional viewer of exported meshes, not a second fitting or simulation path.## Source workflow-Start with the examples in `fixtures/Canonical/Garment`: a two-panel skirt, a-sleeveless tunic, a flared-skirt variation and four-panel shorts. Reuse `Feature (...) -> Profile`, named-Profile boundary spans, `Mirrored Profile` and finite `Pattern ... over Set`-instead of copying per-instance coordinates.+Start with `garmentcode-dress-template.firmament` for a known sewing-pattern+cut and native hem customization; see [GarmentCode import](garmentcode.md).+See [mesh quality and settling controls](garment-meshing-settling-experiment.md)+for rest-mesh diagnostics, solver budgets and failed-drape convergence evidence.+Use `skirt.firmament` as a simpler solver control. The same directory retains a+flared skirt, tunic, shorts and integrated-sleeve dress as separate experiments.+Reuse `Feature (...) -> Profile`, named Profile boundary spans, `Mirrored Profile`+and finite `Pattern ... over Set` instead of copying per-instance coordinates.```firmamentschema Garment@@ -64,6 +74,158 @@ count. Each edge admits one stitch interface. Length mismatch requires anexplicit fractional `ease` tolerance. This is distributed cloth sewing, not arigid Assembly mate. Open boundaries remain open.+## Pattern-first dress workflow++`tshirt-dress.firmament` and `sundress.firmament` are single-garment witnesses,+each with front/back panels. They use a Rect2 seed and immutable Profile Replace+edits rather than manually declaring every point, guide and Segment.+`Feature ... -> Profile` remains a pure, finite construction recipe. It does not+run the cloth solver. Front/back calls share the recipe and vary neckline depth.+`Interpolation: Linear` and optional `SpanNames` belong to the shared Profile+editor; garment-specific sewing consumes the resulting named boundaries.++An edit name also selects its ordered descendants as one garment boundary view.+For example, `front.edges.neckline` can select multiple cubics. Selecting both a+group and one of its children for sewing fails as overlapping seam ownership.+Consumed carrier names are not aliases for arbitrary replacement children.++Use `garment preview` before building a cloth mesh:++```powershell+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll garment preview fixtures/Canonical/Garment/sundress.firmament --body artifacts/local/humanoid-production/antonia.gameplay-body.json --json+```++This writes only `patterns.svg` and `evidence.json` under the garment's `preview`+directory. SVG uses resolved line/arc/cubic paths directly; changing meshSize+does not change the preview. It shows named boundaries, matched seam colors,+orientation, lengths and grain arrows. The evidence contains both seam lengths,+normalized mismatch and allowed ease. Unknown/reused edges and excess length+mismatch fail before meshing. Neither triangulation nor draping is run.++## Figure-bound Concept guides++```firmament+Concept Struct dressLayout {+ FigureFit body {+ figure: Anatolia;+ pose: Rest;+ chestHeight: 1280mm;+ hipHeight: 960mm;+ }+ Points<Point3> arrangement {+ front: Point3(0mm, dressLayout.body.centerY, 650mm);+ back: Point3(0mm, dressLayout.body.centerY, 650mm);+ }+}+```++The host supplies `GarmentFigureBinding`, or CLI supplies `--body` and optional+`--figure` (default `Anatolia`). FigureFit publishes checked Length values before+ordinary Features and Concept point recipes expand. Published members are+`shoulderWidth`, `shoulderHeight`, `neckHeight`, `centerX`, `centerY`,+`chestHeight`, `hipHeight`, `chestCircumference`, `hipCircumference`,+`torsoCircumference`, `frontY` and `backY`. The torso circumference is the greater+of the two measured sections. Front/back Y values bound those sections.++Chest/hip measurements are closed horizontal sections of the supplied OuterSkin+mesh, selected by containing the torso joint's XY probe. Endpoints weld at+0.0001mm; open, branched, ambiguous and vertex-coincident sections reject with+diagnostics. Explicit section heights select the design's measurement protocol;+omitting them uses Chest/Pelvis joint heights. Shoulder and neck guides are+joint proxies, not newly invented surface landmarks or standard anthropometry.+These declarations do not promote the gameplay candidate to canonical status.++Ease, hem height and cut dimensions remain authored design choices. The examples+derive panel width from circumference plus explicit ease and derive initial+wrap radius from that panel width. Rest lengths and mass still come from the flat+cut, not the wrapped arrangement. Length-valued placement fields admit the same+bounded scalar arithmetic used by Features.++Fit evidence retains body ID, topology, skeleton/rest-pose identity, section+measurements, exact rest-surface hash and CLI input-artifact hash. Draping a+compiled fit on a different rest surface rejects and requires recompilation.+The measurement pose is explicit and can differ from the Drape fitting pose.+Its name and resolved pose program accompany the measurements; the rest-surface+hash continues to identify the original body, not a newly rebound skeleton.+`preview`, `inspect`, `build` and `drape` accept the body binding. Generic+`validate`/editor analysis have no body context and report+`garment-fit-body-required` for these fixtures; they do not fabricate measurements.+The fixture qualification registry records this expected missing-input stop.++## Declarative figure poses and motion++`Pose` is a finite anatomical recipe lowered through the existing humanoid+kinematic solver and dual-quaternion skinning. `Rest` preserves the loaded bind+pose, `APose` requests the canonical 35-degree shoulder abduction, and `TPose`+requests 90 degrees. Neither preset changes the original bind skeleton.++```firmament+Pose fitting {+ figure: Anatolia;+ from: TPose;+}+Pose wearing {+ figure: Anatolia;+ from: APose;+ Joint LeftElbow { flexion: 5deg; }+}+PoseTransition lowerArms {+ from: fitting;+ to: wearing;+ duration: 2s;+ easing: SmoothStep;+}+// Inside the Garment declaration:+Drape {+ figure: Anatolia;+ pose: fitting;+ transition: lowerArms;+ clearance: 4mm;+}+```++Named poses can inherit another named pose of the same figure. Forward references+are allowed; cycles, duplicate declarations and inheritance beyond 32 levels+reject. Joint `flexion`, `abduction` and `twist` use absolute degree-valued+anatomical coordinates. Omitted coordinates inherit, including the measured+original bind pose when starting from `Rest`. The existing solver owns supported+joints and limits: shoulder/hip ball joints and elbow/knee hinges. This is not+yet arbitrary finger, spine or facial posing. Invalid requests reject rather+than silently clamping into a different pose.+The current center-based anatomical observer measures flexion and abduction;+it does not independently recover axial twist. Twist requests use the existing+solver, but its reported twist residual is not a separate orientation proof.++Transition endpoints must be named poses of the same figure; `Drape.pose` must+match the transition's `from`. Duration is an explicit seconds literal between+1/60 and 10 seconds. `SmoothStep` is the default; `Linear` is also available.+The drape path sews for 30 ticks, settles for `--ticks` in the fitting pose,+samples the authored transition at each cloth substep, then settles for another+`--ticks` in the wearing pose. Without a transition, a named pose remains static.++The moving body refits the existing triangle BVH with skinned positions and+unchanged topology. The shared CPU solver accepts `IClothKinematicBodySurface3D`+and an explicit `BodyTimeSeconds`; replay supplies that same time together with+the cloth snapshot. There is no implicit animation clock or second skeleton.++Inspect the body pose independently of garment meshing:++```powershell+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll garment pose fixtures/Canonical/Garment/sundress-posed.firmament --body artifacts/local/humanoid-production/antonia.gameplay-body.json --pose fitting --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll garment drape fixtures/Canonical/Garment/sundress-posed.firmament --body artifacts/local/humanoid-production/antonia.gameplay-body.json --ticks 30 --out-dir artifacts/local/garment/sundress-posed/transition --json+```++The pose command also accepts a source containing only Pose declarations. It+writes `body.obj` and surface/semantic evidence without meshing or simulating+cloth. Drape exports paired body/garment OBJ checkpoints for `fitting`, `midway`+and `wearing`, retaining anatomical requests, deformation screens, strain,+contact, seam gaps and a replay check taken during the transition. Exit code 2+retains diagnostic meshes when a screen or fit budget fails.++`scripts/render-garment.py --garment sundress-posed --frame wearing --input-dir+artifacts/local/garment/sundress-posed/transition` presents those actual exports+in Blender. It does not repair or simulate them.+## CasingUse PascalCase for constructs, schema names and enum values; camelCase for@@ -106,6 +268,9 @@ Outputs under `artifacts/local/garment/<source-name>`:stretch, replay, elapsed time and largest contact/stretch outliers. A faileddrape retains geometry and returns exit code 2; it does not report success.+Supplying a body to `build` also writes `body.obj` for inspection of the initial+arrangement. Pattern preview writes neither mesh nor body geometry.+The static drape baseline uses 30 sewing ticks with decreasing stitch compliance,then the requested number of gravity ticks. Default settlement is 60 ticks at theshared solver's fixed timestep. Qualification requires finite state, exact@@ -117,6 +282,15 @@ collision-free certificate. Inspect front, side and back views too:& 'C:\Program Files\Blender Foundation\Blender 5.2\blender.exe' --background --python scripts/render-garment.py -- --bottom skirt```+For a single dress, pass the actual CLI output directory explicitly:++```powershell+& 'C:\Program Files\Blender Foundation\Blender 5.2\blender.exe' --background --python scripts/render-garment.py -- --garment sundress --input-dir artifacts/local/garment/sundress/settled-60+```++The viewer renders front/side/back views and retains the imported OBJ hashes.+It does not modify the mesh, rerun simulation or repair a failed fit.+## Runtime consumption and ownership```csharp@@ -148,9 +322,10 @@ rather than silently ignoring the body.One outer Profile loop per panel; lines, circular arcs and cubic Beziers;15..150mm mesh spacing with bounded conforming refinement. Holes and ellipse-boundaries stop with diagnostics. One fabric per garment. One static Rest-pose-body binding. No seam allowances, darts, zippers, graded sizes, textile material-calibration, animated-body fitting, continuous collision detection, body+boundaries stop with diagnostics. One fabric and one explicit figure binding+per garment, with bounded anatomical poses and an optional authored transition.+No seam allowances, darts, zippers, graded sizes, textile material+calibration, general animation-clip-driven fitting, continuous collision detection, bodyfriction or garment self-contact are qualified in this foundation.Body contact queries an oriented triangle surface and includes vertex, edge and@@ -176,3 +351,104 @@ experiments, not accepted garment baselines. Use the flared skirt as the firstclothing starter and the straight skirt as a simple solver control. Preserve theper-run evidence JSON and inspect the actual front/side/back meshes. Combiningthe tunic and skirt in a viewer does not simulate garment-to-garment contact.++### Single-garment pattern workflow qualification++The FigureFit-backed sundress uses the actual supplied Rest surface, two panels,+four matched stitch interfaces and no pins. Its resolved SVG, compiled mesh and+static drape were exercised through the repository CLI. The final cut has a+210mm neckline width and front/back neckline depths of 80/40mm.++| Run | Gravity ticks after 30 sewing ticks | Maximum stretch | Sampled penetration | Seam gap | Qualification |+| --- | ---: | ---: | ---: | ---: | --- |+| Sundress, initial 180mm neckline | 30 | 23.31% | <0.001mm | 0.259mm | Fail: stretch |+| Sundress, retained 210mm neckline | 30 | 17.31% | <0.001mm | 0.366mm | Fail: stretch |+| Sundress, rejected 230mm neckline | 30 | 23.85% | <0.001mm | 0.194mm | Fail: stretch |+| Sundress, retained cut and standard settling | 60 | 18.00% | <0.001mm | 0.329mm | Fail: stretch |++All four runs were finite and replayed exactly. The longer retained-cut run took+249.95 seconds, including compilation, export and replay checks on this host;+this is an offline authoring measurement, not a runtime performance benchmark.+The 30- and 60-gravity-tick retained runs share source SHA256+`964d17d47ac3b2fca63eb2a0f99873aa1225d0ea0fc1f15a00a4f7e7d99b41b0`.++The largest remaining strain is a front-panel diagonal constraint at material+coordinates (-78.75, 856.25) to (-91.875, 868.9063) mm, near the neckline.+Doubling settlement did not resolve it. The next fitting problem is local+neckline strain and its interaction with body contact and discretization;+seam closure and sampled penetration already meet their budgets. No specific+solver cause is proven by these measurements. Do not relax the 15% strain+budget or mark this dress as an accepted fit.++The integrated-sleeve T-shirt dress also remains an arrangement experiment.+The first flat arrangement produced a 93.1mm seam gap and 432.7% peak stretch;+the cylindrical arrangement closed seams to 5.88mm but produced severe strain+and 38.2mm sampled penetration. Inspected meshes showed sleeves above the+A-pose arms and arms outside the intended side openings. Sleeve arrangement+and arm threading need their own qualification before this cut becomes a starter.++Retained local evidence includes `sundress-fitted-run.json`,+`sundress-final-run.json` (the rejected wider-neck experiment),+`sundress-settled-60-run.json`, the `sundress/preview` analytic SVG, and the+`sundress/settled-60` mesh/artifact exports under `artifacts/local/garment`.+`renders/sundress` contains front/side/back views of the standard-settling output.+These views present the retained solver mesh without mesh repair or another+simulation in Blender.++Both Release solution builds passed. The full Aetheris suite passed 4,447 tests;+the Aurelian consumer suite passed 1,217 tests with its installed Naga executable+selected through `AURELIAN_NAGA`. The initial Aurelian run's missing-tool failure+is retained separately from the successful configured run. These counts qualify+the earlier pattern-authoring milestone; they do not add native GPU body-contact+qualification or certify the newer moving-body experiment below.++### Declarative T-pose to A-pose experiment++`sundress-posed.firmament` retains exactly the baseline cut, material and Rest-pose+measurements. Its cloth content key matches the static baseline:+`0A7A1926E2113F0D3C22C412567C1241A24A54A18A746BAF9F8241D3A3F01E71`.+It adds T-pose fitting, a half-second SmoothStep transition, then A-pose settling.++| Checkpoint | Schedule after 30 sewing ticks | Shoulder abduction | Peak stretch | Seam gap | Qualification |+| --- | --- | ---: | ---: | ---: | --- |+| Static baseline | 60 gravity ticks in Rest/A-pose | 35deg | 18.00% | 0.329mm | Fail: stretch |+| Fitting | 30 gravity ticks in T-pose | 90deg | 18.71% | 0.243mm | Fail: stretch |+| Midway | 15 transition ticks | 62.5deg | 19.31% | 0.347mm | Fail: stretch |+| Wearing | 30 transition and 30 further gravity ticks | 35deg | 18.96% | 0.402mm | Fail: stretch |++All three checkpoints were finite, passed the existing body-deformation screen,+and had sampled penetration below 0.001mm. Cloth replay was exact both during+the transition and after settling. Maximum forward body travel was 4.09mm per+substep. Checkpoint sampling does not certify every intermediate collision or+deformation; this remains discrete, one-way CPU contact without CCD or friction.++The declarative posing and moving-body workflow now works through the real CLI,+original skeleton, skinning and cloth solver. It did **not** improve this cut's+remaining fit failure. The largest final strain is a front-panel diagonal from+(105, 880) to (91.875, 868.906) mm at the neckline. Front/side/back inspection also+shows that the dress remains tent-like rather than behaving like the reference+T-shirt dress. Posing alone is insufficient; local neckline contact,+discretization and drape/material behavior need further qualification before+sleeves or a finished garment can be claimed. No specific solver cause is proven.++Retained evidence is `posed-dress-drape-run.json`, paired checkpoint OBJ exports+in `sundress-posed/transition`, and all nine views in+`renders/sundress-posed/{fitting,midway,wearing}` under `artifacts/local/garment`.+Blender only presents the retained meshes; its render evidence hashes each input.+The run took 352.65 seconds on this host while regression tests also ran, so this+is not an isolated performance benchmark. A separate CLI measurement check also+resolved FigureFit in the T-pose body: chest circumference 892.95mm versus+871.32mm in Rest, while hip circumference stayed 1004.09mm. The comparison cut+continues to use Rest measurements to avoid changing its geometry.++Both Release solution builds passed. The full Aetheris suite passed 4,462 tests;+the Aurelian consumer suite passed 1,217 with its installed Naga selected through+`AURELIAN_NAGA`. These gates verify the shared capability and regressions. The+garment still fails its unchanged 15% strain budget and is retained as a+diagnostic specimen.++## Known sewing-pattern starters++See [GarmentCode import and templates](garmentcode.md) for the MIT-credited+shirt/dress reference, editable Firmament import, native hem customization and+separate pattern-versus-drape qualification.diff --git a/docs/public/firmament/profile-boundary-edits.md b/docs/public/firmament/profile-boundary-edits.mdindex 72f64f3d..1edc0a0a 100644--- a/docs/public/firmament/profile-boundary-edits.md+++ b/docs/public/firmament/profile-boundary-edits.md@@ -114,6 +114,31 @@ Repeated adjacent points, zero derivatives/tangents, cubic cusps and individualcubic self-crossings are rejected. There are at most 1,024 knots per replacementand 1,024 resulting segments in an edited loop.+## Straight cuts and authored span names++`Interpolation: Linear` joins the inherited endpoints and Through-points with+exact line segments. The default remains `Hermite`. Linear construction cannot+also request derivatives, endpoint tangents or `Join: Tangent`.++```firmament+Replace Sleeve {+ On: Blank.Right+ Through: [[280mm,640mm], [400mm,660mm], [400mm,825mm]]+ Interpolation: Linear+ SpanNames: [side, sleeveLower, sleeveOpening, sleeveUpper]+}+```++`SpanNames` is optional for either interpolation. It supplies one unique authored+identifier per resulting line/cubic. Count mismatches and collisions with other+result spans fail. Without it, existing `Sleeve_Span0` names remain unchanged.+This is ordinary Profile construction, also usable by extrusion and Sheet Metal;+it does not encode textile or simulation behavior.++Unchanged edit groups retain their ordered descendant evidence through another+Profile derivation. If any descendant is consumed, its old group is no longer a+complete boundary view and is not silently rebound to the replacement.+## Validation, identities and inspectionValidation checks closure, winding, coincident overlap, inter-span crossings@@ -206,7 +231,8 @@ and reported error bound before they can be materialized. Exact BRep geometry ofan approximant must not be reported as an exact representation of the equation.After equation binding, the ordinary boundary-edit validity checks still apply.See the [larger design proposal](programmable-profile-loops-proposal.md) for-deferred periodic intervals, Curve2 payloads, inner loops and Profile-valued Features.+deferred periodic intervals, Curve2 payloads and inner loops. Profile-valued+Features are supported by the current [garment authoring workflow](garments.md).## Owl authoring updatediff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex 390e7571..5c6f826b 100644--- a/docs/public/firmament/syntax.md+++ b/docs/public/firmament/syntax.md@@ -11,6 +11,7 @@| `Sweep` | Circular-section Concept Path sweeps. || `Revolve` | Bounded Profile revolution about an explicit coplanar Axis. || `SectionChain` | Standalone ruled/G1 section-chain bodies. |+| `Garment` | Profile panels, stitch interfaces, figure measurements and declarative fitting poses. See [garment authoring](garments.md). |For example, begin a formed-wire program with `schema WireForm`. An explicit schema is authoritative: if its frontend rejects the program, Firmament does not retry another frontend. Historical V1 `schema:` mappings remain compatibility metadata; they are distinct from this `schema <Name>` header.@@ -65,7 +66,7 @@ Modify Plate {}```-Parameters are strongly typed and calls may use positional or named arguments. Defaults are optional. A body contains immutable typed `let` derivations and optional private `Point2`, `Rect2`, `RoundedRect2`, `Circle2`, and `Profile` construction declarations followed by one terminal `return`. Local construction names are qualified separately for each invocation. Product Templates specialize before Feature argument binding; Feature results then lower before patterns and Feature AIR. A Feature may return `Hole<Shaft>`, `Hole<Counterbore>`, `Hole<Countersink>`, `Boss`, `Pocket`, or `EdgeFinish`, and may call another Feature with the same return type. Direct and indirect recursion are rejected. Feature names occupy the callable namespace, separate from typed construction declarations such as `Profile`. Named results use `Feature Name = Function(...)`; the name becomes the returned feature identity and appears in invocation inspection. See [functional pickup construction](functional-pickup.md) for a qualified part example.+Parameters are strongly typed and calls may use positional or named arguments. Defaults are optional. A body contains immutable typed `let` derivations and optional private `Point2`, `Line2`, `CubicBezier2`, `Rect2`, `RoundedRect2`, `Circle2`, and `Profile` construction declarations followed by one terminal `return`. Local construction names are qualified separately for each invocation. Product Templates specialize before Feature argument binding; Feature results then lower before patterns and Feature AIR. A Feature may return `Hole<Shaft>`, `Hole<Counterbore>`, `Hole<Countersink>`, `Boss`, `Pocket`, `EdgeFinish`, or `Profile`, and may call another Feature with the same return type. Direct and indirect recursion are rejected. Feature names occupy the callable namespace, separate from typed construction declarations such as `Profile`. Named results use `Feature Name = Function(...)`; the name becomes the returned feature identity and appears in invocation inspection. See [functional pickup construction](functional-pickup.md) for a qualified part example and [garment authoring](garments.md) for reusable Profile recipes.Firmament intentionally does not provide general runtime control flow. `if`/`else`, conditional expressions, `match` inside Feature, mutable variables, exceptions, and `for`/`while` loops are rejected. A Firmament program describes one deterministic engineering construction, not a runtime family of topologically unrelated outputs.diff --git a/fixtures/Canonical/Garment/GarmentCode/LICENSE.txt b/fixtures/Canonical/Garment/GarmentCode/LICENSE.txtnew file mode 100644index 00000000..c3560083--- /dev/null+++ b/fixtures/Canonical/Garment/GarmentCode/LICENSE.txt@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2024 Maria Korosteleva++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/fixtures/Canonical/Garment/GarmentCode/README.md b/fixtures/Canonical/Garment/GarmentCode/README.mdnew file mode 100644index 00000000..49a67e1b--- /dev/null+++ b/fixtures/Canonical/Garment/GarmentCode/README.md@@ -0,0 +1,32 @@+# GarmentCode reference witnesses++These are sewing-pattern outputs from the real MIT-licensed GarmentCode+`Shirt(body, design, fitted=False)` program at commit+`d449629979028123a5c4dc9e732a2ec19b7fce31`, not patterns inferred from a picture.+Credit: Maria Korosteleva and Olga Sorkine-Hornung, *GarmentCode: Programming+Parametric Sewing Patterns*, SIGGRAPH Asia 2023.+Source: https://github.com/maria-korosteleva/GarmentCode.+Keep `LICENSE.txt` with these derivatives; see root `THIRD_PARTY_NOTICES.md`.++- `shirt.json`: upstream t-shirt preset, length multiplier 1.2, sleeves enabled.+- `dress.json`: same recipe, length multiplier 2.2, sleeveless enabled.+- `*-curves.json`: lengths and five samples per edge from upstream's own curve reader.+- `*-design.yaml`, `body-measurements.yaml`: reproducible upstream inputs, centimetres/degrees.+- `provenance.json`: exact revision, modifications and source hashes.++`scripts/research-garmentcode.py` generates these witnesses from an external+checkout. It canonicalizes component/seam presentation order because upstream+component discovery uses a Python set; curve geometry and seam references are+unchanged. The generated JSON repeats byte-for-byte across runs. Python and its+dependencies belong to the ignored research environment, not Aetheris runtime.++Import through `aetheris garment import-garmentcode`. The sibling+`garmentcode-dress.firmament` is its exact editable translation. The sibling+`garmentcode-dress-template.firmament` adds a pure `hemDrop` parameter to each+panel recipe. Zero preserves the original compiled cloth; 100mm extends the+hem without changing armholes, collar curves or panel placement.++These fixtures validate **cut geometry and interchange**, not completed drape+quality or suitability for arbitrary figures. Matching-body and Anatolia+experiments are retained under ignored `artifacts/local/garment/garmentcode-dress/`.+Body meshes are external inputs, not bundled fixtures or invented humanoid rigs.diff --git a/fixtures/Canonical/Garment/GarmentCode/body-measurements.yaml b/fixtures/Canonical/Garment/GarmentCode/body-measurements.yamlnew file mode 100644index 00000000..608c5cd7--- /dev/null+++ b/fixtures/Canonical/Garment/GarmentCode/body-measurements.yaml@@ -0,0 +1,27 @@+body:+ arm_length: 53.9697+ arm_pose_angle: 45.483+ armscye_depth: 12.8679+ back_width: 47.6761+ bum_points: 18.2342+ bust: 99.8407+ bust_line: 25.6947+ bust_points: 16.9463+ crotch_hip_diff: 8.81363+ head_l: 26.3262+ height: 171.99+ hip_back_width: 54.8237+ hip_inclination: 9.86489+ hips: 103.478+ hips_line: 23.4837+ leg_circ: 60.2039+ neck_w: 18.9328+ shoulder_incl: 21.6777+ shoulder_w: 36.4568+ underbust: 86.2455+ vert_bust_line: 21.1388+ waist: 84.3338+ waist_back_width: 39.1358+ waist_line: 36.8913+ waist_over_bust_line: 40.5603+ wrist: 16.5945diff --git a/fixtures/Canonical/Garment/GarmentCode/dress-curves.json b/fixtures/Canonical/Garment/GarmentCode/dress-curves.jsonnew file mode 100644index 00000000..e6e82d7f--- /dev/null+++ b/fixtures/Canonical/Garment/GarmentCode/dress-curves.json@@ -0,0 +1,650 @@+[+ {+ "panel": "left_btorso",+ "edge": 0,+ "lengthMm": 811.6086013836625,+ "samplesMm": [+ [+ 0.0,+ -0.0+ ],+ [+ 0.0,+ 202.90215034591563+ ],+ [+ 0.0,+ 405.80430069183126+ ],+ [+ 0.0,+ 608.7064510377469+ ],+ [+ 0.0,+ 811.6086013836625+ ]+ ]+ },+ {+ "panel": "left_btorso",+ "edge": 1,+ "lengthMm": 126.88825300726279,+ "samplesMm": [+ [+ 2.4698854620335126e-15,+ 811.6086013836625+ ],+ [+ 31.416891316492443,+ 815.4063930294403+ ],+ [+ 61.023865547812726,+ 826.5809784017474+ ],+ [+ 87.1152743546105,+ 844.4885932025409+ ],+ [+ 108.18799999999999,+ 868.097585456578+ ]+ ]+ },+ {+ "panel": "left_btorso",+ "edge": 2,+ "lengthMm": 68.97409814365676,+ "samplesMm": [+ [+ 108.18799999999999,+ 868.097585456578+ ],+ [+ 124.21199999999999,+ 861.7280829312097+ ],+ [+ 140.236,+ 855.3585804058412+ ],+ [+ 156.26000000000002,+ 848.9890778804727+ ],+ [+ 172.284,+ 842.6195753551043+ ]+ ]+ },+ {+ "panel": "left_btorso",+ "edge": 3,+ "lengthMm": 224.04283760438648,+ "samplesMm": [+ [+ 172.284,+ 842.6195753551043+ ],+ [+ 174.09947425781252,+ 769.6690456871356+ ],+ [+ 182.03295656249998,+ 713.5748083238542+ ],+ [+ 204.59584183593748,+ 675.8992544761977+ ],+ [+ 250.29952499999993,+ 658.2047753551037+ ]+ ]+ },+ {+ "panel": "left_btorso",+ "edge": 4,+ "lengthMm": 658.2047753551044,+ "samplesMm": [+ [+ 250.29952500000002,+ 658.2047753551044+ ],+ [+ 250.29952500000002,+ 493.65358151632825+ ],+ [+ 250.29952500000002,+ 329.1023876775522+ ],+ [+ 250.29952500000002,+ 164.5511938387761+ ],+ [+ 250.29952500000002,+ -0.0+ ]+ ]+ },+ {+ "panel": "left_btorso",+ "edge": 5,+ "lengthMm": 250.29952500000002,+ "samplesMm": [+ [+ 250.29952500000002,+ -0.0+ ],+ [+ 187.72464374999998,+ -0.0+ ],+ [+ 125.14976250000001,+ -0.0+ ],+ [+ 62.57488125000002,+ -0.0+ ],+ [+ 0.0,+ -0.0+ ]+ ]+ },+ {+ "panel": "left_ftorso",+ "edge": 0,+ "lengthMm": 273.86415000000005,+ "samplesMm": [+ [+ 0.0,+ -0.0+ ],+ [+ 68.46603750000001,+ -0.0+ ],+ [+ 136.93207500000003,+ -0.0+ ],+ [+ 205.39811250000002,+ -0.0+ ],+ [+ 273.86415000000005,+ -0.0+ ]+ ]+ },+ {+ "panel": "left_ftorso",+ "edge": 1,+ "lengthMm": 658.6508277909344,+ "samplesMm": [+ [+ 273.86415000000005,+ -0.0+ ],+ [+ 273.86415000000005,+ 164.6627069477336+ ],+ [+ 273.86415000000005,+ 329.3254138954672+ ],+ [+ 273.86415000000005,+ 493.9881208432008+ ],+ [+ 273.86415000000005,+ 658.6508277909344+ ]+ ]+ },+ {+ "panel": "left_ftorso",+ "edge": 2,+ "lengthMm": 235.5702887040374,+ "samplesMm": [+ [+ 273.86415000000005,+ 658.6508277909344+ ],+ [+ 224.14711664062503,+ 672.203087673747+ ],+ [+ 196.466289375,+ 709.1606568534343+ ],+ [+ 182.08935492187499,+ 766.9670115018719+ ],+ [+ 172.28399999999996,+ 843.0656277909344+ ]+ ]+ },+ {+ "panel": "left_ftorso",+ "edge": 3,+ "lengthMm": 68.97409316414002,+ "samplesMm": [+ [+ 172.28399999999996,+ 843.0656277909344+ ],+ [+ 156.26,+ 849.4351269461638+ ],+ [+ 140.236,+ 855.8046261013931+ ],+ [+ 124.21199999999997,+ 862.1741252566222+ ],+ [+ 108.18799999999997,+ 868.5436244118516+ ]+ ]+ },+ {+ "panel": "left_ftorso",+ "edge": 4,+ "lengthMm": 223.39396908026657,+ "samplesMm": [+ [+ 108.18799999999996,+ 868.5436244118517+ ],+ [+ 114.78232005945526,+ 813.6308281856213+ ],+ [+ 95.12148260897132,+ 761.9360342777657+ ],+ [+ 53.70268184859901,+ 725.283842119552+ ],+ [+ 3.56620041258319e-14,+ 712.0580261258904+ ]+ ]+ },+ {+ "panel": "left_ftorso",+ "edge": 5,+ "lengthMm": 712.0580261258903,+ "samplesMm": [+ [+ 0.0,+ 712.0580261258903+ ],+ [+ 0.0,+ 534.0435195944177+ ],+ [+ 0.0,+ 356.0290130629451+ ],+ [+ 0.0,+ 178.01450653147256+ ],+ [+ 0.0,+ -0.0+ ]+ ]+ },+ {+ "panel": "right_btorso",+ "edge": 0,+ "lengthMm": 250.29952500000002,+ "samplesMm": [+ [+ 0.0,+ -0.0+ ],+ [+ -62.574881250000004,+ -0.0+ ],+ [+ -125.14976250000001,+ -0.0+ ],+ [+ -187.72464374999998,+ -0.0+ ],+ [+ -250.29952500000002,+ -0.0+ ]+ ]+ },+ {+ "panel": "right_btorso",+ "edge": 1,+ "lengthMm": 658.2047753551044,+ "samplesMm": [+ [+ -250.29952500000002,+ -0.0+ ],+ [+ -250.29952500000002,+ 164.5511938387761+ ],+ [+ -250.29952500000002,+ 329.1023876775522+ ],+ [+ -250.29952500000002,+ 493.65358151632825+ ],+ [+ -250.29952500000002,+ 658.2047753551044+ ]+ ]+ },+ {+ "panel": "right_btorso",+ "edge": 2,+ "lengthMm": 224.04283760438653,+ "samplesMm": [+ [+ -250.29952500000002,+ 658.2047753551044+ ],+ [+ -204.59584183593748,+ 675.899254476198+ ],+ [+ -182.03295656249998,+ 713.5748083238543+ ],+ [+ -174.09947425781252,+ 769.6690456871357+ ],+ [+ -172.284,+ 842.6195753551044+ ]+ ]+ },+ {+ "panel": "right_btorso",+ "edge": 3,+ "lengthMm": 68.97409814365676,+ "samplesMm": [+ [+ -172.284,+ 842.6195753551043+ ],+ [+ -156.26000000000002,+ 848.9890778804727+ ],+ [+ -140.236,+ 855.3585804058412+ ],+ [+ -124.21199999999999,+ 861.7280829312097+ ],+ [+ -108.18799999999999,+ 868.097585456578+ ]+ ]+ },+ {+ "panel": "right_btorso",+ "edge": 4,+ "lengthMm": 126.88825300726279,+ "samplesMm": [+ [+ -108.18799999999999,+ 868.097585456578+ ],+ [+ -87.11527435461053,+ 844.4885932025409+ ],+ [+ -61.02386554781273,+ 826.5809784017474+ ],+ [+ -31.416891316492514,+ 815.4063930294403+ ],+ [+ -1.5599061012301367e-14,+ 811.6086013836625+ ]+ ]+ },+ {+ "panel": "right_btorso",+ "edge": 5,+ "lengthMm": 811.6086013836625,+ "samplesMm": [+ [+ 0.0,+ 811.6086013836625+ ],+ [+ 0.0,+ 608.7064510377469+ ],+ [+ 0.0,+ 405.80430069183126+ ],+ [+ 0.0,+ 202.90215034591563+ ],+ [+ 0.0,+ -0.0+ ]+ ]+ },+ {+ "panel": "right_ftorso",+ "edge": 0,+ "lengthMm": 712.0580261258903,+ "samplesMm": [+ [+ 0.0,+ -0.0+ ],+ [+ 0.0,+ 178.01450653147256+ ],+ [+ 0.0,+ 356.0290130629451+ ],+ [+ 0.0,+ 534.0435195944177+ ],+ [+ 0.0,+ 712.0580261258903+ ]+ ]+ },+ {+ "panel": "right_ftorso",+ "edge": 1,+ "lengthMm": 223.39396908026657,+ "samplesMm": [+ [+ 4.177486186101655e-15,+ 712.0580261258904+ ],+ [+ -53.70268184859893,+ 725.283842119552+ ],+ [+ -95.1214826089712,+ 761.9360342777655+ ],+ [+ -114.78232005945526,+ 813.6308281856213+ ],+ [+ -108.18799999999999,+ 868.5436244118517+ ]+ ]+ },+ {+ "panel": "right_ftorso",+ "edge": 2,+ "lengthMm": 68.97409316414002,+ "samplesMm": [+ [+ -108.18799999999997,+ 868.5436244118516+ ],+ [+ -124.21199999999997,+ 862.1741252566222+ ],+ [+ -140.236,+ 855.8046261013931+ ],+ [+ -156.26,+ 849.4351269461638+ ],+ [+ -172.28399999999996,+ 843.0656277909344+ ]+ ]+ },+ {+ "panel": "right_ftorso",+ "edge": 3,+ "lengthMm": 235.5702887040374,+ "samplesMm": [+ [+ -172.28399999999996,+ 843.0656277909344+ ],+ [+ -182.08935492187499,+ 766.9670115018719+ ],+ [+ -196.466289375,+ 709.1606568534343+ ],+ [+ -224.14711664062503,+ 672.203087673747+ ],+ [+ -273.86415,+ 658.6508277909344+ ]+ ]+ },+ {+ "panel": "right_ftorso",+ "edge": 4,+ "lengthMm": 658.6508277909344,+ "samplesMm": [+ [+ -273.86415000000005,+ 658.6508277909344+ ],+ [+ -273.86415000000005,+ 493.9881208432008+ ],+ [+ -273.86415000000005,+ 329.3254138954672+ ],+ [+ -273.86415000000005,+ 164.66270694773357+ ],+ [+ -273.86415000000005,+ -0.0+ ]+ ]+ },+ {+ "panel": "right_ftorso",+ "edge": 5,+ "lengthMm": 273.86415000000005,+ "samplesMm": [+ [+ -273.86415000000005,+ -0.0+ ],+ [+ -205.39811250000002,+ -0.0+ ],+ [+ -136.93207500000003,+ -0.0+ ],+ [+ -68.4660375,+ -0.0+ ],+ [+ 0.0,+ -0.0+ ]+ ]+ }+]diff --git a/fixtures/Canonical/Garment/GarmentCode/dress-design.yaml b/fixtures/Canonical/Garment/GarmentCode/dress-design.yamlnew file mode 100644index 00000000..8fa27042--- /dev/null+++ b/fixtures/Canonical/Garment/GarmentCode/dress-design.yaml@@ -0,0 +1,885 @@+design:+ meta:+ upper:+ v: Shirt+ range:+ - FittedShirt+ - Shirt+ - null+ type: select_null+ default_prob: 0.3+ wb:+ v: null+ range:+ - StraightWB+ - FittedWB+ - null+ type: select_null+ default_prob: 0.5+ bottom:+ v: null+ range:+ - SkirtCircle+ - AsymmSkirtCircle+ - GodetSkirt+ - Pants+ - Skirt2+ - SkirtManyPanels+ - PencilSkirt+ - SkirtLevels+ - null+ type: select_null+ default_prob: 0.3+ waistband:+ waist:+ v: 1.0+ range:+ - 1.0+ - 2+ type: float+ default_prob: 0.7+ width:+ v: 0.2+ range:+ - 0.1+ - 1.0+ type: float+ default_prob: 0.5+ shirt:+ strapless:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ length:+ v: 2.2+ range:+ - 0.5+ - 3.5+ type: float+ default_prob: 0.7+ width:+ v: 1.05+ range:+ - 1.0+ - 1.3+ type: float+ default_prob: 0.4+ flare:+ v: 1.0+ range:+ - 0.7+ - 1.6+ type: float+ default_prob: 0.4+ collar:+ f_collar:+ v: CircleNeckHalf+ range:+ - CircleNeckHalf+ - CurvyNeckHalf+ - VNeckHalf+ - SquareNeckHalf+ - TrapezoidNeckHalf+ - CircleArcNeckHalf+ - Bezier2NeckHalf+ type: select+ default_prob: 0.4+ b_collar:+ v: CircleNeckHalf+ range:+ - CircleNeckHalf+ - CurvyNeckHalf+ - VNeckHalf+ - SquareNeckHalf+ - TrapezoidNeckHalf+ - CircleArcNeckHalf+ - Bezier2NeckHalf+ type: select+ default_prob: 0.8+ width:+ v: 0.2+ range:+ - -0.5+ - 1+ type: float+ default_prob: 0.4+ fc_depth:+ v: 0.4+ range:+ - 0.3+ - 2+ type: float+ default_prob: 0.3+ bc_depth:+ v: 0+ range:+ - 0+ - 2+ type: float+ default_prob: 0.4+ fc_angle:+ v: 95+ range:+ - 70+ - 110+ type: int+ bc_angle:+ v: 95+ range:+ - 70+ - 110+ type: int+ f_bezier_x:+ v: 0.3+ range:+ - 0.05+ - 0.95+ type: float+ default_prob: 0.4+ f_bezier_y:+ v: 0.55+ range:+ - 0.05+ - 0.95+ type: float+ default_prob: 0.4+ b_bezier_x:+ v: 0.15+ range:+ - 0.05+ - 0.95+ type: float+ default_prob: 0.4+ b_bezier_y:+ v: 0.1+ range:+ - 0.05+ - 0.95+ type: float+ default_prob: 0.4+ f_flip_curve:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ b_flip_curve:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ component:+ style:+ v: null+ range:+ - Turtle+ - SimpleLapel+ - Hood2Panels+ - null+ type: select_null+ default_prob: 0.6+ depth:+ v: 7+ range:+ - 2+ - 8+ type: int+ lapel_standing:+ v: false+ range:+ - true+ - false+ type: bool+ hood_depth:+ v: 1+ range:+ - 1+ - 2+ type: float+ default_prob: 0.6+ hood_length:+ v: 1+ range:+ - 1+ - 1.5+ type: float+ default_prob: 0.6+ sleeve:+ sleeveless:+ v: true+ range:+ - true+ - false+ type: bool+ default_prob: 0.7+ armhole_shape:+ v: ArmholeCurve+ range:+ - ArmholeSquare+ - ArmholeAngle+ - ArmholeCurve+ type: select+ default_prob: 0.7+ length:+ v: 0.3+ range:+ - 0.1+ - 1.15+ type: float+ connecting_width:+ v: 0.2+ range:+ - 0+ - 2+ type: float+ default_prob: 0.6+ end_width:+ v: 1.0+ range:+ - 0.2+ - 2+ type: float+ default_prob: 0.4+ sleeve_angle:+ v: 10+ range:+ - 10+ - 50+ type: int+ opening_dir_mix:+ v: 0.1+ range:+ - -0.9+ - 0.8+ type: float+ default_prob: 1.0+ standing_shoulder:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ standing_shoulder_len:+ v: 5.0+ range:+ - 4+ - 10+ type: float+ connect_ruffle:+ v: 1+ range:+ - 1+ - 2+ type: float+ default_prob: 0.4+ smoothing_coeff:+ v: 0.25+ range:+ - 0.1+ - 0.4+ type: float+ default_prob: 0.8+ cuff:+ type:+ v: null+ range:+ - CuffBand+ - CuffSkirt+ - CuffBandSkirt+ - null+ type: select_null+ top_ruffle:+ v: 1+ range:+ - 1+ - 3+ type: float+ cuff_len:+ v: 0.1+ range:+ - 0.05+ - 0.9+ type: float+ default_prob: 0.7+ skirt_fraction:+ v: 0.5+ range:+ - 0.1+ - 0.9+ type: float+ default_prob: 0.5+ skirt_flare:+ v: 1.2+ range:+ - 1+ - 2+ type: float+ skirt_ruffle:+ v: 1.0+ range:+ - 1+ - 1.5+ type: float+ default_prob: 0.3+ left:+ enable_asym:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ shirt:+ strapless:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ width:+ v: 1.0+ range:+ - 1.0+ - 1.3+ type: float+ default_prob: 0.4+ flare:+ v: 1.0+ range:+ - 0.7+ - 1.6+ type: float+ default_prob: 0.4+ collar:+ f_collar:+ v: CircleNeckHalf+ range:+ - CircleNeckHalf+ - CurvyNeckHalf+ - VNeckHalf+ - SquareNeckHalf+ - TrapezoidNeckHalf+ - CircleArcNeckHalf+ - Bezier2NeckHalf+ type: select+ default_prob: 0.4+ b_collar:+ v: CircleNeckHalf+ range:+ - CircleNeckHalf+ - CurvyNeckHalf+ - VNeckHalf+ - SquareNeckHalf+ - TrapezoidNeckHalf+ - CircleArcNeckHalf+ - Bezier2NeckHalf+ type: select+ default_prob: 0.8+ width:+ v: 0.5+ range:+ - 0+ - 1+ type: float+ default_prob: 0.4+ fc_angle:+ v: 95+ range:+ - 70+ - 110+ type: int+ bc_angle:+ v: 95+ range:+ - 70+ - 110+ type: int+ f_bezier_x:+ v: 0.5+ range:+ - 0.05+ - 0.95+ type: float+ default_prob: 0.4+ f_bezier_y:+ v: 0.3+ range:+ - 0.05+ - 0.95+ type: float+ b_bezier_x:+ v: 0.5+ range:+ - 0.05+ - 0.95+ type: float+ default_prob: 0.4+ b_bezier_y:+ v: 0.3+ range:+ - 0.05+ - 0.95+ type: float+ f_flip_curve:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ b_flip_curve:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ sleeve:+ sleeveless:+ v: true+ range:+ - true+ - false+ type: bool+ default_prob: 0.7+ armhole_shape:+ v: ArmholeCurve+ range:+ - ArmholeSquare+ - ArmholeAngle+ - ArmholeCurve+ type: select+ default_prob: 0.7+ length:+ v: 0.3+ range:+ - 0.1+ - 1.15+ type: float+ connecting_width:+ v: 0.2+ range:+ - 0+ - 2+ type: float+ default_prob: 0.6+ end_width:+ v: 1.0+ range:+ - 0.2+ - 2+ type: float+ default_prob: 0.4+ sleeve_angle:+ v: 10+ range:+ - 10+ - 50+ type: int+ opening_dir_mix:+ v: 0.2+ range:+ - -0.9+ - 0.8+ type: float+ default_prob: 1.0+ standing_shoulder:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ standing_shoulder_len:+ v: 5.0+ range:+ - 4+ - 10+ type: float+ connect_ruffle:+ v: 1+ range:+ - 1+ - 2+ type: float+ default_prob: 0.4+ smoothing_coeff:+ v: 0.25+ range:+ - 0.1+ - 0.4+ type: float+ default_prob: 0.8+ cuff:+ type:+ v: null+ range:+ - CuffBand+ - CuffSkirt+ - CuffBandSkirt+ - null+ type: select_null+ top_ruffle:+ v: 1+ range:+ - 1+ - 2+ type: float+ cuff_len:+ v: 0.1+ range:+ - 0.05+ - 0.9+ type: float+ default_prob: 0.7+ skirt_fraction:+ v: 0.5+ range:+ - 0.1+ - 0.9+ type: float+ default_prob: 0.5+ skirt_flare:+ v: 1.2+ range:+ - 1+ - 2+ type: float+ skirt_ruffle:+ v: 1.0+ range:+ - 1+ - 1.5+ type: float+ default_prob: 0.3+ skirt:+ length:+ v: 0.2+ range:+ - -0.2+ - 0.95+ type: float+ rise:+ v: 1+ range:+ - 0.5+ - 1+ type: float+ default_prob: 0.3+ ruffle:+ v: 1.3+ range:+ - 1+ - 2+ type: float+ default_prob: 0.3+ bottom_cut:+ v: 0+ range:+ - 0+ - 0.9+ type: float+ default_prob: 0.3+ flare:+ v: 0+ range:+ - 0+ - 20+ type: int+ default_prob: 0.5+ flare-skirt:+ length:+ v: 0.2+ range:+ - -0.2+ - 0.95+ type: float+ rise:+ v: 1+ range:+ - 0.5+ - 1+ type: float+ default_prob: 0.3+ suns:+ v: 0.75+ range:+ - 0.1+ - 1.95+ type: float+ skirt-many-panels:+ n_panels:+ v: 4+ range:+ - 4+ - 15+ type: int+ panel_curve:+ v: 0+ range:+ - -0.35+ - -0.25+ - -0.15+ - 0+ - 0.15+ - 0.25+ - 0.35+ - 0.45+ type: select+ asymm:+ front_length:+ v: 0.5+ range:+ - 0.1+ - 0.9+ type: float+ default_prob: 0.5+ cut:+ add:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.6+ depth:+ v: 0.5+ range:+ - 0.05+ - 0.95+ type: float+ default_prob: 0.6+ width:+ v: 0.1+ range:+ - 0.05+ - 0.4+ type: float+ place:+ v: -0.5+ range:+ - -1+ - 1+ type: float+ godet-skirt:+ base:+ v: PencilSkirt+ range:+ - Skirt2+ - PencilSkirt+ type: select+ default_prob: 0.7+ insert_w:+ v: 15+ range:+ - 10+ - 50+ type: int+ insert_depth:+ v: 20+ range:+ - 10+ - 50+ type: int+ num_inserts:+ v: 4+ range:+ - 4+ - 6+ - 8+ - 10+ - 12+ type: select+ cuts_distance:+ v: 5+ range:+ - 0+ - 10+ type: int+ pencil-skirt:+ length:+ v: 0.4+ range:+ - 0.2+ - 0.95+ type: float+ rise:+ v: 1+ range:+ - 0.5+ - 1+ type: float+ default_prob: 0.3+ flare:+ v: 1.0+ range:+ - 0.6+ - 1.5+ type: float+ default_prob: 0.3+ low_angle:+ v: 0+ range:+ - -30+ - 30+ type: int+ default_prob: 0.7+ front_slit:+ v: 0+ range:+ - 0+ - 0.9+ type: float+ default_prob: 0.4+ back_slit:+ v: 0+ range:+ - 0+ - 0.9+ type: float+ default_prob: 0.4+ left_slit:+ v: 0+ range:+ - 0+ - 0.9+ type: float+ default_prob: 0.6+ right_slit:+ v: 0+ range:+ - 0+ - 0.9+ type: float+ default_prob: 0.6+ style_side_cut:+ v: null+ range:+ - Sun+ - SIGGRAPH_logo+ type: select_null+ default_prob: 1.0+ levels-skirt:+ base:+ v: PencilSkirt+ range:+ - Skirt2+ - PencilSkirt+ - SkirtCircle+ - AsymmSkirtCircle+ type: select+ level:+ v: Skirt2+ range:+ - Skirt2+ - SkirtCircle+ - AsymmSkirtCircle+ type: select+ num_levels:+ v: 1+ range:+ - 1+ - 5+ type: int+ level_ruffle:+ v: 1.0+ range:+ - 1+ - 1.7+ type: float+ length:+ v: 0.5+ range:+ - 0.2+ - 0.95+ type: float+ rise:+ v: 1+ range:+ - 0.5+ - 1+ type: float+ default_prob: 0.3+ base_length_frac:+ v: 0.5+ range:+ - 0.2+ - 0.8+ type: float+ pants:+ length:+ v: 0.3+ range:+ - 0.2+ - 0.9+ type: float+ width:+ v: 1.0+ range:+ - 1.0+ - 1.5+ type: float+ default_prob: 0.5+ flare:+ v: 1.0+ range:+ - 0.5+ - 1.2+ type: float+ default_prob: 0.3+ rise:+ v: 1.0+ range:+ - 0.5+ - 1+ type: float+ default_prob: 0.3+ cuff:+ type:+ v: null+ range:+ - CuffBand+ - CuffSkirt+ - CuffBandSkirt+ - null+ type: select_null+ default_prob: 0.5+ top_ruffle:+ v: 1.0+ range:+ - 1+ - 2+ type: float+ cuff_len:+ v: 0.1+ range:+ - 0.05+ - 0.9+ type: float+ default_prob: 0.3+ skirt_fraction:+ v: 0.5+ range:+ - 0.1+ - 0.9+ type: float+ skirt_flare:+ v: 1.2+ range:+ - 1+ - 2+ type: float+ skirt_ruffle:+ v: 1.0+ range:+ - 1+ - 1.5+ type: floatdiff --git a/fixtures/Canonical/Garment/GarmentCode/dress.json b/fixtures/Canonical/Garment/GarmentCode/dress.jsonnew file mode 100644index 00000000..5d6c0e98--- /dev/null+++ b/fixtures/Canonical/Garment/GarmentCode/dress.json@@ -0,0 +1,478 @@+{+ "pattern": {+ "panels": {+ "left_btorso": {+ "translation": [+ 0.0,+ 54.55359501817439,+ -25.0+ ],+ "rotation": [+ -0.0,+ 0.0,+ 0.0+ ],+ "vertices": [+ [+ 0.0,+ 0.0+ ],+ [+ 0.0,+ 81.16086013836625+ ],+ [+ 10.8188,+ 86.8097585456578+ ],+ [+ 17.2284,+ 84.26195753551043+ ],+ [+ 25.0299525,+ 65.82047753551043+ ],+ [+ 25.0299525,+ 0.0+ ]+ ],+ "edges": [+ {+ "endpoints": [+ 0,+ 1+ ]+ },+ {+ "endpoints": [+ 1,+ 2+ ],+ "label": "left_collar",+ "curvature": {+ "type": "circle",+ "params": [+ 13.184560591816423,+ 0,+ 1+ ]+ }+ },+ {+ "endpoints": [+ 2,+ 3+ ]+ },+ {+ "endpoints": [+ 3,+ 4+ ],+ "label": "left_armhole",+ "curvature": {+ "type": "cubic",+ "params": [+ [+ 0.5,+ -0.2+ ],+ [+ 0.8,+ -0.35+ ]+ ]+ }+ },+ {+ "endpoints": [+ 4,+ 5+ ]+ },+ {+ "endpoints": [+ 5,+ 0+ ]+ }+ ]+ },+ "left_ftorso": {+ "translation": [+ 0.0,+ 54.5089908235091,+ 30.0+ ],+ "rotation": [+ -0.0,+ 0.0,+ 0.0+ ],+ "vertices": [+ [+ 0.0,+ 0.0+ ],+ [+ 27.386415000000003,+ 0.0+ ],+ [+ 27.386415000000003,+ 65.86508277909344+ ],+ [+ 17.228399999999997,+ 84.30656277909344+ ],+ [+ 10.818799999999998,+ 86.85436244118516+ ],+ [+ 0.0,+ 71.20580261258903+ ]+ ],+ "edges": [+ {+ "endpoints": [+ 0,+ 1+ ]+ },+ {+ "endpoints": [+ 1,+ 2+ ]+ },+ {+ "endpoints": [+ 2,+ 3+ ],+ "label": "left_armhole",+ "curvature": {+ "type": "cubic",+ "params": [+ [+ 0.19999999999999996,+ 0.35+ ],+ [+ 0.5,+ 0.2+ ]+ ]+ }+ },+ {+ "endpoints": [+ 3,+ 4+ ]+ },+ {+ "endpoints": [+ 4,+ 5+ ],+ "label": "left_collar",+ "curvature": {+ "type": "circle",+ "params": [+ 11.564126734773824,+ 0,+ 0+ ]+ }+ },+ {+ "endpoints": [+ 5,+ 0+ ]+ }+ ]+ },+ "right_btorso": {+ "translation": [+ 0.0,+ 54.55359501817439,+ -25.0+ ],+ "rotation": [+ -0.0,+ 0.0,+ 0.0+ ],+ "vertices": [+ [+ 0,+ 0+ ],+ [+ -25.0299525,+ 0+ ],+ [+ -25.0299525,+ 65.82047753551043+ ],+ [+ -17.2284,+ 84.26195753551043+ ],+ [+ -10.8188,+ 86.8097585456578+ ],+ [+ 0.0,+ 81.16086013836625+ ]+ ],+ "edges": [+ {+ "endpoints": [+ 0,+ 1+ ]+ },+ {+ "endpoints": [+ 1,+ 2+ ]+ },+ {+ "endpoints": [+ 2,+ 3+ ],+ "label": "right_armhole",+ "curvature": {+ "type": "cubic",+ "params": [+ [+ 0.19999999999999996,+ -0.35+ ],+ [+ 0.5,+ -0.2+ ]+ ]+ }+ },+ {+ "endpoints": [+ 3,+ 4+ ]+ },+ {+ "endpoints": [+ 4,+ 5+ ],+ "label": "right_collar",+ "curvature": {+ "type": "circle",+ "params": [+ 13.184560591816423,+ 0,+ 1+ ]+ }+ },+ {+ "endpoints": [+ 5,+ 0+ ]+ }+ ]+ },+ "right_ftorso": {+ "translation": [+ 0.0,+ 54.5089908235091,+ 30.0+ ],+ "rotation": [+ -0.0,+ 0.0,+ 0.0+ ],+ "vertices": [+ [+ 0,+ 0+ ],+ [+ 0.0,+ 71.20580261258903+ ],+ [+ -10.818799999999998,+ 86.85436244118516+ ],+ [+ -17.228399999999997,+ 84.30656277909344+ ],+ [+ -27.386415000000003,+ 65.86508277909344+ ],+ [+ -27.386415000000003,+ 0+ ]+ ],+ "edges": [+ {+ "endpoints": [+ 0,+ 1+ ]+ },+ {+ "endpoints": [+ 1,+ 2+ ],+ "label": "right_collar",+ "curvature": {+ "type": "circle",+ "params": [+ 11.564126734773824,+ 0,+ 0+ ]+ }+ },+ {+ "endpoints": [+ 2,+ 3+ ]+ },+ {+ "endpoints": [+ 3,+ 4+ ],+ "label": "right_armhole",+ "curvature": {+ "type": "cubic",+ "params": [+ [+ 0.5,+ 0.2+ ],+ [+ 0.8,+ 0.35+ ]+ ]+ }+ },+ {+ "endpoints": [+ 4,+ 5+ ]+ },+ {+ "endpoints": [+ 5,+ 0+ ]+ }+ ]+ }+ },+ "stitches": [+ [+ {+ "panel": "right_ftorso",+ "edge": 0+ },+ {+ "panel": "left_ftorso",+ "edge": 5+ }+ ],+ [+ {+ "panel": "left_ftorso",+ "edge": 1+ },+ {+ "panel": "left_btorso",+ "edge": 4+ }+ ],+ [+ {+ "panel": "right_ftorso",+ "edge": 2+ },+ {+ "panel": "right_btorso",+ "edge": 3+ }+ ],+ [+ {+ "panel": "left_ftorso",+ "edge": 3+ },+ {+ "panel": "left_btorso",+ "edge": 2+ }+ ],+ [+ {+ "panel": "right_ftorso",+ "edge": 4+ },+ {+ "panel": "right_btorso",+ "edge": 1+ }+ ],+ [+ {+ "panel": "right_btorso",+ "edge": 5+ },+ {+ "panel": "left_btorso",+ "edge": 0+ }+ ]+ ],+ "panel_order": [+ "left_btorso",+ "left_ftorso",+ "right_btorso",+ "right_ftorso"+ ]+ },+ "parameters": {},+ "parameter_order": [],+ "properties": {+ "curvature_coords": "relative",+ "normalize_panel_translation": false,+ "normalized_edge_loops": true,+ "units_in_meter": 100+ }+}\ No newline at end of filediff --git a/fixtures/Canonical/Garment/GarmentCode/provenance.json b/fixtures/Canonical/Garment/GarmentCode/provenance.jsonnew file mode 100644index 00000000..4d423cd9--- /dev/null+++ b/fixtures/Canonical/Garment/GarmentCode/provenance.json@@ -0,0 +1,28 @@+{+ "upstream": "https://github.com/maria-korosteleva/GarmentCode",+ "revision": "d449629979028123a5c4dc9e732a2ec19b7fce31",+ "template": "assets/garment_programs/bodice.py:Shirt (fitted=False)",+ "bodyMeasurements": "assets/bodies/mean_all.yaml",+ "designPreset": "assets/design_params/t-shirt.yaml",+ "license": "MIT; copyright (c) 2024 Maria Korosteleva",+ "bodyMeshCopied": false,+ "simulated": false,+ "witnesses": [+ {+ "name": "shirt",+ "panels": 8,+ "stitches": 16,+ "lengthMultiplier": 1.2,+ "sleeveless": false,+ "sourceSha256": "9567ad25d9d356c9a14dbdcf782391c50980afb5db882acc45236a7d8f63c1f7"+ },+ {+ "name": "dress",+ "panels": 4,+ "stitches": 6,+ "lengthMultiplier": 2.2,+ "sleeveless": true,+ "sourceSha256": "f70b61d286c1dcb4d38a0bf6585c95a6b54dbbceed66b8630a9908f14f416731"+ }+ ]+}diff --git a/fixtures/Canonical/Garment/GarmentCode/shirt-curves.json b/fixtures/Canonical/Garment/GarmentCode/shirt-curves.jsonnew file mode 100644index 00000000..e5581350--- /dev/null+++ b/fixtures/Canonical/Garment/GarmentCode/shirt-curves.json@@ -0,0 +1,1190 @@+[+ {+ "panel": "left_btorso",+ "edge": 0,+ "lengthMm": 442.6956007084881,+ "samplesMm": [+ [+ 0.0,+ -0.0+ ],+ [+ 0.0,+ 110.67390017712202+ ],+ [+ 0.0,+ 221.34780035424404+ ],+ [+ 0.0,+ 332.02170053136615+ ],+ [+ 0.0,+ 442.6956007084881+ ]+ ]+ },+ {+ "panel": "left_btorso",+ "edge": 1,+ "lengthMm": 126.88825300726279,+ "samplesMm": [+ [+ 2.4698854620335126e-15,+ 442.6956007084881+ ],+ [+ 31.416891316492443,+ 446.49339235426595+ ],+ [+ 61.023865547812726,+ 457.6679777265731+ ],+ [+ 87.1152743546105,+ 475.57559252736655+ ],+ [+ 108.18799999999999,+ 499.18458478140366+ ]+ ]+ },+ {+ "panel": "left_btorso",+ "edge": 2,+ "lengthMm": 68.97409712802181,+ "samplesMm": [+ [+ 108.18799999999999,+ 499.18458478140366+ ],+ [+ 124.21199999999999,+ 492.81508294341734+ ],+ [+ 140.236,+ 486.44558110543096+ ],+ [+ 156.26000000000002,+ 480.0760792674446+ ],+ [+ 172.284,+ 473.7065774294582+ ]+ ]+ },+ {+ "panel": "left_btorso",+ "edge": 3,+ "lengthMm": 224.04283760438653,+ "samplesMm": [+ [+ 172.284,+ 473.7065774294582+ ],+ [+ 174.09947425781252,+ 400.7560477614895+ ],+ [+ 182.03295656249998,+ 344.6618103982082+ ],+ [+ 204.59584183593748,+ 306.98625655055196+ ],+ [+ 250.29952499999993,+ 289.2917774294582+ ]+ ]+ },+ {+ "panel": "left_btorso",+ "edge": 4,+ "lengthMm": 289.2917774294582,+ "samplesMm": [+ [+ 250.29952500000002,+ 289.2917774294582+ ],+ [+ 250.29952500000002,+ 216.96883307209364+ ],+ [+ 250.29952500000002,+ 144.6458887147291+ ],+ [+ 250.29952500000002,+ 72.32294435736456+ ],+ [+ 250.29952500000002,+ -0.0+ ]+ ]+ },+ {+ "panel": "left_btorso",+ "edge": 5,+ "lengthMm": 250.29952500000002,+ "samplesMm": [+ [+ 250.29952500000002,+ -0.0+ ],+ [+ 187.72464374999998,+ -0.0+ ],+ [+ 125.14976250000001,+ -0.0+ ],+ [+ 62.57488125000002,+ -0.0+ ],+ [+ 0.0,+ -0.0+ ]+ ]+ },+ {+ "panel": "left_ftorso",+ "edge": 0,+ "lengthMm": 273.86415000000005,+ "samplesMm": [+ [+ 0.0,+ -0.0+ ],+ [+ 68.46603750000001,+ -0.0+ ],+ [+ 136.93207500000003,+ -0.0+ ],+ [+ 205.39811250000002,+ -0.0+ ],+ [+ 273.86415000000005,+ -0.0+ ]+ ]+ },+ {+ "panel": "left_ftorso",+ "edge": 1,+ "lengthMm": 289.73782566623595,+ "samplesMm": [+ [+ 273.86415000000005,+ -0.0+ ],+ [+ 273.86415000000005,+ 72.43445641655899+ ],+ [+ 273.86415000000005,+ 144.86891283311797+ ],+ [+ 273.86415000000005,+ 217.303369249677+ ],+ [+ 273.86415000000005,+ 289.73782566623595+ ]+ ]+ },+ {+ "panel": "left_ftorso",+ "edge": 2,+ "lengthMm": 228.9590835088925,+ "samplesMm": [+ [+ 273.86415000000005,+ 289.73782566623595+ ],+ [+ 224.88067748863352,+ 302.7916761597503+ ],+ [+ 197.24317940169152,+ 338.39126043218766+ ],+ [+ 182.7223657879334,+ 394.1273227489803+ ],+ [+ 173.08894669611848,+ 467.5906073755601+ ]+ ]+ },+ {+ "panel": "left_ftorso",+ "edge": 3,+ "lengthMm": 6.611205195141515,+ "samplesMm": [+ [+ 173.08894669611848,+ 467.5906073755604+ ],+ [+ 172.88987383065316,+ 469.2219933032632+ ],+ [+ 172.68940214289117,+ 470.85947112638394+ ],+ [+ 172.48746605771328,+ 472.5030216467617+ ],+ [+ 172.2840000000001,+ 474.1526256662357+ ]+ ]+ },+ {+ "panel": "left_ftorso",+ "edge": 4,+ "lengthMm": 68.97409425120793,+ "samplesMm": [+ [+ 172.28399999999996,+ 474.15262566623596+ ],+ [+ 156.26,+ 480.5221255571934+ ],+ [+ 140.236,+ 486.8916254481509+ ],+ [+ 124.21199999999997,+ 493.2611253391084+ ],+ [+ 108.18799999999997,+ 499.63062523006585+ ]+ ]+ },+ {+ "panel": "left_ftorso",+ "edge": 5,+ "lengthMm": 223.39396908026657,+ "samplesMm": [+ [+ 108.18799999999996,+ 499.63062523006585+ ],+ [+ 114.78232005945526,+ 444.7178290038355+ ],+ [+ 95.12148260897132,+ 393.02303509597976+ ],+ [+ 53.70268184859901,+ 356.3708429377661+ ],+ [+ 3.56620041258319e-14,+ 343.14502694410453+ ]+ ]+ },+ {+ "panel": "left_ftorso",+ "edge": 6,+ "lengthMm": 343.14502694410453,+ "samplesMm": [+ [+ 0.0,+ 343.14502694410453+ ],+ [+ 0.0,+ 257.3587702080784+ ],+ [+ 0.0,+ 171.57251347205226+ ],+ [+ 0.0,+ 85.78625673602613+ ],+ [+ 0.0,+ -0.0+ ]+ ]+ },+ {+ "panel": "left_sleeve_b",+ "edge": 0,+ "lengthMm": 210.5093627648485,+ "samplesMm": [+ [+ 0.0,+ -0.0+ ],+ [+ 0.0,+ -52.627340691212126+ ],+ [+ 0.0,+ -105.25468138242425+ ],+ [+ 0.0,+ -157.8820220736364+ ],+ [+ 0.0,+ -210.5093627648485+ ]+ ]+ },+ {+ "panel": "left_sleeve_b",+ "edge": 1,+ "lengthMm": 136.83885652227852,+ "samplesMm": [+ [+ 0.0,+ -210.5093627648485+ ],+ [+ -34.20971413056963,+ -210.5093627648485+ ],+ [+ -68.41942826113926,+ -210.5093627648485+ ],+ [+ -102.6291423917089,+ -210.5093627648485+ ],+ [+ -136.83885652227852,+ -210.5093627648485+ ]+ ]+ },+ {+ "panel": "left_sleeve_b",+ "edge": 2,+ "lengthMm": 224.08713105621098,+ "samplesMm": [+ [+ -136.83885652227852,+ -210.5093627648485+ ],+ [+ -160.77143502261362,+ -164.12649022917478+ ],+ [+ -187.97255443411785,+ -122.60254554592427+ ],+ [+ -210.50862021153654,+ -74.03995064659011+ ],+ [+ -220.44603780961518,+ -6.541127462665308+ ]+ ]+ },+ {+ "panel": "left_sleeve_b",+ "edge": 3,+ "lengthMm": 6.541476094552255,+ "samplesMm": [+ [+ -220.44603780961518,+ -6.541127462665379+ ],+ [+ -220.45382867435617,+ -4.892546595715349+ ],+ [+ -220.44973584835972,+ -3.2528812808566836+ ],+ [+ -220.43386824592483,+ -1.622057191236021+ ],+ [+ -220.40633478135032,+ -0.0+ ]+ ]+ },+ {+ "panel": "left_sleeve_b",+ "edge": 4,+ "lengthMm": 220.40633478135015,+ "samplesMm": [+ [+ -220.40633478135015,+ -0.0+ ],+ [+ -165.30475108601257,+ -0.0+ ],+ [+ -110.20316739067508,+ -0.0+ ],+ [+ -55.10158369533755,+ -0.0+ ],+ [+ 0.0,+ -0.0+ ]+ ]+ },+ {+ "panel": "left_sleeve_f",+ "edge": 0,+ "lengthMm": 220.40633478135015,+ "samplesMm": [+ [+ 0.0,+ -0.0+ ],+ [+ -55.10158369533754,+ -0.0+ ],+ [+ -110.20316739067508,+ -0.0+ ],+ [+ -165.30475108601257,+ -0.0+ ],+ [+ -220.40633478135015,+ -0.0+ ]+ ]+ },+ {+ "panel": "left_sleeve_f",+ "edge": 1,+ "lengthMm": 228.9338347748625,+ "samplesMm": [+ [+ -220.40633478135015,+ -0.0+ ],+ [+ -209.92424172770836,+ -61.91953646054316+ ],+ [+ -186.90835355486576,+ -113.82677640641161+ ],+ [+ -159.74958643049743,+ -161.4479688402864+ ],+ [+ -136.83885652227855,+ -210.50936276484867+ ]+ ]+ },+ {+ "panel": "left_sleeve_f",+ "edge": 2,+ "lengthMm": 136.83885652227852,+ "samplesMm": [+ [+ -136.83885652227852,+ -210.50936276484873+ ],+ [+ -102.6291423917089,+ -210.50936276484873+ ],+ [+ -68.41942826113926,+ -210.50936276484873+ ],+ [+ -34.20971413056962,+ -210.50936276484873+ ],+ [+ 0.0,+ -210.50936276484873+ ]+ ]+ },+ {+ "panel": "left_sleeve_f",+ "edge": 3,+ "lengthMm": 210.50936276484873,+ "samplesMm": [+ [+ 0.0,+ -210.50936276484873+ ],+ [+ 0.0,+ -157.88202207363653+ ],+ [+ 0.0,+ -105.25468138242437+ ],+ [+ 0.0,+ -52.62734069121219+ ],+ [+ 0.0,+ -0.0+ ]+ ]+ },+ {+ "panel": "right_btorso",+ "edge": 0,+ "lengthMm": 250.29952500000002,+ "samplesMm": [+ [+ 0.0,+ -0.0+ ],+ [+ -62.574881250000004,+ -0.0+ ],+ [+ -125.14976250000001,+ -0.0+ ],+ [+ -187.72464374999998,+ -0.0+ ],+ [+ -250.29952500000002,+ -0.0+ ]+ ]+ },+ {+ "panel": "right_btorso",+ "edge": 1,+ "lengthMm": 289.2917774294582,+ "samplesMm": [+ [+ -250.29952500000002,+ -0.0+ ],+ [+ -250.29952500000002,+ 72.32294435736455+ ],+ [+ -250.29952500000002,+ 144.6458887147291+ ],+ [+ -250.29952500000002,+ 216.96883307209364+ ],+ [+ -250.29952500000002,+ 289.2917774294582+ ]+ ]+ },+ {+ "panel": "right_btorso",+ "edge": 2,+ "lengthMm": 224.04283760438653,+ "samplesMm": [+ [+ -250.29952500000002,+ 289.2917774294582+ ],+ [+ -204.59584183593748,+ 306.98625655055196+ ],+ [+ -182.03295656249998,+ 344.6618103982082+ ],+ [+ -174.09947425781252,+ 400.7560477614895+ ],+ [+ -172.284,+ 473.7065774294582+ ]+ ]+ },+ {+ "panel": "right_btorso",+ "edge": 3,+ "lengthMm": 68.97409712802181,+ "samplesMm": [+ [+ -172.284,+ 473.7065774294582+ ],+ [+ -156.26000000000002,+ 480.0760792674446+ ],+ [+ -140.236,+ 486.44558110543096+ ],+ [+ -124.21199999999999,+ 492.81508294341734+ ],+ [+ -108.18799999999999,+ 499.18458478140366+ ]+ ]+ },+ {+ "panel": "right_btorso",+ "edge": 4,+ "lengthMm": 126.88825300726279,+ "samplesMm": [+ [+ -108.18799999999999,+ 499.18458478140366+ ],+ [+ -87.11527435461053,+ 475.57559252736655+ ],+ [+ -61.02386554781273,+ 457.6679777265731+ ],+ [+ -31.416891316492514,+ 446.493392354266+ ],+ [+ -1.5599061012301367e-14,+ 442.6956007084881+ ]+ ]+ },+ {+ "panel": "right_btorso",+ "edge": 5,+ "lengthMm": 442.6956007084881,+ "samplesMm": [+ [+ 0.0,+ 442.6956007084881+ ],+ [+ 0.0,+ 332.02170053136615+ ],+ [+ 0.0,+ 221.34780035424404+ ],+ [+ 0.0,+ 110.673900177122+ ],+ [+ 0.0,+ -0.0+ ]+ ]+ },+ {+ "panel": "right_ftorso",+ "edge": 0,+ "lengthMm": 343.14502694410453,+ "samplesMm": [+ [+ 0.0,+ -0.0+ ],+ [+ 0.0,+ 85.78625673602613+ ],+ [+ 0.0,+ 171.57251347205226+ ],+ [+ 0.0,+ 257.3587702080784+ ],+ [+ 0.0,+ 343.14502694410453+ ]+ ]+ },+ {+ "panel": "right_ftorso",+ "edge": 1,+ "lengthMm": 223.39396908026657,+ "samplesMm": [+ [+ 4.177486186101655e-15,+ 343.14502694410453+ ],+ [+ -53.70268184859893,+ 356.3708429377661+ ],+ [+ -95.1214826089712,+ 393.0230350959796+ ],+ [+ -114.78232005945526,+ 444.71782900383545+ ],+ [+ -108.18799999999999,+ 499.6306252300658+ ]+ ]+ },+ {+ "panel": "right_ftorso",+ "edge": 2,+ "lengthMm": 68.97409425120793,+ "samplesMm": [+ [+ -108.18799999999997,+ 499.63062523006585+ ],+ [+ -124.21199999999997,+ 493.2611253391084+ ],+ [+ -140.236,+ 486.8916254481509+ ],+ [+ -156.26,+ 480.5221255571934+ ],+ [+ -172.28399999999996,+ 474.15262566623596+ ]+ ]+ },+ {+ "panel": "right_ftorso",+ "edge": 3,+ "lengthMm": 6.611205195141515,+ "samplesMm": [+ [+ -172.28399999999996,+ 474.15262566623596+ ],+ [+ -172.48746605771316,+ 472.50302164676185+ ],+ [+ -172.68940214289114,+ 470.85947112638394+ ],+ [+ -172.88987383065313,+ 469.2219933032632+ ],+ [+ -173.08894669611843,+ 467.5906073755604+ ]+ ]+ },+ {+ "panel": "right_ftorso",+ "edge": 4,+ "lengthMm": 228.9590835088925,+ "samplesMm": [+ [+ -173.08894669611848,+ 467.5906073755604+ ],+ [+ -182.7223657879334,+ 394.12732274898053+ ],+ [+ -197.24317940169152,+ 338.39126043218783+ ],+ [+ -224.88067748863347,+ 302.7916761597503+ ],+ [+ -273.86415,+ 289.737825666236+ ]+ ]+ },+ {+ "panel": "right_ftorso",+ "edge": 5,+ "lengthMm": 289.73782566623595,+ "samplesMm": [+ [+ -273.86415000000005,+ 289.73782566623595+ ],+ [+ -273.86415000000005,+ 217.303369249677+ ],+ [+ -273.86415000000005,+ 144.86891283311797+ ],+ [+ -273.86415000000005,+ 72.43445641655899+ ],+ [+ -273.86415000000005,+ -0.0+ ]+ ]+ },+ {+ "panel": "right_ftorso",+ "edge": 6,+ "lengthMm": 273.86415000000005,+ "samplesMm": [+ [+ -273.86415000000005,+ -0.0+ ],+ [+ -205.39811250000002,+ -0.0+ ],+ [+ -136.93207500000003,+ -0.0+ ],+ [+ -68.4660375,+ -0.0+ ],+ [+ 0.0,+ -0.0+ ]+ ]+ },+ {+ "panel": "right_sleeve_b",+ "edge": 0,+ "lengthMm": 220.40633478135015,+ "samplesMm": [+ [+ 0.0,+ -0.0+ ],+ [+ 55.10158369533754,+ -0.0+ ],+ [+ 110.20316739067508,+ -0.0+ ],+ [+ 165.30475108601257,+ -0.0+ ],+ [+ 220.40633478135015,+ -0.0+ ]+ ]+ },+ {+ "panel": "right_sleeve_b",+ "edge": 1,+ "lengthMm": 6.541476094552255,+ "samplesMm": [+ [+ 220.40633478135015,+ -0.0+ ],+ [+ 220.4338682459247,+ -1.622057191236021+ ],+ [+ 220.44973584835964,+ -3.252881280856683+ ],+ [+ 220.45382867435606,+ -4.892546595715349+ ],+ [+ 220.44603780961498,+ -6.541127462665379+ ]+ ]+ },+ {+ "panel": "right_sleeve_b",+ "edge": 2,+ "lengthMm": 224.08713105621098,+ "samplesMm": [+ [+ 220.44603780961518,+ -6.541127462665379+ ],+ [+ 210.50862021153654,+ -74.03995064659011+ ],+ [+ 187.97255443411785,+ -122.60254554592424+ ],+ [+ 160.77143502261364,+ -164.12649022917475+ ],+ [+ 136.83885652227855,+ -210.5093627648485+ ]+ ]+ },+ {+ "panel": "right_sleeve_b",+ "edge": 3,+ "lengthMm": 136.83885652227852,+ "samplesMm": [+ [+ 136.83885652227852,+ -210.5093627648485+ ],+ [+ 102.6291423917089,+ -210.5093627648485+ ],+ [+ 68.41942826113926,+ -210.5093627648485+ ],+ [+ 34.20971413056962,+ -210.5093627648485+ ],+ [+ 0.0,+ -210.5093627648485+ ]+ ]+ },+ {+ "panel": "right_sleeve_b",+ "edge": 4,+ "lengthMm": 210.5093627648485,+ "samplesMm": [+ [+ 0.0,+ -210.5093627648485+ ],+ [+ 0.0,+ -157.8820220736364+ ],+ [+ 0.0,+ -105.25468138242425+ ],+ [+ 0.0,+ -52.62734069121212+ ],+ [+ 0.0,+ -0.0+ ]+ ]+ },+ {+ "panel": "right_sleeve_f",+ "edge": 0,+ "lengthMm": 210.50936276484873,+ "samplesMm": [+ [+ 0.0,+ -0.0+ ],+ [+ 0.0,+ -52.62734069121218+ ],+ [+ 0.0,+ -105.25468138242437+ ],+ [+ 0.0,+ -157.88202207363653+ ],+ [+ 0.0,+ -210.50936276484873+ ]+ ]+ },+ {+ "panel": "right_sleeve_f",+ "edge": 1,+ "lengthMm": 136.83885652227852,+ "samplesMm": [+ [+ 0.0,+ -210.50936276484873+ ],+ [+ 34.20971413056963,+ -210.50936276484873+ ],+ [+ 68.41942826113926,+ -210.50936276484873+ ],+ [+ 102.6291423917089,+ -210.50936276484873+ ],+ [+ 136.83885652227852,+ -210.50936276484873+ ]+ ]+ },+ {+ "panel": "right_sleeve_f",+ "edge": 2,+ "lengthMm": 228.9338347748625,+ "samplesMm": [+ [+ 136.83885652227852,+ -210.50936276484873+ ],+ [+ 159.74958643049743,+ -161.44796884028642+ ],+ [+ 186.90835355486576,+ -113.82677640641164+ ],+ [+ 209.92424172770836,+ -61.91953646054323+ ],+ [+ 220.40633478135015,+ -1.0658141036401503e-13+ ]+ ]+ },+ {+ "panel": "right_sleeve_f",+ "edge": 3,+ "lengthMm": 220.40633478135015,+ "samplesMm": [+ [+ 220.40633478135015,+ -0.0+ ],+ [+ 165.30475108601257,+ -0.0+ ],+ [+ 110.20316739067508,+ -0.0+ ],+ [+ 55.10158369533755,+ -0.0+ ],+ [+ 0.0,+ -0.0+ ]+ ]+ }+]diff --git a/fixtures/Canonical/Garment/GarmentCode/shirt-design.yaml b/fixtures/Canonical/Garment/GarmentCode/shirt-design.yamlnew file mode 100644index 00000000..77200310--- /dev/null+++ b/fixtures/Canonical/Garment/GarmentCode/shirt-design.yaml@@ -0,0 +1,885 @@+design:+ meta:+ upper:+ v: Shirt+ range:+ - FittedShirt+ - Shirt+ - null+ type: select_null+ default_prob: 0.3+ wb:+ v: null+ range:+ - StraightWB+ - FittedWB+ - null+ type: select_null+ default_prob: 0.5+ bottom:+ v: null+ range:+ - SkirtCircle+ - AsymmSkirtCircle+ - GodetSkirt+ - Pants+ - Skirt2+ - SkirtManyPanels+ - PencilSkirt+ - SkirtLevels+ - null+ type: select_null+ default_prob: 0.3+ waistband:+ waist:+ v: 1.0+ range:+ - 1.0+ - 2+ type: float+ default_prob: 0.7+ width:+ v: 0.2+ range:+ - 0.1+ - 1.0+ type: float+ default_prob: 0.5+ shirt:+ strapless:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ length:+ v: 1.2+ range:+ - 0.5+ - 3.5+ type: float+ default_prob: 0.7+ width:+ v: 1.05+ range:+ - 1.0+ - 1.3+ type: float+ default_prob: 0.4+ flare:+ v: 1.0+ range:+ - 0.7+ - 1.6+ type: float+ default_prob: 0.4+ collar:+ f_collar:+ v: CircleNeckHalf+ range:+ - CircleNeckHalf+ - CurvyNeckHalf+ - VNeckHalf+ - SquareNeckHalf+ - TrapezoidNeckHalf+ - CircleArcNeckHalf+ - Bezier2NeckHalf+ type: select+ default_prob: 0.4+ b_collar:+ v: CircleNeckHalf+ range:+ - CircleNeckHalf+ - CurvyNeckHalf+ - VNeckHalf+ - SquareNeckHalf+ - TrapezoidNeckHalf+ - CircleArcNeckHalf+ - Bezier2NeckHalf+ type: select+ default_prob: 0.8+ width:+ v: 0.2+ range:+ - -0.5+ - 1+ type: float+ default_prob: 0.4+ fc_depth:+ v: 0.4+ range:+ - 0.3+ - 2+ type: float+ default_prob: 0.3+ bc_depth:+ v: 0+ range:+ - 0+ - 2+ type: float+ default_prob: 0.4+ fc_angle:+ v: 95+ range:+ - 70+ - 110+ type: int+ bc_angle:+ v: 95+ range:+ - 70+ - 110+ type: int+ f_bezier_x:+ v: 0.3+ range:+ - 0.05+ - 0.95+ type: float+ default_prob: 0.4+ f_bezier_y:+ v: 0.55+ range:+ - 0.05+ - 0.95+ type: float+ default_prob: 0.4+ b_bezier_x:+ v: 0.15+ range:+ - 0.05+ - 0.95+ type: float+ default_prob: 0.4+ b_bezier_y:+ v: 0.1+ range:+ - 0.05+ - 0.95+ type: float+ default_prob: 0.4+ f_flip_curve:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ b_flip_curve:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ component:+ style:+ v: null+ range:+ - Turtle+ - SimpleLapel+ - Hood2Panels+ - null+ type: select_null+ default_prob: 0.6+ depth:+ v: 7+ range:+ - 2+ - 8+ type: int+ lapel_standing:+ v: false+ range:+ - true+ - false+ type: bool+ hood_depth:+ v: 1+ range:+ - 1+ - 2+ type: float+ default_prob: 0.6+ hood_length:+ v: 1+ range:+ - 1+ - 1.5+ type: float+ default_prob: 0.6+ sleeve:+ sleeveless:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.7+ armhole_shape:+ v: ArmholeCurve+ range:+ - ArmholeSquare+ - ArmholeAngle+ - ArmholeCurve+ type: select+ default_prob: 0.7+ length:+ v: 0.3+ range:+ - 0.1+ - 1.15+ type: float+ connecting_width:+ v: 0.2+ range:+ - 0+ - 2+ type: float+ default_prob: 0.6+ end_width:+ v: 1.0+ range:+ - 0.2+ - 2+ type: float+ default_prob: 0.4+ sleeve_angle:+ v: 10+ range:+ - 10+ - 50+ type: int+ opening_dir_mix:+ v: 0.1+ range:+ - -0.9+ - 0.8+ type: float+ default_prob: 1.0+ standing_shoulder:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ standing_shoulder_len:+ v: 5.0+ range:+ - 4+ - 10+ type: float+ connect_ruffle:+ v: 1+ range:+ - 1+ - 2+ type: float+ default_prob: 0.4+ smoothing_coeff:+ v: 0.25+ range:+ - 0.1+ - 0.4+ type: float+ default_prob: 0.8+ cuff:+ type:+ v: null+ range:+ - CuffBand+ - CuffSkirt+ - CuffBandSkirt+ - null+ type: select_null+ top_ruffle:+ v: 1+ range:+ - 1+ - 3+ type: float+ cuff_len:+ v: 0.1+ range:+ - 0.05+ - 0.9+ type: float+ default_prob: 0.7+ skirt_fraction:+ v: 0.5+ range:+ - 0.1+ - 0.9+ type: float+ default_prob: 0.5+ skirt_flare:+ v: 1.2+ range:+ - 1+ - 2+ type: float+ skirt_ruffle:+ v: 1.0+ range:+ - 1+ - 1.5+ type: float+ default_prob: 0.3+ left:+ enable_asym:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ shirt:+ strapless:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ width:+ v: 1.0+ range:+ - 1.0+ - 1.3+ type: float+ default_prob: 0.4+ flare:+ v: 1.0+ range:+ - 0.7+ - 1.6+ type: float+ default_prob: 0.4+ collar:+ f_collar:+ v: CircleNeckHalf+ range:+ - CircleNeckHalf+ - CurvyNeckHalf+ - VNeckHalf+ - SquareNeckHalf+ - TrapezoidNeckHalf+ - CircleArcNeckHalf+ - Bezier2NeckHalf+ type: select+ default_prob: 0.4+ b_collar:+ v: CircleNeckHalf+ range:+ - CircleNeckHalf+ - CurvyNeckHalf+ - VNeckHalf+ - SquareNeckHalf+ - TrapezoidNeckHalf+ - CircleArcNeckHalf+ - Bezier2NeckHalf+ type: select+ default_prob: 0.8+ width:+ v: 0.5+ range:+ - 0+ - 1+ type: float+ default_prob: 0.4+ fc_angle:+ v: 95+ range:+ - 70+ - 110+ type: int+ bc_angle:+ v: 95+ range:+ - 70+ - 110+ type: int+ f_bezier_x:+ v: 0.5+ range:+ - 0.05+ - 0.95+ type: float+ default_prob: 0.4+ f_bezier_y:+ v: 0.3+ range:+ - 0.05+ - 0.95+ type: float+ b_bezier_x:+ v: 0.5+ range:+ - 0.05+ - 0.95+ type: float+ default_prob: 0.4+ b_bezier_y:+ v: 0.3+ range:+ - 0.05+ - 0.95+ type: float+ f_flip_curve:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ b_flip_curve:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ sleeve:+ sleeveless:+ v: true+ range:+ - true+ - false+ type: bool+ default_prob: 0.7+ armhole_shape:+ v: ArmholeCurve+ range:+ - ArmholeSquare+ - ArmholeAngle+ - ArmholeCurve+ type: select+ default_prob: 0.7+ length:+ v: 0.3+ range:+ - 0.1+ - 1.15+ type: float+ connecting_width:+ v: 0.2+ range:+ - 0+ - 2+ type: float+ default_prob: 0.6+ end_width:+ v: 1.0+ range:+ - 0.2+ - 2+ type: float+ default_prob: 0.4+ sleeve_angle:+ v: 10+ range:+ - 10+ - 50+ type: int+ opening_dir_mix:+ v: 0.2+ range:+ - -0.9+ - 0.8+ type: float+ default_prob: 1.0+ standing_shoulder:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.8+ standing_shoulder_len:+ v: 5.0+ range:+ - 4+ - 10+ type: float+ connect_ruffle:+ v: 1+ range:+ - 1+ - 2+ type: float+ default_prob: 0.4+ smoothing_coeff:+ v: 0.25+ range:+ - 0.1+ - 0.4+ type: float+ default_prob: 0.8+ cuff:+ type:+ v: null+ range:+ - CuffBand+ - CuffSkirt+ - CuffBandSkirt+ - null+ type: select_null+ top_ruffle:+ v: 1+ range:+ - 1+ - 2+ type: float+ cuff_len:+ v: 0.1+ range:+ - 0.05+ - 0.9+ type: float+ default_prob: 0.7+ skirt_fraction:+ v: 0.5+ range:+ - 0.1+ - 0.9+ type: float+ default_prob: 0.5+ skirt_flare:+ v: 1.2+ range:+ - 1+ - 2+ type: float+ skirt_ruffle:+ v: 1.0+ range:+ - 1+ - 1.5+ type: float+ default_prob: 0.3+ skirt:+ length:+ v: 0.2+ range:+ - -0.2+ - 0.95+ type: float+ rise:+ v: 1+ range:+ - 0.5+ - 1+ type: float+ default_prob: 0.3+ ruffle:+ v: 1.3+ range:+ - 1+ - 2+ type: float+ default_prob: 0.3+ bottom_cut:+ v: 0+ range:+ - 0+ - 0.9+ type: float+ default_prob: 0.3+ flare:+ v: 0+ range:+ - 0+ - 20+ type: int+ default_prob: 0.5+ flare-skirt:+ length:+ v: 0.2+ range:+ - -0.2+ - 0.95+ type: float+ rise:+ v: 1+ range:+ - 0.5+ - 1+ type: float+ default_prob: 0.3+ suns:+ v: 0.75+ range:+ - 0.1+ - 1.95+ type: float+ skirt-many-panels:+ n_panels:+ v: 4+ range:+ - 4+ - 15+ type: int+ panel_curve:+ v: 0+ range:+ - -0.35+ - -0.25+ - -0.15+ - 0+ - 0.15+ - 0.25+ - 0.35+ - 0.45+ type: select+ asymm:+ front_length:+ v: 0.5+ range:+ - 0.1+ - 0.9+ type: float+ default_prob: 0.5+ cut:+ add:+ v: false+ range:+ - true+ - false+ type: bool+ default_prob: 0.6+ depth:+ v: 0.5+ range:+ - 0.05+ - 0.95+ type: float+ default_prob: 0.6+ width:+ v: 0.1+ range:+ - 0.05+ - 0.4+ type: float+ place:+ v: -0.5+ range:+ - -1+ - 1+ type: float+ godet-skirt:+ base:+ v: PencilSkirt+ range:+ - Skirt2+ - PencilSkirt+ type: select+ default_prob: 0.7+ insert_w:+ v: 15+ range:+ - 10+ - 50+ type: int+ insert_depth:+ v: 20+ range:+ - 10+ - 50+ type: int+ num_inserts:+ v: 4+ range:+ - 4+ - 6+ - 8+ - 10+ - 12+ type: select+ cuts_distance:+ v: 5+ range:+ - 0+ - 10+ type: int+ pencil-skirt:+ length:+ v: 0.4+ range:+ - 0.2+ - 0.95+ type: float+ rise:+ v: 1+ range:+ - 0.5+ - 1+ type: float+ default_prob: 0.3+ flare:+ v: 1.0+ range:+ - 0.6+ - 1.5+ type: float+ default_prob: 0.3+ low_angle:+ v: 0+ range:+ - -30+ - 30+ type: int+ default_prob: 0.7+ front_slit:+ v: 0+ range:+ - 0+ - 0.9+ type: float+ default_prob: 0.4+ back_slit:+ v: 0+ range:+ - 0+ - 0.9+ type: float+ default_prob: 0.4+ left_slit:+ v: 0+ range:+ - 0+ - 0.9+ type: float+ default_prob: 0.6+ right_slit:+ v: 0+ range:+ - 0+ - 0.9+ type: float+ default_prob: 0.6+ style_side_cut:+ v: null+ range:+ - Sun+ - SIGGRAPH_logo+ type: select_null+ default_prob: 1.0+ levels-skirt:+ base:+ v: PencilSkirt+ range:+ - Skirt2+ - PencilSkirt+ - SkirtCircle+ - AsymmSkirtCircle+ type: select+ level:+ v: Skirt2+ range:+ - Skirt2+ - SkirtCircle+ - AsymmSkirtCircle+ type: select+ num_levels:+ v: 1+ range:+ - 1+ - 5+ type: int+ level_ruffle:+ v: 1.0+ range:+ - 1+ - 1.7+ type: float+ length:+ v: 0.5+ range:+ - 0.2+ - 0.95+ type: float+ rise:+ v: 1+ range:+ - 0.5+ - 1+ type: float+ default_prob: 0.3+ base_length_frac:+ v: 0.5+ range:+ - 0.2+ - 0.8+ type: float+ pants:+ length:+ v: 0.3+ range:+ - 0.2+ - 0.9+ type: float+ width:+ v: 1.0+ range:+ - 1.0+ - 1.5+ type: float+ default_prob: 0.5+ flare:+ v: 1.0+ range:+ - 0.5+ - 1.2+ type: float+ default_prob: 0.3+ rise:+ v: 1.0+ range:+ - 0.5+ - 1+ type: float+ default_prob: 0.3+ cuff:+ type:+ v: null+ range:+ - CuffBand+ - CuffSkirt+ - CuffBandSkirt+ - null+ type: select_null+ default_prob: 0.5+ top_ruffle:+ v: 1.0+ range:+ - 1+ - 2+ type: float+ cuff_len:+ v: 0.1+ range:+ - 0.05+ - 0.9+ type: float+ default_prob: 0.3+ skirt_fraction:+ v: 0.5+ range:+ - 0.1+ - 0.9+ type: float+ skirt_flare:+ v: 1.2+ range:+ - 1+ - 2+ type: float+ skirt_ruffle:+ v: 1.0+ range:+ - 1+ - 1.5+ type: floatdiff --git a/fixtures/Canonical/Garment/GarmentCode/shirt.json b/fixtures/Canonical/Garment/GarmentCode/shirt.jsonnew file mode 100644index 00000000..56ccb192--- /dev/null+++ b/fixtures/Canonical/Garment/GarmentCode/shirt.json@@ -0,0 +1,952 @@+{+ "pattern": {+ "panels": {+ "left_btorso": {+ "translation": [+ 0.0,+ 91.4448950181744,+ -25.0+ ],+ "rotation": [+ -0.0,+ 0.0,+ 0.0+ ],+ "vertices": [+ [+ 0.0,+ 0.0+ ],+ [+ 0.0,+ 44.26956007084881+ ],+ [+ 10.8188,+ 49.918458478140366+ ],+ [+ 17.2284,+ 47.37065774294582+ ],+ [+ 25.0299525,+ 28.92917774294582+ ],+ [+ 25.0299525,+ 0.0+ ]+ ],+ "edges": [+ {+ "endpoints": [+ 0,+ 1+ ]+ },+ {+ "endpoints": [+ 1,+ 2+ ],+ "label": "left_collar",+ "curvature": {+ "type": "circle",+ "params": [+ 13.184560591816423,+ 0,+ 1+ ]+ }+ },+ {+ "endpoints": [+ 2,+ 3+ ]+ },+ {+ "endpoints": [+ 3,+ 4+ ],+ "label": "left_armhole",+ "curvature": {+ "type": "cubic",+ "params": [+ [+ 0.5,+ -0.2+ ],+ [+ 0.8,+ -0.35+ ]+ ]+ }+ },+ {+ "endpoints": [+ 4,+ 5+ ]+ },+ {+ "endpoints": [+ 5,+ 0+ ]+ }+ ]+ },+ "left_ftorso": {+ "translation": [+ 0.0,+ 91.40029082350912,+ 30.0+ ],+ "rotation": [+ -0.0,+ 0.0,+ 0.0+ ],+ "vertices": [+ [+ 0.0,+ 0.0+ ],+ [+ 27.386415000000003,+ 0.0+ ],+ [+ 27.386415000000003,+ 28.973782566623598+ ],+ [+ 17.30889466961185,+ 46.75906073755604+ ],+ [+ 17.228399999999997,+ 47.415262566623596+ ],+ [+ 10.818799999999998,+ 49.963062523006585+ ],+ [+ 0.0,+ 34.31450269441045+ ]+ ],+ "edges": [+ {+ "endpoints": [+ 0,+ 1+ ]+ },+ {+ "endpoints": [+ 1,+ 2+ ]+ },+ {+ "endpoints": [+ 2,+ 3+ ],+ "curvature": {+ "type": "cubic",+ "params": [+ [+ 0.2061952508517768,+ 0.35096465500208307+ ],+ [+ 0.505424359190956,+ 0.20577245081543222+ ]+ ]+ }+ },+ {+ "endpoints": [+ 3,+ 4+ ],+ "curvature": {+ "type": "cubic",+ "params": [+ [+ 0.3308272055982163,+ -0.0002699142957428245+ ],+ [+ 0.6641664931259995,+ -0.0003061758205280373+ ]+ ]+ }+ },+ {+ "endpoints": [+ 4,+ 5+ ]+ },+ {+ "endpoints": [+ 5,+ 6+ ],+ "label": "left_collar",+ "curvature": {+ "type": "circle",+ "params": [+ 11.564126734773824,+ 0,+ 0+ ]+ }+ },+ {+ "endpoints": [+ 6,+ 0+ ]+ }+ ]+ },+ "left_sleeve_b": {+ "translation": [+ 37.644720948614996,+ 126.0618151988509,+ -12.5+ ],+ "rotation": [+ -0.0,+ 0.0,+ -45.483+ ],+ "vertices": [+ [+ 0.0,+ 0.0+ ],+ [+ 0.0,+ -21.05093627648485+ ],+ [+ -13.683885652227852,+ -21.05093627648485+ ],+ [+ -22.044603780961516,+ -0.6541127462665379+ ],+ [+ -22.040633478135014,+ 0.0+ ]+ ],+ "edges": [+ {+ "endpoints": [+ 0,+ 1+ ]+ },+ {+ "endpoints": [+ 1,+ 2+ ]+ },+ {+ "endpoints": [+ 2,+ 3+ ],+ "curvature": {+ "type": "cubic",+ "params": [+ [+ 0.3404666185794546,+ -0.01108221054921885+ ],+ [+ 0.5447706529853293,+ 0.18010497156243546+ ]+ ]+ }+ },+ {+ "endpoints": [+ 3,+ 4+ ],+ "curvature": {+ "type": "cubic",+ "params": [+ [+ 0.33692844887476237,+ 0.004851727230738001+ ],+ [+ 0.6702217412378578,+ 0.004792281731376439+ ]+ ]+ }+ },+ {+ "endpoints": [+ 4,+ 0+ ]+ }+ ],+ "label": "arm"+ },+ "left_sleeve_f": {+ "translation": [+ 37.644720948614996,+ 126.0618151988509,+ 17.5+ ],+ "rotation": [+ -0.0,+ 0.0,+ -45.483+ ],+ "vertices": [+ [+ 0.0,+ 0.0+ ],+ [+ -22.040633478135014,+ 0.0+ ],+ [+ -13.683885652227852,+ -21.050936276484872+ ],+ [+ 0.0,+ -21.050936276484872+ ]+ ],+ "edges": [+ {+ "endpoints": [+ 0,+ 1+ ]+ },+ {+ "endpoints": [+ 1,+ 2+ ],+ "curvature": {+ "type": "cubic",+ "params": [+ [+ 0.37971308490402633,+ -0.14175474188545475+ ],+ [+ 0.6780977480636377,+ 0.013843756921904194+ ]+ ]+ }+ },+ {+ "endpoints": [+ 2,+ 3+ ]+ },+ {+ "endpoints": [+ 3,+ 0+ ]+ }+ ],+ "label": "arm"+ },+ "right_btorso": {+ "translation": [+ 0.0,+ 91.4448950181744,+ -25.0+ ],+ "rotation": [+ -0.0,+ 0.0,+ 0.0+ ],+ "vertices": [+ [+ 0,+ 0+ ],+ [+ -25.0299525,+ 0+ ],+ [+ -25.0299525,+ 28.92917774294582+ ],+ [+ -17.2284,+ 47.37065774294582+ ],+ [+ -10.8188,+ 49.918458478140366+ ],+ [+ 0.0,+ 44.26956007084881+ ]+ ],+ "edges": [+ {+ "endpoints": [+ 0,+ 1+ ]+ },+ {+ "endpoints": [+ 1,+ 2+ ]+ },+ {+ "endpoints": [+ 2,+ 3+ ],+ "label": "right_armhole",+ "curvature": {+ "type": "cubic",+ "params": [+ [+ 0.19999999999999996,+ -0.35+ ],+ [+ 0.5,+ -0.2+ ]+ ]+ }+ },+ {+ "endpoints": [+ 3,+ 4+ ]+ },+ {+ "endpoints": [+ 4,+ 5+ ],+ "label": "right_collar",+ "curvature": {+ "type": "circle",+ "params": [+ 13.184560591816423,+ 0,+ 1+ ]+ }+ },+ {+ "endpoints": [+ 5,+ 0+ ]+ }+ ]+ },+ "right_ftorso": {+ "translation": [+ 0.0,+ 91.40029082350912,+ 30.0+ ],+ "rotation": [+ -0.0,+ 0.0,+ 0.0+ ],+ "vertices": [+ [+ 0,+ 0+ ],+ [+ 0.0,+ 34.31450269441045+ ],+ [+ -10.818799999999998,+ 49.963062523006585+ ],+ [+ -17.228399999999997,+ 47.415262566623596+ ],+ [+ -17.30889466961185,+ 46.75906073755604+ ],+ [+ -27.386415000000003,+ 28.973782566623598+ ],+ [+ -27.386415000000003,+ 0+ ]+ ],+ "edges": [+ {+ "endpoints": [+ 0,+ 1+ ]+ },+ {+ "endpoints": [+ 1,+ 2+ ],+ "label": "right_collar",+ "curvature": {+ "type": "circle",+ "params": [+ 11.564126734773824,+ 0,+ 0+ ]+ }+ },+ {+ "endpoints": [+ 2,+ 3+ ]+ },+ {+ "endpoints": [+ 3,+ 4+ ],+ "curvature": {+ "type": "cubic",+ "params": [+ [+ 0.3358335068740005,+ -0.0003061758205280373+ ],+ [+ 0.6691727944017837,+ -0.0002699142957428245+ ]+ ]+ }+ },+ {+ "endpoints": [+ 4,+ 5+ ],+ "curvature": {+ "type": "cubic",+ "params": [+ [+ 0.4945756408090441,+ 0.20577245081543222+ ],+ [+ 0.7938047491482232,+ 0.35096465500208307+ ]+ ]+ }+ },+ {+ "endpoints": [+ 5,+ 6+ ]+ },+ {+ "endpoints": [+ 6,+ 0+ ]+ }+ ]+ },+ "right_sleeve_b": {+ "translation": [+ -37.644720948614996,+ 126.0618151988509,+ -12.5+ ],+ "rotation": [+ -0.0,+ 0.0,+ 45.483+ ],+ "vertices": [+ [+ 0,+ 0+ ],+ [+ 22.040633478135014,+ 0.0+ ],+ [+ 22.044603780961516,+ -0.6541127462665379+ ],+ [+ 13.683885652227852,+ -21.05093627648485+ ],+ [+ 0,+ -21.05093627648485+ ]+ ],+ "edges": [+ {+ "endpoints": [+ 0,+ 1+ ]+ },+ {+ "endpoints": [+ 1,+ 2+ ],+ "curvature": {+ "type": "cubic",+ "params": [+ [+ 0.3297782587621422,+ 0.004792281731376439+ ],+ [+ 0.6630715511252376,+ 0.004851727230738001+ ]+ ]+ }+ },+ {+ "endpoints": [+ 2,+ 3+ ],+ "curvature": {+ "type": "cubic",+ "params": [+ [+ 0.45522934701467066,+ 0.18010497156243546+ ],+ [+ 0.6595333814205454,+ -0.01108221054921885+ ]+ ]+ }+ },+ {+ "endpoints": [+ 3,+ 4+ ]+ },+ {+ "endpoints": [+ 4,+ 0+ ]+ }+ ],+ "label": "arm"+ },+ "right_sleeve_f": {+ "translation": [+ -37.644720948614996,+ 126.0618151988509,+ 17.5+ ],+ "rotation": [+ -0.0,+ 0.0,+ 45.483+ ],+ "vertices": [+ [+ 0,+ 0+ ],+ [+ 0,+ -21.050936276484872+ ],+ [+ 13.683885652227852,+ -21.050936276484872+ ],+ [+ 22.040633478135014,+ 0.0+ ]+ ],+ "edges": [+ {+ "endpoints": [+ 0,+ 1+ ]+ },+ {+ "endpoints": [+ 1,+ 2+ ]+ },+ {+ "endpoints": [+ 2,+ 3+ ],+ "curvature": {+ "type": "cubic",+ "params": [+ [+ 0.3219022519363623,+ 0.013843756921904194+ ],+ [+ 0.6202869150959737,+ -0.14175474188545475+ ]+ ]+ }+ },+ {+ "endpoints": [+ 3,+ 0+ ]+ }+ ],+ "label": "arm"+ }+ },+ "stitches": [+ [+ {+ "panel": "left_sleeve_f",+ "edge": 0+ },+ {+ "panel": "left_sleeve_b",+ "edge": 4+ }+ ],+ [+ {+ "panel": "right_ftorso",+ "edge": 0+ },+ {+ "panel": "left_ftorso",+ "edge": 6+ }+ ],+ [+ {+ "panel": "left_ftorso",+ "edge": 1+ },+ {+ "panel": "left_btorso",+ "edge": 4+ }+ ],+ [+ {+ "panel": "left_sleeve_f",+ "edge": 1+ },+ {+ "panel": "left_ftorso",+ "edge": 2+ }+ ],+ [+ {+ "panel": "right_sleeve_b",+ "edge": 1+ },+ {+ "panel": "right_ftorso",+ "edge": 3+ }+ ],+ [+ {+ "panel": "right_sleeve_f",+ "edge": 1+ },+ {+ "panel": "right_sleeve_b",+ "edge": 3+ }+ ],+ [+ {+ "panel": "left_sleeve_b",+ "edge": 2+ },+ {+ "panel": "left_btorso",+ "edge": 3+ }+ ],+ [+ {+ "panel": "left_sleeve_f",+ "edge": 2+ },+ {+ "panel": "left_sleeve_b",+ "edge": 1+ }+ ],+ [+ {+ "panel": "right_ftorso",+ "edge": 2+ },+ {+ "panel": "right_btorso",+ "edge": 3+ }+ ],+ [+ {+ "panel": "right_sleeve_b",+ "edge": 2+ },+ {+ "panel": "right_btorso",+ "edge": 2+ }+ ],+ [+ {+ "panel": "right_sleeve_f",+ "edge": 2+ },+ {+ "panel": "right_ftorso",+ "edge": 4+ }+ ],+ [+ {+ "panel": "left_sleeve_b",+ "edge": 3+ },+ {+ "panel": "left_ftorso",+ "edge": 3+ }+ ],+ [+ {+ "panel": "right_sleeve_f",+ "edge": 3+ },+ {+ "panel": "right_sleeve_b",+ "edge": 0+ }+ ],+ [+ {+ "panel": "left_ftorso",+ "edge": 4+ },+ {+ "panel": "left_btorso",+ "edge": 2+ }+ ],+ [+ {+ "panel": "right_btorso",+ "edge": 5+ },+ {+ "panel": "left_btorso",+ "edge": 0+ }+ ],+ [+ {+ "panel": "right_ftorso",+ "edge": 5+ },+ {+ "panel": "right_btorso",+ "edge": 1+ }+ ]+ ],+ "panel_order": [+ "left_btorso",+ "left_ftorso",+ "left_sleeve_b",+ "left_sleeve_f",+ "right_btorso",+ "right_ftorso",+ "right_sleeve_b",+ "right_sleeve_f"+ ]+ },+ "parameters": {},+ "parameter_order": [],+ "properties": {+ "curvature_coords": "relative",+ "normalize_panel_translation": false,+ "normalized_edge_loops": true,+ "units_in_meter": 100+ }+}\ No newline at end of filediff --git a/fixtures/Canonical/Garment/README.md b/fixtures/Canonical/Garment/README.mdindex a685b46f..61f92de0 100644--- a/fixtures/Canonical/Garment/README.md+++ b/fixtures/Canonical/Garment/README.md@@ -12,6 +12,39 @@ See `docs/public/firmament/garments.md` for commands, ownership and bounds.- `shorts.firmament`: mirrored Profile, four independently arranged panels,interpolated waist/leg rings and eight stitch interfaces. A tighter fitexperiment; consult retained drape evidence before using it as a baseline.+- `sundress.firmament`: one garment, two panels, four seams, open armholes,+ Rect2-derived named edits and figure-bound Concept fitting. Supply `--body`+ through the garment commands; standalone validation reports the missing input.+ The current static fit closes seams and passes sampled contact, but its 18.0%+ peak neckline stretch exceeds the 15% limit. It is an authoring specimen,+ not an accepted fit; retained evidence and limits are in the garment guide.+- `tshirt-dress.firmament`: the same authoring workflow with integrated sleeves+ and eight seams. An arrangement/contact experiment, not an accepted fit.+- `sundress-posed.firmament`: exactly the sundress cut and Rest-pose measurements,+ with declarative T-pose fitting and a half-second transition to A-pose. This+ isolates pose/motion from pattern changes; inspect all retained checkpoints+ before treating it as an accepted fit.`qualification.json` validates language/compilation. It does not certify a bodyfit. The actual local humanoid is supplied to `garment drape --body ...`.++## GarmentCode reference starters++`GarmentCode/` contains pinned MIT-credited upstream pattern JSON, design inputs,+independent curve samples and provenance. `garmentcode-dress.firmament` is its+editable translation; `garmentcode-dress-template.firmament` adds pure hem+customization. These qualify source geometry/interchange, not production drape.+See [workflow documentation](../../../docs/public/firmament/garmentcode.md).++`garmentcode-dress-guided.firmament` preserves the imported cut and combines+an erased Concept collar guide with T-pose sewing and a half-second transition+to A-pose. The guide releases before the transition, with 40 unsupported fitting+frames in the 60-frame experiment. It requires the actual figure artifact.+See [armhole investigation](../../../docs/public/firmament/garment-armhole-experiment.md)+for contact probes, checkpoint metrics and the unresolved strain limit.++`temporary-fitting.firmament` is an analytic authoring/solver witness: an erased+Concept plane supports named panel boundaries for five settling frames. The+shared drape path then releases the guide and requires 15 unsupported frames.+It introduces no permanent pins or additional material panel. See+[temporary fitting](../../../docs/public/firmament/garment-temporary-fitting.md).diff --git a/fixtures/Canonical/Garment/garmentcode-dress-guided.firmament b/fixtures/Canonical/Garment/garmentcode-dress-guided.firmamentnew file mode 100644index 00000000..bf5fa395--- /dev/null+++ b/fixtures/Canonical/Garment/garmentcode-dress-guided.firmament@@ -0,0 +1,230 @@+schema Garment+Pose fittingPose { figure: Anatolia; from: TPose; }+Pose wearingPose { figure: Anatolia; from: APose; }+PoseTransition lowerArms {+ from: fittingPose;+ to: wearingPose;+ duration: 0.5s;+ easing: SmoothStep;+}+Concept Struct fitting {+ FigureFit body { figure: Anatolia; pose: Rest; chestHeight: 1280mm; hipHeight: 960mm; }+ collarFloor: Plane {+ origin: [fitting.body.centerX, fitting.body.centerY, fitting.body.shoulderHeight + 45mm]+ normal: [0, 0, 1]+ }+}+// Imported from GarmentCode; MIT, copyright (c) 2024 Maria Korosteleva.+// Keep the source specification and its applicable license with this derivative.+// Controlled dressing experiment: unchanged GarmentCode cut, raised arrangement,+// temporary Concept collar support, T-pose sewing, then A-pose wearing.+// This is a diagnostic authoring specimen, not an accepted production fit.+// Input SHA-256: f70b61d286c1dcb4d38a0bf6585c95a6b54dbbceed66b8630a9908f14f416731+// Local XY remains the flat rest pattern. Placement maps upstream Y-up to Aetheris Z-up.++Feature left_btorsoPattern() -> Profile {+ Point2 vertex0 { position: [0mm, 0mm] }+ Point2 vertex1 { position: [0mm, 811.608601383663mm] }+ Point2 vertex2 { position: [108.188mm, 868.097585456578mm] }+ Point2 vertex3 { position: [172.284mm, 842.619575355104mm] }+ Point2 vertex4 { position: [250.299525mm, 658.204775355104mm] }+ Point2 vertex5 { position: [250.299525mm, 0mm] }+ Line2 edge5Guide { from: vertex0; to: vertex5 }+ Line2 edge4Guide { from: vertex5; to: vertex4 }+ Point2 edge3_left_armholeControl1 { position: [170.15124mm, 667.782301605104mm] }+ Point2 edge3_left_armholeControl2 { position: [174.4088025mm, 734.809070355104mm] }+ CubicBezier2 edge3_left_armholeGuide { from: vertex4; control1: edge3_left_armholeControl1; control2: edge3_left_armholeControl2; to: vertex3 }+ Line2 edge2Guide { from: vertex3; to: vertex2 }+ Point2 edge1_left_collarCenter { position: [-0mm, 943.454207301827mm] }+ Circle2 edge1_left_collarGuide { center: edge1_left_collarCenter; radius: 131.845605918164mm }+ Line2 edge0Guide { from: vertex1; to: vertex0 }+ return Profile {+ Loop Outer {+ Segment edge5 { trace: edge5Guide; from: vertex0; to: vertex5 }+ Segment edge4 { trace: edge4Guide; from: vertex5; to: vertex4 }+ Segment edge3_left_armhole { trace: edge3_left_armholeGuide; from: vertex4; to: vertex3 }+ Segment edge2 { trace: edge2Guide; from: vertex3; to: vertex2 }+ Segment edge1_left_collar { trace: edge1_left_collarGuide; from: vertex2; to: vertex1; sweep: Clockwise }+ Segment edge0 { trace: edge0Guide; from: vertex1; to: vertex0 }+ }+ }+}+Feature left_btorsoCut = left_btorsoPattern();++Feature left_ftorsoPattern() -> Profile {+ Point2 vertex0 { position: [0mm, 0mm] }+ Point2 vertex1 { position: [273.86415mm, 0mm] }+ Point2 vertex2 { position: [273.86415mm, 658.650827790934mm] }+ Point2 vertex3 { position: [172.284mm, 843.065627790934mm] }+ Point2 vertex4 { position: [108.188mm, 868.543624411852mm] }+ Point2 vertex5 { position: [0mm, 712.05802612589mm] }+ Line2 edge0Guide { from: vertex0; to: vertex1 }+ Line2 edge1Guide { from: vertex1; to: vertex2 }+ Point2 edge2_left_armholeControl1 { position: [189.00294mm, 659.980735290934mm] }+ Point2 edge2_left_armholeControl2 { position: [186.191115mm, 730.542197790934mm] }+ CubicBezier2 edge2_left_armholeGuide { from: vertex2; control1: edge2_left_armholeControl1; control2: edge2_left_armholeControl2; to: vertex3 }+ Line2 edge3Guide { from: vertex3; to: vertex4 }+ Point2 edge4_left_collarCenter { position: [0mm, 827.699293473629mm] }+ Circle2 edge4_left_collarGuide { center: edge4_left_collarCenter; radius: 115.641267347738mm }+ Line2 edge5Guide { from: vertex5; to: vertex0 }+ return Profile {+ Loop Outer {+ Segment edge0 { trace: edge0Guide; from: vertex0; to: vertex1 }+ Segment edge1 { trace: edge1Guide; from: vertex1; to: vertex2 }+ Segment edge2_left_armhole { trace: edge2_left_armholeGuide; from: vertex2; to: vertex3 }+ Segment edge3 { trace: edge3Guide; from: vertex3; to: vertex4 }+ Segment edge4_left_collar { trace: edge4_left_collarGuide; from: vertex4; to: vertex5; sweep: Clockwise }+ Segment edge5 { trace: edge5Guide; from: vertex5; to: vertex0 }+ }+ }+}+Feature left_ftorsoCut = left_ftorsoPattern();++Feature right_btorsoPattern() -> Profile {+ Point2 vertex0 { position: [0mm, 0mm] }+ Point2 vertex1 { position: [-250.299525mm, 0mm] }+ Point2 vertex2 { position: [-250.299525mm, 658.204775355104mm] }+ Point2 vertex3 { position: [-172.284mm, 842.619575355104mm] }+ Point2 vertex4 { position: [-108.188mm, 868.097585456578mm] }+ Point2 vertex5 { position: [0mm, 811.608601383663mm] }+ Line2 edge5Guide { from: vertex0; to: vertex5 }+ Point2 edge4_right_collarCenter { position: [0mm, 943.454207301827mm] }+ Circle2 edge4_right_collarGuide { center: edge4_right_collarCenter; radius: 131.845605918164mm }+ Line2 edge3Guide { from: vertex4; to: vertex3 }+ Point2 edge2_right_armholeControl1 { position: [-174.4088025mm, 734.809070355104mm] }+ Point2 edge2_right_armholeControl2 { position: [-170.15124mm, 667.782301605104mm] }+ CubicBezier2 edge2_right_armholeGuide { from: vertex3; control1: edge2_right_armholeControl1; control2: edge2_right_armholeControl2; to: vertex2 }+ Line2 edge1Guide { from: vertex2; to: vertex1 }+ Line2 edge0Guide { from: vertex1; to: vertex0 }+ return Profile {+ Loop Outer {+ Segment edge5 { trace: edge5Guide; from: vertex0; to: vertex5 }+ Segment edge4_right_collar { trace: edge4_right_collarGuide; from: vertex5; to: vertex4; sweep: Clockwise }+ Segment edge3 { trace: edge3Guide; from: vertex4; to: vertex3 }+ Segment edge2_right_armhole { trace: edge2_right_armholeGuide; from: vertex3; to: vertex2 }+ Segment edge1 { trace: edge1Guide; from: vertex2; to: vertex1 }+ Segment edge0 { trace: edge0Guide; from: vertex1; to: vertex0 }+ }+ }+}+Feature right_btorsoCut = right_btorsoPattern();++Feature right_ftorsoPattern() -> Profile {+ Point2 vertex0 { position: [0mm, 0mm] }+ Point2 vertex1 { position: [0mm, 712.05802612589mm] }+ Point2 vertex2 { position: [-108.188mm, 868.543624411852mm] }+ Point2 vertex3 { position: [-172.284mm, 843.065627790934mm] }+ Point2 vertex4 { position: [-273.86415mm, 658.650827790934mm] }+ Point2 vertex5 { position: [-273.86415mm, 0mm] }+ Line2 edge0Guide { from: vertex0; to: vertex1 }+ Point2 edge1_right_collarCenter { position: [-0mm, 827.699293473629mm] }+ Circle2 edge1_right_collarGuide { center: edge1_right_collarCenter; radius: 115.641267347738mm }+ Line2 edge2Guide { from: vertex2; to: vertex3 }+ Point2 edge3_right_armholeControl1 { position: [-186.191115mm, 730.542197790934mm] }+ Point2 edge3_right_armholeControl2 { position: [-189.00294mm, 659.980735290934mm] }+ CubicBezier2 edge3_right_armholeGuide { from: vertex3; control1: edge3_right_armholeControl1; control2: edge3_right_armholeControl2; to: vertex4 }+ Line2 edge4Guide { from: vertex4; to: vertex5 }+ Line2 edge5Guide { from: vertex5; to: vertex0 }+ return Profile {+ Loop Outer {+ Segment edge0 { trace: edge0Guide; from: vertex0; to: vertex1 }+ Segment edge1_right_collar { trace: edge1_right_collarGuide; from: vertex1; to: vertex2; sweep: Clockwise }+ Segment edge2 { trace: edge2Guide; from: vertex2; to: vertex3 }+ Segment edge3_right_armhole { trace: edge3_right_armholeGuide; from: vertex3; to: vertex4 }+ Segment edge4 { trace: edge4Guide; from: vertex4; to: vertex5 }+ Segment edge5 { trace: edge5Guide; from: vertex5; to: vertex0 }+ }+ }+}+Feature right_ftorsoCut = right_ftorsoPattern();+Garment ImportedGarment {+ meshSize: 60mm;+ // Aetheris cotton defaults; upstream JSON does not specify fabric physics.+ Fabric cotton {+ thickness: 2mm;+ arealDensity: 0.2;+ warpCompliance: 0.00000001;+ weftCompliance: 0.00000001;+ diagonalCompliance: 0.00000004;+ }+ Panel left_btorso {+ profile: left_btorsoCut;+ origin: [0mm, -250mm, 645.535950181744mm];+ u: [1, 0, 0];+ v: [0, 0, 1];+ grain: [0, 1];+ }+ Panel left_ftorso {+ profile: left_ftorsoCut;+ origin: [0mm, 300mm, 645.089908235091mm];+ u: [1, 0, 0];+ v: [0, 0, 1];+ grain: [0, 1];+ }+ Panel right_btorso {+ profile: right_btorsoCut;+ origin: [0mm, -250mm, 645.535950181744mm];+ u: [1, 0, 0];+ v: [0, 0, 1];+ grain: [0, 1];+ }+ Panel right_ftorso {+ profile: right_ftorsoCut;+ origin: [0mm, 300mm, 645.089908235091mm];+ u: [1, 0, 0];+ v: [0, 0, 1];+ grain: [0, 1];+ }+ Interface<Stitch> seam0 {+ a: right_ftorso.edges.edge0;+ b: left_ftorso.edges.edge5;+ orientation: Reversed;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0;+ }+ Interface<Stitch> seam1 {+ a: left_ftorso.edges.edge1;+ b: left_btorso.edges.edge4;+ orientation: Same;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0.0006772214;+ }+ Interface<Stitch> seam2 {+ a: right_ftorso.edges.edge2;+ b: right_btorso.edges.edge3;+ orientation: Same;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0.000000072194;+ }+ Interface<Stitch> seam3 {+ a: left_ftorso.edges.edge3;+ b: left_btorso.edges.edge2;+ orientation: Same;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0.000000072194;+ }+ Interface<Stitch> seam4 {+ a: right_ftorso.edges.edge4;+ b: right_btorso.edges.edge1;+ orientation: Same;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0.0006772214;+ }+ Interface<Stitch> seam5 {+ a: right_btorso.edges.edge5;+ b: left_btorso.edges.edge0;+ orientation: Reversed;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0;+ }+ Fitting collar {+ on: fitting.collarFloor;+ edges: [left_ftorso.edges.edge4_left_collar, right_ftorso.edges.edge1_right_collar,+ left_btorso.edges.edge1_left_collar, right_btorso.edges.edge4_right_collar];+ compliance: 0.00000001;+ releaseAfter: 20;+ }+ Drape { figure: Anatolia; pose: fittingPose; transition: lowerArms; }+}++diff --git a/fixtures/Canonical/Garment/garmentcode-dress-template.firmament b/fixtures/Canonical/Garment/garmentcode-dress-template.firmamentnew file mode 100644index 00000000..33316b4e--- /dev/null+++ b/fixtures/Canonical/Garment/garmentcode-dress-template.firmament@@ -0,0 +1,204 @@+schema Garment+// Imported from GarmentCode; MIT, copyright (c) 2024 Maria Korosteleva.+// Keep the source specification and its applicable license with this derivative.+// Input SHA-256: f70b61d286c1dcb4d38a0bf6585c95a6b54dbbceed66b8630a9908f14f416731+// Known GarmentCode Shirt block, extended into a sleeveless dress.+// hemDrop changes only the hem; armhole, neck and shoulder construction stay fixed.+// Local XY remains the flat rest pattern. Placement maps upstream Y-up to Aetheris Z-up.++Feature left_btorsoPattern(hemDrop: Length = 0mm) -> Profile {+ Point2 vertex0 { position: [0mm, 0mm - hemDrop] }+ Point2 vertex1 { position: [0mm, 811.608601383663mm] }+ Point2 vertex2 { position: [108.188mm, 868.097585456578mm] }+ Point2 vertex3 { position: [172.284mm, 842.619575355104mm] }+ Point2 vertex4 { position: [250.299525mm, 658.204775355104mm] }+ Point2 vertex5 { position: [250.299525mm, 0mm - hemDrop] }+ Line2 edge5Guide { from: vertex0; to: vertex5 }+ Line2 edge4Guide { from: vertex5; to: vertex4 }+ Point2 edge3_left_armholeControl1 { position: [170.15124mm, 667.782301605104mm] }+ Point2 edge3_left_armholeControl2 { position: [174.4088025mm, 734.809070355104mm] }+ CubicBezier2 edge3_left_armholeGuide { from: vertex4; control1: edge3_left_armholeControl1; control2: edge3_left_armholeControl2; to: vertex3 }+ Line2 edge2Guide { from: vertex3; to: vertex2 }+ Point2 edge1_left_collarCenter { position: [-0mm, 943.454207301827mm] }+ Circle2 edge1_left_collarGuide { center: edge1_left_collarCenter; radius: 131.845605918164mm }+ Line2 edge0Guide { from: vertex1; to: vertex0 }+ return Profile {+ Loop Outer {+ Segment edge5 { trace: edge5Guide; from: vertex0; to: vertex5 }+ Segment edge4 { trace: edge4Guide; from: vertex5; to: vertex4 }+ Segment edge3_left_armhole { trace: edge3_left_armholeGuide; from: vertex4; to: vertex3 }+ Segment edge2 { trace: edge2Guide; from: vertex3; to: vertex2 }+ Segment edge1_left_collar { trace: edge1_left_collarGuide; from: vertex2; to: vertex1; sweep: Clockwise }+ Segment edge0 { trace: edge0Guide; from: vertex1; to: vertex0 }+ }+ }+}+Feature left_btorsoCut = left_btorsoPattern();++Feature left_ftorsoPattern(hemDrop: Length = 0mm) -> Profile {+ Point2 vertex0 { position: [0mm, 0mm - hemDrop] }+ Point2 vertex1 { position: [273.86415mm, 0mm - hemDrop] }+ Point2 vertex2 { position: [273.86415mm, 658.650827790934mm] }+ Point2 vertex3 { position: [172.284mm, 843.065627790934mm] }+ Point2 vertex4 { position: [108.188mm, 868.543624411852mm] }+ Point2 vertex5 { position: [0mm, 712.05802612589mm] }+ Line2 edge0Guide { from: vertex0; to: vertex1 }+ Line2 edge1Guide { from: vertex1; to: vertex2 }+ Point2 edge2_left_armholeControl1 { position: [189.00294mm, 659.980735290934mm] }+ Point2 edge2_left_armholeControl2 { position: [186.191115mm, 730.542197790934mm] }+ CubicBezier2 edge2_left_armholeGuide { from: vertex2; control1: edge2_left_armholeControl1; control2: edge2_left_armholeControl2; to: vertex3 }+ Line2 edge3Guide { from: vertex3; to: vertex4 }+ Point2 edge4_left_collarCenter { position: [0mm, 827.699293473629mm] }+ Circle2 edge4_left_collarGuide { center: edge4_left_collarCenter; radius: 115.641267347738mm }+ Line2 edge5Guide { from: vertex5; to: vertex0 }+ return Profile {+ Loop Outer {+ Segment edge0 { trace: edge0Guide; from: vertex0; to: vertex1 }+ Segment edge1 { trace: edge1Guide; from: vertex1; to: vertex2 }+ Segment edge2_left_armhole { trace: edge2_left_armholeGuide; from: vertex2; to: vertex3 }+ Segment edge3 { trace: edge3Guide; from: vertex3; to: vertex4 }+ Segment edge4_left_collar { trace: edge4_left_collarGuide; from: vertex4; to: vertex5; sweep: Clockwise }+ Segment edge5 { trace: edge5Guide; from: vertex5; to: vertex0 }+ }+ }+}+Feature left_ftorsoCut = left_ftorsoPattern();++Feature right_btorsoPattern(hemDrop: Length = 0mm) -> Profile {+ Point2 vertex0 { position: [0mm, 0mm - hemDrop] }+ Point2 vertex1 { position: [-250.299525mm, 0mm - hemDrop] }+ Point2 vertex2 { position: [-250.299525mm, 658.204775355104mm] }+ Point2 vertex3 { position: [-172.284mm, 842.619575355104mm] }+ Point2 vertex4 { position: [-108.188mm, 868.097585456578mm] }+ Point2 vertex5 { position: [0mm, 811.608601383663mm] }+ Line2 edge5Guide { from: vertex0; to: vertex5 }+ Point2 edge4_right_collarCenter { position: [0mm, 943.454207301827mm] }+ Circle2 edge4_right_collarGuide { center: edge4_right_collarCenter; radius: 131.845605918164mm }+ Line2 edge3Guide { from: vertex4; to: vertex3 }+ Point2 edge2_right_armholeControl1 { position: [-174.4088025mm, 734.809070355104mm] }+ Point2 edge2_right_armholeControl2 { position: [-170.15124mm, 667.782301605104mm] }+ CubicBezier2 edge2_right_armholeGuide { from: vertex3; control1: edge2_right_armholeControl1; control2: edge2_right_armholeControl2; to: vertex2 }+ Line2 edge1Guide { from: vertex2; to: vertex1 }+ Line2 edge0Guide { from: vertex1; to: vertex0 }+ return Profile {+ Loop Outer {+ Segment edge5 { trace: edge5Guide; from: vertex0; to: vertex5 }+ Segment edge4_right_collar { trace: edge4_right_collarGuide; from: vertex5; to: vertex4; sweep: Clockwise }+ Segment edge3 { trace: edge3Guide; from: vertex4; to: vertex3 }+ Segment edge2_right_armhole { trace: edge2_right_armholeGuide; from: vertex3; to: vertex2 }+ Segment edge1 { trace: edge1Guide; from: vertex2; to: vertex1 }+ Segment edge0 { trace: edge0Guide; from: vertex1; to: vertex0 }+ }+ }+}+Feature right_btorsoCut = right_btorsoPattern();++Feature right_ftorsoPattern(hemDrop: Length = 0mm) -> Profile {+ Point2 vertex0 { position: [0mm, 0mm - hemDrop] }+ Point2 vertex1 { position: [0mm, 712.05802612589mm] }+ Point2 vertex2 { position: [-108.188mm, 868.543624411852mm] }+ Point2 vertex3 { position: [-172.284mm, 843.065627790934mm] }+ Point2 vertex4 { position: [-273.86415mm, 658.650827790934mm] }+ Point2 vertex5 { position: [-273.86415mm, 0mm - hemDrop] }+ Line2 edge0Guide { from: vertex0; to: vertex1 }+ Point2 edge1_right_collarCenter { position: [-0mm, 827.699293473629mm] }+ Circle2 edge1_right_collarGuide { center: edge1_right_collarCenter; radius: 115.641267347738mm }+ Line2 edge2Guide { from: vertex2; to: vertex3 }+ Point2 edge3_right_armholeControl1 { position: [-186.191115mm, 730.542197790934mm] }+ Point2 edge3_right_armholeControl2 { position: [-189.00294mm, 659.980735290934mm] }+ CubicBezier2 edge3_right_armholeGuide { from: vertex3; control1: edge3_right_armholeControl1; control2: edge3_right_armholeControl2; to: vertex4 }+ Line2 edge4Guide { from: vertex4; to: vertex5 }+ Line2 edge5Guide { from: vertex5; to: vertex0 }+ return Profile {+ Loop Outer {+ Segment edge0 { trace: edge0Guide; from: vertex0; to: vertex1 }+ Segment edge1_right_collar { trace: edge1_right_collarGuide; from: vertex1; to: vertex2; sweep: Clockwise }+ Segment edge2 { trace: edge2Guide; from: vertex2; to: vertex3 }+ Segment edge3_right_armhole { trace: edge3_right_armholeGuide; from: vertex3; to: vertex4 }+ Segment edge4 { trace: edge4Guide; from: vertex4; to: vertex5 }+ Segment edge5 { trace: edge5Guide; from: vertex5; to: vertex0 }+ }+ }+}+Feature right_ftorsoCut = right_ftorsoPattern();+Garment ImportedGarment {+ meshSize: 60mm;+ // Aetheris cotton defaults; upstream JSON does not specify fabric physics.+ Fabric cotton {+ thickness: 2mm;+ arealDensity: 0.2;+ warpCompliance: 0.00000001;+ weftCompliance: 0.00000001;+ diagonalCompliance: 0.00000004;+ }+ Panel left_btorso {+ profile: left_btorsoCut;+ origin: [0mm, -250mm, 545.535950181744mm];+ u: [1, 0, 0];+ v: [0, 0, 1];+ grain: [0, 1];+ }+ Panel left_ftorso {+ profile: left_ftorsoCut;+ origin: [0mm, 300mm, 545.089908235091mm];+ u: [1, 0, 0];+ v: [0, 0, 1];+ grain: [0, 1];+ }+ Panel right_btorso {+ profile: right_btorsoCut;+ origin: [0mm, -250mm, 545.535950181744mm];+ u: [1, 0, 0];+ v: [0, 0, 1];+ grain: [0, 1];+ }+ Panel right_ftorso {+ profile: right_ftorsoCut;+ origin: [0mm, 300mm, 545.089908235091mm];+ u: [1, 0, 0];+ v: [0, 0, 1];+ grain: [0, 1];+ }+ Interface<Stitch> seam0 {+ a: right_ftorso.edges.edge0;+ b: left_ftorso.edges.edge5;+ orientation: Reversed;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0;+ }+ Interface<Stitch> seam1 {+ a: left_ftorso.edges.edge1;+ b: left_btorso.edges.edge4;+ orientation: Same;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0.0006772214;+ }+ Interface<Stitch> seam2 {+ a: right_ftorso.edges.edge2;+ b: right_btorso.edges.edge3;+ orientation: Same;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0.000000072194;+ }+ Interface<Stitch> seam3 {+ a: left_ftorso.edges.edge3;+ b: left_btorso.edges.edge2;+ orientation: Same;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0.000000072194;+ }+ Interface<Stitch> seam4 {+ a: right_ftorso.edges.edge4;+ b: right_btorso.edges.edge1;+ orientation: Same;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0.0006772214;+ }+ Interface<Stitch> seam5 {+ a: right_btorso.edges.edge5;+ b: left_btorso.edges.edge0;+ orientation: Reversed;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0;+ }+}diff --git a/fixtures/Canonical/Garment/garmentcode-dress.firmament b/fixtures/Canonical/Garment/garmentcode-dress.firmamentnew file mode 100644index 00000000..863996ce--- /dev/null+++ b/fixtures/Canonical/Garment/garmentcode-dress.firmament@@ -0,0 +1,202 @@+schema Garment+// Imported from GarmentCode; MIT, copyright (c) 2024 Maria Korosteleva.+// Keep the source specification and its applicable license with this derivative.+// Input SHA-256: f70b61d286c1dcb4d38a0bf6585c95a6b54dbbceed66b8630a9908f14f416731+// Local XY remains the flat rest pattern. Placement maps upstream Y-up to Aetheris Z-up.++Feature left_btorsoPattern() -> Profile {+ Point2 vertex0 { position: [0mm, 0mm] }+ Point2 vertex1 { position: [0mm, 811.608601383663mm] }+ Point2 vertex2 { position: [108.188mm, 868.097585456578mm] }+ Point2 vertex3 { position: [172.284mm, 842.619575355104mm] }+ Point2 vertex4 { position: [250.299525mm, 658.204775355104mm] }+ Point2 vertex5 { position: [250.299525mm, 0mm] }+ Line2 edge5Guide { from: vertex0; to: vertex5 }+ Line2 edge4Guide { from: vertex5; to: vertex4 }+ Point2 edge3_left_armholeControl1 { position: [170.15124mm, 667.782301605104mm] }+ Point2 edge3_left_armholeControl2 { position: [174.4088025mm, 734.809070355104mm] }+ CubicBezier2 edge3_left_armholeGuide { from: vertex4; control1: edge3_left_armholeControl1; control2: edge3_left_armholeControl2; to: vertex3 }+ Line2 edge2Guide { from: vertex3; to: vertex2 }+ Point2 edge1_left_collarCenter { position: [-0mm, 943.454207301827mm] }+ Circle2 edge1_left_collarGuide { center: edge1_left_collarCenter; radius: 131.845605918164mm }+ Line2 edge0Guide { from: vertex1; to: vertex0 }+ return Profile {+ Loop Outer {+ Segment edge5 { trace: edge5Guide; from: vertex0; to: vertex5 }+ Segment edge4 { trace: edge4Guide; from: vertex5; to: vertex4 }+ Segment edge3_left_armhole { trace: edge3_left_armholeGuide; from: vertex4; to: vertex3 }+ Segment edge2 { trace: edge2Guide; from: vertex3; to: vertex2 }+ Segment edge1_left_collar { trace: edge1_left_collarGuide; from: vertex2; to: vertex1; sweep: Clockwise }+ Segment edge0 { trace: edge0Guide; from: vertex1; to: vertex0 }+ }+ }+}+Feature left_btorsoCut = left_btorsoPattern();++Feature left_ftorsoPattern() -> Profile {+ Point2 vertex0 { position: [0mm, 0mm] }+ Point2 vertex1 { position: [273.86415mm, 0mm] }+ Point2 vertex2 { position: [273.86415mm, 658.650827790934mm] }+ Point2 vertex3 { position: [172.284mm, 843.065627790934mm] }+ Point2 vertex4 { position: [108.188mm, 868.543624411852mm] }+ Point2 vertex5 { position: [0mm, 712.05802612589mm] }+ Line2 edge0Guide { from: vertex0; to: vertex1 }+ Line2 edge1Guide { from: vertex1; to: vertex2 }+ Point2 edge2_left_armholeControl1 { position: [189.00294mm, 659.980735290934mm] }+ Point2 edge2_left_armholeControl2 { position: [186.191115mm, 730.542197790934mm] }+ CubicBezier2 edge2_left_armholeGuide { from: vertex2; control1: edge2_left_armholeControl1; control2: edge2_left_armholeControl2; to: vertex3 }+ Line2 edge3Guide { from: vertex3; to: vertex4 }+ Point2 edge4_left_collarCenter { position: [0mm, 827.699293473629mm] }+ Circle2 edge4_left_collarGuide { center: edge4_left_collarCenter; radius: 115.641267347738mm }+ Line2 edge5Guide { from: vertex5; to: vertex0 }+ return Profile {+ Loop Outer {+ Segment edge0 { trace: edge0Guide; from: vertex0; to: vertex1 }+ Segment edge1 { trace: edge1Guide; from: vertex1; to: vertex2 }+ Segment edge2_left_armhole { trace: edge2_left_armholeGuide; from: vertex2; to: vertex3 }+ Segment edge3 { trace: edge3Guide; from: vertex3; to: vertex4 }+ Segment edge4_left_collar { trace: edge4_left_collarGuide; from: vertex4; to: vertex5; sweep: Clockwise }+ Segment edge5 { trace: edge5Guide; from: vertex5; to: vertex0 }+ }+ }+}+Feature left_ftorsoCut = left_ftorsoPattern();++Feature right_btorsoPattern() -> Profile {+ Point2 vertex0 { position: [0mm, 0mm] }+ Point2 vertex1 { position: [-250.299525mm, 0mm] }+ Point2 vertex2 { position: [-250.299525mm, 658.204775355104mm] }+ Point2 vertex3 { position: [-172.284mm, 842.619575355104mm] }+ Point2 vertex4 { position: [-108.188mm, 868.097585456578mm] }+ Point2 vertex5 { position: [0mm, 811.608601383663mm] }+ Line2 edge5Guide { from: vertex0; to: vertex5 }+ Point2 edge4_right_collarCenter { position: [0mm, 943.454207301827mm] }+ Circle2 edge4_right_collarGuide { center: edge4_right_collarCenter; radius: 131.845605918164mm }+ Line2 edge3Guide { from: vertex4; to: vertex3 }+ Point2 edge2_right_armholeControl1 { position: [-174.4088025mm, 734.809070355104mm] }+ Point2 edge2_right_armholeControl2 { position: [-170.15124mm, 667.782301605104mm] }+ CubicBezier2 edge2_right_armholeGuide { from: vertex3; control1: edge2_right_armholeControl1; control2: edge2_right_armholeControl2; to: vertex2 }+ Line2 edge1Guide { from: vertex2; to: vertex1 }+ Line2 edge0Guide { from: vertex1; to: vertex0 }+ return Profile {+ Loop Outer {+ Segment edge5 { trace: edge5Guide; from: vertex0; to: vertex5 }+ Segment edge4_right_collar { trace: edge4_right_collarGuide; from: vertex5; to: vertex4; sweep: Clockwise }+ Segment edge3 { trace: edge3Guide; from: vertex4; to: vertex3 }+ Segment edge2_right_armhole { trace: edge2_right_armholeGuide; from: vertex3; to: vertex2 }+ Segment edge1 { trace: edge1Guide; from: vertex2; to: vertex1 }+ Segment edge0 { trace: edge0Guide; from: vertex1; to: vertex0 }+ }+ }+}+Feature right_btorsoCut = right_btorsoPattern();++Feature right_ftorsoPattern() -> Profile {+ Point2 vertex0 { position: [0mm, 0mm] }+ Point2 vertex1 { position: [0mm, 712.05802612589mm] }+ Point2 vertex2 { position: [-108.188mm, 868.543624411852mm] }+ Point2 vertex3 { position: [-172.284mm, 843.065627790934mm] }+ Point2 vertex4 { position: [-273.86415mm, 658.650827790934mm] }+ Point2 vertex5 { position: [-273.86415mm, 0mm] }+ Line2 edge0Guide { from: vertex0; to: vertex1 }+ Point2 edge1_right_collarCenter { position: [-0mm, 827.699293473629mm] }+ Circle2 edge1_right_collarGuide { center: edge1_right_collarCenter; radius: 115.641267347738mm }+ Line2 edge2Guide { from: vertex2; to: vertex3 }+ Point2 edge3_right_armholeControl1 { position: [-186.191115mm, 730.542197790934mm] }+ Point2 edge3_right_armholeControl2 { position: [-189.00294mm, 659.980735290934mm] }+ CubicBezier2 edge3_right_armholeGuide { from: vertex3; control1: edge3_right_armholeControl1; control2: edge3_right_armholeControl2; to: vertex4 }+ Line2 edge4Guide { from: vertex4; to: vertex5 }+ Line2 edge5Guide { from: vertex5; to: vertex0 }+ return Profile {+ Loop Outer {+ Segment edge0 { trace: edge0Guide; from: vertex0; to: vertex1 }+ Segment edge1_right_collar { trace: edge1_right_collarGuide; from: vertex1; to: vertex2; sweep: Clockwise }+ Segment edge2 { trace: edge2Guide; from: vertex2; to: vertex3 }+ Segment edge3_right_armhole { trace: edge3_right_armholeGuide; from: vertex3; to: vertex4 }+ Segment edge4 { trace: edge4Guide; from: vertex4; to: vertex5 }+ Segment edge5 { trace: edge5Guide; from: vertex5; to: vertex0 }+ }+ }+}+Feature right_ftorsoCut = right_ftorsoPattern();+Garment ImportedGarment {+ meshSize: 60mm;+ // Aetheris cotton defaults; upstream JSON does not specify fabric physics.+ Fabric cotton {+ thickness: 2mm;+ arealDensity: 0.2;+ warpCompliance: 0.00000001;+ weftCompliance: 0.00000001;+ diagonalCompliance: 0.00000004;+ }+ Panel left_btorso {+ profile: left_btorsoCut;+ origin: [0mm, -250mm, 545.535950181744mm];+ u: [1, 0, 0];+ v: [0, 0, 1];+ grain: [0, 1];+ }+ Panel left_ftorso {+ profile: left_ftorsoCut;+ origin: [0mm, 300mm, 545.089908235091mm];+ u: [1, 0, 0];+ v: [0, 0, 1];+ grain: [0, 1];+ }+ Panel right_btorso {+ profile: right_btorsoCut;+ origin: [0mm, -250mm, 545.535950181744mm];+ u: [1, 0, 0];+ v: [0, 0, 1];+ grain: [0, 1];+ }+ Panel right_ftorso {+ profile: right_ftorsoCut;+ origin: [0mm, 300mm, 545.089908235091mm];+ u: [1, 0, 0];+ v: [0, 0, 1];+ grain: [0, 1];+ }+ Interface<Stitch> seam0 {+ a: right_ftorso.edges.edge0;+ b: left_ftorso.edges.edge5;+ orientation: Reversed;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0;+ }+ Interface<Stitch> seam1 {+ a: left_ftorso.edges.edge1;+ b: left_btorso.edges.edge4;+ orientation: Same;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0.0006772214;+ }+ Interface<Stitch> seam2 {+ a: right_ftorso.edges.edge2;+ b: right_btorso.edges.edge3;+ orientation: Same;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0.000000072194;+ }+ Interface<Stitch> seam3 {+ a: left_ftorso.edges.edge3;+ b: left_btorso.edges.edge2;+ orientation: Same;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0.000000072194;+ }+ Interface<Stitch> seam4 {+ a: right_ftorso.edges.edge4;+ b: right_btorso.edges.edge1;+ orientation: Same;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0.0006772214;+ }+ Interface<Stitch> seam5 {+ a: right_btorso.edges.edge5;+ b: left_btorso.edges.edge0;+ orientation: Reversed;+ // Measured mismatch in the upstream pattern, explicitly retained as ease.+ ease: 0;+ }+}diff --git a/fixtures/Canonical/Garment/sundress-posed.firmament b/fixtures/Canonical/Garment/sundress-posed.firmamentnew file mode 100644index 00000000..9143cd2b--- /dev/null+++ b/fixtures/Canonical/Garment/sundress-posed.firmament@@ -0,0 +1,79 @@+schema Garment++Pose fitting { figure: Anatolia; from: TPose; }+Pose wearing { figure: Anatolia; from: APose; }+PoseTransition lowerArms {+ from: fitting;+ to: wearing;+ duration: 0.5s;+ easing: SmoothStep;+}+++// A single loose dress. Armholes stay open; there is no sleeve threading or layering.+Concept Struct dressLayout {+ FigureFit body { figure: Anatolia; pose: Rest; chestHeight: 1280mm; hipHeight: 960mm; }+ Points<Point3> arrangement {+ front: Point3(0mm, dressLayout.body.centerY, 650mm);+ back: Point3(0mm, dressLayout.body.centerY, 650mm);+ }+}++Feature SundressPanel(bodyWidth: Length, shoulderWidth: Length,+ height: Length = 880mm, necklineWidth: Length = 210mm, necklineDepth: Length = 80mm) -> Profile {+ let halfShoulder: Length = shoulderWidth / 2;+ let halfBody: Length = bodyWidth / 2;+ let halfHeight: Length = height / 2;+ let pitHeight: Length = height - 240mm;+ let shoulderRise: Length = height - 120mm;+ let halfNeck: Length = necklineWidth / 2;+ let neckStart: Length = halfShoulder - halfNeck;+ let neckEnd: Length = halfShoulder + halfNeck;+ let neckBottom: Length = height - necklineDepth;+ Rect2 blank { center: [0mm, halfHeight]; size: [shoulderWidth, height] }+ return Profile {+ from: blank;+ Replace rightCut {+ on: blank.Right;+ through: [[halfBody, 0mm], [halfBody, pitHeight], [halfShoulder, shoulderRise]];+ interpolation: Linear;+ spanNames: [rightHem, rightSide, rightArmholeLower, rightArmholeUpper];+ }+ Replace leftCut {+ on: blank.Left;+ through: [[-halfShoulder, shoulderRise], [-halfBody, pitHeight], [-halfBody, 0mm]];+ interpolation: Linear;+ spanNames: [leftArmholeUpper, leftArmholeLower, leftSide, leftHem];+ }+ Replace neckline {+ on: blank.Top; range: [neckStart, neckEnd]; through: [[0mm, neckBottom]];+ }+ }+}+Feature frontCut = SundressPanel(bodyWidth: dressLayout.body.torsoCircumference / 2 + 160mm,+ shoulderWidth: dressLayout.body.shoulderWidth + 30mm);+Feature backCut = SundressPanel(bodyWidth: dressLayout.body.torsoCircumference / 2 + 160mm,+ shoulderWidth: dressLayout.body.shoulderWidth + 30mm, necklineDepth: 40mm);++Garment Sundress {+ meshSize: 65mm;+ Fabric cotton {+ thickness: 2mm; arealDensity: 0.2;+ warpCompliance: 0.00000001; weftCompliance: 0.00000001; diagonalCompliance: 0.00000004;+ }+ Panel front {+ profile: frontCut; origin: dressLayout.arrangement.front;+ u: [1, 0, 0]; v: [0, 0, 1]; grain: [0, 1];+ wrapRadius: (dressLayout.body.torsoCircumference / 2 + 160mm) / 3.141592653589793;+ }+ Panel back {+ profile: backCut; origin: dressLayout.arrangement.back;+ u: [-1, 0, 0]; v: [0, 0, 1]; grain: [0, 1];+ wrapRadius: (dressLayout.body.torsoCircumference / 2 + 160mm) / 3.141592653589793;+ }+ Interface<Stitch> rightSide { a: front.edges.rightSide; b: back.edges.leftSide; orientation: Reversed; }+ Interface<Stitch> leftSide { a: front.edges.leftSide; b: back.edges.rightSide; orientation: Reversed; }+ Interface<Stitch> rightShoulder { a: front.edges.Top_Between_Start_neckline; b: back.edges.Top_Between_neckline_End; orientation: Reversed; }+ Interface<Stitch> leftShoulder { a: front.edges.Top_Between_neckline_End; b: back.edges.Top_Between_Start_neckline; orientation: Reversed; }+ Drape { figure: Anatolia; pose: fitting; transition: lowerArms; clearance: 4mm; }+}diff --git a/fixtures/Canonical/Garment/sundress.firmament b/fixtures/Canonical/Garment/sundress.firmamentnew file mode 100644index 00000000..80ed1462--- /dev/null+++ b/fixtures/Canonical/Garment/sundress.firmament@@ -0,0 +1,69 @@+schema Garment++// A single loose dress. Armholes stay open; there is no sleeve threading or layering.+Concept Struct dressLayout {+ FigureFit body { figure: Anatolia; pose: Rest; chestHeight: 1280mm; hipHeight: 960mm; }+ Points<Point3> arrangement {+ front: Point3(0mm, dressLayout.body.centerY, 650mm);+ back: Point3(0mm, dressLayout.body.centerY, 650mm);+ }+}++Feature SundressPanel(bodyWidth: Length, shoulderWidth: Length,+ height: Length = 880mm, necklineWidth: Length = 210mm, necklineDepth: Length = 80mm) -> Profile {+ let halfShoulder: Length = shoulderWidth / 2;+ let halfBody: Length = bodyWidth / 2;+ let halfHeight: Length = height / 2;+ let pitHeight: Length = height - 240mm;+ let shoulderRise: Length = height - 120mm;+ let halfNeck: Length = necklineWidth / 2;+ let neckStart: Length = halfShoulder - halfNeck;+ let neckEnd: Length = halfShoulder + halfNeck;+ let neckBottom: Length = height - necklineDepth;+ Rect2 blank { center: [0mm, halfHeight]; size: [shoulderWidth, height] }+ return Profile {+ from: blank;+ Replace rightCut {+ on: blank.Right;+ through: [[halfBody, 0mm], [halfBody, pitHeight], [halfShoulder, shoulderRise]];+ interpolation: Linear;+ spanNames: [rightHem, rightSide, rightArmholeLower, rightArmholeUpper];+ }+ Replace leftCut {+ on: blank.Left;+ through: [[-halfShoulder, shoulderRise], [-halfBody, pitHeight], [-halfBody, 0mm]];+ interpolation: Linear;+ spanNames: [leftArmholeUpper, leftArmholeLower, leftSide, leftHem];+ }+ Replace neckline {+ on: blank.Top; range: [neckStart, neckEnd]; through: [[0mm, neckBottom]];+ }+ }+}+Feature frontCut = SundressPanel(bodyWidth: dressLayout.body.torsoCircumference / 2 + 160mm,+ shoulderWidth: dressLayout.body.shoulderWidth + 30mm);+Feature backCut = SundressPanel(bodyWidth: dressLayout.body.torsoCircumference / 2 + 160mm,+ shoulderWidth: dressLayout.body.shoulderWidth + 30mm, necklineDepth: 40mm);++Garment Sundress {+ meshSize: 65mm;+ Fabric cotton {+ thickness: 2mm; arealDensity: 0.2;+ warpCompliance: 0.00000001; weftCompliance: 0.00000001; diagonalCompliance: 0.00000004;+ }+ Panel front {+ profile: frontCut; origin: dressLayout.arrangement.front;+ u: [1, 0, 0]; v: [0, 0, 1]; grain: [0, 1];+ wrapRadius: (dressLayout.body.torsoCircumference / 2 + 160mm) / 3.141592653589793;+ }+ Panel back {+ profile: backCut; origin: dressLayout.arrangement.back;+ u: [-1, 0, 0]; v: [0, 0, 1]; grain: [0, 1];+ wrapRadius: (dressLayout.body.torsoCircumference / 2 + 160mm) / 3.141592653589793;+ }+ Interface<Stitch> rightSide { a: front.edges.rightSide; b: back.edges.leftSide; orientation: Reversed; }+ Interface<Stitch> leftSide { a: front.edges.leftSide; b: back.edges.rightSide; orientation: Reversed; }+ Interface<Stitch> rightShoulder { a: front.edges.Top_Between_Start_neckline; b: back.edges.Top_Between_neckline_End; orientation: Reversed; }+ Interface<Stitch> leftShoulder { a: front.edges.Top_Between_neckline_End; b: back.edges.Top_Between_Start_neckline; orientation: Reversed; }+ Drape { figure: Anatolia; pose: Rest; clearance: 4mm; }+}diff --git a/fixtures/Canonical/Garment/temporary-fitting.firmament b/fixtures/Canonical/Garment/temporary-fitting.firmamentnew file mode 100644index 00000000..dc8fb3ff--- /dev/null+++ b/fixtures/Canonical/Garment/temporary-fitting.firmament@@ -0,0 +1,20 @@+schema Garment+// Construction geometry has no material mesh or runtime scene occurrence.+Concept Struct guides {+ collarFloor: Plane {+ origin: [0mm, 0mm, 1000mm]+ normal: [0, 0, 1]+ }+}+Rect2 blank { center: [0mm, 0mm]; size: [100mm, 100mm]; }+Profile cut { from: blank; }+Garment FittingWitness {+ Fabric cotton { thickness: 2mm; arealDensity: 0.2; }+ Panel sheet { profile: cut; origin: [0mm, 0mm, 1000mm]; v: [0, 1, 0]; }+ Fitting collar {+ on: guides.collarFloor;+ edges: [sheet.edges.Left, sheet.edges.Right, sheet.edges.Top, sheet.edges.Bottom];+ compliance: 0;+ releaseAfter: 5;+ }+}diff --git a/fixtures/Canonical/Garment/tshirt-dress.firmament b/fixtures/Canonical/Garment/tshirt-dress.firmamentnew file mode 100644index 00000000..aba7935c--- /dev/null+++ b/fixtures/Canonical/Garment/tshirt-dress.firmament@@ -0,0 +1,84 @@+schema Garment++// A loose single garment with two panels and integrated short sleeves.+// Figure facts come from the supplied gameplay body; ease is a design choice.+Concept Struct dressLayout {+ FigureFit body {+ figure: Anatolia;+ pose: Rest;+ chestHeight: 1280mm;+ hipHeight: 960mm;+ }+ Points<Point3> arrangement {+ front: Point3(0mm, dressLayout.body.centerY, 650mm);+ back: Point3(0mm, dressLayout.body.centerY, 650mm);+ }+}++Feature DressPanel(width: Length, height: Length = 880mm,+ sleeveLength: Length = 120mm, necklineDepth: Length = 65mm) -> Profile {+ let halfWidth: Length = width / 2;+ let halfHeight: Length = height / 2;+ let sleeveX: Length = halfWidth + sleeveLength;+ let pitHeight: Length = height - 240mm;+ let cuffLow: Length = pitHeight + 20mm;+ let cuffHigh: Length = height - 55mm;+ let neckStart: Length = halfWidth - 90mm;+ let neckEnd: Length = halfWidth + 90mm;+ let neckBottom: Length = height - necklineDepth;+ Rect2 blank { center: [0mm, halfHeight]; size: [width, height] }+ return Profile {+ from: blank;+ Replace rightCut {+ on: blank.Right;+ through: [[halfWidth, pitHeight], [sleeveX, cuffLow], [sleeveX, cuffHigh]];+ interpolation: Linear;+ spanNames: [rightSide, rightSleeveLower, rightSleeveOpening, rightSleeveUpper];+ }+ Replace leftCut {+ on: blank.Left;+ through: [[-sleeveX, cuffHigh], [-sleeveX, cuffLow], [-halfWidth, pitHeight]];+ interpolation: Linear;+ spanNames: [leftSleeveUpper, leftSleeveOpening, leftSleeveLower, leftSide];+ }+ Replace neckline {+ on: blank.Top;+ range: [neckStart, neckEnd];+ through: [[0mm, neckBottom]];+ }+ }+}+Feature frontCut = DressPanel(width: dressLayout.body.torsoCircumference / 2 + 160mm);+Feature backCut = DressPanel(width: dressLayout.body.torsoCircumference / 2 + 160mm, necklineDepth: 25mm);++Garment TshirtDress {+ meshSize: 55mm;+ Fabric cotton {+ thickness: 2mm;+ arealDensity: 0.2;+ warpCompliance: 0.00000001;+ weftCompliance: 0.00000001;+ diagonalCompliance: 0.00000004;+ }+ Panel front {+ profile: frontCut;+ origin: dressLayout.arrangement.front;+ u: [1, 0, 0]; v: [0, 0, 1]; grain: [0, 1];+ wrapRadius: (dressLayout.body.torsoCircumference / 2 + 160mm) / 3.141592653589793;+ }+ Panel back {+ profile: backCut;+ origin: dressLayout.arrangement.back;+ u: [-1, 0, 0]; v: [0, 0, 1]; grain: [0, 1];+ wrapRadius: (dressLayout.body.torsoCircumference / 2 + 160mm) / 3.141592653589793;+ }+ Interface<Stitch> rightSide { a: front.edges.rightSide; b: back.edges.leftSide; orientation: Reversed; }+ Interface<Stitch> leftSide { a: front.edges.leftSide; b: back.edges.rightSide; orientation: Reversed; }+ Interface<Stitch> rightSleeveLower { a: front.edges.rightSleeveLower; b: back.edges.leftSleeveLower; orientation: Reversed; }+ Interface<Stitch> leftSleeveLower { a: front.edges.leftSleeveLower; b: back.edges.rightSleeveLower; orientation: Reversed; }+ Interface<Stitch> rightSleeveUpper { a: front.edges.rightSleeveUpper; b: back.edges.leftSleeveUpper; orientation: Reversed; }+ Interface<Stitch> leftSleeveUpper { a: front.edges.leftSleeveUpper; b: back.edges.rightSleeveUpper; orientation: Reversed; }+ Interface<Stitch> rightShoulder { a: front.edges.Top_Between_Start_neckline; b: back.edges.Top_Between_neckline_End; orientation: Reversed; }+ Interface<Stitch> leftShoulder { a: front.edges.Top_Between_neckline_End; b: back.edges.Top_Between_Start_neckline; orientation: Reversed; }+ Drape { figure: Anatolia; pose: Rest; clearance: 4mm; }+}diff --git a/fixtures/Canonical/qualification.json b/fixtures/Canonical/qualification.jsonindex 447e1e1e..92378eda 100644--- a/fixtures/Canonical/qualification.json+++ b/fixtures/Canonical/qualification.json@@ -1,6 +1,10 @@{"schemaVersion": 1,"expectedDiagnostics": [+ { "path": "Garment/garmentcode-dress-guided.firmament", "codes": ["garment-fit-body-required"] },+ { "path": "Garment/tshirt-dress.firmament", "codes": ["garment-fit-body-required"] },+ { "path": "Garment/sundress.firmament", "codes": ["garment-fit-body-required"] },+ { "path": "Garment/sundress-posed.firmament", "codes": ["garment-fit-body-required"] },{ "path": "PlasticShell/plastic-shell-autorib-materialized.firmament", "codes": ["plastic-shell-constant-section-feature-zero-draft"] },{ "path": "PlasticShell/plastic-shell-enclosure.firmament", "codes": ["plastic-shell-constant-section-feature-zero-draft"] },{ "path": "PlasticShell/plastic-shell-materialized-enclosure.firmament", "codes": ["plastic-shell-constant-section-feature-zero-draft"] },diff --git a/scripts/inspect-garment-strain.cs b/scripts/inspect-garment-strain.csnew file mode 100644index 00000000..b475cd20--- /dev/null+++ b/scripts/inspect-garment-strain.cs@@ -0,0 +1,164 @@+#:project ../Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj+#:property PublishAot=false+#:property JsonSerializerIsReflectionEnabledByDefault=true+// Read-only inspection and bounded replay probes through the shared CPU solver.+using System.Collections.Immutable;+using System.Numerics;+using System.Security.Cryptography;+using System.Text.Json;+using System.Text.Json.Serialization;+using Aetheris.Cloth3D;+using Aetheris.Humanoid;+using Aetheris.Kernel.Firmament.Garment;+using Aetheris.Kernel.Firmament.Humanoid;++if (args.Length != 4)+{+ throw new ArgumentException("dotnet run -c Release scripts/inspect-garment-strain.cs -- source.firmament body.json garment.json output.json");+}+var json = new JsonSerializerOptions+{+ IncludeFields = true,+ WriteIndented = true,+ Converters = { new JsonStringEnumConverter() },+};+string sourcePath = Path.GetFullPath(args[0]);+string bodyPath = Path.GetFullPath(args[1]);+string snapshotPath = Path.GetFullPath(args[2]);+string output = Path.GetFullPath(args[3]);+if (new[] { sourcePath, bodyPath, snapshotPath }.Contains(output, StringComparer.OrdinalIgnoreCase))+{+ throw new ArgumentException("Inspection output must not replace its input.");+}+string bodyHash = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(bodyPath)));+var body = HumanoidGameplayBody.Load(bodyPath);+var binding = new GarmentFigureBinding("Anatolia", body, bodyHash);+var result = GarmentCompiler.Compile(File.ReadAllText(sourcePath), sourcePath, binding);+if (!result.IsSuccess)+{+ throw new InvalidDataException(string.Join("; ", result.Diagnostics));+}+var garment = result.Garment!;+using var document = JsonDocument.Parse(File.ReadAllText(snapshotPath));+string sourceHash = garment.Source.SourceHash;+if (document.RootElement.GetProperty("sourceHash").GetString() != sourceHash)+{+ throw new InvalidDataException("Snapshot source hash does not match the supplied authoring source.");+}+var retainedFits = document.RootElement.GetProperty("figureFits").EnumerateArray().ToArray();+if (retainedFits.Length == 0)+{+ throw new InvalidDataException("This probe requires a FigureFit binding to verify the retained body's artifact hash.");+}+foreach (var fit in retainedFits)+{+ if (fit.GetProperty("ArtifactHash").GetString() != bodyHash)+ {+ throw new InvalidDataException("Snapshot figure binding does not match the supplied body artifact.");+ }+}+var snapshot = document.RootElement.GetProperty("settled").Deserialize<ClothSnapshot3D>(json)+ ?? throw new InvalidDataException("A retained settled snapshot is required.");+ClothState3D.ValidateSnapshot(garment.Cloth, snapshot);+string finalPose = garment.Source.Pose+ ?? throw new InvalidDataException("The retained drape requires an authored pose binding.");+if (garment.Source.Transition is { } transitionName)+{+ finalPose = garment.Source.Posing!.Transitions[transitionName].To;+}+var surface = GarmentDraping.BodySurface(body);+if (finalPose != "Rest")+{+ var recipe = garment.Source.Posing!.Resolve(finalPose, "Anatolia");+ var pose = HumanoidPoseAuthoring.Solve(recipe, body);+ var posedPositions = body.EvaluatePositions(pose);+ surface = GarmentDraping.BodySurface(body, posedPositions);+}+var contacts = new ClothContacts3D { BodySurface = surface, BodyClearance = garment.Source.BodyClearance };+var structuralLinks = garment.Cloth.Constraints.Where(constraint =>+ constraint.Vertices.Length == 2 && constraint.Weights.IsEmpty);+var outliers = structuralLinks+ .Select(constraint => new+ {+ constraint.Kind,+ constraint.RestLength,+ stretch = Vector3.Distance(snapshot.Positions[constraint.Vertices[0]],+ snapshot.Positions[constraint.Vertices[1]]) / constraint.RestLength - 1,+ vertices = constraint.Vertices.Select(DescribeVertex),+ })+ .OrderByDescending(link => link.stretch)+ .Take(8)+ .ToArray();+var probes = new List<object>();+foreach (bool contact in new[] { true, false })+{+ foreach (int substeps in new[] { 8, 32 })+ {+ Console.Error.WriteLine($"Replay: body contact={contact}, substeps={substeps}, frames=5");+ using var solver = new ClothSolver3D(garment.Cloth);+ solver.Restore(snapshot with+ {+ Velocities = snapshot.Velocities.Select(_ => Vector3.Zero).ToImmutableArray(),+ });+ var options = new ClothStepOptions3D+ {+ Gravity = Vector3.Zero,+ Substeps = substeps,+ Iterations = 24,+ ContactIterations = 1,+ };+ var probeContacts = contact ? contacts : new ClothContacts3D();+ for (int tick = 0; tick < 5; tick++)+ {+ solver.Step(options, probeContacts);+ }+ probes.Add(new+ {+ contact,+ substeps,+ ticks = 5,+ measuredAgainstOriginalBody = ClothState3D.Measure(garment.Cloth, solver.Capture(), contacts),+ seamGap = garment.MaximumSeamGap(solver.Capture()),+ });+ }+}+string report = JsonSerializer.Serialize(new+{+ sourcePath,+ sourceHash,+ bodyPath,+ bodyHash,+ finalPose,+ snapshotPath,+ garment.Cloth.ContentKey,+ initial = ClothState3D.Measure(garment.Cloth, snapshot, contacts),+ outliers,+ probes,+ limits = new[]+ {+ "Retained final snapshot and its authored final body pose; not an intermediate checkpoint",+ "Five replay probe frames",+ "Zero gravity and initial velocity",+ "Contact-disabled probes are diagnostic only, not admissible fits",+ },+}, json);+Directory.CreateDirectory(Path.GetDirectoryName(output)!);+File.WriteAllText(output, report);+Console.WriteLine(report);++object DescribeVertex(int vertex)+{+ var semanticEdges = garment.Panels.SelectMany(panel =>+ panel.Edges.Where(edge => edge.Value.Contains(vertex))+ .Select(edge => panel.Identity + ".edges." + edge.Key));+ float inverseMass = garment.Cloth.InverseMasses[vertex];+ return new+ {+ vertex,+ position = snapshot.Positions[vertex],+ material = garment.Cloth.Definition.Positions[vertex],+ inverseMass,+ body = surface.Query(snapshot.Positions[vertex]),+ edges = semanticEdges.ToArray(),+ };+}diff --git a/scripts/qualify-garmentcode-reference.cs b/scripts/qualify-garmentcode-reference.csnew file mode 100644index 00000000..f707d10f--- /dev/null+++ b/scripts/qualify-garmentcode-reference.cs@@ -0,0 +1,99 @@+#:project ../Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj+#:property PublishAot=false+#:property JsonSerializerIsReflectionEnabledByDefault=true+// Research orchestration only. Sewing, settling, contacts and replay retain Aetheris owners.+// The supplied upstream OBJ is a local reference input, not a redistributed fixture or rig.+using System.Collections.Immutable;+using System.Globalization;+using System.Numerics;+using System.Security.Cryptography;+using System.Text;+using System.Text.Json;+using Aetheris.Cloth3D;+using Aetheris.Kernel.Firmament.Garment;++if (args.Length != 3)+{+ throw new ArgumentException("dotnet run scripts/qualify-garmentcode-reference.cs -- pattern.firmament upstream-Y-up-metres.obj output-directory");+}+string patternPath = Path.GetFullPath(args[0]);+string bodyPath = Path.GetFullPath(args[1]);+string output = Path.GetFullPath(args[2]);+var vertices = new List<Vector3>();+var indices = new List<int>();+foreach (string line in File.ReadLines(bodyPath))+{+ string[] values = line.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);+ if (values.Length == 0)+ {+ continue;+ }+ if (values[0] == "v")+ {+ if (values.Length != 4)+ {+ throw new InvalidDataException("Reference OBJ must contain XYZ vertices.");+ }+ float x = float.Parse(values[1], CultureInfo.InvariantCulture);+ float y = float.Parse(values[2], CultureInfo.InvariantCulture);+ float z = float.Parse(values[3], CultureInfo.InvariantCulture);+ vertices.Add(new(x, z, y));+ }+ if (values[0] == "f")+ {+ if (values.Length != 4)+ {+ throw new InvalidDataException("Reference OBJ must contain triangles; no implicit retopology.");+ }+ // Y-up -> Z-up swaps axes, so reverse each face to preserve outward normals.+ foreach (int column in new[] { 1, 3, 2 })+ {+ indices.Add(int.Parse(values[column].Split('/')[0], CultureInfo.InvariantCulture) - 1);+ }+ }+}+var surface = new ClothTriangleBody3D(vertices.ToImmutableArray(), indices.ToImmutableArray());+var compiled = GarmentCompiler.Compile(File.ReadAllText(patternPath), patternPath);+if (!compiled.IsSuccess)+{+ throw new InvalidDataException(string.Join("; ", compiled.Diagnostics));+}+string bodyHash = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(bodyPath)));+var garment = compiled.Garment!;+var drape = GarmentDraping.SettleOnSurface(garment, surface, "garmentcode.mean_all", bodyHash, 30,+ progress => Console.Error.WriteLine($"{progress.Phase}: {progress.Completed}/{progress.Total} ({progress.ElapsedSeconds:F1}s)"));+Directory.CreateDirectory(output);+File.WriteAllText(Path.Combine(output, "garment.obj"), GarmentExport.Obj(garment, drape.Snapshot));+File.WriteAllText(Path.Combine(output, "garment.json"), GarmentExport.Artifact(garment, drape.Snapshot));+File.WriteAllText(Path.Combine(output, "patterns.svg"), GarmentPatternPreview.Svg(garment.Source));+var obj = new StringBuilder();+foreach (var point in vertices)+{+ obj.AppendLine(FormattableString.Invariant($"v {point.X:R} {point.Y:R} {point.Z:R}"));+}+for (int i = 0; i < indices.Count; i += 3)+{+ obj.AppendLine($"f {indices[i] + 1} {indices[i + 1] + 1} {indices[i + 2] + 1}");+}+File.WriteAllText(Path.Combine(output, "body.obj"), obj.ToString());+bool passed = drape.Metrics.Finite && drape.Metrics.MaximumStretch <= .15f+ && drape.Metrics.MaximumSurfacePenetration <= .005f && drape.MaximumSeamGap <= .01f && drape.ReplayExact;+string evidence = JsonSerializer.Serialize(new+{+ qualification = passed ? "passed" : "failed",+ bodyPath,+ bodyHash,+ garment.Source.SourceHash,+ garment.Cloth.ContentKey,+ drape.Metrics,+ drape.MaximumSeamGap,+ drape.ReplayExact,+ drape.StretchOutliers,+ drape.SurfaceContactOutliers,+ upstreamSimulationUsed = false,+ limits = new[] { "Static reference body", "30 sewing ticks + 30 gravity ticks", "Discrete oriented contact",+ "No friction, CCD or self-contact", "Source body remains an external research input" },+}, new JsonSerializerOptions { WriteIndented = true });+File.WriteAllText(Path.Combine(output, "evidence.json"), evidence);+Console.WriteLine(evidence);+return passed ? 0 : 2;diff --git a/scripts/render-garment.py b/scripts/render-garment.pyindex 07bbf4c1..eff457a7 100644--- a/scripts/render-garment.py+++ b/scripts/render-garment.py@@ -45,19 +45,37 @@ def main():parser = argparse.ArgumentParser()parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])parser.add_argument("--bottom", choices=("shorts", "skirt", "flared-skirt"), default="skirt")+ parser.add_argument("--garment", help="Render one garment instead of composing a tunic and bottom.")+ parser.add_argument("--input-dir", type=Path, help="Directory containing the actual garment.obj and body.obj exports.")parser.add_argument("--samples", type=int, default=32)+ parser.add_argument("--frame", choices=("guided", "fitting", "midway", "wearing"), help="Render a retained solver checkpoint.")options = parser.parse_args(sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [])source = options.root / "artifacts/local/garment"- output = source / "renders" / options.bottom+ output = source / "renders" / (options.garment or options.bottom)+ if options.frame:+ if not options.garment:+ parser.error("--frame requires --garment")+ output = output / options.frameoutput.mkdir(parents=True, exist_ok=True)bpy.ops.object.select_all(action="SELECT")bpy.ops.object.delete(use_global=False)- body_path = source / options.bottom / "body.obj"- tunic_path = source / "tunic/garment.obj"- bottom_path = source / options.bottom / "garment.obj"+ if options.garment:+ inputs = options.input_dir or source / options.garment+ prefix = options.frame + "-" if options.frame else ""+ body_path = inputs / (prefix + "body.obj")+ garment_path = inputs / (prefix + "garment.obj")+ garment_inputs = [body_path, garment_path]+ else:+ body_path = source / options.bottom / "body.obj"+ tunic_path = source / "tunic/garment.obj"+ bottom_path = source / options.bottom / "garment.obj"+ garment_inputs = [body_path, tunic_path, bottom_path]load_obj(body_path, material("neutral mannequin", (.48, .47, .43), .65))- load_obj(tunic_path, material("untextured tunic", (.08, .24, .31), .8))- load_obj(bottom_path, material("untextured bottom", (.11, .14, .22), .8))+ if options.garment:+ load_obj(garment_path, material("untextured dress", (.035, .19, .18), .8))+ else:+ load_obj(tunic_path, material("untextured tunic", (.08, .24, .31), .8))+ load_obj(bottom_path, material("untextured bottom", (.11, .14, .22), .8))bpy.ops.mesh.primitive_plane_add(size=200, location=(0, 0, -.005))bpy.context.object.data.materials.append(material("floor", (.24, .26, .29), .9))scene = bpy.context.scene@@ -89,9 +107,9 @@ def main():camera.data.ortho_scale = 2.05scene.camera = camerafor name, location in (- ("front", (2.6, 4, 2)),- ("side", (4, .3, 1.8)),- ("back", (2.6, -4, 2)),+ ("front", (0, 4, 1.2)),+ ("side", (4, -.035, 1.2)),+ ("back", (0, -4, 1.2)),):camera.location = locationcamera.rotation_euler = (Vector((0, -.035, .9)) - camera.location).to_track_quat("-Z", "Y").to_euler()@@ -99,9 +117,10 @@ def main():bpy.ops.render.render(write_still=True)bpy.ops.wm.save_as_mainfile(filepath=str(output / "garment-preview.blend"))evidence = {- "geometryAuthority": "Aetheris.CLI garment drape; Blender only presents retained OBJ meshes",- "inputs": {str(path): hashlib.sha256(path.read_bytes()).hexdigest() for path in (body_path, tunic_path, bottom_path)},- "bottom": options.bottom,+ "geometryAuthority": "Aetheris garment runtime exports; Blender only presents retained OBJ meshes",+ "inputs": {str(path): hashlib.sha256(path.read_bytes()).hexdigest() for path in garment_inputs},+ "garment": options.garment or options.bottom,+ "frame": options.frame,"textures": False,}(output / "render-evidence.json").write_text(json.dumps(evidence, indent=2), encoding="utf-8")diff --git a/scripts/research-garmentcode.py b/scripts/research-garmentcode.pynew file mode 100644index 00000000..3f86ff25--- /dev/null+++ b/scripts/research-garmentcode.py@@ -0,0 +1,93 @@+"""Generate reproducible sewing-pattern witnesses using an external GarmentCode checkout.++This calls upstream templates, not Aetheris simulation. Install pattern-only dependencies+in a research venv; no Python dependency is introduced into the Aetheris runtime.+"""+import argparse+import copy+import hashlib+import json+from pathlib import Path+import subprocess+import sys++parser = argparse.ArgumentParser()+parser.add_argument("--upstream", type=Path, required=True)+parser.add_argument("--out-dir", type=Path, required=True)+args = parser.parse_args()+upstream = args.upstream.resolve()+sys.path.insert(0, str(upstream))++import yaml+import numpy as np+from assets.bodies.body_params import BodyParameters+from assets.garment_programs.bodice import Shirt++revision = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=upstream, text=True).strip()+expected = "d449629979028123a5c4dc9e732a2ec19b7fce31"+if revision != expected:+ raise RuntimeError(f"Expected GarmentCode {expected}; found {revision}")++body_path = upstream / "assets/bodies/mean_all.yaml"+design_path = upstream / "assets/design_params/t-shirt.yaml"+base_design = yaml.safe_load(design_path.read_text())["design"]+output = args.out_dir.resolve()+output.mkdir(parents=True, exist_ok=True)+records = []+for name, length, sleeveless in [("shirt", 1.2, False), ("dress", 2.2, True)]:+ body = BodyParameters(str(body_path))+ design = copy.deepcopy(base_design)+ design["shirt"]["length"]["v"] = length+ design["sleeve"]["sleeveless"]["v"] = sleeveless+ garment = Shirt(body, design)+ if garment.is_self_intersecting():+ raise RuntimeError(f"{name}: upstream reported a self-intersecting pattern")+ pattern = garment.assembly()+ pattern.name = name+ # Upstream discovers components through a Python set. Canonicalize presentation order+ # without changing panel geometry, seam endpoints or arrangement.+ pattern.pattern["panels"] = dict(sorted(pattern.pattern["panels"].items()))+ pattern.pattern["stitches"].sort(key=lambda pair: json.dumps(pair, sort_keys=True))+ pattern.pattern["panel_order"] = sorted(pattern.pattern["panels"])+ directory = output / name+ directory.mkdir(exist_ok=True)+ # Use upstream JSON serialization. Disable printable PDF (not needed for this witness).+ pattern.serialize(str(directory), to_subfolder=False, with_3d=False,+ with_text=True, view_ids=True, with_printable=False)+ oracle = []+ for panel_name, panel in pattern.pattern["panels"].items():+ # Exercise upstream's own curve reader; its SVG path flips Y for display.+ svg_vertices = np.asarray(panel["vertices"]) * [1, -1]+ for index, edge in enumerate(panel["edges"]):+ curve = pattern._edge_as_curve(svg_vertices, edge)+ oracle.append({+ "panel": panel_name,+ "edge": index,+ "lengthMm": curve.length() * 10,+ "samplesMm": [[curve.point(t).real * 10, -curve.point(t).imag * 10]+ for t in [0, .25, .5, .75, 1]],+ })+ (directory / "curve-oracle.json").write_text(json.dumps(oracle, indent=2) + "\n")+ (directory / "body-measurements.yaml").write_text(body_path.read_text())+ (directory / "design.yaml").write_text(yaml.safe_dump({"design": design}, sort_keys=False))+ records.append({+ "name": name,+ "panels": len(pattern.pattern["panels"]),+ "stitches": len(pattern.pattern["stitches"]),+ "lengthMultiplier": length,+ "sleeveless": sleeveless,+ "sourceSha256": hashlib.sha256((directory / f"{name}_specification.json").read_bytes()).hexdigest(),+ })++(output / "provenance.json").write_text(json.dumps({+ "upstream": "https://github.com/maria-korosteleva/GarmentCode",+ "revision": revision,+ "template": "assets/garment_programs/bodice.py:Shirt (fitted=False)",+ "bodyMeasurements": "assets/bodies/mean_all.yaml",+ "designPreset": "assets/design_params/t-shirt.yaml",+ "license": "MIT; copyright (c) 2024 Maria Korosteleva",+ "bodyMeshCopied": False,+ "simulated": False,+ "witnesses": records,+}, indent=2) + "\n")+print(json.dumps(records, indent=2))