Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add G0/G1 section chains and STEP wireframe previews
Yuechen Li9362a2e5d5ca
diff --git a/Aetheris.CLI.Tests/WireframeCliTests.cs b/Aetheris.CLI.Tests/WireframeCliTests.csnew file mode 100644index 00000000..af38b26d--- /dev/null+++ b/Aetheris.CLI.Tests/WireframeCliTests.cs@@ -0,0 +1,49 @@+using System.Text.Json;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Surfacing;++namespace Aetheris.CLI.Tests;++public sealed class WireframeCliTests+{+ [Fact]+ public void WireframeCommandRendersImportedTrimmedBrepDeterministically()+ {+ var directory = Path.Combine(Path.GetTempPath(), "aetheris-wireframe-" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(directory);+ try+ {+ var body = SectionChainMaterializer.Materialize(SectionChainTemplates.ErgonomicFairingG1()).Body!;+ var step = Step242Exporter.ExportBody(body);+ Assert.True(step.IsSuccess);+ var input = Path.Combine(directory, "model.step"); var first = Path.Combine(directory, "first.svg"); var second = Path.Combine(directory, "second.svg");+ File.WriteAllText(input, step.Value);++ var stdout = new StringWriter(); var stderr = new StringWriter();+ var exit = CliRunner.Run(["wireframe", input, "--out", first, "--view", "iso", "--density", "9", "--json"], stdout, stderr);+ Assert.Equal(0, exit); Assert.Empty(stderr.ToString()); Assert.True(File.Exists(first));+ using var json = JsonDocument.Parse(stdout.ToString());+ var evidence = json.RootElement.GetProperty("evidence");+ Assert.Equal(30, evidence.GetProperty("faceCount").GetInt32());+ Assert.Equal(30, evidence.GetProperty("facesWithTrimmedIsolines").GetInt32());+ Assert.True(evidence.GetProperty("isoPolylineCount").GetInt32() > 0);+ Assert.Equal(120, json.RootElement.GetProperty("pcurveRecovery").GetProperty("count").GetInt32());++ Assert.Equal(0, CliRunner.Run(["wireframe", input, "--out", second, "--view", "iso", "--density", "9"], new StringWriter(), new StringWriter()));+ Assert.Equal(File.ReadAllText(first), File.ReadAllText(second));+ }+ finally+ {+ if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true);+ }+ }++ [Fact]+ public void WireframeCommandRejectsOutOfRangeDensity()+ {+ var stderr = new StringWriter();+ var exit = CliRunner.Run(["wireframe", "missing.step", "--density", "99"], new StringWriter(), stderr);+ Assert.Equal(1, exit);+ Assert.Contains("Usage: aetheris wireframe", stderr.ToString());+ }+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex ce086a83..e865717a 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -9,6 +9,7 @@ using Aetheris.Kernel.Core.Brep.Verification;using Aetheris.Kernel.Core.Brep.Tessellation;using Aetheris.Kernel.Core.Math;using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Core.Visualization;using Aetheris.Kernel.Firmament;using Aetheris.Kernel.Firmament.Assembly;using Aetheris.Kernel.Firmament.Drawing;@@ -166,7 +167,8 @@ public static class CliRunnerprivate const string SheetMetalUsage = "Usage: aetheris sheetmetal recognize <part.step> [--plan <recognition.json>] [--json] | aetheris sheetmetal recover-flat <part.step> --out-dir <directory> [--recognition-plan <recognition.json>] [--json] | aetheris sheetmetal compare-flat <recovered-flat.json> <native.firmament> [--semantic] [--json] | aetheris sheetmetal inspect <part.step|part.firmament> [--k-factor <0..1>] [--json] | aetheris sheetmetal paths <part.firmament> [--json] | aetheris sheetmetal recover <part.step> --out-dir <directory> [--json] | aetheris sheetmetal compare <part.step|part.firmament> <intent.firmament> [--semantic] [--json] | aetheris sheetmetal flatten <part.step|part.firmament> [--step <flat.step>] [--firmament <recovered.firmament>] [--svg <flat.svg>] [--k-factor <0..1>] [--json]";private const string ExperimentalLoopChamferCorpusUsage = "Usage: aetheris experimental loop-chamfer-corpus --out-dir <dir> [--json]";private const string SculptureUsage = "Usage: aetheris sculpture build <sol-1.sculpture.json> [--out <sol-1.step>] [--evidence <sol-1.evidence.json>] [--preview <sol-1.preview.svg>] [--json]";- private const string SectionChainUsage = "Usage: aetheris section-chain <build|inspect|validate> <file.firmament|flagship|twist|two-profile> [--out <model.step>] [--json]";+ private const string SectionChainUsage = "Usage: aetheris section-chain <build|inspect|validate> <file.firmament|flagship|flagship-g0|twist|two-profile> [--out <model.step>] [--json]";+ private const string WireframeUsage = "Usage: aetheris wireframe <model.step> [--out <preview.svg>] [--view <iso|front|top|right>] [--density <2..32>] [--samples <8..256>] [--json]";internal static readonly JsonSerializerOptions JsonOptions = new(){@@ -231,6 +233,7 @@ public static class CliRunner"sheetmetal" => RunSheetMetal(args.Skip(1).ToArray(), stdout, stderr),"sculpture" => RunSculpture(args.Skip(1).ToArray(), stdout, stderr),"section-chain" => RunSectionChain(args.Skip(1).ToArray(), stdout, stderr),+ "wireframe" => RunWireframe(args.Skip(1).ToArray(), stdout, stderr),"reconstruct" => ReconstructionCli.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),_ => UnknownCommand(args[0], stderr)};@@ -539,7 +542,7 @@ public static class CliRunner{if (args.Length == 0 || IsHelpFlag(args[0])){- stdout.WriteLine("Materialize an ordered semantic SectionChain through ruled pairwise transitions.");+ stdout.WriteLine("Materialize an ordered semantic SectionChain through local ruled/G0 or polynomial/G1 pairwise transitions.");stdout.WriteLine(SectionChainUsage);return args.Length == 0 ? 1 : 0;}@@ -568,7 +571,8 @@ public static class CliRunner{chain = witness switch{- "flagship" => SectionChainTemplates.ErgonomicFairing(),+ "flagship" => SectionChainTemplates.ErgonomicFairingG1(),+ "flagship-g0" => SectionChainTemplates.ErgonomicFairing("surf-x4-section-chain-ergonomic-g0", smooth: false),"twist" => SectionChainTemplates.TwistWitness(),"two-profile" => SectionChainTemplates.TwoProfileRuled(),_ => throw new ArgumentException($"Unknown SectionChain witness '{witness}'.")@@ -596,8 +600,9 @@ public static class CliRunnerresolution = chain.Correspondence.Any(item => item.SourceSectionId == chain.Sections[index].SectionId && item.TargetSectionId == chain.Sections[index + 1].SectionId) ? "Explicit" : "InferredSemanticIdentity",spans = chain.Sections[index].Profile.Spans.Select((span, spanIndex) => new { source = span.SpanId, target = chain.Sections[index + 1].Profile.Spans[spanIndex].SpanId })}),- chain.TransitionPolicy, chain.StartTermination, chain.EndTermination,+ chain.TransitionPolicy, chain.Continuity, chain.SmoothPolicy, chain.StartTermination, chain.EndTermination,transitions = materialized.Transitions, pcurves = materialized.Pcurves, selfIntersection = materialized.SelfIntersection,+ continuityEvidence = materialized.ContinuityEvidence, smoothSelection = materialized.SmoothSelection,diagnostics = materialized.Diagnostics};stdout.WriteLine(JsonSerializer.Serialize(inspection, JsonOptions));@@ -610,12 +615,14 @@ public static class CliRunnerreturn 1;}Directory.CreateDirectory(Path.GetDirectoryName(output)!); File.WriteAllText(output, export.Value);+ var previewPath = Path.ChangeExtension(output, ".preview.svg");+ if (materialized.PreviewSvg is not null) File.WriteAllText(previewPath, materialized.PreviewSvg);var reimport = Step242Importer.ImportBody(export.Value);var surfaces = materialized.Body!.Geometry.Surfaces.Select(item => item.Value.Kind).GroupBy(kind => kind).ToDictionary(group => group.Key.ToString(), group => group.Count(), StringComparer.Ordinal);var report = new{- command = "section-chain build", success = true, witness, output, sha256 = Hash(export.Value),+ command = "section-chain build", success = true, witness, output, preview = previewPath, sha256 = Hash(export.Value),sectionChain = new{chain.StableId, sectionCount = chain.Sections.Count, transitionCount = materialized.Transitions.Count,@@ -628,12 +635,14 @@ public static class CliRunnerspans = chain.Sections[index].Profile.Spans.Select((span, spanIndex) => new { source = span.SpanId, target = chain.Sections[index + 1].Profile.Spans[spanIndex].SpanId })}),transitionPolicy = chain.TransitionPolicy,+ continuity = chain.Continuity, smoothPolicy = chain.SmoothPolicy,startTermination = chain.StartTermination, endTermination = chain.EndTermination,structure = materialized.StructureKind, transitions = materialized.Transitions},topology = new { bodies = materialized.Body.Topology.Bodies.Count(), shells = materialized.Body.Topology.Shells.Count(), faces = materialized.Body.Topology.Faces.Count(), edges = materialized.Body.Topology.Edges.Count(), vertices = materialized.Body.Topology.Vertices.Count() },surfaceInventory = surfaces, rationalProductSurfaces = 0, facetedProductFallback = 0, pcurves = materialized.Pcurves,selfIntersection = materialized.SelfIntersection,+ continuityEvidence = materialized.ContinuityEvidence, smoothSelection = materialized.SmoothSelection,stepReimport = new { success = reimport.IsSuccess, diagnostics = reimport.Diagnostics.Select(item => item.Message) },timingsMilliseconds = materialized.Timing};@@ -644,6 +653,57 @@ public static class CliRunnerreturn reimport.IsSuccess ? 0 : 1;}+ private static int RunWireframe(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0 || IsHelpFlag(args[0]))+ {+ stdout.WriteLine("Render deterministic trim-aware SVG isolines and exact topology edges from a STEP BRep.");+ stdout.WriteLine(WireframeUsage);+ stdout.WriteLine("The result is diagnostic visualization, not a tessellated product or hidden-line engineering drawing.");+ return args.Length == 0 ? 1 : 0;+ }+ var input = Path.GetFullPath(args[0]); string? output = null; var json = false;+ var view = WireframeView.Isometric; var density = 8; var samples = 48;+ for (var index = 1; index < args.Length; index++)+ {+ if (args[index] == "--json") json = true;+ else if (args[index] == "--out" && index + 1 < args.Length) output = Path.GetFullPath(args[++index]);+ else if (args[index] == "--density" && index + 1 < args.Length && int.TryParse(args[++index], out density)) { }+ else if (args[index] == "--samples" && index + 1 < args.Length && int.TryParse(args[++index], out samples)) { }+ else if (args[index] == "--view" && index + 1 < args.Length)+ {+ view = args[++index].ToLowerInvariant() switch+ {+ "iso" or "isometric" => WireframeView.Isometric,+ "front" => WireframeView.Front,+ "top" => WireframeView.Top,+ "right" => WireframeView.Right,+ _ => throw new ArgumentException(WireframeUsage)+ };+ }+ else { stderr.WriteLine(WireframeUsage); return 1; }+ }+ if (density is < 2 or > 32 || samples is < 8 or > 256) { stderr.WriteLine(WireframeUsage); return 1; }+ if (!File.Exists(input)) { stderr.WriteLine($"STEP file not found: {input}"); return 1; }+ output ??= Path.Combine(Path.GetDirectoryName(input)!, Path.GetFileNameWithoutExtension(input) + ".wireframe.svg");+ var imported = Step242Importer.ImportBody(File.ReadAllText(input));+ if (!imported.IsSuccess || imported.Value is null)+ {+ foreach (var diagnostic in imported.Diagnostics) stderr.WriteLine($"error: {diagnostic.Message}");+ return 1;+ }+ PcurveBuildResult? recoveredPcurves = null;+ if (!imported.Value.Bindings.PcurveBindings.Any())+ recoveredPcurves = BoundedPcurveBuilder.Populate(imported.Value.Topology, imported.Value.Geometry, imported.Value.Bindings);+ var rendered = BrepWireframeSvgRenderer.Render(imported.Value, new(view, density, samples));+ Directory.CreateDirectory(Path.GetDirectoryName(output)!); File.WriteAllText(output, rendered.Svg);+ var report = new { command = "wireframe", success = true, input, output, rendered.Evidence,+ pcurveRecovery = recoveredPcurves is null ? null : new { recoveredPcurves.IsSuccess, recoveredPcurves.Count, recoveredPcurves.MaximumResidual, recoveredPcurves.Diagnostics } };+ if (json) stdout.WriteLine(JsonSerializer.Serialize(report, JsonOptions));+ else stdout.WriteLine($"Wireframe SVG: {output}\nFaces: {rendered.Evidence.FaceCount}; edges: {rendered.Evidence.EdgeCount}; trimmed faces: {rendered.Evidence.FacesWithTrimmedIsolines}\nSHA-256: {rendered.Evidence.Sha256}");+ return 0;+ }+private static int RunSculptingBuild(string sourcePath, string? outPath, bool json, TextWriter stdout, TextWriter stderr){var compile = SculptingAuthoring.CompileFile(sourcePath);@@ -4319,7 +4379,8 @@ Model CanonicalPanel {stdout.WriteLine(" modules Inspect built-in engineering Modules and capabilities.");stdout.WriteLine(" sheetmetal Inspect/recover sheet semantics and generate manufacturing flat-pattern SVG.");stdout.WriteLine(" sculpture Build bounded non-manufacturing virtual sculpture artifacts.");- stdout.WriteLine(" section-chain Build bounded ruled SectionChain qualification artifacts.");+ stdout.WriteLine(" section-chain Build bounded G0/G1 SectionChain qualification artifacts.");+ stdout.WriteLine(" wireframe Render a deterministic trim-aware SVG preview from a STEP BRep.");stdout.WriteLine(" verify Build/reimport and verify a model.");stdout.WriteLine(" reconstruct Experimentally reconstruct a structured mesh from triangle PLY input.");stdout.WriteLine();@@ -4338,6 +4399,7 @@ Model CanonicalPanel {stdout.WriteLine(" aetheris sheetmetal flatten bracket.firmament --step bracket-flat.step --svg bracket-flat.svg --json");stdout.WriteLine(" aetheris sculpture build fixtures/Canonical/VirtualSculpture/sol-1.sculpture.json");stdout.WriteLine(" aetheris section-chain build flagship --json");+ stdout.WriteLine(" aetheris wireframe model.step --out model.wireframe.svg --view iso --density 8");stdout.WriteLine(" aetheris reconstruct mesh scan.ply --mode fast --out scan-remesh.obj --report scan-report.json");stdout.WriteLine();stdout.WriteLine("Run 'aetheris <command> --help' for command-specific usage.");diff --git a/Aetheris.Kernel.Core/Visualization/BrepWireframeSvgRenderer.cs b/Aetheris.Kernel.Core/Visualization/BrepWireframeSvgRenderer.csnew file mode 100644index 00000000..cef84456--- /dev/null+++ b/Aetheris.Kernel.Core/Visualization/BrepWireframeSvgRenderer.cs@@ -0,0 +1,262 @@+using System.Security.Cryptography;+using System.Text;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Core.Visualization;++public enum WireframeView { Isometric, Front, Top, Right }++public sealed record BrepWireframeOptions(+ WireframeView View = WireframeView.Isometric,+ int Density = 8,+ int CurveSamples = 48,+ int Width = 1200,+ int Height = 700,+ string Background = "#10151d",+ string IsoLineColor = "#79b8ff",+ string BoundaryColor = "#dbeafe");++public sealed record BrepWireframeEvidence(+ WireframeView View,+ int Density,+ int FaceCount,+ int FacesWithTrimmedIsolines,+ int EdgeCount,+ int IsoPolylineCount,+ int BoundaryPolylineCount,+ IReadOnlyDictionary<string, int> SurfaceFamilies,+ IReadOnlyList<string> UnsupportedSurfaceFamilies,+ IReadOnlyList<string> UnsupportedCurveFamilies,+ string Sha256);++public sealed record BrepWireframeResult(string Svg, BrepWireframeEvidence Evidence);++/// <summary>+/// Deterministic diagnostic SVG renderer for exact BRep models. Topology edges are sampled from+/// their authoritative 3D curves. Face isolines are sampled from exact supports and clipped in UV+/// with the face's pcurve loops using the even/odd trim rule. The SVG is evidence/inspection output,+/// not a tessellated product representation or a hidden-line engineering drawing.+/// </summary>+public static class BrepWireframeSvgRenderer+{+ public static BrepWireframeResult Render(BrepBody body, BrepWireframeOptions? options = null)+ {+ ArgumentNullException.ThrowIfNull(body);+ options ??= new();+ if (options.Density is < 2 or > 32) throw new ArgumentOutOfRangeException(nameof(options), "Wireframe density must be between 2 and 32.");+ if (options.CurveSamples is < 8 or > 256) throw new ArgumentOutOfRangeException(nameof(options), "CurveSamples must be between 8 and 256.");+ if (options.Width < 320 || options.Height < 240) throw new ArgumentOutOfRangeException(nameof(options), "Wireframe dimensions are too small.");++ var iso = new List<IReadOnlyList<Point3D>>();+ var boundaries = new List<IReadOnlyList<Point3D>>();+ var unsupported = new SortedSet<string>(StringComparer.Ordinal);+ var unsupportedCurves = new SortedSet<string>(StringComparer.Ordinal);+ var families = body.Topology.Faces.Select(face => body.TryGetFaceSurfaceGeometry(face.Id, out var surface) ? surface?.Kind.ToString() ?? "Unbound" : "Unbound")+ .GroupBy(name => name, StringComparer.Ordinal).ToDictionary(group => group.Key, group => group.Count(), StringComparer.Ordinal);+ var trimmedFaces = 0;++ foreach (var edge in body.Topology.Edges.OrderBy(edge => edge.Id.Value))+ {+ if (!body.Bindings.TryGetEdgeBinding(edge.Id, out var binding)+ || !body.Geometry.TryGetCurve(binding.CurveGeometryId, out var curve) || curve is null) continue;+ if (!CanEvaluate(curve)) { unsupportedCurves.Add(curve.UnsupportedKind ?? curve.Kind.ToString()); continue; }+ var interval = binding.TrimInterval ?? CurveDomain(curve);+ if (interval is null) continue;+ var points = SampleCurve(curve, interval.Value, options.CurveSamples).ToArray();+ if (points.Length > 1) boundaries.Add(points);+ }++ foreach (var face in body.Topology.Faces.OrderBy(face => face.Id.Value))+ {+ if (!body.Bindings.TryGetFaceBinding(face.Id, out var faceBinding)+ || !body.Geometry.TryGetSurface(faceBinding.SurfaceGeometryId, out var surface) || surface is null) continue;+ var loops = TrimLoops(body, face).ToArray();+ if (loops.Length == 0 || loops.All(loop => loop.Count < 3)) continue;+ var uv = loops.SelectMany(loop => loop).ToArray();+ var u0 = uv.Min(point => point.U); var u1 = uv.Max(point => point.U);+ var v0 = uv.Min(point => point.V); var v1 = uv.Max(point => point.V);+ if (!double.IsFinite(u0) || !double.IsFinite(u1) || !double.IsFinite(v0) || !double.IsFinite(v1)+ || u1 - u0 <= 1e-12d || v1 - v0 <= 1e-12d) continue;+ if (!CanEvaluate(surface)) { unsupported.Add(surface.Kind.ToString()); continue; }+ var before = iso.Count;+ for (var line = 1; line < options.Density; line++)+ {+ var u = u0 + (u1 - u0) * line / options.Density;+ AddTrimmedIso(iso, loops, options.CurveSamples, t => new(u, v0 + (v1 - v0) * t), point => Evaluate(surface, point.U, point.V));+ var v = v0 + (v1 - v0) * line / options.Density;+ AddTrimmedIso(iso, loops, options.CurveSamples, t => new(u0 + (u1 - u0) * t, v), point => Evaluate(surface, point.U, point.V));+ }+ if (iso.Count > before) trimmedFaces++;+ }++ var all = boundaries.Concat(iso).SelectMany(points => points).ToArray();+ if (all.Length == 0) throw new InvalidOperationException("The BRep contains no renderable bound curves or trimmed surface supports.");+ var svg = ComposeSvg(all, iso, boundaries, options);+ var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(svg))).ToLowerInvariant();+ return new(svg, new(options.View, options.Density, body.Topology.Faces.Count(), trimmedFaces,+ body.Topology.Edges.Count(), iso.Count, boundaries.Count, families, unsupported.ToArray(), unsupportedCurves.ToArray(), hash));+ }++ private static IEnumerable<IReadOnlyList<SurfaceParameterPoint>> TrimLoops(BrepBody body, Face face)+ {+ foreach (var loopId in face.LoopIds)+ {+ var loop = body.Topology.GetLoop(loopId); var points = new List<SurfaceParameterPoint>();+ foreach (var coedgeId in loop.CoedgeIds)+ {+ var coedge = body.Topology.GetCoedge(coedgeId);+ if (!body.Bindings.TryGetPcurveBinding(coedgeId, out var binding)) continue;+ var reverse = coedge.IsReversed == binding.SameSense;+ for (var sample = 0; sample <= 16; sample++)+ {+ var fraction = sample / 16d;+ var parameter = reverse+ ? binding.Pcurve.Domain.End - (binding.Pcurve.Domain.End - binding.Pcurve.Domain.Start) * fraction+ : binding.Pcurve.Domain.Start + (binding.Pcurve.Domain.End - binding.Pcurve.Domain.Start) * fraction;+ var point = binding.Pcurve.Evaluate(parameter);+ if (points.Count == 0 || DistanceSquared(points[^1], point) > 1e-20d) points.Add(point);+ }+ }+ if (points.Count >= 3) yield return points;+ }+ }++ private static void AddTrimmedIso(List<IReadOnlyList<Point3D>> output, IReadOnlyList<IReadOnlyList<SurfaceParameterPoint>> loops,+ int samples, Func<double, SurfaceParameterPoint> parameter, Func<SurfaceParameterPoint, Point3D> evaluate)+ {+ List<Point3D>? run = null;+ for (var index = 0; index < samples; index++)+ {+ var a = parameter(index / (double)samples); var b = parameter((index + 1d) / samples);+ var midpoint = new SurfaceParameterPoint((a.U + b.U) / 2d, (a.V + b.V) / 2d);+ if (InsideTrim(midpoint, loops))+ {+ run ??= [];+ if (run.Count == 0) run.Add(evaluate(a));+ run.Add(evaluate(b));+ }+ else if (run is { Count: > 1 }) { output.Add(run); run = null; }+ else run = null;+ }+ if (run is { Count: > 1 }) output.Add(run);+ }++ private static bool InsideTrim(SurfaceParameterPoint point, IReadOnlyList<IReadOnlyList<SurfaceParameterPoint>> loops)+ {+ var crossings = 0;+ foreach (var polygon in loops)+ {+ var inside = false;+ for (var i = 0; i < polygon.Count; i++)+ {+ var a = polygon[i]; var b = polygon[(i + 1) % polygon.Count];+ if ((a.V > point.V) == (b.V > point.V)) continue;+ var intersection = (b.U - a.U) * (point.V - a.V) / (b.V - a.V) + a.U;+ if (point.U < intersection) inside = !inside;+ }+ if (inside) crossings++;+ }+ return crossings % 2 == 1;+ }++ private static string ComposeSvg(IReadOnlyList<Point3D> all, IReadOnlyList<IReadOnlyList<Point3D>> iso,+ IReadOnlyList<IReadOnlyList<Point3D>> boundaries, BrepWireframeOptions options)+ {+ var projected = all.Select(point => Project(point, options.View)).ToArray();+ var minX = projected.Min(p => p.X); var maxX = projected.Max(p => p.X);+ var minY = projected.Min(p => p.Y); var maxY = projected.Max(p => p.Y);+ const double margin = 42d;+ var scale = System.Math.Min((options.Width - 2d * margin) / System.Math.Max(maxX - minX, 1e-9d),+ (options.Height - 2d * margin) / System.Math.Max(maxY - minY, 1e-9d));+ string P(Point3D point)+ {+ var p = Project(point, options.View);+ return FormattableString.Invariant($"{margin + (p.X - minX) * scale:F2},{margin + (p.Y - minY) * scale:F2}");+ }+ var svg = new StringBuilder();+ svg.Append("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"").Append(options.Width).Append("\" height=\"").Append(options.Height)+ .Append("\" viewBox=\"0 0 ").Append(options.Width).Append(' ').Append(options.Height).Append("\"><rect width=\"100%\" height=\"100%\" fill=\"")+ .Append(options.Background).Append("\"/><g fill=\"none\" stroke-linecap=\"round\" stroke-linejoin=\"round\">");+ foreach (var line in iso) svg.Append("<polyline points=\"").Append(string.Join(' ', line.Select(P))).Append("\" stroke=\"")+ .Append(options.IsoLineColor).Append("\" stroke-width=\"1\" opacity=\".43\"/>");+ foreach (var line in boundaries) svg.Append("<polyline points=\"").Append(string.Join(' ', line.Select(P))).Append("\" stroke=\"")+ .Append(options.BoundaryColor).Append("\" stroke-width=\"1.35\" opacity=\".88\"/>");+ svg.Append("</g><text x=\"24\" y=\"").Append(options.Height - 20).Append("\" fill=\"").Append(options.BoundaryColor)+ .Append("\" opacity=\".78\" font-family=\"ui-monospace,monospace\" font-size=\"14\">Aetheris exact BRep wireframe · ")+ .Append(options.View).Append(" · density ").Append(options.Density).Append("</text></svg>");+ return svg.ToString();+ }++ private static (double X, double Y) Project(Point3D p, WireframeView view) => view switch+ {+ WireframeView.Front => (p.X, -p.Z),+ WireframeView.Top => (p.X, -p.Y),+ WireframeView.Right => (p.Y, -p.Z),+ _ => (p.Z + .45d * p.X, -p.Y + .28d * p.X - .18d * p.Z)+ };++ private static bool CanEvaluate(SurfaceGeometry surface) => surface.Kind switch+ {+ SurfaceGeometryKind.LinearExtrusion => CanEvaluate(surface.LinearExtrusion!.Value.Directrix),+ SurfaceGeometryKind.SurfaceOfRevolution => CanEvaluate(surface.SurfaceOfRevolution!.Value.Directrix),+ _ => surface.Kind is SurfaceGeometryKind.Plane or SurfaceGeometryKind.Cylinder or SurfaceGeometryKind.Cone+ or SurfaceGeometryKind.Sphere or SurfaceGeometryKind.Torus or SurfaceGeometryKind.BSplineSurfaceWithKnots+ };++ private static bool CanEvaluate(CurveGeometry curve) => curve.Kind is CurveGeometryKind.Line3 or CurveGeometryKind.Circle3+ or CurveGeometryKind.BSpline3 or CurveGeometryKind.Ellipse3 or CurveGeometryKind.Hyperbola3;++ private static Point3D Evaluate(SurfaceGeometry surface, double u, double v) => surface.Kind switch+ {+ SurfaceGeometryKind.Plane => surface.Plane!.Value.Evaluate(u, v),+ SurfaceGeometryKind.Cylinder => surface.Cylinder!.Value.Evaluate(u, v),+ SurfaceGeometryKind.Cone => surface.Cone!.Value.Evaluate(u, v),+ SurfaceGeometryKind.Sphere => surface.Sphere!.Value.Evaluate(u, v),+ SurfaceGeometryKind.Torus => surface.Torus!.Value.Evaluate(u, v),+ SurfaceGeometryKind.BSplineSurfaceWithKnots => surface.BSplineSurfaceWithKnots!.Evaluate(u, v),+ SurfaceGeometryKind.LinearExtrusion => EvaluateLinearExtrusion(surface.LinearExtrusion!.Value, u, v),+ SurfaceGeometryKind.SurfaceOfRevolution => EvaluateRevolution(surface.SurfaceOfRevolution!.Value, u, v),+ _ => throw new InvalidOperationException($"Unsupported surface family {surface.Kind}.")+ };++ private static Point3D EvaluateLinearExtrusion(LinearExtrusionSurface surface, double u, double v) =>+ EvaluateCurve(surface.Directrix, u) + surface.ExtrusionVector * v;++ private static Point3D EvaluateRevolution(SurfaceOfRevolutionSurface surface, double u, double v)+ {+ var point = EvaluateCurve(surface.Directrix, u); var axis = surface.AxisDirection.ToVector();+ var offset = point - surface.AxisOrigin; var axial = axis * offset.Dot(axis); var radial = offset - axial;+ return surface.AxisOrigin + axial + radial * System.Math.Cos(v) + axis.Cross(radial) * System.Math.Sin(v);+ }++ private static IEnumerable<Point3D> SampleCurve(CurveGeometry curve, ParameterInterval interval, int samples)+ {+ for (var i = 0; i <= samples; i++) yield return EvaluateCurve(curve, interval.Start + (interval.End - interval.Start) * i / samples);+ }++ private static Point3D EvaluateCurve(CurveGeometry curve, double parameter) => curve.Kind switch+ {+ CurveGeometryKind.Line3 => curve.Line3!.Value.Evaluate(parameter),+ CurveGeometryKind.Circle3 => curve.Circle3!.Value.Evaluate(parameter),+ CurveGeometryKind.BSpline3 => curve.BSpline3!.Value.Evaluate(parameter),+ CurveGeometryKind.Ellipse3 => curve.Ellipse3!.Value.Evaluate(parameter),+ CurveGeometryKind.Hyperbola3 => curve.Hyperbola3!.Value.Evaluate(parameter),+ _ => throw new InvalidOperationException($"Unsupported curve family {curve.Kind}.")+ };++ private static ParameterInterval? CurveDomain(CurveGeometry curve) => curve.Kind switch+ {+ CurveGeometryKind.BSpline3 => new(curve.BSpline3!.Value.DomainStart, curve.BSpline3.Value.DomainEnd),+ _ => null+ };++ private static double DistanceSquared(SurfaceParameterPoint a, SurfaceParameterPoint b)+ {+ var u = a.U - b.U; var v = a.V - b.V; return u * u + v * v;+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/SectionChainAuthoringTests.cs b/Aetheris.Kernel.Firmament.Tests/SectionChainAuthoringTests.csindex 50698a27..656ed90f 100644--- a/Aetheris.Kernel.Firmament.Tests/SectionChainAuthoringTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/SectionChainAuthoringTests.cs@@ -10,6 +10,8 @@ public sealed class SectionChainAuthoringTests[InlineData("six-section-ergonomic.firmament", 6, SectionTermination.Cap, SectionTermination.Cap)][InlineData("eight-section-ergonomic.firmament", 8, SectionTermination.Cap, SectionTermination.Cap)][InlineData("open-chain.firmament", 2, SectionTermination.Open, SectionTermination.Open)]+ [InlineData("g1-two-transition.firmament", 3, SectionTermination.Cap, SectionTermination.Cap)]+ [InlineData("g0-explicit-ruled.firmament", 2, SectionTermination.Cap, SectionTermination.Cap)]public void CanonicalFixtureCorpusQualifies(string name, int count, SectionTermination start, SectionTermination end){var result = SectionChainAuthoringParser.Compile(FirmamentCorpusHarness.ReadFixtureText("fixtures/Canonical/SectionChain/" + name));@@ -19,6 +21,19 @@ public sealed class SectionChainAuthoringTestsAssert.Equal(end, result.Chain.EndTermination);}+ [Fact]+ public void ContinuityIntentSelectsTheSeparatedTransitionLaw()+ {+ var g1 = SectionChainAuthoringParser.Compile(FirmamentCorpusHarness.ReadFixtureText("fixtures/Canonical/SectionChain/g1-two-transition.firmament"));+ var g0 = SectionChainAuthoringParser.Compile(FirmamentCorpusHarness.ReadFixtureText("fixtures/Canonical/SectionChain/g0-explicit-ruled.firmament"));+ Assert.True(g1.IsSuccess, string.Join(Environment.NewLine, g1.Diagnostics));+ Assert.True(g0.IsSuccess, string.Join(Environment.NewLine, g0.Diagnostics));+ Assert.Equal(SectionChainContinuity.G1, g1.Chain!.Continuity);+ Assert.Equal(SectionTransitionPolicy.SmoothPolynomial, g1.Chain.TransitionPolicy);+ Assert.Equal(SectionChainContinuity.G0, g0.Chain!.Continuity);+ Assert.Equal(SectionTransitionPolicy.Ruled, g0.Chain.TransitionPolicy);+ }+[Fact]public void InvalidFoldoverFixtureFailsBeforeAnyStepArtifact(){diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.csindex 5fe418b4..7a747b05 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs@@ -32,7 +32,12 @@ public static class SectionChainAuthoringParservar declaration = declarations[0];var profiles = ProfileAuthoringParser.BindPathDerivedProfiles(source, diagnostics);- var transitionText = Field(declaration.Body, "Transition") ?? "Ruled";+ var authoredTransition = Field(declaration.Body, "Transition");+ var continuityText = Field(declaration.Body, "Continuity") ?? (authoredTransition == "Ruled" ? "G0" : "G1");+ if (!Enum.TryParse<SectionChainContinuity>(continuityText, false, out var continuity))+ diagnostics.Add($"section-chain-continuity-invalid:{continuityText}");+ var transitionText = authoredTransition+ ?? (continuity == SectionChainContinuity.G0 ? "Ruled" : "SmoothPolynomial");if (!Enum.TryParse<SectionTransitionPolicy>(transitionText, false, out var transition))diagnostics.Add($"section-chain-transition-policy-invalid:{transitionText}");var startText = Field(declaration.Body, "Start") ?? "Open";@@ -76,7 +81,7 @@ public static class SectionChainAuthoringParser}if (diagnostics.Count != 0) return Fail(diagnostics);- var chain = new SectionChain(declaration.Name, sections, correspondence, transition, start, end);+ var chain = new SectionChain(declaration.Name, sections, correspondence, transition, start, end, continuity);if (!materialize) return new(true, chain, null, []);var result = SectionChainMaterializer.Materialize(chain);if (!result.IsSuccess)diff --git a/Aetheris.Modules.Tests/SurfX3bConstructionStateTests.cs b/Aetheris.Modules.Tests/SurfX3bConstructionStateTests.csindex 87d04ec6..6b818bff 100644--- a/Aetheris.Modules.Tests/SurfX3bConstructionStateTests.cs+++ b/Aetheris.Modules.Tests/SurfX3bConstructionStateTests.cs@@ -66,6 +66,8 @@ public sealed class SurfX3bConstructionStateTests[Theory][InlineData("surf-x3b-add-section-chain-grip.firmament", "AddSectionChain")][InlineData("surf-x3b-remove-section-chain-duct.firmament", "RemoveSectionChain")]+ [InlineData("surf-x4-add-section-chain-g1-grip.firmament", "AddSectionChain")]+ [InlineData("surf-x4-remove-section-chain-g1-duct.firmament", "RemoveSectionChain")]public void FirmamentFlagshipsLowerToTypedOperationsAndReplay(string fixture, string kind){var compiled = SculptingAuthoring.CompileFile(Fixture("Canonical", "BodyState", fixture));diff --git a/Aetheris.Modules.Tests/SurfX4ContinuousSectionChainTests.cs b/Aetheris.Modules.Tests/SurfX4ContinuousSectionChainTests.csnew file mode 100644index 00000000..3979732c--- /dev/null+++ b/Aetheris.Modules.Tests/SurfX4ContinuousSectionChainTests.cs@@ -0,0 +1,52 @@+using Aetheris.Kernel.Core.Step242;+using Aetheris.Surfacing;+using Xunit;++namespace Aetheris.Modules.Tests;++public sealed class SurfX4ContinuousSectionChainTests+{+ [Fact]+ public void ErgonomicFlagshipIsVerifiedG1AndExportsWithoutRationalSurfaces()+ {+ var chain = SectionChainTemplates.ErgonomicFairingG1();+ var result = SectionChainMaterializer.Materialize(chain);++ Assert.True(result.IsSuccess, string.Join(Environment.NewLine, result.Diagnostics));+ Assert.Equal(SectionChainContinuity.G1, chain.Continuity);+ Assert.Equal(3, result.SmoothSelection!.CandidateCount);+ Assert.True(result.ContinuityEvidence!.MaximumPositionError < 1e-10d);+ Assert.True(result.ContinuityEvidence.MaximumTangentPlaneAngleDegrees < 1e-3d);+ Assert.All(result.Body!.Geometry.Surfaces.Where(pair => pair.Value.Kind == Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind.BSplineSurfaceWithKnots),+ pair => Assert.NotNull(pair.Value.BSplineSurfaceWithKnots));+ var step = Step242Exporter.ExportBody(result.Body);+ Assert.True(step.IsSuccess, string.Join(Environment.NewLine, step.Diagnostics.Select(item => item.Message)));+ Assert.DoesNotContain("RATIONAL_B_SPLINE_SURFACE", step.Value, StringComparison.Ordinal);+ Assert.True(Step242Importer.ImportBody(step.Value).IsSuccess);+ }++ [Fact]+ public void ExplicitRuledRemainsG0AndMiddleEditHasBoundedG1Stencil()+ {+ var g0 = SectionChainTemplates.ErgonomicFairing("g0", smooth: false);+ Assert.True(SectionChainMaterializer.Materialize(g0).IsSuccess);+ Assert.Equal(SectionChainContinuity.G0, g0.Continuity);++ var g1 = SectionChainTemplates.ErgonomicFairingG1();+ var replacement = g1.Sections[3] with { Frame = g1.Sections[3].Frame with { Origin = g1.Sections[3].Frame.Origin + new Aetheris.Kernel.Core.Math.Vector3D(0, 1, 0) } };+ var edit = SectionChainEditor.ReplaceSection(g1, replacement).Delta;+ Assert.Equal(["PalmFront", "Rise", "Peak"], edit.RecomputedTangentFields);+ Assert.Equal(["Front->PalmFront", "PalmFront->Rise", "Rise->Peak", "Peak->PalmRear"], edit.RebuiltTransitions);+ Assert.Contains("Nose->Front", edit.PreservedTransitions);+ Assert.Contains("PalmRear->Rear", edit.PreservedTransitions);+ }++ [Fact]+ public void SameSemanticInputProducesIdenticalStep()+ {+ var chain = SectionChainTemplates.ErgonomicFairingG1();+ var first = Step242Exporter.ExportBody(SectionChainMaterializer.Materialize(chain).Body!).Value;+ var second = Step242Exporter.ExportBody(SectionChainMaterializer.Materialize(chain).Body!).Value;+ Assert.Equal(first, second);+ }+}diff --git a/Aetheris.Surfacing/SculptingAuthoring.cs b/Aetheris.Surfacing/SculptingAuthoring.csindex 24986773..41be69e1 100644--- a/Aetheris.Surfacing/SculptingAuthoring.cs+++ b/Aetheris.Surfacing/SculptingAuthoring.cs@@ -227,7 +227,13 @@ public static class SculptingAuthoring{ diagnostics.Add(new("section-chain-termination-invalid", $"SectionChain '{block.Name}' terminations must be Open or Cap.", block.Name)); return null; }var correspondence = stations.Zip(stations.Skip(1), (source, target) => new AdjacentSectionCorrespondence(source.SectionId, target.SectionId,spanIds.Select(span => new SectionSpanCorrespondence(span, span)).ToArray())).ToArray();- return new(block.Name, stations, correspondence, SectionTransitionPolicy.Ruled, start, end);+ // The compact X3b sculpt-operation grammar predates SURF-X4; absence remains G0 for replay compatibility.+ var continuityText = ScalarText(block.Body, "Continuity") ?? "G0";+ if (!Enum.TryParse<SectionChainContinuity>(continuityText, true, out var continuity))+ { diagnostics.Add(new("section-chain-continuity-invalid", $"SectionChain '{block.Name}' Continuity must be G0 or G1.", block.Name)); return null; }+ return new(block.Name, stations, correspondence,+ continuity == SectionChainContinuity.G1 ? SectionTransitionPolicy.SmoothPolynomial : SectionTransitionPolicy.Ruled,+ start, end, continuity);}private static IReadOnlyList<Block> Blocks(string source, string keyword)diff --git a/Aetheris.Surfacing/SectionChainHousingBrepBuilder.cs b/Aetheris.Surfacing/SectionChainHousingBrepBuilder.csindex c1cd803e..f0b5218a 100644--- a/Aetheris.Surfacing/SectionChainHousingBrepBuilder.cs+++ b/Aetheris.Surfacing/SectionChainHousingBrepBuilder.cs@@ -73,6 +73,10 @@ internal static class SectionChainHousingBrepBuilderif (!tool.IsSuccess)return new(null, chain, tool.Pcurves, tool.Diagnostics.Select(item => new SculptDiagnostic(item.Code, item.Message, chain.StableId)).ToArray());+ var transitionSupports = tool.Body!.Geometry.Surfaces.OrderBy(pair => pair.Key.Value)+ .Take((chain.Sections.Count - 1) * 4).Select(pair => pair.Value).ToArray();+ var longitudinalSupports = tool.Body.Geometry.Curves.OrderBy(pair => pair.Key.Value)+ .Skip(chain.Sections.Count * 4).Take((chain.Sections.Count - 1) * 4).Select(pair => pair.Value).ToArray();var builder = new TopologyBuilder();var points = new Dictionary<VertexId, Point3D>();var curves = new Dictionary<EdgeId, (CurveGeometry Curve, ParameterInterval Interval)>();@@ -116,7 +120,8 @@ internal static class SectionChainHousingBrepBuildervar longitudinal = new EdgeId[chain.Sections.Count - 1][];for (var transition = 0; transition < longitudinal.Length; transition++)- longitudinal[transition] = Enumerable.Range(0, 4).Select(index => AddLine(chainVertices[transition][index], chainVertices[transition + 1][index])).ToArray();+ longitudinal[transition] = Enumerable.Range(0, 4).Select(index => AddCurve(chainVertices[transition][index], chainVertices[transition + 1][index],+ longitudinalSupports[transition * 4 + index])).ToArray();var bottomLoops = new List<LoopId> { AddLoop(eb.Select(edge => new Use(edge, false)).ToArray()) };var topLoops = new List<LoopId> { AddLoop(et.Select(edge => new Use(edge, true)).Reverse().ToArray()) };@@ -151,8 +156,7 @@ internal static class SectionChainHousingBrepBuilderelseuses = [Cycle(chainEdges[transition][span], false), new(longitudinal[transition][span], false),Cycle(chainEdges[transition + 1][span], true), new(longitudinal[transition][next], true)];- faces.Add((builder.AddFace([AddLoop(uses)]), TransitionSurface(chainPoints[transition][span], chainPoints[transition][next],- chainPoints[transition + 1][span], chainPoints[transition + 1][next])));+ faces.Add((builder.AddFace([AddLoop(uses)]), transitionSupports[transition * 4 + span]));}if (additive)@@ -194,6 +198,17 @@ internal static class SectionChainHousingBrepBuildervar edge = builder.AddEdge(start, end); var vector = points[end] - points[start];curves[edge] = (CurveGeometry.FromLine(new Line3Curve(points[start], Direction3D.Create(vector))), new(0d, vector.Length)); return edge;}+ EdgeId AddCurve(VertexId start, VertexId end, CurveGeometry curve)+ {+ var edge = builder.AddEdge(start, end);+ var interval = curve.Kind switch+ {+ CurveGeometryKind.Line3 => new ParameterInterval(0d, (points[end] - points[start]).Length),+ CurveGeometryKind.BSpline3 => new ParameterInterval(curve.BSpline3!.Value.DomainStart, curve.BSpline3.Value.DomainEnd),+ _ => throw new InvalidOperationException($"Unsupported SectionChain longitudinal curve {curve.Kind}.")+ };+ curves[edge] = (curve, interval); return edge;+ }EdgeId AddCircle(VertexId seam, HousingHole hole, double z){var edge = builder.AddEdge(seam, seam);@@ -213,7 +228,8 @@ internal static class SectionChainHousingBrepBuilderif (construction.HasCrown || construction.ReplacementPatch is not null)yield return new("section-chain-housing-base-unsupported", "The admitted X3b composition lane requires a planar uncrowned Housing base; replay fails closed for upstream crown/patch changes.");if (chain.Sections.Count < 2) yield return new("section-chain-section-count-invalid", "SectionChain requires at least two sections.");- if (chain.TransitionPolicy != SectionTransitionPolicy.Ruled) yield return new("section-chain-transition-policy-invalid", "Only Ruled transitions are admitted.");+ if (chain.TransitionPolicy is not (SectionTransitionPolicy.Ruled or SectionTransitionPolicy.SmoothPolynomial))+ yield return new("section-chain-transition-policy-invalid", "Only Ruled/G0 and SmoothPolynomial/G1 transitions are admitted.");foreach (var section in chain.Sections){if (section.Profile.Spans.Count != 4 || section.Profile.Spans.Any(span => span.Curve is not SectionProfileCurve.Line))diff --git a/Aetheris.Surfacing/SectionChainSelfIntersectionValidator.cs b/Aetheris.Surfacing/SectionChainSelfIntersectionValidator.csindex c5f80c1c..380b4e9a 100644--- a/Aetheris.Surfacing/SectionChainSelfIntersectionValidator.cs+++ b/Aetheris.Surfacing/SectionChainSelfIntersectionValidator.cs@@ -3,7 +3,7 @@ using Aetheris.Kernel.Core.Math;namespace Aetheris.Surfacing;-internal sealed record SectionChainValidationPatch(int TransitionIndex, string TransitionId, string SpanId, RuledSurfacePatch Patch);+internal sealed record SectionChainValidationPatch(int TransitionIndex, string TransitionId, string SpanId, ISectionChainTransitionPatch Patch);internal sealed record SectionChainSelfIntersectionValidationResult(bool Passed, SectionChainSelfIntersectionEvidence Evidence, string Detail);/// <summary>@@ -34,7 +34,7 @@ internal static class SectionChainSelfIntersectionValidatorreturn Result(false, candidates, qualified, detail);}return Result(true, candidates, qualified,- $"No non-neighbour transition or remote cap crossings were detected by the deterministic {UDivisions}x{VDivisions} ruled-surface proxy.");+ $"No non-neighbour transition or remote cap crossings were detected by the deterministic {UDivisions}x{VDivisions} surface proxy.");static bool SameOrAuthorizedNeighbor(Triangle a, Triangle b){diff --git a/Aetheris.Surfacing/SectionChainTemplates.cs b/Aetheris.Surfacing/SectionChainTemplates.csindex 2342dae1..31564a90 100644--- a/Aetheris.Surfacing/SectionChainTemplates.cs+++ b/Aetheris.Surfacing/SectionChainTemplates.cs@@ -7,7 +7,7 @@ public static class SectionChainTemplatesprivate static readonly string[] SpanIds = ["South", "East", "North", "West"];/// <summary>Eight changing, explicitly framed stations for the SURF-X3 flagship fairing.</summary>- public static SectionChain ErgonomicFairing(string stableId = "surf-x3-section-chain-ergonomic-body")+ public static SectionChain ErgonomicFairing(string stableId = "surf-x3-section-chain-ergonomic-body", bool smooth = false){var stations = new[]{@@ -20,10 +20,13 @@ public static class SectionChainTemplatesStation("Rear", new(0, 0, 89), 17, 9.0, 3.0, -1, 1),Station("Tail", new(0, 0, 100), 6, 4.0, 0.0, -1, 0),};- return new(stableId, stations, ExplicitCorrespondence(stations), SectionTransitionPolicy.Ruled,- SectionTermination.Cap, SectionTermination.Cap);+ return new(stableId, stations, ExplicitCorrespondence(stations), smooth ? SectionTransitionPolicy.SmoothPolynomial : SectionTransitionPolicy.Ruled,+ SectionTermination.Cap, SectionTermination.Cap, smooth ? SectionChainContinuity.G1 : SectionChainContinuity.G0);}+ public static SectionChain ErgonomicFairingG1(string stableId = "surf-x4-section-chain-ergonomic-g1") =>+ ErgonomicFairing(stableId, smooth: true);+public static SectionChain TwistWitness(string stableId = "section-chain-twist"){var stations = new[]diff --git a/Aetheris.Surfacing/SectionChains.cs b/Aetheris.Surfacing/SectionChains.csindex bac0d5ec..c788201e 100644--- a/Aetheris.Surfacing/SectionChains.cs+++ b/Aetheris.Surfacing/SectionChains.cs@@ -6,6 +6,8 @@ using Aetheris.Kernel.Core.Geometry.Surfaces;using Aetheris.Kernel.Core.Math;using Aetheris.Kernel.Core.Topology;using System.Text.Json.Serialization;+using Aetheris.Kernel.Core.Judgment;+using Aetheris.Kernel.Core.Visualization;namespace Aetheris.Surfacing;@@ -51,7 +53,9 @@ public sealed record AdjacentSectionCorrespondence(IReadOnlyList<SectionSpanCorrespondence> Spans,string Resolution = "Explicit");-public enum SectionTransitionPolicy { Ruled }+public enum SectionTransitionPolicy { Ruled, SmoothPolynomial }+public enum SectionChainContinuity { G0, G1 }+public enum SectionChainSmoothPolicy { Fair }public enum SectionTermination { Cap, Open }public enum SectionChainStructureKind { ClosedSolid, OpenShell }@@ -61,7 +65,9 @@ public sealed record SectionChain(IReadOnlyList<AdjacentSectionCorrespondence> Correspondence,SectionTransitionPolicy TransitionPolicy,SectionTermination StartTermination,- SectionTermination EndTermination);+ SectionTermination EndTermination,+ SectionChainContinuity Continuity = SectionChainContinuity.G0,+ SectionChainSmoothPolicy SmoothPolicy = SectionChainSmoothPolicy.Fair);public static class SectionChainCanonical{@@ -78,7 +84,7 @@ public static class SectionChainCanonical});return $"{section.SectionId}@{section.Frame.Origin.X:R},{section.Frame.Origin.Y:R},{section.Frame.Origin.Z:R}:{string.Join(',', spans)}";});- return string.Join('|', chain.StableId, chain.TransitionPolicy, chain.StartTermination, chain.EndTermination, string.Join(';', sections));+ return string.Join('|', chain.StableId, chain.TransitionPolicy, chain.Continuity, chain.SmoothPolicy, chain.StartTermination, chain.EndTermination, string.Join(';', sections));}}@@ -130,10 +136,25 @@ public sealed record SectionChainMaterializationResult(public bool IsSuccess => Body is not null && Diagnostics.Count == 0;public SectionChainPcurveEvidence? Pcurves { get; init; }public SectionChainSelfIntersectionEvidence? SelfIntersection { get; init; }+ public SectionChainContinuityEvidence? ContinuityEvidence { get; init; }+ public SectionChainSmoothSelectionEvidence? SmoothSelection { get; init; }+ public string? PreviewSvg { get; init; }}+public sealed record SectionChainBoundaryContinuityEvidence(string SectionId, double MaximumPositionError,+ double MaximumNormalAngleDegrees, double MaximumTangentPlaneAngleDegrees);+public sealed record SectionChainContinuityEvidence(double MaximumPositionError, double MaximumNormalAngleDegrees,+ double MaximumTangentPlaneAngleDegrees, string? WorstBoundary,+ IReadOnlyList<SectionChainBoundaryContinuityEvidence> Boundaries);+public sealed record SectionChainSmoothCandidateEvidence(string Policy, double MagnitudeScale, bool Eligible,+ double BendingEnergy, double CurvatureVariation, double MaximumOvershoot, string? RejectionReason, double Utility);+public sealed record SectionChainSmoothSelectionEvidence(string TangentDerivation, string StationSpacingMetric,+ string EndpointPolicy, int CandidateCount, string SelectedPolicy,+ IReadOnlyList<SectionChainSmoothCandidateEvidence> Candidates);+public sealed record SectionChainEditDelta(string ReplacedSection,+ IReadOnlyList<string> RecomputedTangentFields,IReadOnlyList<string> RebuiltTransitions,IReadOnlyList<string> PreservedTransitions,IReadOnlyList<string> PreservedTerminations);@@ -146,13 +167,18 @@ public static class SectionChainEditorif (index < 0) throw new ArgumentException($"Section '{replacement.SectionId}' does not exist.", nameof(replacement));var sections = source.Sections.ToArray();sections[index] = replacement;- var rebuilt = new List<string>();- if (index > 0) rebuilt.Add(TransitionId(sections[index - 1].SectionId, sections[index].SectionId));- if (index < sections.Length - 1) rebuilt.Add(TransitionId(sections[index].SectionId, sections[index + 1].SectionId));+ var tangentIndices = source.Continuity == SectionChainContinuity.G1+ ? Enumerable.Range(Math.Max(0, index - 1), Math.Min(sections.Length - 1, index + 1) - Math.Max(0, index - 1) + 1).ToArray()+ : Array.Empty<int>();+ var transitionIndices = source.Continuity == SectionChainContinuity.G1+ ? tangentIndices.SelectMany(i => new[] { i - 1, i }).Where(i => i >= 0 && i < sections.Length - 1).Distinct().Order().ToArray()+ : new[] { index - 1, index }.Where(i => i >= 0 && i < sections.Length - 1).ToArray();+ var rebuilt = transitionIndices.Select(i => TransitionId(sections[i].SectionId, sections[i + 1].SectionId)).ToList();var preserved = Enumerable.Range(0, sections.Length - 1).Select(i => TransitionId(sections[i].SectionId, sections[i + 1].SectionId)).Where(id => !rebuilt.Contains(id, StringComparer.Ordinal)).ToArray();- return (source with { Sections = sections }, new(replacement.SectionId, rebuilt, preserved,+ return (source with { Sections = sections }, new(replacement.SectionId,+ tangentIndices.Select(i => sections[i].SectionId).ToArray(), rebuilt, preserved,["StartTermination", "EndTermination"]));}@@ -183,13 +209,27 @@ public static class SectionChainMaterializerreturn Failure(chain, diagnostics, profileMs, correspondenceMs);var transitionStarted = Stopwatch.GetTimestamp();- var transitionPatches = new List<(PreparedTransition Transition, RuledSurfacePatch[] Patches)>();- for (var transitionIndex = 0; transitionIndex < chain.Sections.Count - 1; transitionIndex++)+ var transitionPatches = new List<(PreparedTransition Transition, ISectionChainTransitionPatch[] Patches)>();+ SectionChainSmoothSelectionEvidence? smoothSelection = null;+ if (chain.TransitionPolicy == SectionTransitionPolicy.SmoothPolynomial)+ {+ var smooth = SmoothSectionChainBuilder.Build(chain, prepared.Select(item => item.Boundaries).ToArray(), resolved);+ if (!smooth.IsSuccess)+ {+ diagnostics.AddRange(smooth.Diagnostics);+ return Failure(chain, diagnostics, profileMs, correspondenceMs,+ Stopwatch.GetElapsedTime(transitionStarted).TotalMilliseconds);+ }+ smoothSelection = smooth.Selection;+ for (var index = 0; index < smooth.Patches.Count; index++)+ transitionPatches.Add((new(index, prepared[index], prepared[index + 1], resolved[index]), smooth.Patches[index]));+ }+ else for (var transitionIndex = 0; transitionIndex < chain.Sections.Count - 1; transitionIndex++){var source = prepared[transitionIndex];var target = prepared[transitionIndex + 1];var map = resolved[transitionIndex];- var patches = new RuledSurfacePatch[source.Boundaries.Length];+ var patches = new ISectionChainTransitionPatch[source.Boundaries.Length];for (var spanIndex = 0; spanIndex < source.Boundaries.Length; spanIndex++){var targetIndex = map[spanIndex];@@ -203,8 +243,8 @@ public static class SectionChainMaterializerforeach (var item in lowered.Diagnostics)diagnostics.Add(new SurfacingDiagnostic("section-chain-transition-invalid",$"{transitionId}/{source.Section.Profile.Spans[spanIndex].SpanId}: {item.Message}"));- else patches[spanIndex] = lowered.Patch;- if (lowered.Patch is { } patch && HasFoldover(patch))+ else patches[spanIndex] = new RuledSectionChainTransitionPatch(lowered.Patch);+ if (lowered.Patch is { } patch && HasFoldover(new RuledSectionChainTransitionPatch(patch)))diagnostics.Add(new("section-chain-transition-foldover",$"{transitionId}/{source.Section.Profile.Spans[spanIndex].SpanId}: sampled ruled Jacobian is singular or reverses orientation."));}@@ -260,17 +300,24 @@ public static class SectionChainMaterializerdiagnostics.Add(new("section-chain-pcurve-error", item));}var validationMs = Stopwatch.GetElapsedTime(validationStarted).TotalMilliseconds;+ var continuityEvidence = body is null ? null : MeasureContinuity(chain, transitionPatches);+ if (chain.Continuity == SectionChainContinuity.G1 && continuityEvidence is { MaximumTangentPlaneAngleDegrees: > 1e-3d })+ diagnostics.Add(new("section-chain-g1-verification-failed", $"Maximum tangent-plane discontinuity {continuityEvidence.MaximumTangentPlaneAngleDegrees:R} degrees exceeds 0.001 degrees."));if (diagnostics.Count > 0) body = null;return new(chain, body, Structure(chain), evidence, diagnostics,new(profileMs, correspondenceMs, transitionMs, stitchMs, validationMs))- { Pcurves = pcurveEvidence, SelfIntersection = selfIntersection.Evidence };+ { Pcurves = pcurveEvidence, SelfIntersection = selfIntersection.Evidence, ContinuityEvidence = continuityEvidence,+ SmoothSelection = smoothSelection, PreviewSvg = body is null ? null : BrepWireframeSvgRenderer.Render(body).Svg };}private static IReadOnlyList<SurfacingDiagnostic> Validate(SectionChain chain, IReadOnlyList<PreparedSection> sections){var diagnostics = new List<SurfacingDiagnostic>();if (string.IsNullOrWhiteSpace(chain.StableId)) diagnostics.Add(new("section-chain-id-invalid", "SectionChain requires a stable identity."));- if (chain.TransitionPolicy != SectionTransitionPolicy.Ruled) diagnostics.Add(new("section-chain-transition-policy-invalid", "X3 qualifies Ruled transitions only."));+ if (chain.TransitionPolicy == SectionTransitionPolicy.Ruled && chain.Continuity != SectionChainContinuity.G0)+ diagnostics.Add(new("section-chain-continuity-transition-incompatible", "Ruled transitions require Continuity G0."));+ if (chain.TransitionPolicy == SectionTransitionPolicy.SmoothPolynomial && chain.Continuity != SectionChainContinuity.G1)+ diagnostics.Add(new("section-chain-continuity-transition-incompatible", "SmoothPolynomial transitions currently require Continuity G1."));if (sections.Count < 2) diagnostics.Add(new("section-chain-section-count-invalid", "SectionChain requires at least two ordered sections."));if (sections.Select(section => section.Section.SectionId).Distinct(StringComparer.Ordinal).Count() != sections.Count)diagnostics.Add(new("section-chain-section-id-duplicate", "Section identities must be unique."));@@ -352,7 +399,7 @@ public static class SectionChainMaterializerprivate static (BrepBody Body, IReadOnlyList<SectionTransitionEvidence> Evidence) BuildBody(SectionChain chain,IReadOnlyList<PreparedSection> sections,- IReadOnlyList<(PreparedTransition Transition, RuledSurfacePatch[] Patches)> transitions)+ IReadOnlyList<(PreparedTransition Transition, ISectionChainTransitionPatch[] Patches)> transitions){var builder = new TopologyBuilder(); var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel();var points = new Dictionary<VertexId, Point3D>(); var nextCurve = 1; var nextSurface = 1;@@ -381,7 +428,9 @@ public static class SectionChainMaterializerfor (var vertex = 0; vertex < longitudinal.Length; vertex++){longitudinal[vertex] = builder.AddEdge(vertices[sourceIndex][vertex], vertices[targetIndex][vertex]);- BindLine(longitudinal[vertex], points[vertices[sourceIndex][vertex]], points[vertices[targetIndex][vertex]]);+ var curve = entry.Patches[vertex].LongitudinalBoundary(false);+ if (curve is null) BindLine(longitudinal[vertex], points[vertices[sourceIndex][vertex]], points[vertices[targetIndex][vertex]]);+ else BindSpline(longitudinal[vertex], curve.Value);}var surfaces = new List<SectionTransitionSurfaceEvidence>();for (var span = 0; span < transition.Source.Boundaries.Length; span++)@@ -456,6 +505,12 @@ public static class SectionChainMaterializergeometry.AddCurve(curveId, CurveGeometry.FromLine(new Line3Curve(start, Direction3D.Create(delta))));bindings.AddEdgeBinding(new(edge, curveId, new(0, delta.Length)));}+ void BindSpline(EdgeId edge, BSpline3Curve curve)+ {+ var curveId = new CurveGeometryId(nextCurve++);+ geometry.AddCurve(curveId, CurveGeometry.FromBSpline(curve));+ bindings.AddEdgeBinding(new(edge, curveId, new(curve.DomainStart, curve.DomainEnd)));+ }}private static PreparedSection Prepare(Section section)@@ -564,7 +619,7 @@ public static class SectionChainMaterializerreturn o1 * o2 < -Tolerance && o3 * o4 < -Tolerance;}- private static bool HasFoldover(RuledSurfacePatch patch)+ internal static bool HasFoldover(ISectionChainTransitionPatch patch){var normals = new Vector3D[17, 5];for (var uIndex = 0; uIndex <= 16; uIndex++)@@ -586,6 +641,40 @@ public static class SectionChainMaterializerreturn false;}+ private static SectionChainContinuityEvidence MeasureContinuity(SectionChain chain,+ IReadOnlyList<(PreparedTransition Transition, ISectionChainTransitionPatch[] Patches)> transitions)+ {+ var boundaries = new List<SectionChainBoundaryContinuityEvidence>();+ for (var section = 1; section < chain.Sections.Count - 1; section++)+ {+ var maxPosition = 0d; var maxNormal = 0d; var maxTangent = 0d;+ for (var span = 0; span < transitions[section - 1].Patches.Length; span++)+ for (var sample = 0; sample <= 32; sample++)+ {+ var u = sample / 32d; const double h = 1e-6d;+ var incoming = transitions[section - 1].Patches[span];+ var outgoing = transitions[section].Patches[span];+ maxPosition = Math.Max(maxPosition, (incoming.Evaluate(u, 1d) - outgoing.Evaluate(u, 0d)).Length);+ var incomingDu = incoming.Evaluate(Math.Min(1d, u + h), 1d) - incoming.Evaluate(Math.Max(0d, u - h), 1d);+ var outgoingDu = outgoing.Evaluate(Math.Min(1d, u + h), 0d) - outgoing.Evaluate(Math.Max(0d, u - h), 0d);+ var incomingDv = incoming.Evaluate(u, 1d) - incoming.Evaluate(u, 1d - h);+ var outgoingDv = outgoing.Evaluate(u, h) - outgoing.Evaluate(u, 0d);+ if (incomingDv.TryNormalize(out var ti) && outgoingDv.TryNormalize(out var to))+ maxTangent = Math.Max(maxTangent, AngleDegrees(ti, to));+ var ni = incomingDu.Cross(incomingDv); var no = outgoingDu.Cross(outgoingDv);+ if (ni.TryNormalize(out var nui) && no.TryNormalize(out var nuo))+ maxNormal = Math.Max(maxNormal, AngleDegrees(nui, nuo));+ }+ boundaries.Add(new(chain.Sections[section].SectionId, maxPosition, maxNormal, maxTangent));+ }+ var worst = boundaries.OrderByDescending(item => item.MaximumTangentPlaneAngleDegrees).ThenBy(item => item.SectionId, StringComparer.Ordinal).FirstOrDefault();+ return new(boundaries.Count == 0 ? 0d : boundaries.Max(item => item.MaximumPositionError),+ boundaries.Count == 0 ? 0d : boundaries.Max(item => item.MaximumNormalAngleDegrees),+ boundaries.Count == 0 ? 0d : boundaries.Max(item => item.MaximumTangentPlaneAngleDegrees), worst?.SectionId, boundaries);++ static double AngleDegrees(Vector3D a, Vector3D b) => Math.Acos(Math.Clamp(a.Dot(b), -1d, 1d)) * 180d / Math.PI;+ }+private static SectionPoint2D Lerp(SectionPoint2D a, SectionPoint2D b, double t) =>new(a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t);diff --git a/Aetheris.Surfacing/SmoothSectionChains.cs b/Aetheris.Surfacing/SmoothSectionChains.csnew file mode 100644index 00000000..c973c8ce--- /dev/null+++ b/Aetheris.Surfacing/SmoothSectionChains.cs@@ -0,0 +1,225 @@+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Judgment;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Surfacing;++internal interface ISectionChainTransitionPatch+{+ SurfaceGeometry ExactSurface { get; }+ SurfaceMaterializationKind MaterializationKind { get; }+ Point3D Evaluate(double u, double v);+ BSpline3Curve? LongitudinalBoundary(bool atEndU);+}++internal sealed record RuledSectionChainTransitionPatch(RuledSurfacePatch Patch) : ISectionChainTransitionPatch+{+ public SurfaceGeometry ExactSurface => Patch.ExactSurface;+ public SurfaceMaterializationKind MaterializationKind => Patch.MaterializationKind;+ public Point3D Evaluate(double u, double v) => Patch.Evaluate(u, v);+ public BSpline3Curve? LongitudinalBoundary(bool atEndU) => null;+}++internal sealed record SmoothSectionChainTransitionPatch(BSplineSurfaceWithKnots Spline) : ISectionChainTransitionPatch+{+ public SurfaceGeometry ExactSurface => SurfaceGeometry.FromBSplineSurfaceWithKnots(Spline);+ public SurfaceMaterializationKind MaterializationKind => SurfaceMaterializationKind.ExactPolynomialBSpline;+ public Point3D Evaluate(double u, double v) => Spline.Evaluate(u, v);+ public BSpline3Curve? LongitudinalBoundary(bool atEndU)+ {+ var controls = Spline.ControlPoints[atEndU ? ^1 : 0];+ return new(3, controls, [4, 4], [0d, 1d], "UNSPECIFIED", false, false, "UNSPECIFIED");+ }+}++internal sealed record SmoothSectionChainBuildResult(IReadOnlyList<ISectionChainTransitionPatch[]> Patches,+ SectionChainSmoothSelectionEvidence? Selection, IReadOnlyList<SurfacingDiagnostic> Diagnostics)+{+ public bool IsSuccess => Diagnostics.Count == 0;+}++internal static class SmoothSectionChainBuilder+{+ private static readonly (string Name, double Scale)[] Policies =+ [+ ("ConservativeCompact", 0.5d),+ ("CentripetalLike", 0.75d),+ ("ChordLengthFair", 1d)+ ];++ public static SmoothSectionChainBuildResult Build(SectionChain chain, IReadOnlyList<RuledBoundary[]> boundaries,+ IReadOnlyList<int[]> correspondence)+ {+ var diagnostics = ValidateCompatibility(chain, boundaries, correspondence).ToList();+ if (diagnostics.Count > 0) return new([], null, diagnostics);+ var stations = StationParameters(chain);+ var candidates = Policies.Select(policy => MaterializeCandidate(chain, boundaries, correspondence, stations, policy.Name, policy.Scale)).ToArray();+ var context = new CandidateContext(candidates);+ var judged = new JudgmentEngine<CandidateContext>().Evaluate(context, candidates.Select(candidate =>+ new JudgmentCandidate<CandidateContext>(candidate.Name, _ => candidate.RejectionReason is null,+ _ => candidate.Utility, _ => candidate.RejectionReason ?? "ineligible",+ TieBreakerPriority: Array.FindIndex(Policies, item => item.Name == candidate.Name))).ToArray());+ if (!judged.IsSuccess)+ {+ diagnostics.AddRange(candidates.Where(c => c.RejectionReason is not null).Select(c =>+ new SurfacingDiagnostic(c.RejectionReason!.StartsWith("section-chain-g1-overshoot", StringComparison.Ordinal)+ ? "section-chain-g1-overshoot" : "section-chain-g1-foldover", $"{c.Name}: {c.RejectionReason}")));+ diagnostics.Add(new("section-chain-g1-no-eligible-solution", "No bounded non-rational cubic tangent policy passed foldover and overshoot eligibility."));+ return new([], Evidence(candidates, "<none>"), diagnostics);+ }+ var selected = candidates.Single(item => item.Name == judged.Selection!.Value.Candidate.Name);+ return new(selected.Patches, Evidence(candidates, selected.Name), []);+ }++ private static IEnumerable<SurfacingDiagnostic> ValidateCompatibility(SectionChain chain, IReadOnlyList<RuledBoundary[]> boundaries,+ IReadOnlyList<int[]> correspondence)+ {+ for (var transition = 0; transition < correspondence.Count; transition++)+ for (var span = 0; span < correspondence[transition].Length; span++)+ {+ var a = ExtractCurveData(boundaries[transition][span]);+ var b = ExtractCurveData(boundaries[transition + 1][correspondence[transition][span]]);+ var identity = $"{chain.Sections[transition].SectionId}->{chain.Sections[transition + 1].SectionId}/{chain.Sections[transition].Profile.Spans[span].SpanId}";+ if (a is null || b is null)+ yield return new("section-chain-g1-degree-limit", $"{identity}: G1 currently admits line and polynomial B-spline profile spans; circular arcs require a future bounded polynomial normalization.");+ else if (a.Degree != b.Degree || !a.Multiplicities.SequenceEqual(b.Multiplicities) || !a.Knots.SequenceEqual(b.Knots))+ yield return new("section-chain-g1-degree-limit", $"{identity}: corresponding spans require equal non-rational degree and knot structure in the bounded G1 lane.");+ }+ }++ private static Candidate MaterializeCandidate(SectionChain chain, IReadOnlyList<RuledBoundary[]> boundaries,+ IReadOnlyList<int[]> correspondence, IReadOnlyList<double> stations, string name, double scale)+ {+ var controls = boundaries.Select(section => section.Select(boundary => ExtractCurveData(boundary)!).ToArray()).ToArray();+ var patches = new List<ISectionChainTransitionPatch[]>();+ for (var transition = 0; transition < chain.Sections.Count - 1; transition++)+ {+ var spanPatches = new ISectionChainTransitionPatch[controls[transition].Length];+ for (var span = 0; span < spanPatches.Length; span++)+ {+ var targetSpan = correspondence[transition][span];+ var source = controls[transition][span]; var target = controls[transition + 1][targetSpan];+ var net = new Point3D[source.Points.Count][];+ var distance = stations[transition + 1] - stations[transition];+ for (var point = 0; point < net.Length; point++)+ {+ var d0 = Tangent(controls, correspondence, stations, transition, span, point);+ var d1 = Tangent(controls, correspondence, stations, transition + 1, targetSpan, point);+ net[point] = [source.Points[point], source.Points[point] + d0 * (distance * scale / 3d),+ target.Points[point] - d1 * (distance * scale / 3d), target.Points[point]];+ }+ var spline = new BSplineSurfaceWithKnots(source.Degree, 3, net, "UNSPECIFIED", false, false, false,+ source.Multiplicities, [4, 4], source.Knots, [0d, 1d], "UNSPECIFIED");+ spanPatches[span] = new SmoothSectionChainTransitionPatch(spline);+ }+ patches.Add(spanPatches);+ }+ var flat = patches.SelectMany(item => item).ToArray();+ var foldover = flat.Any(SectionChainMaterializer.HasFoldover);+ var maxOvershoot = MaximumOvershoot(chain, flat);+ var bending = BendingEnergy(flat); var variation = NormalVariation(flat);+ var rejection = foldover ? "section-chain-g1-foldover: sampled Jacobian is singular or reverses orientation"+ : maxOvershoot > 0.55d ? $"section-chain-g1-overshoot: normalized envelope deviation {maxOvershoot:R} exceeds 0.55" : null;+ var utility = rejection is null ? 1d / (1d + bending + 0.25d * variation + 0.1d * maxOvershoot) : 0d;+ return new(name, scale, patches, bending, variation, maxOvershoot, rejection, utility);+ }++ private static Vector3D Tangent(CurveData[][] sections, IReadOnlyList<int[]> maps, IReadOnlyList<double> s,+ int section, int span, int point)+ {+ var current = sections[section][span].Points[point];+ if (section == 0)+ {+ var nextSpan = maps[0][span];+ return (sections[1][nextSpan].Points[point] - current) / (s[1] - s[0]);+ }+ if (section == sections.Length - 1)+ {+ var previousSpan = Array.IndexOf(maps[section - 1], span);+ return (current - sections[section - 1][previousSpan].Points[point]) / (s[section] - s[section - 1]);+ }+ var previous = Array.IndexOf(maps[section - 1], span); var next = maps[section][span];+ var h0 = s[section] - s[section - 1]; var h1 = s[section + 1] - s[section];+ var p0 = sections[section - 1][previous].Points[point]; var p2 = sections[section + 1][next].Points[point];+ return (p0 - Point3D.Origin) * (-h1 / (h0 * (h0 + h1)))+ + (current - Point3D.Origin) * ((h1 - h0) / (h0 * h1))+ + (p2 - Point3D.Origin) * (h0 / (h1 * (h0 + h1)));+ }++ private static IReadOnlyList<double> StationParameters(SectionChain chain)+ {+ var result = new double[chain.Sections.Count];+ for (var i = 1; i < result.Length; i++) result[i] = result[i - 1] + (chain.Sections[i].Frame.Origin - chain.Sections[i - 1].Frame.Origin).Length;+ return result;+ }++ private static CurveData? ExtractCurveData(RuledBoundary boundary) => boundary switch+ {+ RuledBoundary.Line line => new(3,+ [line.Start, line.Start + (line.End - line.Start) / 3d, line.Start + (line.End - line.Start) * (2d / 3d), line.End],+ [4, 4], [0d, 1d]),+ RuledBoundary.BSpline spline => new(spline.Curve.Degree, spline.Curve.ControlPoints,+ spline.Curve.KnotMultiplicities, spline.Curve.KnotValues),+ _ => null+ };++ private static double MaximumOvershoot(SectionChain chain, IReadOnlyList<ISectionChainTransitionPatch> patches)+ {+ var points = chain.Sections.SelectMany(section => section.Profile.Spans.SelectMany(span => span.Curve switch+ {+ SectionProfileCurve.Line line => new[] { section.Frame.Transform(line.Start), section.Frame.Transform(line.End) },+ SectionProfileCurve.PolynomialBSpline spline => spline.ControlPoints.Select(section.Frame.Transform),+ _ => Array.Empty<Point3D>()+ })).ToArray();+ var diagonal = new Vector3D(points.Max(p => p.X) - points.Min(p => p.X), points.Max(p => p.Y) - points.Min(p => p.Y), points.Max(p => p.Z) - points.Min(p => p.Z)).Length;+ var max = 0d;+ foreach (var patch in patches) for (var u = 0; u <= 8; u++) for (var v = 0; v <= 8; v++)+ {+ var p = patch.Evaluate(u / 8d, v / 8d);+ var outside = Math.Max(0, points.Min(x => x.X) - p.X) + Math.Max(0, p.X - points.Max(x => x.X))+ + Math.Max(0, points.Min(x => x.Y) - p.Y) + Math.Max(0, p.Y - points.Max(x => x.Y))+ + Math.Max(0, points.Min(x => x.Z) - p.Z) + Math.Max(0, p.Z - points.Max(x => x.Z));+ max = Math.Max(max, outside / Math.Max(diagonal, 1e-9));+ }+ return max;+ }++ private static double BendingEnergy(IReadOnlyList<ISectionChainTransitionPatch> patches) => patches.Sum(patch =>+ {+ var energy = 0d;+ for (var u = 1; u < 8; u++) for (var v = 1; v < 8; v++)+ {+ var c = patch.Evaluate(u / 8d, v / 8d);+ var longitudinal = (patch.Evaluate(u / 8d, (v + 1) / 8d) - c)+ - (c - patch.Evaluate(u / 8d, (v - 1) / 8d));+ energy += longitudinal.LengthSquared;+ }+ return energy / 49d;+ });++ private static double NormalVariation(IReadOnlyList<ISectionChainTransitionPatch> patches) => patches.Sum(patch =>+ {+ var variation = 0d; Vector3D? previous = null;+ for (var v = 0; v <= 16; v++)+ {+ var t = v / 16d; const double h = 1e-5;+ var normal = (patch.Evaluate(.5 + h, t) - patch.Evaluate(.5 - h, t)).Cross(patch.Evaluate(.5, Math.Min(1, t + h)) - patch.Evaluate(.5, Math.Max(0, t - h)));+ if (normal.TryNormalize(out var n) && previous is { } p) variation += Math.Acos(Math.Clamp(p.Dot(n), -1d, 1d));+ if (normal.TryNormalize(out n)) previous = n;+ }+ return variation;+ });++ private static SectionChainSmoothSelectionEvidence Evidence(IReadOnlyList<Candidate> candidates, string selected) =>+ new("world-space nonuniform three-section quadratic derivative stencil", "cumulative section-frame-origin chord length",+ "one-sided first chord derivative", candidates.Count, selected,+ candidates.Select(c => new SectionChainSmoothCandidateEvidence(c.Name, c.Scale, c.RejectionReason is null,+ c.Bending, c.Variation, c.Overshoot, c.RejectionReason, c.Utility)).ToArray());++ private sealed record CurveData(int Degree, IReadOnlyList<Point3D> Points, IReadOnlyList<int> Multiplicities, IReadOnlyList<double> Knots);+ private sealed record Candidate(string Name, double Scale, IReadOnlyList<ISectionChainTransitionPatch[]> Patches,+ double Bending, double Variation, double Overshoot, string? RejectionReason, double Utility);+ private sealed record CandidateContext(IReadOnlyList<Candidate> Candidates);+}diff --git a/docs/public/README.md b/docs/public/README.mdindex d09705c2..5948890f 100644--- a/docs/public/README.md+++ b/docs/public/README.md@@ -9,7 +9,7 @@ Start with [Getting Started](getting-started.md), then use these guides:- Standard Library: [product-family index, invocation, authoring, and compatibility](standard-library/README.md)- Interoperability: [Forge Host Protocol v1](forge/interop.md)- Inspection: [Cadmata](cadmata/overview.md) and [Cadmata PMI](cadmata/pmi.md)-- Reference: [CLI](reference/cli.md), [targets/selectors](reference/targets.md), [diagnostics](reference/diagnostics.md), [supported features](reference/supported-features.md), [known issues](reference/known-issues.md), and [release notes](reference/release-notes.md)+- Reference: [CLI](reference/cli.md), [wireframe SVG previews](reference/wireframe.md), [targets/selectors](reference/targets.md), [diagnostics](reference/diagnostics.md), [supported features](reference/supported-features.md), [known issues](reference/known-issues.md), and [release notes](reference/release-notes.md)The Windows ZIP begins with the tested [release-bundle walkthrough](release-bundle.md).diff --git a/docs/public/firmament/section-chains.md b/docs/public/firmament/section-chains.mdindex e1ca72e7..079f522e 100644--- a/docs/public/firmament/section-chains.md+++ b/docs/public/firmament/section-chains.md@@ -1,6 +1,6 @@# Section chains-A SectionChain builds a surface or closed body from an ordered sequence of framed profiles. It is the low-level ruled-loft substrate for cases where the profile itself changes from station to station.+A SectionChain builds a surface or closed body from an ordered sequence of framed profiles. G1 is the normal freeform authoring default; explicit G0/Ruled remains available when straight generators are intentional.```textSection0 -> Section1 -> Section2 -> Section3@@ -10,9 +10,13 @@ Each `Section` owns a stable `SectionId`, a complete right-handed frame (`OriginAdjacent sections use one-to-one semantic span correspondence. Matching IDs may establish strong semantic identity, while explicit `AdjacentSectionCorrespondence` records the mapping in the flagship. Aetheris does not silently use nearest points, nearest edges, or tessellated vertex indices to define topology. The X3 lane requires the same span count and seam-relative order on both sides of a transition.-`Ruled` is the only qualified transition policy. Each matched pair is sent through the existing `RuledSurfaceIr` lowering path, so there is one mathematical ruled implementation. Exact planar line pairs become `PLANE`; compatible line/B-spline and B-spline/B-spline pairs become exact non-rational `B_SPLINE_SURFACE_WITH_KNOTS`; coaxial compatible circles retain existing cylinder/cone recognition. Rational product surfaces are prohibited.+Continuity intent and transition law are separate. `Continuity: G0` selects the existing `Ruled` law. `Continuity: G1` selects local `SmoothPolynomial` transitions. G0 makes adjacent surfaces meet. G1 also makes their tangent planes agree, so highlights and silhouettes flow smoothly across section boundaries.-Every internal section edge is allocated once. The preceding and following transition faces use that same edge, curve, vertices, and parameter direction. Editing one section therefore rebuilds only its two adjacent transition identities; distant transitions and terminal conditions remain preserved in `SectionChainEditDelta`.+For G1, Aetheris transforms corresponding polynomial controls into world space and derives a shared tangent field at every section. Interior tangents use a nonuniform three-section quadratic-derivative stencil; cumulative frame-origin chord length is the station metric, and endpoints use a bounded one-sided chord derivative. Three deterministic magnitude policies are qualified for foldover and overshoot before the Judgment Engine compares bending energy and normal variation. Continuity is a hard eligibility constraint, never an aesthetic score.++Each matched span becomes an exact non-rational cubic transition in the longitudinal direction. Lines are exactly degree-elevated to cubic when needed; compatible polynomial B-splines retain their boundary geometry and knot structure. Circular-arc G1 normalization and mixed incompatible knot structures currently fail with `section-chain-g1-degree-limit`; Aetheris never introduces rational weights or a faceted fallback. The G0 path still preserves exact plane/cylinder/cone recognition where applicable.++Every internal section edge is allocated once. The preceding and following transition faces use that same edge, curve, vertices, and parameter direction. For G0, editing one section rebuilds its two adjacent transitions. G1 has a bounded dependency neighborhood: editing section `i` recomputes tangent fields `i-1..i+1` and may rebuild transitions `i-2->i-1` through `i+1->i+2`. Distant transitions and terminal conditions remain preserved in `SectionChainEditDelta`; there is no global loft solve.Every transition and cap coedge also owns a face-local pcurve. Aetheris builds these through the same bounded Plane/Cylinder/non-rational-B-spline machinery used by trimmed SURF faces, then independently checks reconstruction deviation, surface-domain containment, both oriented endpoints, and UV loop closure. The two faces meeting at an internal section therefore share one authoritative 3D edge while retaining separate local 2D representations.@@ -38,7 +42,7 @@ Concept Path NoseOutline {Profile NoseProfile From NoseOutlineSectionChain Fairing {- Transition: Ruled+ Continuity: G1Section Nose {Frame: NoseFrameProfile: NoseProfile@@ -54,7 +58,7 @@ SectionChain Fairing {}```-Equal ordered span identities infer correspondence. When identities differ, author a `Correspond` block with `From`, `To`, and explicit `Source -> Target` rows. Missing, incomplete, reordered, or duplicate mappings fail before BRep construction. `Ruled`, `Cap`, and `Open` are the only currently qualified transition/termination vocabulary.+Equal ordered span identities infer correspondence. When identities differ, author a `Correspond` block with `From`, `To`, and explicit `Source -> Target` rows. Missing, incomplete, reordered, or duplicate mappings fail before BRep construction. Omit `Continuity` for the G1 default, or write `Continuity: G0` and `Transition: Ruled` for intentionally faceted/straight-generator construction. G2 is not claimed. `Cap` and `Open` remain separate termination intent; planar caps meet the transition at G0 unless separately designed.```firmamentCorrespond NoseToFront {@@ -76,14 +80,14 @@ A SectionChain is useful as a geometric generator: each framed profile is an ordGenerate and inspect the eight-section flagship through the production BRep/STEP path:```powershell-aetheris section-chain validate fixtures/Canonical/SectionChain/eight-section-ergonomic.firmament --json-aetheris section-chain inspect fixtures/Canonical/SectionChain/eight-section-ergonomic.firmament --json-aetheris section-chain build fixtures/Canonical/SectionChain/eight-section-ergonomic.firmament --out artifacts/local/surf-x3a/fairing.step --json+aetheris section-chain inspect flagship --json+aetheris section-chain build flagship-g0 --out artifacts/local/surf-x4/surf-x4-ergonomic-g0.step --json+aetheris section-chain build flagship --out artifacts/local/surf-x4/surf-x4-ergonomic-g1.step --json```On a source checkout where the tool is not installed, replace `aetheris` with `dotnet run --project Aetheris.CLI -c Release --`.-The compatibility `section-chain build` command also supports the generated `flagship`, `twist`, and `two-profile` witnesses. That standalone command writes sibling `.evidence.json` containing section frames, spans, correspondence, transition classes, terminations, topology, pcurve qualification, conservative intersection evidence, timings, SHA-256, rational-surface count, and STEP reimport evidence. Ordinary X3b BodyState `build` instead writes the sculpting `.delta.json` construction/delta evidence described in the sculpting guide; it does not write both sibling formats.+The compatibility command supports `flagship` (G1), `flagship-g0`, `twist`, and `two-profile`. Its structured inspection/evidence includes continuity intent, tangent derivation, candidate/rejection metrics, the selected policy, measured G0/G1 errors, representation, pcurves, topology, SHA-256, and STEP reimport. Its sibling preview uses the same general [BRep wireframe renderer](../reference/wireframe.md) exposed by `aetheris wireframe`; SectionChains no longer own a private visualization implementation.SURF-X3b adds a bounded `BodyState` composition lane. `AddSectionChain` retains the chain, terminal Section, semantic support, span correspondence, authorized envelope, preservation contracts, and requirements as one typed replay operation. `RemoveSectionChain` retains the changing-profile tool and both explicit penetration supports. Neither lowers to public `Union` or `Difference`; a SectionChain-specific builder emits the known shared topology directly.@@ -100,6 +104,6 @@ The current canonical grip qualifies 24 faces, 50 edges, 28 vertices, and 100 pc## Current limits-The standalone lane has one closed outer loop, no holes, same-topology one-to-one correspondence, ruled transitions, and Cap/Open terminals. It checks frame handedness, loop closure and orientation, sampled profile self-intersection, section spacing, semantic mapping order, sampled transition Jacobian foldover, non-neighbour transition crossings, and remote cap penetration using a deterministic validation-only triangle proxy. The proxy is conservative detection evidence, not a global proof. BodyState composition is additionally limited to the planar housing support lanes described above; arbitrary supports, rotated/non-four-line profiles, crown/patch predecessors, branches, G1/G2 continuity, and arbitrary freeform Boolean composition fail closed. Invalid chains never produce a faceted product fallback.+The standalone lane has one closed outer loop, no holes, same-topology one-to-one correspondence, G0/G1 pairwise transitions, and Cap/Open terminals. It checks frame handedness, loop closure/orientation, profile self-intersection, physical spacing, semantic mapping order, transition Jacobian foldover, bounded overshoot, non-neighbour crossings, remote cap penetration, pcurves, and realized continuity. The triangle proxy is conservative detection evidence, not a global proof. BodyState composition remains limited to the planar housing support lanes; arbitrary supports, branches, G2, rail lofts, topology-changing correspondence, and arbitrary freeform Boolean composition fail closed.Stable diagnostic families include `section-chain-correspondence-missing`, `section-chain-correspondence-duplicate`, `section-chain-profile-orientation-mismatch`, `section-chain-transition-foldover`, `section-chain-self-intersection`, and `section-chain-pcurve-error`. `section-chain validate` returns a nonzero exit status and emits no STEP when any of these blocks materialization. Transition identities are formatted `SourceSection->TargetSection` in structured evidence and diagnostic detail.diff --git a/docs/public/reference/cli.md b/docs/public/reference/cli.mdindex 041be734..43af526d 100644--- a/docs/public/reference/cli.md+++ b/docs/public/reference/cli.md@@ -13,6 +13,7 @@ Primary public commands:| `sheetmetal ...` | Inspect, recognize, recover, compare, or flatten Sheet Metal || `sculpture build <source> ...` | Build the bounded non-manufacturing Sol 1 AP242 artwork, evidence, and SVG preview || `section-chain <build\|inspect\|validate> <file.firmament\|flagship\|twist\|two-profile> ...` | Lower authored profiles into SectionChain IR and report frames, spans, correspondence, pcurves, conservative intersection qualification, STEP, and reimport evidence |+| `wireframe <model.step> [--out preview.svg] [--view iso\|front\|top\|right] [--density N] [--json]` | Render deterministic exact-edge and trim-clipped surface-isoline SVG evidence || `asm ...` | Inspect/execute/import/export assemblies |-Run `aetheris <command> --help` for exact options. JSON is a public automation surface, but its root is command-specific: process exit status is authoritative, `validate` reports `firmamentV2Validation.status`, and materializing/analysis commands report `success` where documented. Diagnostics are structured; artifact paths are explicit; Sheet Metal reports regions, bends, and lowered features separately; FEA reports requested/result artifacts; sculpting builds report every `BodyState`, `GeometricDelta`, validation evidence, surface-family inventory, and the sibling `.delta.json` path; other builds report emitted features and PMI export evidence. Counts describe semantic items at the stated layer, not arbitrary STEP entity counts.+Run `aetheris <command> --help` for exact options. JSON is a public automation surface, but its root is command-specific: process exit status is authoritative, `validate` reports `firmamentV2Validation.status`, and materializing/analysis commands report `success` where documented. Diagnostics are structured; artifact paths are explicit; wireframe reports trim/pcurve coverage and a deterministic SVG hash; Sheet Metal reports regions, bends, and lowered features separately; FEA reports requested/result artifacts; sculpting builds report every `BodyState`, `GeometricDelta`, validation evidence, surface-family inventory, and the sibling `.delta.json` path; other builds report emitted features and PMI export evidence. Counts describe semantic items at the stated layer, not arbitrary STEP entity counts.diff --git a/docs/public/reference/wireframe.md b/docs/public/reference/wireframe.mdnew file mode 100644index 00000000..a46647f7--- /dev/null+++ b/docs/public/reference/wireframe.md@@ -0,0 +1,20 @@+# Wireframe SVG previews++`aetheris wireframe` renders a deterministic SVG inspection preview from an imported STEP BRep:++```powershell+aetheris wireframe model.step --out model.wireframe.svg --view iso --density 8 --json+```++Available views are `iso`, `front`, `top`, and `right`. `--density` controls the number of interior constant-parameter lines per face from `2` through `32`; `--samples` controls curve sampling from `8` through `256`.++The renderer draws two kinds of evidence:++- bright boundary lines sampled from the BRep's authoritative bound 3D edge curves;+- translucent constant-`u` and constant-`v` lines evaluated on exact face supports and clipped against face-local pcurve loops with the even/odd trim rule.++STEP imports that do not retain usable pcurve bindings are passed through Aetheris's bounded pcurve recovery before rendering. JSON reports the view, density, topology counts, face coverage, isoline/boundary polyline counts, surface-family inventory, pcurve recovery result, unsupported families, and deterministic SVG SHA-256.++The current exact-support evaluator covers planes, cylinders, cones, spheres, tori, linear extrusions, surfaces of revolution, and non-rational B-spline surfaces. A face without usable trim loops remains visible through its topology edges but does not receive speculative interior isolines.++This output is a diagnostic visualization. It is not a tessellated product representation, hidden-line-removed engineering drawing, shaded render, or substitute for STEP/BRep validation. All lines remain visible through the model, deliberately producing the technical “x-ray wireframe” appearance.diff --git a/docs/release/SURF-X4-CONTINUOUS-SECTION-CHAINS.md b/docs/release/SURF-X4-CONTINUOUS-SECTION-CHAINS.mdnew file mode 100644index 00000000..24f4c1f3--- /dev/null+++ b/docs/release/SURF-X4-CONTINUOUS-SECTION-CHAINS.md@@ -0,0 +1,61 @@+# SURF-X4 — continuous section chains++## Executive verdict++**Accepted for the bounded SectionChain lane.** Aetheris can materialize changing-profile G1 SectionChains with compiler-derived, world-space tangent fields, exact non-rational polynomial product surfaces, shared BRep topology, deterministic candidate selection, and bounded edit/replay dependencies. G2, rail lofts, global surface fitting, topology-changing correspondence, and general freeform Booleans remain outside the claim.++## Architecture audit++1. **Reused from BlendBoundary:** hard continuity eligibility before scoring, deterministic `JudgmentEngine` selection/manual-policy structure, bending/normal-variation quality concepts, non-rational representation gates, and independent realized-boundary verification.+2. **Reused non-rational construction:** `BSplineSurfaceWithKnots`, `BSpline3Curve`, STEP polynomial B-spline export/import, BRep face/edge bindings, shared topology, and bounded pcurve construction/validation.+3. **Specialized for SectionChains:** semantic-span control correspondence, frame-to-world conversion, cumulative frame-origin chord spacing, a nonuniform three-section derivative stencil, one-sided endpoint tangents, pairwise Hermite control nets, longitudinal seam curves, overshoot/foldover qualification, and bounded edit locality.+4. **Kept different from pairwise boundary blending:** BlendBoundary's planar vanishing-power shape is not a longitudinal tangent estimator. SectionChain does not replace a region against an analytic shoulder and does not request G2 normal-curvature matching. It interpolates every authored station and shares one tangent direction between two neighboring pairwise patches.+5. **Untouched Ruled paths:** explicit G0 SectionChains still use `RuledSurfaceIr`/`RuledSurfaceLowering`; old Firmament fixtures with `Transition: Ruled` migrate to G0; Sweep/Paperclip remains on its cylinder/torus/plane path; X3b sources without a continuity field retain G0 replay semantics.++## Tangent derivation and judgment++At section `i`, corresponding polynomial controls are first transformed through their complete section frames. Interior derivatives are the derivative at the middle sample of the nonuniform quadratic through sections `i-1`, `i`, and `i+1`. Station parameter is cumulative Euclidean distance between frame origins. Endpoints use the first/last one-sided chord derivative.++Each transition is a cubic Hermite/Bezier polynomial in the longitudinal parameter. Candidate magnitude scales are `ConservativeCompact = 0.5`, `CentripetalLike = 0.75`, and `ChordLengthFair = 1.0`. Foldover and normalized envelope overshoot are hard rejection gates. Eligible candidates are scored deterministically from bending energy, normal variation, and compactness; ties use declared policy order and ordinal name. Continuity is independently sampled after construction and cannot be traded for quality.++The selected flagship policy and all raw metrics are emitted by `section-chain inspect/build --json`; constants are centralized in `SmoothSectionChainBuilder`.++## Representation and topology++The eight-section flagship has 7 transitions and 28 polynomial transition faces. Its line spans are exactly degree-elevated and its existing cubic profile spans retain compatible knots. The longitudinal degree is 3; no rational weights exist. Adjacent patches reuse actual section edges and vertices, while each coedge receives its own face-local pcurve. Terminal planar caps are claimed only as G0.++The product boundary remains:++```text+RationalProductSurfaces = 0+FacetedCanonicalFallback = 0+```++Circular-arc G1 spans and incompatible polynomial degrees/knot structures currently fail closed with `section-chain-g1-degree-limit`; they are not rationalized.++## Locality and construction state++G0 edit locality remains the two adjacent transitions. With the G1 three-section stencil, editing `Rise` recomputes tangent fields `PalmFront`, `Rise`, and `Peak`, and rebuilds `Front->PalmFront`, `PalmFront->Rise`, `Rise->Peak`, and `Peak->PalmRear`. `Nose->Front`, `PalmRear->Rear`, and `Rear->Tail` remain preserved. This set is recorded by `SectionChainEditDelta`.++`SectionChain` stores sections, frames, profiles, correspondence, `Continuity`, `TransitionPolicy`, and `SmoothPolicy`; tangent fields and control nets are derived evidence rather than semantic authority. Existing typed `AddSectionChain`/`RemoveSectionChain` construction-state payloads therefore replay the intent. The bounded housing builder consumes the exact transition supports and longitudinal curves produced by the same materializer.++## Before/after and reproduction++The two flagship commands use the identical eight-section definition; only continuity/transition intent differs:++```powershell+dotnet run --project Aetheris.CLI -c Release -- section-chain build flagship-g0 --out artifacts/local/surf-x4/surf-x4-ergonomic-g0.step --json+dotnet run --project Aetheris.CLI -c Release -- section-chain build flagship --out artifacts/local/surf-x4/surf-x4-ergonomic-g1.step --json+```++The G0 artifact has straight ruled generators and visible station tangent changes. The G1 artifact interpolates the same profiles using shared cross-section tangent directions. Machine-specific STEP files, evidence JSON, and previews remain under ignored `artifacts/local/surf-x4/` per generated-artifact policy.++The preview implementation is now a shared Kernel.Core BRep renderer rather than SectionChain-specific code. `aetheris wireframe model.step` reimports any qualified STEP body, recovers bounded pcurves when required, draws authoritative topology curves, and clips exact-support isolines against trim loops. SectionChain sibling previews consume this same path.++## Qualification++Release validation covers Release build, SectionChain G0 regressions, G1 flagship construction, nonuniform spacing via its unequal flagship chord intervals, world-space twisted frames, semantic correspondence, endpoints, foldover/self-intersection, overshoot candidate qualification, independent G0/G1 metrics, pcurves/shared topology, zero rational STEP output, reimport, deterministic repeat export, Firmament G0/G1 binding, and bounded edit locality. The full serial repository suite is the final regression gate, including SURF-X2/X3/X3b and Paperclip/Sweep tests.++## Manual review checklist++Compare the G0 and G1 artifacts from one camera and inspect section bands, highlight continuity, flat spots, pinching, bulging/overshoot, nose/tail behavior, silhouette quality, and whether the result reads as one smooth sculpted mass. For G1 grips inspect attachment and remote preservation; for ducts inspect internal flow, membranes, and constrictions.diff --git a/fixtures/Canonical/BodyState/surf-x4-add-section-chain-g1-grip.firmament b/fixtures/Canonical/BodyState/surf-x4-add-section-chain-g1-grip.firmamentnew file mode 100644index 00000000..92b8e3d6--- /dev/null+++ b/fixtures/Canonical/BodyState/surf-x4-add-section-chain-g1-grip.firmament@@ -0,0 +1,38 @@+Model SurfX4AddSectionChainG1Grip {+ Units: mm+ SectionChain GripChain {+ Continuity: G1+ StartTermination: Open+ EndTermination: Cap+ Station Attach { Origin: [0mm, 0mm, 10mm]+ Size: [40mm, 20mm] }+ Station Neck { Origin: [10mm, 0mm, 10mm]+ Size: [34mm, 18mm] }+ Station PalmFront { Origin: [22mm, 0mm, 10mm]+ Size: [30mm, 16mm] }+ Station PalmRear { Origin: [36mm, 0mm, 10mm]+ Size: [24mm, 14mm] }+ Station Tail { Origin: [48mm, 0mm, 10mm]+ Size: [14mm, 10mm] }+ }+ BodyState Base {+ Size: [80mm, 40mm, 20mm]+ Hole MountA { Center: [-25mm, -12mm]+ Diameter: 4mm }+ Hole MountB { Center: [25mm, 12mm]+ Diameter: 4mm }+ }+ SculptState GripAdded {+ Input: Base+ AddSectionChain Grip {+ Chain: GripChain+ Support: HousingSideEast+ Terminal: Attach+ InfluenceEnvelope: [40mm, -20mm, 0mm, 100mm, 20mm, 20mm]+ }+ MayModify: [HousingSideEast]+ Preserve: [BottomMountingInterface, MountingHolePattern]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ Output: GripAdded+}diff --git a/fixtures/Canonical/BodyState/surf-x4-remove-section-chain-g1-duct.firmament b/fixtures/Canonical/BodyState/surf-x4-remove-section-chain-g1-duct.firmamentnew file mode 100644index 00000000..f6ec028e--- /dev/null+++ b/fixtures/Canonical/BodyState/surf-x4-remove-section-chain-g1-duct.firmament@@ -0,0 +1,37 @@+Model SurfX4RemoveSectionChainG1Duct {+ Units: mm+ SectionChain DuctChain {+ Continuity: G1+ StartTermination: Open+ EndTermination: Open+ Station West { Origin: [-40mm, 0mm, 10mm]+ Size: [10mm, 8mm] }+ Station Entry { Origin: [-20mm, 0mm, 10mm]+ Size: [13mm, 9mm] }+ Station Center { Origin: [0mm, 0mm, 10mm]+ Size: [12mm, 10mm] }+ Station Exit { Origin: [20mm, 0mm, 10mm]+ Size: [9mm, 7mm] }+ Station East { Origin: [40mm, 0mm, 10mm]+ Size: [11mm, 8mm] }+ }+ BodyState Base {+ Size: [80mm, 40mm, 20mm]+ Hole MountA { Center: [-25mm, -12mm]+ Diameter: 4mm }+ Hole MountB { Center: [25mm, 12mm]+ Diameter: 4mm }+ }+ SculptState DuctRemoved {+ Input: Base+ RemoveSectionChain Duct {+ Chain: DuctChain+ Supports: [HousingSideWest, HousingSideEast]+ InfluenceEnvelope: [-40mm, -7mm, 5mm, 40mm, 7mm, 15mm]+ }+ MayModify: [HousingSideWest, HousingSideEast]+ Preserve: [BottomMountingInterface, MountingHolePattern]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ Output: DuctRemoved+}diff --git a/fixtures/Canonical/SectionChain/g0-explicit-ruled.firmament b/fixtures/Canonical/SectionChain/g0-explicit-ruled.firmamentnew file mode 100644index 00000000..7dc73f4c--- /dev/null+++ b/fixtures/Canonical/SectionChain/g0-explicit-ruled.firmament@@ -0,0 +1,27 @@+Model G0ExplicitRuled {+ Units: mm+ Concept Struct Stations {+ D0: Plane { Origin: [0mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ D1: Plane { Origin: [20mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ }+ Construction Plane F0 { Trace: Stations.D0 }+ Construction Plane F1 { Trace: Stations.D1 }+ Concept Path Box { Start: Point2(-4mm,-3mm) Heading: 0deg Line Bottom { Length: 8mm } Line Right { Turn: 90deg; Length: 6mm } Line Top { Turn: 90deg; Length: 8mm } Close Left }+ Profile PBox From Box+ SectionChain G0ExplicitRuled {+ Continuity: G0+ Transition: Ruled+ Section A {+ Frame: F0+ Profile: PBox+ Seam: Bottom+ }+ Section B {+ Frame: F1+ Profile: PBox+ Seam: Bottom+ }+ Start: Cap+ End: Cap+ }+}diff --git a/fixtures/Canonical/SectionChain/g1-two-transition.firmament b/fixtures/Canonical/SectionChain/g1-two-transition.firmamentnew file mode 100644index 00000000..8ca8dbac--- /dev/null+++ b/fixtures/Canonical/SectionChain/g1-two-transition.firmament@@ -0,0 +1,35 @@+Model G1TwoTransition {+ Units: mm+ Concept Struct Stations {+ D0: Plane { Origin: [0mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ D1: Plane { Origin: [20mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ D2: Plane { Origin: [55mm,2mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }+ }+ Construction Plane F0 { Trace: Stations.D0 }+ Construction Plane F1 { Trace: Stations.D1 }+ Construction Plane F2 { Trace: Stations.D2 }+ Concept Path Small { Start: Point2(-4mm,-3mm) Heading: 0deg Line Bottom { Length: 8mm } Line Right { Turn: 90deg; Length: 6mm } Line Top { Turn: 90deg; Length: 8mm } Close Left }+ Concept Path Large { Start: Point2(-10mm,-7mm) Heading: 0deg Line Bottom { Length: 20mm } Line Right { Turn: 90deg; Length: 14mm } Line Top { Turn: 90deg; Length: 20mm } Close Left }+ Profile PSmall From Small+ Profile PLarge From Large+ SectionChain G1TwoTransition {+ Continuity: G1+ Section A {+ Frame: F0+ Profile: PSmall+ Seam: Bottom+ }+ Section B {+ Frame: F1+ Profile: PLarge+ Seam: Bottom+ }+ Section C {+ Frame: F2+ Profile: PSmall+ Seam: Bottom+ }+ Start: Cap+ End: Cap+ }+}