Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add bounded sculpting support to CLI and surfacing module
Yuechen Li0ee5433e25db
diff --git a/Aetheris.CLI.Tests/ModulesCommandTests.cs b/Aetheris.CLI.Tests/ModulesCommandTests.csindex a20e458c..360714cf 100644--- a/Aetheris.CLI.Tests/ModulesCommandTests.cs+++ b/Aetheris.CLI.Tests/ModulesCommandTests.cs@@ -15,6 +15,6 @@ public sealed class ModulesCommandTests[Fact]public void ModulesTextMakesBuiltInNonPluginScopeExplicit(){- var stdout=new StringWriter();var stderr=new StringWriter();Assert.Equal(0,CliRunner.Run(["modules"],stdout,stderr));Assert.Contains("no dynamic plugins",stdout.ToString());Assert.Contains("Aetheris.Surfacing 0.2.0",stdout.ToString());+ var stdout=new StringWriter();var stderr=new StringWriter();Assert.Equal(0,CliRunner.Run(["modules"],stdout,stderr));Assert.Contains("no dynamic plugins",stdout.ToString());Assert.Contains("Aetheris.Surfacing 0.3.0",stdout.ToString());}}diff --git a/Aetheris.CLI.Tests/SculptingCliTests.cs b/Aetheris.CLI.Tests/SculptingCliTests.csnew file mode 100644index 00000000..38965481--- /dev/null+++ b/Aetheris.CLI.Tests/SculptingCliTests.cs@@ -0,0 +1,30 @@+using System.Text.Json;+using Aetheris.CLI;++namespace Aetheris.CLI.Tests;++public sealed class SculptingCliTests+{+ [Fact]+ public void BuildInspectAndValidateExposeStructuredSculptStateEvidence()+ {+ var fixture = Path.Combine(Root(), "fixtures", "Canonical", "Sculpting", "sculpted-housing.firmament");+ var output = Path.Combine(Path.GetTempPath(), "aetheris-surf-x0-" + Guid.NewGuid().ToString("N") + ".step");+ try+ {+ var buildOut = new StringWriter(); var buildErr = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["build", fixture, "--output", output, "--json"], buildOut, buildErr));+ using var build = JsonDocument.Parse(buildOut.ToString()); Assert.True(build.RootElement.GetProperty("success").GetBoolean());+ Assert.Equal("Sculpting", build.RootElement.GetProperty("domain").GetString()); Assert.Equal(0, build.RootElement.GetProperty("rationalNurbs").GetInt32());+ Assert.Equal("state-8960030e57e7b7d897d9", build.RootElement.GetProperty("geometricDelta").GetProperty("inputState").GetProperty("value").GetString());+ Assert.True(File.Exists(output)); Assert.True(File.Exists(Path.ChangeExtension(output, ".delta.json")));+ var inspectOut = new StringWriter(); Assert.Equal(0, CliRunner.Run(["inspect", fixture, "--json"], inspectOut, new StringWriter()));+ using var inspect = JsonDocument.Parse(inspectOut.ToString()); Assert.Equal(2, inspect.RootElement.GetProperty("states").GetArrayLength());+ var validateOut = new StringWriter(); Assert.Equal(0, CliRunner.Run(["validate", fixture, "--json"], validateOut, new StringWriter()));+ Assert.Contains("\"domain\": \"Sculpting\"", validateOut.ToString(), StringComparison.Ordinal);+ }+ finally { if (File.Exists(output)) File.Delete(output); var delta = Path.ChangeExtension(output, ".delta.json"); if (File.Exists(delta)) File.Delete(delta); }+ }++ private static string Root() { var d = new DirectoryInfo(AppContext.BaseDirectory); while (d is not null && !File.Exists(Path.Combine(d.FullName, "Aetheris.slnx"))) d = d.Parent; return d!.FullName; }+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 4c35239f..63a00e01 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -262,6 +262,22 @@ public static class CliRunner}if (string.Equals(Path.GetExtension(stepPath), ".firmament", StringComparison.OrdinalIgnoreCase)){+ var sourceText = File.Exists(stepPath) ? File.ReadAllText(stepPath) : string.Empty;+ if (SculptingAuthoring.IsSculptingSource(sourceText))+ {+ var sculpt = SculptingAuthoring.Compile(sourceText);+ var sculptExport = sculpt.OutputState is null ? null : SculptStepExporter.Export(sculpt.OutputState, sculpt.ModelName);+ if (!sculpt.IsSuccess || sculptExport?.IsSuccess != true || sculptExport.Step is null)+ {+ var messages = sculpt.Diagnostics.Select(x => $"{x.Code}: {x.Message}").Concat(sculptExport?.Diagnostics.Select(x => $"{x.Code}: {x.Message}") ?? []);+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "verify", success = false, input = Path.GetFullPath(stepPath), diagnostics = messages }, JsonOptions));+ else foreach (var message in messages) stderr.WriteLine($"error: {message}");+ return 1;+ }+ var sculptStepPath = Path.ChangeExtension(Path.GetFullPath(stepPath), ".step"); File.WriteAllText(sculptStepPath, sculptExport.Step); stepPath = sculptStepPath;+ }+ else+ {var build = FirmamentBuildAndExport.Run(stepPath);if (!build.IsSuccess){@@ -270,6 +286,7 @@ public static class CliRunnerreturn 1;}stepPath = build.Value.OutputPath;+ }}else if (!string.Equals(Path.GetExtension(stepPath), ".step", StringComparison.OrdinalIgnoreCase) && !string.Equals(Path.GetExtension(stepPath), ".stp", StringComparison.OrdinalIgnoreCase)){@@ -413,6 +430,8 @@ public static class CliRunnerif (File.Exists(sourcePath) && SheetMetalFirmament.LooksLikeSheetMetal(File.ReadAllText(sourcePath)))return RunSheetMetalAuthoredBuild(sourcePath, outPath, json, stdout, stderr);+ if (File.Exists(sourcePath) && SculptingAuthoring.IsSculptingSource(File.ReadAllText(sourcePath)))+ return RunSculptingBuild(sourcePath, outPath, json, stdout, stderr);var build = FirmamentBuildAndExport.Run(sourcePath, outPath);if (!build.IsSuccess)@@ -494,6 +513,52 @@ public static class CliRunnerreturn 0;}+ private static int RunSculptingBuild(string sourcePath, string? outPath, bool json, TextWriter stdout, TextWriter stderr)+ {+ var compile = SculptingAuthoring.CompileFile(sourcePath);+ if (!compile.IsSuccess || compile.OutputState is null)+ {+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "build", success = false, input = Path.GetFullPath(sourcePath), domain = "Sculpting", diagnostics = compile.Diagnostics }, JsonOptions));+ else { stderr.WriteLine("Build failed:"); foreach (var diagnostic in compile.Diagnostics) stderr.WriteLine($"- [Error] {diagnostic.Code}: {diagnostic.Message}"); }+ return 1;+ }+ var exportClock = Stopwatch.StartNew(); var export = SculptStepExporter.Export(compile.OutputState, compile.ModelName); exportClock.Stop();+ if (!export.IsSuccess || export.Step is null)+ {+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "build", success = false, input = Path.GetFullPath(sourcePath), domain = "Sculpting", diagnostics = export.Diagnostics, surfaceInventory = export.Inventory }, JsonOptions));+ else foreach (var diagnostic in export.Diagnostics) stderr.WriteLine($"- [Error] {diagnostic.Code}: {diagnostic.Message}");+ return 1;+ }+ var output = Path.GetFullPath(outPath ?? Path.ChangeExtension(sourcePath, ".step")); Directory.CreateDirectory(Path.GetDirectoryName(output)!); File.WriteAllText(output, export.Step);+ var deltaPath = Path.ChangeExtension(output, ".delta.json");+ File.WriteAllText(deltaPath, JsonSerializer.Serialize(new+ {+ inputState = compile.OutputState.PredecessorStateId,+ outputState = compile.OutputState.StateId,+ compile.OutputState.Delta,+ validationEvidence = compile.OutputState.ValidationEvidence,+ surfaceInventory = export.Inventory,+ productBoundary = new { rationalNurbs = export.Inventory.RationalNurbs, admitted = export.Inventory.RationalNurbs == 0 },+ timingsMilliseconds = compile.Timings with { StepExportMilliseconds = exportClock.Elapsed.TotalMilliseconds }+ }, JsonOptions));+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new+ {+ command = "build", success = true, input = Path.GetFullPath(sourcePath), output, domain = "Sculpting", model = compile.ModelName,+ state = DescribeSculptState(compile.OutputState), states = compile.States.Values.Select(DescribeSculptState), geometricDelta = compile.OutputState.Delta,+ validationEvidence = compile.OutputState.ValidationEvidence, surfaceInventory = export.Inventory, rationalNurbs = export.Inventory.RationalNurbs,+ deltaArtifact = deltaPath, timingsMilliseconds = compile.Timings with { StepExportMilliseconds = exportClock.Elapsed.TotalMilliseconds }, diagnostics = compile.Diagnostics+ }, JsonOptions));+ else { stdout.WriteLine($"Built {Path.GetFileName(sourcePath)}"); stdout.WriteLine($"STEP: {output}"); stdout.WriteLine($"State: {compile.OutputState.AuthoredName} ({compile.OutputState.StateId}) <- {compile.OutputState.PredecessorStateId}"); stdout.WriteLine($"Geometric delta: {deltaPath}"); stdout.WriteLine($"STEP surfaces: Plane={export.Inventory.Plane}, Cylinder={export.Inventory.Cylinder}, NonRationalBSpline={export.Inventory.NonRationalBSpline}, RationalNURBS={export.Inventory.RationalNurbs}"); }+ return 0;+ }++ private static object DescribeSculptState(BodyState state) => new+ {+ state.AuthoredName, state.StateId, state.PredecessorStateId, state.BodyStableId,+ construction = new { state.Construction.Width, state.Construction.Depth, state.Construction.BaseHeight, state.Construction.CrownWidth, state.Construction.CrownDepth, state.Construction.CrownOffset, state.Construction.FinalHeight },+ semanticInventory = state.SemanticInventory.Values, hasDelta = state.Delta is not null+ };+private static int RunSheetMetalAuthoredBuild(string sourcePath, string? outPath, bool json, TextWriter stdout, TextWriter stderr){var authored=SheetMetalFirmament.CompileFile(sourcePath);@@ -995,6 +1060,17 @@ Model CanonicalPanel {}var source = File.ReadAllText(fullPath);+ if (SculptingAuthoring.IsSculptingSource(source))+ {+ var sculpt = SculptingAuthoring.Compile(source);+ var sculptReport = new { command = "inspect", success = sculpt.IsSuccess, input = fullPath, domain = "Sculpting", model = sculpt.ModelName,+ states = sculpt.States.Values.Select(state => new { state = DescribeSculptState(state), geometricDelta = state.Delta, validationEvidence = state.ValidationEvidence }),+ outputState = sculpt.OutputState?.StateId, timingsMilliseconds = sculpt.Timings, diagnostics = sculpt.Diagnostics };+ if (json) stdout.WriteLine(JsonSerializer.Serialize(sculptReport, JsonOptions));+ else if (sculpt.IsSuccess) { stdout.WriteLine($"Sculpting model {sculpt.ModelName}: {sculpt.States.Count} immutable states; output {sculpt.OutputState!.AuthoredName} ({sculpt.OutputState.StateId})"); foreach (var state in sculpt.States.Values) stdout.WriteLine($"State {state.AuthoredName}: {state.StateId} <- {state.PredecessorStateId?.Value ?? "<initial>"}"); }+ else foreach (var diagnostic in sculpt.Diagnostics) stderr.WriteLine($"error: {diagnostic.Code}: {diagnostic.Message}");+ return sculpt.IsSuccess ? 0 : 1;+ }if (PipingAuthoring.IsPipingSource(source)){var piping = PipingAuthoring.Compile(source, fullPath);@@ -1154,14 +1230,28 @@ Model CanonicalPanel {string stepPath;if (string.Equals(extension, ".firmament", StringComparison.OrdinalIgnoreCase)){- var build = FirmamentBuildAndExport.Run(fullInput);- if (!build.IsSuccess)+ var viewSource = File.ReadAllText(fullInput);+ if (SculptingAuthoring.IsSculptingSource(viewSource)){- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "view", success = false, input = fullInput, diagnostics = build.Diagnostics.Select(d => new { d.Source, d.Message, severity = d.Severity.ToString() }) }, JsonOptions));- else { stderr.WriteLine("View stopped because build failed."); foreach (var diagnostic in build.Diagnostics) stderr.WriteLine($"error: {diagnostic.Message}"); }- return 1;+ var sculpt = SculptingAuthoring.Compile(viewSource); var export = sculpt.OutputState is null ? null : SculptStepExporter.Export(sculpt.OutputState, sculpt.ModelName);+ if (!sculpt.IsSuccess || export?.IsSuccess != true || export.Step is null)+ {+ var messages = sculpt.Diagnostics.Select(x => $"{x.Code}: {x.Message}").Concat(export?.Diagnostics.Select(x => $"{x.Code}: {x.Message}") ?? []).ToArray();+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "view", success = false, input = fullInput, diagnostics = messages }, JsonOptions)); else foreach (var message in messages) stderr.WriteLine($"error: {message}"); return 1;+ }+ stepPath = Path.ChangeExtension(fullInput, ".step"); File.WriteAllText(stepPath, export.Step);+ }+ else+ {+ var build = FirmamentBuildAndExport.Run(fullInput);+ if (!build.IsSuccess)+ {+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "view", success = false, input = fullInput, diagnostics = build.Diagnostics.Select(d => new { d.Source, d.Message, severity = d.Severity.ToString() }) }, JsonOptions));+ else { stderr.WriteLine("View stopped because build failed."); foreach (var diagnostic in build.Diagnostics) stderr.WriteLine($"error: {diagnostic.Message}"); }+ return 1;+ }+ stepPath = build.Value.OutputPath;}- stepPath = build.Value.OutputPath;if (!json){stdout.WriteLine($"✓ Built {Path.GetFileName(fullInput)}");@@ -1647,6 +1737,14 @@ Model CanonicalPanel {}var validationSource=File.ReadAllText(sourcePath);+ if (SculptingAuthoring.IsSculptingSource(validationSource))+ {+ var sculpt = SculptingAuthoring.Compile(validationSource);+ var payload = new { source = sourcePath, status = sculpt.IsSuccess ? "valid" : "invalid", domain = "Sculpting", summary = new { fatalDiagnosticCount = sculpt.Diagnostics.Count, warningDiagnosticCount = 0, states = sculpt.States.Count }, diagnostics = sculpt.Diagnostics };+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));+ else stdout.WriteLine($"Firmament V2 Sculpting validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");+ return sculpt.IsSuccess ? 0 : 1;+ }if (PipingAuthoring.IsPipingSource(validationSource)){var piping = PipingAuthoring.Compile(validationSource, Path.GetFullPath(sourcePath));diff --git a/Aetheris.Modules.Tests/ModuleArchitectureTests.cs b/Aetheris.Modules.Tests/ModuleArchitectureTests.csindex ae9dac55..81cc106d 100644--- a/Aetheris.Modules.Tests/ModuleArchitectureTests.cs+++ b/Aetheris.Modules.Tests/ModuleArchitectureTests.cs@@ -19,7 +19,7 @@ public sealed class ModuleArchitectureTestsvar first=BuiltInModules.Catalog;var second=AetherisModuleCatalog.Create(first.Modules.Reverse());Assert.Equal(["Aetheris.Core","Aetheris.Piping","Aetheris.Surfacing","Aetheris.SheetMetal"],first.Modules.Select(m=>m.Id.Value));Assert.Equal(first.Modules.Select(m=>m.Id.Value),second.Modules.Select(m=>m.Id.Value));- Assert.Equal("0.2.0",first.Modules.Single(m=>m.Id==SurfacingModule.Id).Version.ToString());+ Assert.Equal("0.3.0",first.Modules.Single(m=>m.Id==SurfacingModule.Id).Version.ToString());Assert.Equal(first.Capabilities.Select(c=>c.Id).Order(StringComparer.Ordinal),first.Capabilities.Select(c=>c.Id));}diff --git a/Aetheris.Modules.Tests/SurfX0SculptingTests.cs b/Aetheris.Modules.Tests/SurfX0SculptingTests.csnew file mode 100644index 00000000..730ad4ff--- /dev/null+++ b/Aetheris.Modules.Tests/SurfX0SculptingTests.cs@@ -0,0 +1,85 @@+using Aetheris.Kernel.Core.Step242;+using Aetheris.Surfacing;+using Xunit;++namespace Aetheris.Modules.Tests;++public sealed class SurfX0SculptingTests+{+ [Fact]+ public void CanonicalOffsetRegionProducesImmutableSinglePredecessorStateAndInspectableDelta()+ {+ var result = Compile("Canonical/Sculpting/sculpted-housing.firmament");+ Assert.True(result.IsSuccess, string.Join(';', result.Diagnostics.Select(x => x.Code)));+ var state = Assert.IsType<BodyState>(result.OutputState);+ Assert.NotNull(state.PredecessorStateId); Assert.Equal(result.States["Base"].StateId, state.PredecessorStateId);+ Assert.NotSame(result.States["Base"].Body, state.Body); Assert.Equal(20d, result.States["Base"].Construction.FinalHeight); Assert.Equal(26d, state.Construction.FinalHeight);+ Assert.Contains(SculptedHousingFactory.BottomMountingInterface, state.Delta!.Preserves);+ Assert.Contains(SculptedHousingFactory.CrownRegion, state.Delta.Replaces);+ Assert.Contains(SculptedHousingFactory.TransitionZone, state.Delta.Introduces);+ }++ [Fact]+ public void BranchVariantsDeriveFromBaseWithoutMutatingEachOtherAndAreDeterministic()+ {+ var first = Compile("Canonical/Sculpting/sculpt-branch-variants.firmament"); var second = Compile("Canonical/Sculpting/sculpt-branch-variants.firmament");+ Assert.True(first.IsSuccess); Assert.Equal(first.OutputState!.StateId, second.OutputState!.StateId);+ var baseState = first.States["Base"]; var six = first.States["CrownRaised"]; var ten = first.States["CrownHigh"];+ Assert.Equal(baseState.StateId, six.PredecessorStateId); Assert.Equal(baseState.StateId, ten.PredecessorStateId);+ Assert.NotEqual(six.StateId, ten.StateId); Assert.Equal(20d, baseState.Construction.FinalHeight); Assert.Equal(26d, six.Construction.FinalHeight); Assert.Equal(30d, ten.Construction.FinalHeight);+ }++ [Fact]+ public void LocalityAndPreservationAreExactAndClosedBrepIsIndependentlyVerified()+ {+ var state = Compile("Canonical/Sculpting/sculpt-preserve-interface.firmament").OutputState!;+ Assert.Contains(state.ValidationEvidence, x => x.Check == "AuthorizedLocality" && x.Level == LocalityEvidenceLevel.ExactAnalytic && x.MaximumObservedDeviation == 0d);+ Assert.Contains(state.ValidationEvidence, x => x.Check == "Preserve:MountingHolePattern" && x.Satisfied);+ Assert.Contains(state.ValidationEvidence, x => x.Check == "ClosedManifold" && x.Satisfied);+ Assert.Contains(state.ValidationEvidence, x => x.Check == "OrientationConsistency" && x.Satisfied);+ }++ [Theory]+ [InlineData("Invalid/Sculpting/sculpt-outside-authorized-region.firmament", "sculpt-outside-authorized-region")]+ [InlineData("Invalid/Sculpting/sculpt-breaks-preserved-interface.firmament", "sculpt-breaks-preserved-interface")]+ [InlineData("Invalid/Sculpting/sculpt-self-intersection.firmament", "sculpt-self-intersection")]+ [InlineData("Invalid/Sculpting/sculpt-disconnected-result.firmament", "sculpt-target-domain-invalid")]+ public void FailedSculptIsAtomicAndTyped(string fixture, string diagnostic)+ {+ var result = Compile(fixture); Assert.False(result.IsSuccess); Assert.Contains(result.Diagnostics, x => x.Code == diagnostic);+ Assert.True(result.States.TryGetValue("Base", out var baseState)); Assert.Equal(20d, baseState.Construction.FinalHeight);+ Assert.DoesNotContain(result.States.Values, x => x.AuthoredName == "CrownRaised");+ }++ [Fact]+ public void StepBoundaryIsAnalyticRationalFreeAndReimports()+ {+ var state = Compile("Canonical/Sculpting/sculpted-housing.firmament").OutputState!; var export = SculptStepExporter.Export(state, "SURF-X0");+ Assert.True(export.IsSuccess, string.Join(';', export.Diagnostics.Select(x => x.Code))); Assert.Equal(0, export.Inventory.RationalNurbs);+ Assert.Equal(10, export.Inventory.Plane); Assert.Equal(4, export.Inventory.Cylinder); Assert.Equal(0, export.Inventory.NonRationalBSpline);+ Assert.DoesNotContain("RATIONAL_B_SPLINE_SURFACE", export.Step!, StringComparison.Ordinal);+ var import = Step242Importer.ImportBody(export.Step!); Assert.True(import.IsSuccess, string.Join(';', import.Diagnostics.Select(x => x.Message)));+ }++ [Fact]+ public void TemporaryEqualWeightRationalSurfaceRecoversExactPlaneAndNonRemovableRationalityBlocks()+ {+ var points = new[] { new[] { new Aetheris.Kernel.Core.Math.Point3D(0, 0, 0), new(0, 1, 0) }, new[] { new Aetheris.Kernel.Core.Math.Point3D(1, 0, 0), new(1, 1, 0) } };+ var exact = RationalSurfaceNormalizer.Normalize(new(1, 1, points, new[] { new[] { 2d, 2d }, new[] { 2d, 2d } }));+ Assert.True(exact.IsSuccess); Assert.Equal("Plane", exact.EmittedFamily);+ var nonPlanar = new[] { new[] { new Aetheris.Kernel.Core.Math.Point3D(0, 0, 0), new(0, 1, 0) }, new[] { new Aetheris.Kernel.Core.Math.Point3D(1, 0, 0), new(1, 1, 1) } };+ var normalized = RationalSurfaceNormalizer.Normalize(new(1, 1, nonPlanar, new[] { new[] { 3d, 3d }, new[] { 3d, 3d } }));+ Assert.True(normalized.IsSuccess); Assert.Equal("NonRationalBSpline", normalized.EmittedFamily); Assert.NotNull(normalized.Surface!.BSplineSurfaceWithKnots);+ var blocked = RationalSurfaceNormalizer.Normalize(new(1, 1, points, new[] { new[] { 1d, .7d }, new[] { .7d, 1d } }));+ Assert.False(blocked.IsSuccess); Assert.Contains("surf-surface-export-normalization-failed", blocked.Diagnostic);+ }++ private static SculptingCompileResult Compile(string relative)+ => SculptingAuthoring.CompileFile(Path.Combine(RepositoryRoot(), "fixtures", relative.Replace('/', Path.DirectorySeparatorChar)));+ private static string RepositoryRoot()+ {+ var current = new DirectoryInfo(AppContext.BaseDirectory);+ while (current is not null && !File.Exists(Path.Combine(current.FullName, "Aetheris.slnx"))) current = current.Parent;+ return current?.FullName ?? throw new DirectoryNotFoundException("Repository root not found.");+ }+}diff --git a/Aetheris.Surfacing/SculptedHousingBrepBuilder.cs b/Aetheris.Surfacing/SculptedHousingBrepBuilder.csnew file mode 100644index 00000000..45d77081--- /dev/null+++ b/Aetheris.Surfacing/SculptedHousingBrepBuilder.cs@@ -0,0 +1,127 @@+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.Surfacing;++internal static class SculptedHousingBrepBuilder+{+ internal sealed record BuildResult(BrepBody? Body, IReadOnlyList<SculptDiagnostic> Diagnostics);++ public static BuildResult Build(HousingConstruction construction)+ {+ var diagnostics = Validate(construction);+ if (diagnostics.Count > 0) return new(null, diagnostics);++ var sections = construction.HasCrown+ ? new[] { Section(construction.Width, construction.Depth, 0d), Section(construction.Width, construction.Depth, construction.BaseHeight), Section(construction.CrownWidth, construction.CrownDepth, construction.FinalHeight) }+ : new[] { Section(construction.Width, construction.Depth, 0d), Section(construction.Width, construction.Depth, construction.BaseHeight) };+ var b = new TopologyBuilder();+ var vertices = new VertexId[sections.Length, 4];+ var points = new Dictionary<VertexId, Point3D>();+ for (var s = 0; s < sections.Length; s++)+ for (var i = 0; i < 4; i++) { vertices[s, i] = b.AddVertex(); points[vertices[s, i]] = sections[s][i]; }++ var profileEdges = new EdgeId[sections.Length, 4];+ for (var s = 0; s < sections.Length; s++)+ for (var i = 0; i < 4; i++) profileEdges[s, i] = b.AddEdge(vertices[s, i], vertices[s, (i + 1) % 4]);+ var risers = new EdgeId[sections.Length - 1, 4];+ for (var s = 0; s < sections.Length - 1; s++)+ for (var i = 0; i < 4; i++) risers[s, i] = b.AddEdge(vertices[s, i], vertices[s + 1, i]);++ var bottomHoleVertices = new VertexId[construction.Holes.Count];+ var topHoleVertices = new VertexId[construction.Holes.Count];+ var bottomHoleEdges = new EdgeId[construction.Holes.Count];+ var topHoleEdges = new EdgeId[construction.Holes.Count];+ var seamEdges = new EdgeId[construction.Holes.Count];+ for (var i = 0; i < construction.Holes.Count; i++)+ {+ var hole = construction.Holes[i];+ bottomHoleVertices[i] = b.AddVertex(); topHoleVertices[i] = b.AddVertex();+ var seamX = hole.CenterX + hole.Diameter / 2d;+ points[bottomHoleVertices[i]] = new(seamX, hole.CenterY, 0d);+ points[topHoleVertices[i]] = new(seamX, hole.CenterY, construction.FinalHeight);+ bottomHoleEdges[i] = b.AddEdge(bottomHoleVertices[i], bottomHoleVertices[i]);+ topHoleEdges[i] = b.AddEdge(topHoleVertices[i], topHoleVertices[i]);+ seamEdges[i] = b.AddEdge(bottomHoleVertices[i], topHoleVertices[i]);+ }++ var bottomLoops = new List<LoopId> { AddLoop(b, Enumerable.Range(0, 4).Select(i => new Use(profileEdges[0, i], false)).ToArray()) };+ for (var i = 0; i < construction.Holes.Count; i++) bottomLoops.Add(AddLoop(b, [new(bottomHoleEdges[i], true)]));+ var faces = new List<(FaceId Face, SurfaceGeometry Surface)>();+ faces.Add((b.AddFace(bottomLoops), SurfaceGeometry.FromPlane(new PlaneSurface(Point3D.Origin, Dir(0, 0, -1), Dir(1, 0, 0)))));++ var last = sections.Length - 1;+ var topLoops = new List<LoopId> { AddLoop(b, Enumerable.Range(0, 4).Select(i => new Use(profileEdges[last, i], true)).Reverse().ToArray()) };+ for (var i = 0; i < construction.Holes.Count; i++) topLoops.Add(AddLoop(b, [new(topHoleEdges[i], false)]));+ faces.Add((b.AddFace(topLoops), SurfaceGeometry.FromPlane(new PlaneSurface(new(0, 0, construction.FinalHeight), Dir(0, 0, 1), Dir(1, 0, 0)))));++ for (var s = 0; s < sections.Length - 1; s++)+ for (var i = 0; i < 4; i++)+ {+ var n = (i + 1) % 4;+ var loop = AddLoop(b, [new(profileEdges[s, i], false), new(risers[s, n], false), new(profileEdges[s + 1, i], true), new(risers[s, i], true)]);+ var p0 = sections[s][i]; var p1 = sections[s][n]; var p3 = sections[s + 1][i];+ var edge = p1 - p0; var rise = p3 - p0; var normal = edge.Cross(rise);+ faces.Add((b.AddFace([loop]), SurfaceGeometry.FromPlane(new PlaneSurface(p0, Direction3D.Create(normal), Direction3D.Create(edge)))));+ }++ for (var i = 0; i < construction.Holes.Count; i++)+ {+ var loop = AddLoop(b, [new(bottomHoleEdges[i], false), new(seamEdges[i], false), new(topHoleEdges[i], true), new(seamEdges[i], true)]);+ var h = construction.Holes[i];+ faces.Add((b.AddFace([loop]), SurfaceGeometry.FromCylinder(new CylinderSurface(new(h.CenterX, h.CenterY, 0), Dir(0, 0, 1), h.Diameter / 2d, Dir(1, 0, 0)))));+ }++ var shell = b.AddShell(faces.Select(x => x.Face).ToArray()); b.AddBody([shell]);+ var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel(); var curveId = 1;+ foreach (var edge in b.Model.Edges.OrderBy(x => x.Id.Value))+ {+ var p0 = points[edge.StartVertexId]; var p1 = points[edge.EndVertexId];+ var holeIndex = Array.IndexOf(bottomHoleEdges, edge.Id); if (holeIndex < 0) holeIndex = Array.IndexOf(topHoleEdges, edge.Id);+ CurveGeometry curve; ParameterInterval interval;+ if (holeIndex >= 0)+ {+ var h = construction.Holes[holeIndex]; curve = CurveGeometry.FromCircle(new Circle3Curve(new(h.CenterX, h.CenterY, p0.Z), Dir(0, 0, 1), h.Diameter / 2d, Dir(1, 0, 0))); interval = new(0, 2 * double.Pi);+ }+ else { var vector = p1 - p0; curve = CurveGeometry.FromLine(new Line3Curve(p0, Direction3D.Create(vector))); interval = new(0, vector.Length); }+ var id = new CurveGeometryId(curveId++); geometry.AddCurve(id, curve); bindings.AddEdgeBinding(new(edge.Id, id, interval));+ }+ var surfaceId = 1;+ foreach (var (face, surface) in faces) { var id = new SurfaceGeometryId(surfaceId++); geometry.AddSurface(id, surface); bindings.AddFaceBinding(new(face, id)); }+ var body = new BrepBody(b.Model, geometry, bindings, points);+ var binding = BrepBindingValidator.Validate(body, true);+ if (!binding.IsSuccess) return new(null, binding.Diagnostics.Select(x => new SculptDiagnostic("sculpt-brep-binding-invalid", x.Message)).ToArray());+ return new(body, []);+ }++ private static List<SculptDiagnostic> Validate(HousingConstruction c)+ {+ var d = new List<SculptDiagnostic>();+ if (!Positive(c.Width) || !Positive(c.Depth) || !Positive(c.BaseHeight)) d.Add(new("sculpt-housing-invalid", "Housing width, depth, and base height must be positive and finite."));+ if (!Positive(c.CrownWidth) || !Positive(c.CrownDepth) || c.CrownWidth > c.Width || c.CrownDepth > c.Depth) d.Add(new("sculpt-target-domain-invalid", "Crown region must be positive and contained by the housing footprint."));+ if (!double.IsFinite(c.CrownOffset) || c.FinalHeight <= 0d) d.Add(new("sculpt-self-intersection", "Offset crosses or collapses the bottom mounting plane."));+ foreach (var h in c.Holes)+ {+ var r = h.Diameter / 2d;+ if (!Positive(h.Diameter) || Math.Abs(h.CenterX) + r >= c.CrownWidth / 2d || Math.Abs(h.CenterY) + r >= c.CrownDepth / 2d)+ d.Add(new("sculpt-hole-pattern-outside-crown", $"Mounting hole '{h.StableId}' must remain inside the bounded crown support.", h.StableId));+ }+ for (var i = 0; i < c.Holes.Count; i++) for (var j = i + 1; j < c.Holes.Count; j++)+ { var a = c.Holes[i]; var h = c.Holes[j]; if (Math.Sqrt(Math.Pow(a.CenterX - h.CenterX, 2) + Math.Pow(a.CenterY - h.CenterY, 2)) <= (a.Diameter + h.Diameter) / 2d) d.Add(new("sculpt-self-intersection", $"Mounting holes '{a.StableId}' and '{h.StableId}' overlap.")); }+ return d;+ }+ private static bool Positive(double value) => double.IsFinite(value) && value > 1e-9;+ private static Point3D[] Section(double width, double depth, double z) { var x = width / 2d; var y = depth / 2d; return [new(-x, -y, z), new(x, -y, z), new(x, y, z), new(-x, y, z)]; }+ private static Direction3D Dir(double x, double y, double z) => Direction3D.Create(new Vector3D(x, y, z));+ private static LoopId AddLoop(TopologyBuilder b, IReadOnlyList<Use> uses)+ {+ var loop = b.AllocateLoopId(); var ids = uses.Select(_ => b.AllocateCoedgeId()).ToArray();+ for (var i = 0; i < ids.Length; i++) b.AddCoedge(new(ids[i], uses[i].Edge, loop, ids[(i + 1) % ids.Length], ids[(i + ids.Length - 1) % ids.Length], uses[i].Reversed));+ b.AddLoop(new Loop(loop, ids)); return loop;+ }+ private readonly record struct Use(EdgeId Edge, bool Reversed);+}diff --git a/Aetheris.Surfacing/SculptingAuthoring.cs b/Aetheris.Surfacing/SculptingAuthoring.csnew file mode 100644index 00000000..5b779dcf--- /dev/null+++ b/Aetheris.Surfacing/SculptingAuthoring.cs@@ -0,0 +1,112 @@+using System.Diagnostics;+using System.Globalization;+using System.Text.RegularExpressions;++namespace Aetheris.Surfacing;++public sealed record SculptingTimingEvidence(double BasePreparationMilliseconds, double OperationConstructionMilliseconds, double LocalityAndPreservationMilliseconds, double BrepValidationMilliseconds, double StepExportMilliseconds);+public sealed record SculptingCompileResult(bool IsSuccess, string ModelName, BodyState? OutputState, IReadOnlyDictionary<string, BodyState> States, IReadOnlyList<SculptDiagnostic> Diagnostics, SculptingTimingEvidence Timings);++public static class SculptingAuthoring+{+ private static readonly Regex ModelHeader = new(@"\bModel\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);++ public static bool IsSculptingSource(string source) => Regex.IsMatch(source, @"\b(?:BodyState|SculptState)\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant);+ public static SculptingCompileResult CompileFile(string path) => Compile(File.ReadAllText(path));++ public static SculptingCompileResult Compile(string source)+ {+ var total = Stopwatch.StartNew(); var diagnostics = new List<SculptDiagnostic>(); var states = new Dictionary<string, BodyState>(StringComparer.Ordinal);+ var model = ModelHeader.Match(source); if (!model.Success) return Fail("<unknown>", "sculpt-source-malformed", "Sculpting source requires 'Model Name { ... }'.");+ if (!Regex.IsMatch(source, @"\bUnits\s*:\s*mm\b", RegexOptions.CultureInvariant)) diagnostics.Add(new("sculpt-units-invalid", "SURF-X0 authoring requires millimetres."));+ var baseClock = Stopwatch.StartNew();+ foreach (var block in Blocks(source, "BodyState"))+ {+ var size = Vector(block.Body, "Size", 3, diagnostics); var holes = ParseHoles(block.Body, diagnostics);+ if (size is null) continue;+ var created = SculptedHousingFactory.CreateBase(block.Name, size[0], size[1], size[2], holes);+ if (!created.IsSuccess || created.OutputState is null) diagnostics.AddRange(created.Diagnostics);+ else if (!states.TryAdd(block.Name, created.OutputState)) diagnostics.Add(new("sculpt-state-duplicate", $"BodyState '{block.Name}' is declared more than once."));+ }+ baseClock.Stop(); var opConstruction = TimeSpan.Zero; var verification = TimeSpan.Zero; var brep = TimeSpan.Zero;+ foreach (var block in Blocks(source, "SculptState"))+ {+ var operationClock = Stopwatch.StartNew();+ var inputName = ScalarText(block.Body, "Input");+ if (inputName is null || !states.TryGetValue(inputName, out var input)) { diagnostics.Add(new("sculpt-predecessor-unresolved", $"SculptState '{block.Name}' must name one previously accepted Input state.")); continue; }+ var operationBlock = Blocks(block.Body, "OffsetRegion").SingleOrDefault();+ if (operationBlock is null) { diagnostics.Add(new("sculpt-operation-unsupported", $"SculptState '{block.Name}' requires exactly one OffsetRegion operation.")); continue; }+ var target = ScalarText(operationBlock.Body, "Target") ?? string.Empty;+ var offset = Length(operationBlock.Body, "Offset", diagnostics);+ var region = Vector(operationBlock.Body, "Region", 2, diagnostics);+ var envelope = Vector(operationBlock.Body, "InfluenceEnvelope", 6, diagnostics);+ var mayModify = List(block.Body, "MayModify"); var preserve = List(block.Body, "Preserve"); var requirements = List(block.Body, "Require");+ var boundary = ScalarText(operationBlock.Body, "Boundary") ?? "G0";+ operationClock.Stop(); opConstruction += operationClock.Elapsed;+ if (offset is null || region is null || envelope is null) continue;+ var contracts = preserve.Select(x => new PreservationContract(x, x == SculptedHousingFactory.MountingHolePattern ? PreservationMode.PatternPlacementAndDiameter : PreservationMode.ExactGeometry)).ToArray();+ var parsedRequirements = new List<SculptRequirement>();+ foreach (var requirement in requirements)+ if (Enum.TryParse<SculptRequirement>(requirement, out var parsed)) parsedRequirements.Add(parsed); else diagnostics.Add(new("sculpt-requirement-unsupported", $"Requirement '{requirement}' is not supported by SURF-X0."));+ var operation = new OffsetRegionOperation(block.Name + ".OffsetRegion", target, offset.Value, region[0], region[1], mayModify,+ new(envelope[0], envelope[1], envelope[2], envelope[3], envelope[4], envelope[5]), contracts, parsedRequirements, boundary);+ var applyClock = Stopwatch.StartNew(); var result = OffsetRegionSculptor.Apply(input, block.Name, operation); applyClock.Stop(); verification += applyClock.Elapsed;+ if (!result.IsSuccess || result.OutputState is null) diagnostics.AddRange(result.Diagnostics);+ else if (!states.TryAdd(block.Name, result.OutputState)) diagnostics.Add(new("sculpt-state-duplicate", $"State '{block.Name}' is declared more than once."));+ }+ var outputName = ScalarText(source, "Output");+ BodyState? output = null;+ if (outputName is null || !states.TryGetValue(outputName, out output)) diagnostics.Add(new("sculpt-output-unresolved", "Output must name one accepted BodyState or SculptState."));+ total.Stop();+ return new(diagnostics.Count == 0 && output is not null, model.Groups["name"].Value, output, states, diagnostics,+ new(baseClock.Elapsed.TotalMilliseconds, opConstruction.TotalMilliseconds, verification.TotalMilliseconds, brep.TotalMilliseconds, 0d));++ SculptingCompileResult Fail(string name, string code, string message) => new(false, name, null, states, [new(code, message)], new(0, 0, 0, 0, 0));+ }++ private static IReadOnlyList<HousingHole> ParseHoles(string body, List<SculptDiagnostic> diagnostics)+ {+ var result = new List<HousingHole>();+ foreach (var hole in Blocks(body, "Hole"))+ {+ var center = Vector(hole.Body, "Center", 2, diagnostics); var diameter = Length(hole.Body, "Diameter", diagnostics);+ if (center is not null && diameter is not null) result.Add(new(hole.Name, center[0], center[1], diameter.Value));+ }+ if (result.Count == 0) diagnostics.Add(new("sculpt-hole-pattern-required", "The X0 housing witness requires at least one bounded mounting hole."));+ return result;+ }++ private static IReadOnlyList<Block> Blocks(string source, string keyword)+ {+ var result = new List<Block>(); var regex = new Regex($@"\b{Regex.Escape(keyword)}(?:\s+(?<name>[A-Za-z_]\w*))?\s*\{{", RegexOptions.CultureInvariant);+ for (var start = 0; start < source.Length;)+ {+ var match = regex.Match(source, start); if (!match.Success) break; var open = source.IndexOf('{', match.Index + match.Length - 1); var close = MatchingBrace(source, open);+ if (close < 0) break; result.Add(new(match.Groups["name"].Success ? match.Groups["name"].Value : keyword, source[(open + 1)..close])); start = close + 1;+ }+ return result;+ }+ private static int MatchingBrace(string source, int open) { var depth = 0; var quoted = false; for (var i = open; i < source.Length; i++) { if (source[i] == '"' && (i == 0 || source[i - 1] != '\\')) quoted = !quoted; if (quoted) continue; if (source[i] == '{') depth++; else if (source[i] == '}' && --depth == 0) return i; } return -1; }+ private static string? ScalarText(string body, string field) { var m = Regex.Match(body, $@"(?m)^\s*{Regex.Escape(field)}\s*:\s*(?<v>[A-Za-z_]\w*)\s*$", RegexOptions.CultureInvariant); return m.Success ? m.Groups["v"].Value : null; }+ private static double? Length(string body, string field, List<SculptDiagnostic> diagnostics)+ {+ var m = Regex.Match(body, $@"(?m)^\s*{Regex.Escape(field)}\s*:\s*(?<v>[-+]?\d+(?:\.\d+)?)mm\s*$", RegexOptions.CultureInvariant);+ if (m.Success) return double.Parse(m.Groups["v"].Value, CultureInfo.InvariantCulture); diagnostics.Add(new("sculpt-field-invalid", $"Field '{field}' requires a millimetre length.")); return null;+ }+ private static double[]? Vector(string body, string field, int count, List<SculptDiagnostic> diagnostics)+ {+ var m = Regex.Match(body, $@"(?m)^\s*{Regex.Escape(field)}\s*:\s*\[(?<v>[^\]]+)\]\s*$", RegexOptions.CultureInvariant);+ if (m.Success)+ {+ var values = m.Groups["v"].Value.Split(',').Select(x => Regex.Match(x.Trim(), @"^(?<v>[-+]?\d+(?:\.\d+)?)mm$", RegexOptions.CultureInvariant)).ToArray();+ if (values.Length == count && values.All(x => x.Success)) return values.Select(x => double.Parse(x.Groups["v"].Value, CultureInfo.InvariantCulture)).ToArray();+ }+ diagnostics.Add(new("sculpt-field-invalid", $"Field '{field}' requires {count} comma-separated millimetre lengths.")); return null;+ }+ private static IReadOnlyList<string> List(string body, string field)+ {+ var m = Regex.Match(body, $@"(?m)^\s*{Regex.Escape(field)}\s*:\s*\[(?<v>[^\]]*)\]\s*$", RegexOptions.CultureInvariant);+ return m.Success ? m.Groups["v"].Value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) : [];+ }+ private sealed record Block(string Name, string Body);+}diff --git a/Aetheris.Surfacing/SculptingExecution.cs b/Aetheris.Surfacing/SculptingExecution.csnew file mode 100644index 00000000..97b886d8--- /dev/null+++ b/Aetheris.Surfacing/SculptingExecution.cs@@ -0,0 +1,235 @@+using System.Security.Cryptography;+using System.Text;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Surfacing;++public static class SculptedHousingFactory+{+ public const string CrownRegion = "HousingCrown";+ public const string TransitionZone = "CrownTransitionZone";+ public const string BottomMountingInterface = "BottomMountingInterface";+ public const string MountingHolePattern = "MountingHolePattern";+ public const string OuterFootprintBoundary = "OuterFootprintBoundary";++ public static SculptResult CreateBase(string stateName, double width, double depth, double height, IReadOnlyList<HousingHole> holes)+ {+ var construction = new HousingConstruction(width, depth, height, width, depth, 0d, holes);+ var built = SculptedHousingBrepBuilder.Build(construction);+ if (built.Body is null) return SculptResult.Failure(built.Diagnostics);+ var canonical = $"BodyState0|{width:R}|{depth:R}|{height:R}|{string.Join(';', holes.OrderBy(x => x.StableId, StringComparer.Ordinal).Select(HoleFingerprint))}";+ var stateId = BodyStateId.Derive(canonical);+ var inventory = Inventory(construction);+ var evidence = ValidateBody(built.Body, height);+ if (evidence.Any(x => !x.Satisfied)) return SculptResult.Failure(+ [new("sculpt-base-invalid", "Initial body did not satisfy the body-state validity contract: " + string.Join("; ", evidence.Where(x => !x.Satisfied).Select(x => $"{x.Check}: {x.Detail}")))], evidence);+ return new(true, new(stateId, null, "housing-body", stateName, built.Body, construction, inventory, null, evidence), null, evidence, []);+ }++ internal static IReadOnlyDictionary<string, SculptSemanticEntity> Inventory(HousingConstruction c)+ => new Dictionary<string, SculptSemanticEntity>(StringComparer.Ordinal)+ {+ [CrownRegion] = new(CrownRegion, SculptEntityKind.Region, $"rect:{c.CrownWidth:R}x{c.CrownDepth:R}@z={c.FinalHeight:R}", "Bounded top/crown support."),+ [TransitionZone] = new(TransitionZone, SculptEntityKind.Region, $"transition:z={c.BaseHeight:R}..{c.FinalHeight:R}", "G0 crown reconnection zone."),+ [BottomMountingInterface] = new(BottomMountingInterface, SculptEntityKind.Interface, $"plane:z=0;rect={c.Width:R}x{c.Depth:R};holes={HolePattern(c.Holes)}", "Protected planar mounting interface."),+ [MountingHolePattern] = new(MountingHolePattern, SculptEntityKind.Pattern, HolePattern(c.Holes), "Protected mounting-hole axes, centers, and diameters."),+ [OuterFootprintBoundary] = new(OuterFootprintBoundary, SculptEntityKind.Region, $"rect:{c.Width:R}x{c.Depth:R}@z=0", "Protected lower outer footprint boundary."),+ };++ internal static IReadOnlyList<SculptValidationEvidence> ValidateBody(BrepBody body, double localityTolerance)+ {+ var preflight = BrepExportPreflight.Validate(body);+ var mass = BrepMassProperties.Evaluate(body);+ return+ [+ new("ClosedManifold", preflight.IsValid && mass.IsEnclosed, LocalityEvidenceLevel.CertifiedBounded, null, 1e-6, $"BRep preflight errors={preflight.ErrorCount}; independent edge-incidence enclosure={mass.IsEnclosed}."),+ new("OrientationConsistency", mass.IsOrientationConsistent, LocalityEvidenceLevel.CertifiedBounded, null, 1e-9, $"Independent boundary verifier orientationConsistent={mass.IsOrientationConsistent}."),+ new("NoSelfIntersection", preflight.IsValid, LocalityEvidenceLevel.CertifiedBounded, null, 1e-6, "Bounded analytic construction validation plus BRep export preflight; this is not a general-purpose global intersection proof."),+ ];+ }++ private static string HolePattern(IEnumerable<HousingHole> holes) => string.Join(';', holes.OrderBy(x => x.StableId, StringComparer.Ordinal).Select(HoleFingerprint));+ private static string HoleFingerprint(HousingHole h) => $"{h.StableId}@{h.CenterX:R},{h.CenterY:R}:d={h.Diameter:R}";+}++public static class OffsetRegionSculptor+{+ private const double LocalityTolerance = 1e-6;++ public static SculptResult Apply(BodyState input, string outputName, OffsetRegionOperation operation)+ {+ ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(operation);+ var diagnostics = new List<SculptDiagnostic>(); var evidence = new List<SculptValidationEvidence>();+ if (!input.SemanticInventory.ContainsKey(operation.TargetRegion)) diagnostics.Add(new("sculpt-target-unresolved", $"Target region '{operation.TargetRegion}' does not exist in the input state.", operation.TargetRegion));+ if (!operation.MayModify.Contains(operation.TargetRegion, StringComparer.Ordinal)) diagnostics.Add(new("sculpt-target-not-authorized", "Target region is not present in MayModify.", operation.TargetRegion));+ if (operation.BoundaryContinuity != "G0") diagnostics.Add(new("sculpt-boundary-continuity-unsupported", "SURF-X0 supports G0 positional continuity only."));+ foreach (var contract in operation.Preserves)+ {+ if (!input.SemanticInventory.ContainsKey(contract.EntityId)) diagnostics.Add(new("sculpt-preserve-unresolved", $"Preserved entity '{contract.EntityId}' does not exist.", contract.EntityId));+ if (operation.MayModify.Contains(contract.EntityId, StringComparer.Ordinal)) diagnostics.Add(new("sculpt-breaks-preserved-interface", $"'{contract.EntityId}' cannot be both modified and preserved.", contract.EntityId));+ }+ var actualDomain = new SpatialInfluenceEnvelope(-input.Construction.Width / 2d, -input.Construction.Depth / 2d, input.Construction.BaseHeight,+ input.Construction.Width / 2d, input.Construction.Depth / 2d, input.Construction.BaseHeight + operation.Offset);+ if (!operation.InfluenceEnvelope.Contains(actualDomain, LocalityTolerance)) diagnostics.Add(new("sculpt-outside-authorized-region", "The declared influence envelope does not contain the analytic transition and crown change domain."));+ if (operation.InfluenceEnvelope.MinZ < input.Construction.BaseHeight - LocalityTolerance)+ diagnostics.Add(new("sculpt-breaks-preserved-interface", "The influence envelope reaches below the authorized top boundary and could affect protected lower geometry."));+ if (!double.IsFinite(operation.Offset) || input.Construction.BaseHeight + operation.Offset <= 0d)+ diagnostics.Add(new("sculpt-self-intersection", "The requested offset crosses or collapses the bottom mounting plane."));+ if (operation.RegionWidth <= 0d || operation.RegionDepth <= 0d || operation.RegionWidth > input.Construction.Width || operation.RegionDepth > input.Construction.Depth)+ diagnostics.Add(new("sculpt-target-domain-invalid", "OffsetRegion dimensions must be positive and contained by the input footprint."));+ if (diagnostics.Count > 0) return SculptResult.Failure(diagnostics, evidence);++ var outputConstruction = input.Construction with { CrownWidth = operation.RegionWidth, CrownDepth = operation.RegionDepth, CrownOffset = operation.Offset };+ var built = SculptedHousingBrepBuilder.Build(outputConstruction);+ if (built.Body is null) return SculptResult.Failure(built.Diagnostics, evidence);+ var inventory = SculptedHousingFactory.Inventory(outputConstruction);+ foreach (var contract in operation.Preserves)+ {+ var before = input.SemanticInventory[contract.EntityId]; var after = inventory[contract.EntityId];+ var satisfied = string.Equals(before.StableId, after.StableId, StringComparison.Ordinal) && string.Equals(before.GeometryFingerprint, after.GeometryFingerprint, StringComparison.Ordinal);+ evidence.Add(new($"Preserve:{contract.EntityId}", satisfied, LocalityEvidenceLevel.ExactSemantic, satisfied ? 0d : null, LocalityTolerance,+ satisfied ? $"Stable identity and {contract.Mode} fingerprint are identical." : "Protected identity or contract fingerprint changed."));+ if (!satisfied) diagnostics.Add(new("sculpt-preservation-failed", $"Preservation contract failed for '{contract.EntityId}'.", contract.EntityId));+ }+ var locality = SculptLocalityVerifier.CompareOutsideTopEnvelope(input.Body, built.Body, input.Construction.BaseHeight, LocalityTolerance);+ evidence.Add(locality);+ if (!locality.Satisfied) diagnostics.Add(new("sculpt-outside-authorized-region", locality.Detail));+ evidence.AddRange(SculptedHousingFactory.ValidateBody(built.Body, LocalityTolerance));+ foreach (var requirement in operation.Requirements)+ {+ var check = requirement.ToString();+ if (!evidence.Any(x => x.Check == check && x.Satisfied)) diagnostics.Add(new("sculpt-postcondition-failed", $"Required postcondition '{check}' was not proven."));+ }+ if (diagnostics.Count > 0 || evidence.Any(x => !x.Satisfied)) return SculptResult.Failure(diagnostics, evidence);++ var outputId = BodyStateId.Derive($"{input.StateId.Value}|OffsetRegion|{operation.Canonical}");+ var correspondence = new List<GeometricDeltaEntry>+ {+ new(SculptedHousingFactory.BottomMountingInterface, GeometricChangeKind.Preserved, [SculptedHousingFactory.BottomMountingInterface], "Exact semantic identity and planar trim fingerprint."),+ new(SculptedHousingFactory.MountingHolePattern, GeometricChangeKind.Preserved, [SculptedHousingFactory.MountingHolePattern], "Exact axes, centers, and diameters; upper cylindrical extent is introduced inside the authorized region."),+ new(SculptedHousingFactory.OuterFootprintBoundary, GeometricChangeKind.Preserved, [SculptedHousingFactory.OuterFootprintBoundary], "Exact lower boundary coordinates."),+ new(SculptedHousingFactory.CrownRegion, GeometricChangeKind.Replaced, [$"{SculptedHousingFactory.CrownRegion}@{outputId.Value}"], "Planar top support offset and bounded to the authored region."),+ new("<none>", GeometricChangeKind.Introduced, [SculptedHousingFactory.TransitionZone], "Four analytic planar G0 transition faces."),+ };+ var delta = new GeometricDelta(input.StateId, outputId, [operation.TargetRegion, .. operation.Preserves.Select(x => x.EntityId)], operation.Preserves.Select(x => x.EntityId).ToArray(),+ [SculptedHousingFactory.CrownRegion], [], [SculptedHousingFactory.TransitionZone], operation.MayModify, operation.InfluenceEnvelope, correspondence);+ var output = new BodyState(outputId, input.StateId, input.BodyStableId, outputName, built.Body, outputConstruction, inventory, delta, evidence);+ return new(true, output, delta, evidence, []);+ }+}++internal static class SculptLocalityVerifier+{+ public static SculptValidationEvidence CompareOutsideTopEnvelope(BrepBody input, BrepBody output, double boundaryZ, double tolerance)+ {+ var deviations = new List<double>(); var details = new List<string>();+ var inputPoints = PointsBelow(input, boundaryZ, tolerance); var outputPoints = PointsBelow(output, boundaryZ, tolerance);+ var pointsMatch = CompareSets(inputPoints, outputPoints, PointDistance, tolerance, deviations);+ details.Add($"lowerVertices={inputPoints.Count}/{outputPoints.Count}");+ var inputPlanes = LowerPlanes(input, boundaryZ, tolerance); var outputPlanes = LowerPlanes(output, boundaryZ, tolerance);+ var planesMatch = CompareSets(inputPlanes, outputPlanes, VectorDistance, tolerance, deviations);+ details.Add($"lowerPlanes={inputPlanes.Count}/{outputPlanes.Count}");+ var inputCylinders = Cylinders(input); var outputCylinders = Cylinders(output);+ var cylindersMatch = CompareSets(inputCylinders, outputCylinders, VectorDistance, tolerance, deviations);+ details.Add($"cylinderSupports={inputCylinders.Count}/{outputCylinders.Count}");+ var inputCircles = CirclesBelow(input, boundaryZ, tolerance); var outputCircles = CirclesBelow(output, boundaryZ, tolerance);+ var circlesMatch = CompareSets(inputCircles, outputCircles, VectorDistance, tolerance, deviations);+ details.Add($"lowerCircularTrims={inputCircles.Count}/{outputCircles.Count}");+ var max = deviations.Count == 0 ? 0d : deviations.Max(); var satisfied = pointsMatch && planesMatch && cylindersMatch && circlesMatch && max <= tolerance;+ return new("AuthorizedLocality", satisfied, LocalityEvidenceLevel.ExactAnalytic, max, tolerance,+ $"Independent realized-BRep comparison below z={boundaryZ:R}: {string.Join(", ", details)}; analytic supports and trims matched={satisfied}.");+ }++ private static IReadOnlyList<Point3D> PointsBelow(BrepBody body, double boundary, double tolerance) => body.Topology.Vertices+ .Select(x => body.TryGetVertexPoint(x.Id, out var point) ? (Point3D?)point : null).Where(x => x is not null && x.Value.Z < boundary - tolerance).Select(x => x!.Value).ToArray();+ private static IReadOnlyList<double[]> LowerPlanes(BrepBody body, double boundary, double tolerance)+ {+ var result = new List<double[]>();+ foreach (var face in body.Topology.Faces)+ {+ if (!body.TryGetFaceSurfaceGeometry(face.Id, out var geometry) || geometry?.Plane is not { } plane) continue;+ var points = face.LoopIds.SelectMany(id => body.Topology.GetLoop(id).CoedgeIds).Select(id => body.Topology.GetEdge(body.Topology.GetCoedge(id).EdgeId)).SelectMany(edge => new[] { edge.StartVertexId, edge.EndVertexId }).Distinct().Select(id => body.TryGetVertexPoint(id, out var p) ? (Point3D?)p : null).Where(x => x is not null).Select(x => x!.Value).ToArray();+ if (points.Length == 0 || points.Min(x => x.Z) >= boundary - tolerance || points.Max(x => x.Z) > boundary + tolerance) continue;+ var n = Canonical(plane.Normal.ToVector()); var d = n.X * plane.Origin.X + n.Y * plane.Origin.Y + n.Z * plane.Origin.Z;+ result.Add([n.X, n.Y, n.Z, d]);+ }+ return result;+ }+ private static IReadOnlyList<double[]> Cylinders(BrepBody body) => body.Topology.Faces.Select(face => body.TryGetFaceSurfaceGeometry(face.Id, out var geometry) ? geometry?.Cylinder : null).Where(x => x is not null).Select(x =>+ {+ var c = x!.Value; var axis = Canonical(c.Axis.ToVector()); var origin = new Vector3D(c.Origin.X, c.Origin.Y, c.Origin.Z); var perpendicular = origin - axis * origin.Dot(axis);+ return new[] { axis.X, axis.Y, axis.Z, perpendicular.X, perpendicular.Y, perpendicular.Z, c.Radius };+ }).ToArray();+ private static IReadOnlyList<double[]> CirclesBelow(BrepBody body, double boundary, double tolerance) => body.Bindings.EdgeBindings.Select(binding => body.Geometry.TryGetCurve(binding.CurveGeometryId, out var curve) ? curve?.Circle3 : null).Where(x => x is not null && x.Value.Center.Z < boundary - tolerance).Select(x =>+ { var c = x!.Value; var n = Canonical(c.Normal.ToVector()); return new[] { c.Center.X, c.Center.Y, c.Center.Z, n.X, n.Y, n.Z, c.Radius }; }).ToArray();++ private static bool CompareSets<T>(IReadOnlyList<T> left, IReadOnlyList<T> right, Func<T, T, double> distance, double tolerance, ICollection<double> deviations)+ {+ if (left.Count != right.Count) return false; var remaining = right.ToList();+ foreach (var item in left) { var match = remaining.Select((candidate, index) => (index, delta: distance(item, candidate))).OrderBy(x => x.delta).FirstOrDefault(); deviations.Add(match.delta); if (match.delta > tolerance) return false; remaining.RemoveAt(match.index); }+ return remaining.Count == 0;+ }+ private static double PointDistance(Point3D a, Point3D b) => (a - b).Length;+ private static double VectorDistance(double[] a, double[] b) => a.Length != b.Length ? double.PositiveInfinity : a.Zip(b, (x, y) => Math.Abs(x - y)).Max();+ private static Vector3D Canonical(Vector3D value)+ {+ var n = value / value.Length; var sign = Math.Abs(n.X) > 1e-12 ? Math.Sign(n.X) : Math.Abs(n.Y) > 1e-12 ? Math.Sign(n.Y) : Math.Sign(n.Z); return sign < 0 ? -n : n;+ }+}++public sealed record StepSurfaceInventory(int Plane, int Cylinder, int Cone, int Sphere, int Torus, int NonRationalBSpline, int Other, int RationalNurbs);+public sealed record SculptStepResult(bool IsSuccess, string? Step, StepSurfaceInventory Inventory, IReadOnlyList<SculptDiagnostic> Diagnostics);++public static class SculptStepExporter+{+ public static SculptStepResult Export(BodyState state, string productName)+ {+ var export = Step242Exporter.ExportBody(state.Body, options: new Step242ExportOptions { BrepExportPreflightMode = BrepExportPreflightMode.Enforce, ProductName = productName });+ if (!export.IsSuccess) return new(false, null, Empty(), export.Diagnostics.Select(x => new SculptDiagnostic("surf-step-export-failed", x.Message)).ToArray());+ var text = export.Value;+ var inventory = new StepSurfaceInventory(Count(text, "=PLANE("), Count(text, "=CYLINDRICAL_SURFACE("), Count(text, "=CONICAL_SURFACE("), Count(text, "=SPHERICAL_SURFACE("), Count(text, "=TOROIDAL_SURFACE("), Count(text, "=B_SPLINE_SURFACE_WITH_KNOTS("), 0, Count(text, "RATIONAL_B_SPLINE_SURFACE"));+ if (inventory.RationalNurbs != 0)+ return new(false, null, inventory, [new("surf-surface-export-normalization-failed", "STEP product boundary contains a rational NURBS surface; export was blocked.")]);+ return new(true, text, inventory, []);+ }+ private static int Count(string text, string marker) => (text.Length - text.Replace(marker, string.Empty, StringComparison.Ordinal).Length) / marker.Length;+ private static StepSurfaceInventory Empty() => new(0, 0, 0, 0, 0, 0, 0, 0);+}++public sealed record InternalRationalSurfaceCandidate(int DegreeU, int DegreeV, IReadOnlyList<IReadOnlyList<Point3D>> ControlPoints, IReadOnlyList<IReadOnlyList<double>> Weights);+public sealed record SurfaceNormalizationResult(bool IsSuccess, string EmittedFamily, SurfaceGeometry? Surface, string Diagnostic);+public static class RationalSurfaceNormalizer+{+ public static SurfaceNormalizationResult Normalize(InternalRationalSurfaceCandidate candidate)+ {+ var weights = candidate.Weights.SelectMany(x => x).ToArray();+ var controlCountV = candidate.ControlPoints.Count == 0 ? 0 : candidate.ControlPoints[0].Count;+ if (weights.Length == 0 || candidate.Weights.Count != candidate.ControlPoints.Count || candidate.Weights.Any(x => x.Count != controlCountV) || weights.Any(x => !double.IsFinite(x) || x <= 0d)) return new(false, "None", null, "surf-surface-export-normalization-failed: invalid rational weights");+ if (weights.Max() - weights.Min() > 1e-12d) return new(false, "None", null, "surf-surface-export-normalization-failed: analytic recovery failed and rationality is not removable");+ if (candidate.DegreeU == 1 && candidate.DegreeV == 1 && candidate.ControlPoints.Count == 2 && candidate.ControlPoints.All(x => x.Count == 2))+ {+ var p = candidate.ControlPoints; var u = p[1][0] - p[0][0]; var v = p[0][1] - p[0][0]; var normal = u.Cross(v);+ if (normal.Length > 1e-12d && Math.Abs((p[1][1] - p[0][0]).Dot(normal / normal.Length)) <= 1e-12d)+ return new(true, "Plane", SurfaceGeometry.FromPlane(new PlaneSurface(p[0][0], Direction3D.Create(normal), Direction3D.Create(u))), "Equal weights removed; exact analytic plane recovered.");+ }+ try+ {+ var (multU, knotsU) = OpenUniformKnots(candidate.ControlPoints.Count, candidate.DegreeU); var (multV, knotsV) = OpenUniformKnots(controlCountV, candidate.DegreeV);+ var surface = new BSplineSurfaceWithKnots(candidate.DegreeU, candidate.DegreeV, candidate.ControlPoints, "UNSPECIFIED", false, false, false, multU, multV, knotsU, knotsV, "UNSPECIFIED");+ return new(true, "NonRationalBSpline", SurfaceGeometry.FromBSplineSurfaceWithKnots(surface), "All weights are equal; common rational scale removed exactly and a non-rational B-spline was produced.");+ }+ catch (ArgumentException exception) { return new(false, "None", null, $"surf-surface-export-normalization-failed: equal-weight non-rational conversion rejected: {exception.Message}"); }+ }++ private static (IReadOnlyList<int> Multiplicities, IReadOnlyList<double> Values) OpenUniformKnots(int controlCount, int degree)+ {+ if (controlCount < degree + 1) throw new ArgumentException("Control count must be at least degree plus one.");+ var internalCount = controlCount - degree - 1; var values = Enumerable.Range(0, internalCount + 2).Select(i => i / (double)(internalCount + 1)).ToArray();+ var multiplicities = Enumerable.Range(0, values.Length).Select(i => i == 0 || i == values.Length - 1 ? degree + 1 : 1).ToArray(); return (multiplicities, values);+ }+}diff --git a/Aetheris.Surfacing/SculptingState.cs b/Aetheris.Surfacing/SculptingState.csnew file mode 100644index 00000000..f51e269d--- /dev/null+++ b/Aetheris.Surfacing/SculptingState.cs@@ -0,0 +1,100 @@+using System.Security.Cryptography;+using System.Text;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Surfacing;++public readonly record struct BodyStateId(string Value)+{+ public override string ToString() => Value;+ public static BodyStateId Derive(string canonical)+ => new("state-" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(canonical))).ToLowerInvariant()[..20]);+}++public enum SculptEntityKind { Body, Region, Interface, Pattern, Datum, Surface }+public enum PreservationMode { ExactGeometry, SemanticIdentity, PatternPlacementAndDiameter }+public enum SculptRequirement { ClosedManifold, OrientationConsistency, NoSelfIntersection }+public enum GeometricChangeKind { Preserved, Replaced, Introduced, Removed }+public enum LocalityEvidenceLevel { ExactSemantic, ExactAnalytic, CertifiedBounded, SampledConservative }++public sealed record SculptSemanticEntity(string StableId, SculptEntityKind Kind, string GeometryFingerprint, string Description);+public sealed record PreservationContract(string EntityId, PreservationMode Mode);+public sealed record SpatialInfluenceEnvelope(double MinX, double MinY, double MinZ, double MaxX, double MaxY, double MaxZ)+{+ public bool Contains(SpatialInfluenceEnvelope other, double tolerance) =>+ MinX <= other.MinX + tolerance && MinY <= other.MinY + tolerance && MinZ <= other.MinZ + tolerance+ && MaxX >= other.MaxX - tolerance && MaxY >= other.MaxY - tolerance && MaxZ >= other.MaxZ - tolerance;+}++public sealed record GeometricDeltaEntry(string InputEntity, GeometricChangeKind Change, IReadOnlyList<string> OutputEntities, string Evidence);+public sealed record GeometricDelta(+ BodyStateId InputState,+ BodyStateId OutputState,+ IReadOnlyList<string> Reads,+ IReadOnlyList<string> Preserves,+ IReadOnlyList<string> Replaces,+ IReadOnlyList<string> Removes,+ IReadOnlyList<string> Introduces,+ IReadOnlyList<string> AuthorizedRegion,+ SpatialInfluenceEnvelope InfluenceEnvelope,+ IReadOnlyList<GeometricDeltaEntry> Correspondence);++public sealed record SculptValidationEvidence(+ string Check,+ bool Satisfied,+ LocalityEvidenceLevel Level,+ double? MaximumObservedDeviation,+ double Tolerance,+ string Detail);++public sealed record HousingHole(string StableId, double CenterX, double CenterY, double Diameter);+public sealed record HousingConstruction(+ double Width,+ double Depth,+ double BaseHeight,+ double CrownWidth,+ double CrownDepth,+ double CrownOffset,+ IReadOnlyList<HousingHole> Holes)+{+ public double FinalHeight => BaseHeight + CrownOffset;+ public bool HasCrown => CrownOffset > 0d && (CrownWidth < Width || CrownDepth < Depth);+}++public sealed record BodyState(+ BodyStateId StateId,+ BodyStateId? PredecessorStateId,+ string BodyStableId,+ string AuthoredName,+ BrepBody Body,+ HousingConstruction Construction,+ IReadOnlyDictionary<string, SculptSemanticEntity> SemanticInventory,+ GeometricDelta? Delta,+ IReadOnlyList<SculptValidationEvidence> ValidationEvidence);++public sealed record OffsetRegionOperation(+ string StableId,+ string TargetRegion,+ double Offset,+ double RegionWidth,+ double RegionDepth,+ IReadOnlyList<string> MayModify,+ SpatialInfluenceEnvelope InfluenceEnvelope,+ IReadOnlyList<PreservationContract> Preserves,+ IReadOnlyList<SculptRequirement> Requirements,+ string BoundaryContinuity = "G0")+{+ public string Canonical => string.Join('|', StableId, TargetRegion, Offset.ToString("R"), RegionWidth.ToString("R"), RegionDepth.ToString("R"),+ string.Join(',', MayModify.Order(StringComparer.Ordinal)),+ $"{InfluenceEnvelope.MinX:R},{InfluenceEnvelope.MinY:R},{InfluenceEnvelope.MinZ:R},{InfluenceEnvelope.MaxX:R},{InfluenceEnvelope.MaxY:R},{InfluenceEnvelope.MaxZ:R}",+ string.Join(',', Preserves.OrderBy(x => x.EntityId, StringComparer.Ordinal).Select(x => $"{x.EntityId}:{x.Mode}")),+ string.Join(',', Requirements.Order()), BoundaryContinuity);+}++public sealed record SculptDiagnostic(string Code, string Message, string? Entity = null);+public sealed record SculptResult(bool IsSuccess, BodyState? OutputState, GeometricDelta? Delta, IReadOnlyList<SculptValidationEvidence> Evidence, IReadOnlyList<SculptDiagnostic> Diagnostics)+{+ public static SculptResult Failure(IEnumerable<SculptDiagnostic> diagnostics, IEnumerable<SculptValidationEvidence>? evidence = null)+ => new(false, null, null, evidence?.ToArray() ?? [], diagnostics.ToArray());+}diff --git a/Aetheris.Surfacing/SurfacingModule.cs b/Aetheris.Surfacing/SurfacingModule.csindex 1b818c8d..67b9bb51 100644--- a/Aetheris.Surfacing/SurfacingModule.cs+++ b/Aetheris.Surfacing/SurfacingModule.cs@@ -5,13 +5,14 @@ namespace Aetheris.Surfacing;public static class SurfacingModule{public static readonly AetherisModuleId Id = new("Aetheris.Surfacing");- public static readonly ModuleVersion Version = new(0, 2, 0);+ public static readonly ModuleVersion Version = new(0, 3, 0);public const string RuledSurfaceCapability = "Surfacing.RuledSurface";public const string RuledTransitionCapability = "Surfacing.RuledTransition";public const string ParametricSurfaceCapability = "Surfacing.ParametricSurface";public const string SectionSurfaceCapability = "Surfacing.SectionSurface";public const string BoundaryPatchCapability = "Surfacing.BoundaryPatch";public const string PanelCapability = "Surfacing.Panel";+ public const string BoundedSculptingCapability = "Surfacing.BoundedSculpting";public static AetherisModule Definition { get; } = new(Id, "Surfacing", Version,@@ -20,9 +21,10 @@ public static class SurfacingModulenew(ParametricSurfaceCapability,Id,Version,"Unit-aware bounded equation surface with automatic derivatives and normals."),new(SectionSurfaceCapability,Id,Version,"Ordered-section surface with explicit non-rational materialization evidence."),new(BoundaryPatchCapability,Id,Version,"Four-boundary G0 patch preserving boundary intent."),- new(PanelCapability,Id,Version,"Bounded oriented engineering surface with ordered semantic boundary edges and developability evidence.")],+ new(PanelCapability,Id,Version,"Bounded oriented engineering surface with ordered semantic boundary edges and developability evidence."),+ new(BoundedSculptingCapability,Id,Version,"Immutable single-predecessor BodyState derivation with bounded OffsetRegion authority, preservation contracts, and inspectable GeometricDelta evidence.")],["Surfacing.PanelConcept", "Surfacing.SurfacePatchConcept"], ["Surfacing.RuledCanopyPanel","Surfacing.HyperbolicParaboloid","Surfacing.ParabolicCylinder","Surfacing.EllipticParaboloid","Surfacing.Helicoid"],["Surface construction -> PanelIR -> semantic edges", "Panel edge Interface/Mate -> deterministic G0 evidence", "PanelIR -> bounded BRep-backed STEP export envelope"],- ["panel-incomplete-boundary", "panel-boundary-orientation-inconsistent","panel-mate-endpoint-mismatch","panel-mate-g0-failure","panel-mate-g1-failure","panel-mate-g1-unknown","panel-mate-g2-failure","panel-mate-g2-unknown","surfacing-panel-thickness-invalid"],+ ["panel-incomplete-boundary", "panel-boundary-orientation-inconsistent","panel-mate-endpoint-mismatch","panel-mate-g0-failure","panel-mate-g1-failure","panel-mate-g1-unknown","panel-mate-g2-failure","panel-mate-g2-unknown","surfacing-panel-thickness-invalid","sculpt-outside-authorized-region","sculpt-preservation-failed","sculpt-self-intersection","surf-surface-export-normalization-failed"],[new(CoreModule.Id, new(1, 0, 0))], new("docs/development/milestones/modules/surfacing.md"));}diff --git a/docs/public/README.md b/docs/public/README.mdindex 22b75bd5..d54b47c3 100644--- a/docs/public/README.md+++ b/docs/public/README.md@@ -4,7 +4,7 @@ This directory is the only authoritative in-repository guide to behavior shippedStart with [Getting Started](getting-started.md), then use these guides:-- Firmament: [overview](firmament/overview.md), [language style](firmament/language-style.md), [syntax](firmament/syntax.md), [geometry](firmament/geometry.md), [Circular Sweep](firmament/sweep.md), [Structural members and weldments](firmament/structural.md), [Semantic piping and local autorouting](firmament/piping.md), [Paperclip Template](firmament/paperclip.md), [Templates](firmament/templates.md), [materials](firmament/materials.md), [PMI](firmament/pmi.md), [Sheet Metal](firmament/sheet-metal.md), [FEA](firmament/fea.md), and [STEP import](firmament/step-import.md)+- Firmament: [overview](firmament/overview.md), [language style](firmament/language-style.md), [syntax](firmament/syntax.md), [geometry](firmament/geometry.md), [bounded mathematical sculpting](firmament/sculpting.md), [Circular Sweep](firmament/sweep.md), [Structural members and weldments](firmament/structural.md), [Semantic piping and local autorouting](firmament/piping.md), [Paperclip Template](firmament/paperclip.md), [Templates](firmament/templates.md), [materials](firmament/materials.md), [PMI](firmament/pmi.md), [Sheet Metal](firmament/sheet-metal.md), [FEA](firmament/fea.md), and [STEP import](firmament/step-import.md)- 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)diff --git a/docs/public/firmament/sculpting.md b/docs/public/firmament/sculpting.mdnew file mode 100644index 00000000..b09209f0--- /dev/null+++ b/docs/public/firmament/sculpting.md@@ -0,0 +1,67 @@+# Bounded mathematical sculpting++SURF-X0 supports bounded mathematical sculpting and locality-preserving region modification. It does not provide full general surfacing.++Sculpting is a lower-authority escape hatch for geometry that an engineering feature such as `Boss`, `Pocket`, `Hole`, `Sweep`, `Fillet`, or `Chamfer` cannot express. Prefer those features whenever they carry the intended engineering meaning.++## Body states++Every accepted operation consumes exactly one immutable semantic `BodyState` and produces a new one:++```text+Base -> CrownRaised+Base -> CrownHigh+```++Both variants can share `Base`; neither mutates it or the other. State IDs are deterministic hashes of the predecessor and canonical operation contract. Ordinary authoring always references the current predecessor, not topology from an arbitrary historical state.++## X0 authoring++The current operation is `OffsetRegion`. The canonical controller-cover example is [`fixtures/Canonical/Sculpting/sculpted-housing.firmament`](../../../fixtures/Canonical/Sculpting/sculpted-housing.firmament):++```firmament+SculptState CrownRaised {+ Input: Base+ OffsetRegion {+ Target: HousingCrown+ Offset: 6mm+ Region: [60mm, 40mm]+ InfluenceEnvelope: [-50mm, -40mm, 20mm, 50mm, 40mm, 26mm]+ Boundary: G0+ }+ MayModify: [HousingCrown, CrownTransitionZone]+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+}+```++`MayModify` grants authority; `Preserve` requires semantic identity and the declared geometry fingerprint to survive; `Require` is a postcondition on the result. They are deliberately different contracts. The X0 influence envelope is a conservative axis-aligned volume, not a general spatial-logic language.++`Region` is ordered `[width, depth]` and bounds the raised crown plateau. The larger influence envelope must also contain the authorized G0 transition zone; in the flagship it covers the full footprint above `z=20`.++The accepted operation records reads, preserved/replaced/introduced/removed entities, the authorized domain, correspondence, and validation evidence in `GeometricDelta`. `aetheris inspect model.firmament --json` reports every state. `aetheris build model.firmament --json` also writes a sibling `.delta.json` artifact.++## Guarantees and evidence++The housing lane verifies:++- exact semantic preservation of the bottom mounting interface, mounting-hole centers/axes/diameters, and lower footprint;+- exact analytic equality below the crown boundary, with maximum outside-domain deviation reported as zero;+- G0 reconnection through four analytic transition planes;+- BRep binding/preflight validity, edge-incidence enclosure, and orientation consistency before commit;+- failure atomicity: rejected operations never produce an accepted output state;+- STEP reimport and a post-serialization rational-surface scan.++`NoSelfIntersection` in X0 is a certified bounded guarantee for the admitted rectangular crown construction. It is not advertised as a universal intersection theorem.++## Product surface boundary++**Aetheris does not use NURBS as its universal surface abstraction.**++Internal algorithms may temporarily use rational spline mathematics, but exported product geometry must normalize to analytic or non-rational forms. The export order is exact analytic surface, exact or explicitly bounded non-rational B-spline, then a blocking diagnostic. Arbitrary rational NURBS fallback is prohibited. The diagnostic is `surf-surface-export-normalization-failed`.++The X0 housing emits only `PLANE` and `CYLINDRICAL_SURFACE`. A final STEP scan must report `RationalNURBS = 0`; otherwise export fails.++## Current limits++SURF-X0 does not support general NURBS authoring, arbitrary freeform patches, Loft, Trim/Extend, G1/G2 patch networks, arbitrary deformation, global surface replacement, or arbitrary imported-face sculpting. The first materializer is intentionally limited to a rectangular housing with a bounded rectangular crown and through mounting holes. PMI and Assembly Interface persistence through this lane remain follow-up work; X0 preserves the named mounting-interface and hole-pattern semantic contracts but does not claim new AP242 PMI types.diff --git a/docs/public/reference/cli.md b/docs/public/reference/cli.mdindex cce00f72..5a04a5e1 100644--- a/docs/public/reference/cli.md+++ b/docs/public/reference/cli.md@@ -13,4 +13,4 @@ Primary public commands:| `sheetmetal ...` | Inspect, recognize, recover, compare, or flatten Sheet Metal || `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; 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; 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/supported-features.md b/docs/public/reference/supported-features.mdindex dafb7b76..bd798602 100644--- a/docs/public/reference/supported-features.md+++ b/docs/public/reference/supported-features.md@@ -5,6 +5,7 @@| Area | Status | Preview 3 boundary ||---|---|---|| Firmament V2 native primitives/profiles | Bounded | Named Box/Cylinder/Frustum/RoundedBox and admitted line/arc profile construction/composition |+| Bounded mathematical sculpting | Bounded (SURF-X0) | Immutable single-predecessor `BodyState`, rectangular-housing `OffsetRegion`, explicit authority/preservation/postconditions, analytic locality proof, and rational-free STEP. This is not general surfacing. See the [sculpting guide](../firmament/sculpting.md). || Firmament V2 analytic primitives | Bounded | Direct named Sphere, Cone (including zero-radius pointed end), and Torus routes round-trip through AP242; legacy `solid` declarations remain compatibility inputs, not canonical authoring || Circular Sweep | Bounded (X0) | Open planar XY Concept Path, tangent line/arc segments, constant circular diameter, analytic cylinder/torus faces, capped solid; no general 3D/variable/rail/twist sweep || Structural / weldment | Bounded (X2) | Explicit 3D nodes and straight paths; identifiable members; square/rectangular/round tube, angle, flat/round bar; orientation; catalog material; two-member butt and polygonal miter joints; semantic fillet welds; AP242 member assembly and deterministic JSON Cut List. No coping, curved routing, multi-member miter, connection design, weld analysis, or structural FEA. See [guide](../firmament/structural.md). |diff --git a/docs/release/SURF-X0-GEOMETRIC-STATE-LOCALITY.md b/docs/release/SURF-X0-GEOMETRIC-STATE-LOCALITY.mdnew file mode 100644index 00000000..71e282c1--- /dev/null+++ b/docs/release/SURF-X0-GEOMETRIC-STATE-LOCALITY.md@@ -0,0 +1,103 @@+# SURF-X0 — geometric state and locality++## Executive verdict++**Accepted.** Aetheris has a trustworthy execution model for the admitted bounded mathematical-sculpting lane. The verdict is intentionally limited to the rectangular-housing `OffsetRegion` witness; it is not a claim of general surfacing.++## State model++`BodyState` is an immutable semantic record containing a deterministic `StateId`, optional single `PredecessorStateId`, stable body identity, BRep, construction state, semantic inventory, delta, and validation evidence. `Base` is `state-8960030e57e7b7d897d9`; the 6 mm state is `state-8f9f9011f77eb90790aa`. Both the 6 mm and 10 mm fixtures derive from `Base`, proving branching without parent or sibling mutation. Construction is attempted, verified, and only then returned as accepted state; failures return no output state.++The full chain is recoverable deterministically from Firmament source. No runtime object identity or hidden predecessor object is serialized as semantic authority.++## GeometricDelta++The flagship delta records:++| Classification | Semantic entities |+|---|---|+| Preserved | `BottomMountingInterface`, `MountingHolePattern`, `OuterFootprintBoundary` |+| Replaced | `HousingCrown` -> `HousingCrown@state-8f9f9011f77eb90790aa` |+| Introduced | `CrownTransitionZone` (four analytic G0 transition planes) |+| Removed | none |++The structured record also includes reads, authorized region, spatial envelope, and correspondence evidence. `aetheris inspect --json` shows both states; `aetheris build --json` writes [`surf-x0-sculpted-housing.delta.json`](../../artifacts/local/surf-x0/surf-x0-sculpted-housing.delta.json).++## Locality++- Authorized semantic domain: `HousingCrown`, `CrownTransitionZone`.+- Spatial envelope: `[-50,-40,20]` to `[50,40,26]` mm.+- Method: independent comparison of the two realized BReps below `z=20` (8 vertices, 5 plane supports, 4 cylinder supports, and 4 bottom circular trims), plus BRep preflight and edge-incidence enclosure verification.+- Evidence level: `ExactAnalytic` outside the modified crown and `CertifiedBounded` for result validity.+- Maximum observed deviation outside the domain: `0 mm` at `1e-6 mm` locality tolerance.++The negative locality fixture starts its declared envelope at `z=21`; it fails with `sculpt-outside-authorized-region`. An envelope reaching protected lower geometry fails before materialization.++## Preservation contracts++The bottom mounting interface retains its stable identity, `z=0` plane, 100 x 80 mm outer trim, and four circular inner trims. The hole pattern retains stable hole identities, axes, centers `(±20,±12)` mm, and 4 mm diameters. The upper cylindrical extent grows only inside the authorized crown domain. The lower outer footprint remains an exact 100 x 80 mm boundary.++This witness does not author AP242 PMI or an Assembly Interface object, so no PMI/interface round-trip claim is made. Persistence of those richer associations is classified `SURFX1`; their absence is not hidden behind a geometric-similarity claim.++## Surface representation++Public/product representations used by the flagship are `Plane` and `Cylinder`. Aetheris also has a non-rational `BSplineSurfaceWithKnots` product type with no weights. SURF-X0 adds an internal-only rational candidate normalization boundary to prove three behaviors: equal weights plus a bilinear planar net recover an exact `Plane`; equal-weight non-planar data recovers an exact non-rational `BSplineSurfaceWithKnots`; non-removable rationality produces `surf-surface-export-normalization-failed`.++STEP surface inventory after serialization and independent reimport:++| Artifact | Plane | Cylinder | Cone | Sphere | Torus | Non-rational B-spline | Other | Rational NURBS |+|---|---:|---:|---:|---:|---:|---:|---:|---:|+| Base | 6 | 4 | 0 | 0 | 0 | 0 | 0 | **0** |+| Sculpted | 10 | 4 | 0 | 0 | 0 | 0 | 0 | **0** |++**Rational NURBS product surfaces: ZERO.** `SculptStepExporter` scans the emitted STEP text and blocks the artifact if `RATIONAL_B_SPLINE_SURFACE` occurs.++## Export normalization++The flagship is analytic throughout: internal planes -> STEP `PLANE`; internal cylinders -> STEP `CYLINDRICAL_SURFACE`. No approximation occurs. Regression witnesses cover internal equal-weight rational bilinear planar data -> exact `Plane`, and equal-weight non-planar data -> exact non-rational `BSplineSurfaceWithKnots`. Non-removable rational data has no fallback route.++## Flagship witness++- Source: [`fixtures/Canonical/Sculpting/sculpted-housing.firmament`](../../fixtures/Canonical/Sculpting/sculpted-housing.firmament)+- Generation: `dotnet run --project Aetheris.CLI -c Release -- build fixtures/Canonical/Sculpting/sculpted-housing.firmament --output artifacts/local/surf-x0/surf-x0-sculpted-housing.step --json`+- Base bounds: `[-50,-40,0]` to `[50,40,20]` mm+- Final bounds: `[-50,-40,0]` to `[50,40,26]` mm+- Base topology: 1 body, 1 shell, 10 faces, 24 edges, 16 vertices, enclosed manifold+- Final topology: 1 body, 1 shell, 14 faces, 32 edges, 20 vertices, enclosed manifold+- Changed region: top/crown at `z >= 20 mm`+- Preserved: bottom mounting interface, four-hole placement/diameter pattern, lower footprint+- Base SHA-256: `0852fa0bf3b69be53c0f073c846eb872a42e702ed5f3324ce7d7a7730f6198db`+- Final SHA-256: `be05e0547b116b52f99277183843457f2e7957bf87c5f02cd46b7e53e8eb2274`+- Reimport: both artifacts report `enclosed-manifold`; final surface inventory is 10 planes and 4 cylinders+- Determinism: repeated final build produced identical STEP SHA-256++Manual artifacts are [`surf-x0-base-housing.step`](../../artifacts/local/surf-x0/surf-x0-base-housing.step) and [`surf-x0-sculpted-housing.step`](../../artifacts/local/surf-x0/surf-x0-sculpted-housing.step). Inspect the intended raised crown, unchanged bottom and footprint, unchanged hole placement, four planar transitions, and any unexpected dents or warts.++## Fresh-agent tests++One context-free agent used only `docs/public/` and `fixtures/Canonical/`; it did not inspect implementation source or edit files. All four tasks succeeded on the first attempt:++- A selected `Base`, authored a 6 mm `OffsetRegion`, bounded `HousingCrown`, and preserved the mounting interface, hole pattern, and footprint.+- B authored `CrownHigh` as a sibling derived from `Base`, leaving the existing 6 mm state unchanged and inspectable.+- C used `Region: [60mm, 40mm]`, semantic `MayModify`, and the conservative transition-containing envelope. It correctly distinguished the crown plateau from the larger G0 influence volume.+- D used `aetheris build`, reinspected with `aetheris analyze`, and required analytic/non-rational product surfaces with `RationalNURBS = 0`.++The agent built and inspected all five canonical sculpting fixtures with exit code 0. The 6 mm artifact reimported as an enclosed manifold with maximum Z 26 mm, 10 planes, 4 cylinders, and no B-splines; the 10 mm sibling had maximum Z 30 mm with the same rational-free surface families. The one documentation friction item—explicit `[width, depth]` ordering and crown-plateau versus transition-envelope distinction—was corrected in the public guide.++## Qualification++Focused qualification covers state identity, single predecessor, branching, failure atomicity, locality, preservation, BRep enclosure/orientation, self-intersection rejection, deterministic STEP, product-boundary scanning, rational normalization/blocking, STEP reimport, and CLI build/inspect/validate structured output. Repository qualification completed with a zero-warning Release solution build; all 3,118 discovered .NET tests; all 92 canonical fixtures; 82 client tests plus build/lint; 13 VS Code extension tests plus typecheck/build/package; deterministic STEP comparison; and a freshly installed CLI NuGet tool that rebuilt the flagship successfully. Forge/NativeAOT was not affected by this Surfacing/CLI lane.++## Bugs and friction++| Classification | Finding |+|---|---|+| DocsFix | Existing public support material had no sculpting/effect-system vocabulary; the guide, CLI note, support matrix, and canonical cookbook now agree. |+| SURFX1 | Persist authored AP242 PMI and Assembly Interface associations through `BodyState` and verify reimport parity. |+| SURFX1 | Admit safe features after a sculpted state and extend semantic correspondence beyond the bounded housing inventory. |+| SURFX1 | Generalize locality comparison beyond exact rectangular analytic construction, using layered semantic/analytic/topological/CIR evidence. |+| Deferred | Non-rational freeform export with explicit approximation tolerance/error is existing surfacing infrastructure but is not exercised by `OffsetRegion` X0. |++## Deferred surfacing++General NURBS authoring, general freeform patches, general Trim/Extend, G2 network blending, Loft, arbitrary 3D deformation, global surface replacement, arbitrary imported-face sculpting, and a timeline UI remain unsupported. Aetheris does not claim full general surfacing.diff --git a/fixtures/Canonical/README.md b/fixtures/Canonical/README.mdindex 9bc47f82..43b34fb2 100644--- a/fixtures/Canonical/README.md+++ b/fixtures/Canonical/README.md@@ -24,6 +24,7 @@ Everything in this directory is current authoring guidance. Examples progress fr| build a Paperclip Template | `Templates/paperclip.firmament` | `Record`, `Static`, `with`, `Template<PaperclipPolicy>`, circular `Sweep` || use a CNC policy | `Templates/cnc-dfm-policy.firmament` | Record defaults, `with`, `Template<Policy>`, enforcement || make Sheet Metal | `SheetMetal/l-bracket-with-hole.firmament` | material, bend, planar hole, formed/flat output |+| apply a bounded mathematical sculpt | `Sculpting/sculpted-housing.firmament` | immutable `BodyState`, `OffsetRegion`, locality, preservation contracts || make a data-driven Sheet Metal tab | `SheetMetal/profile-delta-tab-family.firmament` | Table, `with`, reusable `ProfileDelta Tab` || run FEA | `FEA/cantilever.firmament` | material, `Fixed`, `Force`, four result families || analyze imported STEP | `FEA/inline-step-cantilever.firmament` | repository-stable `inlineSTEP`, face selection, FEA |@@ -40,6 +41,7 @@ Everything in this directory is current authoring guidance. Examples progress fr| Basics, Primitives, Profiles, Features, Patterns, Templates | `Aetheris.Kernel.Firmament.Tests` || PMI and STEP round-trip | `Aetheris.CLI.Tests` and `Aetheris.Kernel.Firmament.Tests` || Sheet Metal | `Aetheris.SheetMetal.Tests` |+| Sculpting | `Aetheris.Modules.Tests` and `Aetheris.CLI.Tests` || FEA and Materials | `Aetheris.FEA.Tests` || Assembly | `Aetheris.Kernel.Firmament.Tests` assembly suite || Piping | `PipingX3Tests` |diff --git a/fixtures/Canonical/Sculpting/sculpt-base-housing.firmament b/fixtures/Canonical/Sculpting/sculpt-base-housing.firmamentnew file mode 100644index 00000000..9093013e--- /dev/null+++ b/fixtures/Canonical/Sculpting/sculpt-base-housing.firmament@@ -0,0 +1,29 @@+Model BaseHousing {+ Units: mm+ BodyState Base {+ Size: [100mm, 80mm, 20mm]+ Hole H1 { Center: [-20mm, -12mm]+ Diameter: 4mm }+ Hole H2 { Center: [20mm, -12mm]+ Diameter: 4mm }+ Hole H3 { Center: [20mm, 12mm]+ Diameter: 4mm }+ Hole H4 { Center: [-20mm, 12mm]+ Diameter: 4mm }+ }+ SculptState CrownRaised {+ Input: Base+ OffsetRegion {+ Target: HousingCrown+ Offset: 6mm+ Region: [60mm, 40mm]+ InfluenceEnvelope: [-50mm, -40mm, 20mm, 50mm, 40mm, 26mm]+ Boundary: G0+ }+ MayModify: [HousingCrown, CrownTransitionZone]+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ Output: Base+}+diff --git a/fixtures/Canonical/Sculpting/sculpt-branch-variants.firmament b/fixtures/Canonical/Sculpting/sculpt-branch-variants.firmamentnew file mode 100644index 00000000..07008dc5--- /dev/null+++ b/fixtures/Canonical/Sculpting/sculpt-branch-variants.firmament@@ -0,0 +1,46 @@++Model SculptBranchVariants {+ Units: mm++ BodyState Base {+ Size: [100mm, 80mm, 20mm]+ Hole H1 { Center: [-20mm, -12mm]+ Diameter: 4mm }+ Hole H2 { Center: [20mm, -12mm]+ Diameter: 4mm }+ Hole H3 { Center: [20mm, 12mm]+ Diameter: 4mm }+ Hole H4 { Center: [-20mm, 12mm]+ Diameter: 4mm }+ }++ SculptState CrownRaised {+ Input: Base+ OffsetRegion {+ Target: HousingCrown+ Offset: 6mm+ Region: [60mm, 40mm]+ InfluenceEnvelope: [-50mm, -40mm, 20mm, 50mm, 40mm, 26mm]+ Boundary: G0+ }+ MayModify: [HousingCrown, CrownTransitionZone]+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }++ SculptState CrownHigh {+ Input: Base+ OffsetRegion {+ Target: HousingCrown+ Offset: 10mm+ Region: [60mm, 40mm]+ InfluenceEnvelope: [-50mm, -40mm, 20mm, 50mm, 40mm, 30mm]+ Boundary: G0+ }+ MayModify: [HousingCrown, CrownTransitionZone]+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }++ Output: CrownHigh+}+diff --git a/fixtures/Canonical/Sculpting/sculpt-offset-region.firmament b/fixtures/Canonical/Sculpting/sculpt-offset-region.firmamentnew file mode 100644index 00000000..1643f1ef--- /dev/null+++ b/fixtures/Canonical/Sculpting/sculpt-offset-region.firmament@@ -0,0 +1,32 @@++Model SculptedHousing {+ Units: mm++ BodyState Base {+ Size: [100mm, 80mm, 20mm]+ Hole H1 { Center: [-20mm, -12mm]+ Diameter: 4mm }+ Hole H2 { Center: [20mm, -12mm]+ Diameter: 4mm }+ Hole H3 { Center: [20mm, 12mm]+ Diameter: 4mm }+ Hole H4 { Center: [-20mm, 12mm]+ Diameter: 4mm }+ }++ SculptState CrownRaised {+ Input: Base+ OffsetRegion {+ Target: HousingCrown+ Offset: 6mm+ Region: [60mm, 40mm]+ InfluenceEnvelope: [-50mm, -40mm, 20mm, 50mm, 40mm, 26mm]+ Boundary: G0+ }+ MayModify: [HousingCrown, CrownTransitionZone]+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }++ Output: CrownRaised+}+diff --git a/fixtures/Canonical/Sculpting/sculpt-preserve-interface.firmament b/fixtures/Canonical/Sculpting/sculpt-preserve-interface.firmamentnew file mode 100644index 00000000..4e316df6--- /dev/null+++ b/fixtures/Canonical/Sculpting/sculpt-preserve-interface.firmament@@ -0,0 +1,32 @@++Model SculptPreserveInterface {+ Units: mm++ BodyState Base {+ Size: [100mm, 80mm, 20mm]+ Hole H1 { Center: [-20mm, -12mm]+ Diameter: 4mm }+ Hole H2 { Center: [20mm, -12mm]+ Diameter: 4mm }+ Hole H3 { Center: [20mm, 12mm]+ Diameter: 4mm }+ Hole H4 { Center: [-20mm, 12mm]+ Diameter: 4mm }+ }++ SculptState CrownRaised {+ Input: Base+ OffsetRegion {+ Target: HousingCrown+ Offset: 6mm+ Region: [60mm, 40mm]+ InfluenceEnvelope: [-50mm, -40mm, 20mm, 50mm, 40mm, 26mm]+ Boundary: G0+ }+ MayModify: [HousingCrown, CrownTransitionZone]+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }++ Output: CrownRaised+}+diff --git a/fixtures/Canonical/Sculpting/sculpted-housing.firmament b/fixtures/Canonical/Sculpting/sculpted-housing.firmamentnew file mode 100644index 00000000..12ab76ab--- /dev/null+++ b/fixtures/Canonical/Sculpting/sculpted-housing.firmament@@ -0,0 +1,32 @@++Model ControllerCover {+ Units: mm++ BodyState Base {+ Size: [100mm, 80mm, 20mm]+ Hole H1 { Center: [-20mm, -12mm]+ Diameter: 4mm }+ Hole H2 { Center: [20mm, -12mm]+ Diameter: 4mm }+ Hole H3 { Center: [20mm, 12mm]+ Diameter: 4mm }+ Hole H4 { Center: [-20mm, 12mm]+ Diameter: 4mm }+ }++ SculptState CrownRaised {+ Input: Base+ OffsetRegion {+ Target: HousingCrown+ Offset: 6mm+ Region: [60mm, 40mm]+ InfluenceEnvelope: [-50mm, -40mm, 20mm, 50mm, 40mm, 26mm]+ Boundary: G0+ }+ MayModify: [HousingCrown, CrownTransitionZone]+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }++ Output: CrownRaised+}+diff --git a/fixtures/Canonical/qualification.json b/fixtures/Canonical/qualification.jsonindex 0afda076..856dffed 100644--- a/fixtures/Canonical/qualification.json+++ b/fixtures/Canonical/qualification.json@@ -6,6 +6,7 @@{ "path": "FEA", "operation": "fea-solve" },{ "path": "Materials", "operation": "fea-solve" },{ "path": "SheetMetal", "operation": "sheet-metal-flatten" },+ { "path": "Sculpting", "operation": "build-step" },{ "path": "Structural", "operation": "build-step" },{ "path": "Piping", "operation": "build-step" },{ "path": "Basics", "operation": "build-step" },diff --git a/fixtures/Invalid/Sculpting/sculpt-breaks-preserved-interface.firmament b/fixtures/Invalid/Sculpting/sculpt-breaks-preserved-interface.firmamentnew file mode 100644index 00000000..316cf9e5--- /dev/null+++ b/fixtures/Invalid/Sculpting/sculpt-breaks-preserved-interface.firmament@@ -0,0 +1,29 @@+Model BreakPreserved {+ Units: mm+ BodyState Base {+ Size: [100mm, 80mm, 20mm]+ Hole H1 { Center: [-20mm, -12mm]+ Diameter: 4mm }+ Hole H2 { Center: [20mm, -12mm]+ Diameter: 4mm }+ Hole H3 { Center: [20mm, 12mm]+ Diameter: 4mm }+ Hole H4 { Center: [-20mm, 12mm]+ Diameter: 4mm }+ }+ SculptState CrownRaised {+ Input: Base+ OffsetRegion {+ Target: HousingCrown+ Offset: 6mm+ Region: [60mm, 40mm]+ InfluenceEnvelope: [-50mm, -40mm, 20mm, 50mm, 40mm, 26mm]+ Boundary: G0+ }+ MayModify: [HousingCrown, CrownTransitionZone, BottomMountingInterface]+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ Output: CrownRaised+}+diff --git a/fixtures/Invalid/Sculpting/sculpt-disconnected-result.firmament b/fixtures/Invalid/Sculpting/sculpt-disconnected-result.firmamentnew file mode 100644index 00000000..54f52e80--- /dev/null+++ b/fixtures/Invalid/Sculpting/sculpt-disconnected-result.firmament@@ -0,0 +1,29 @@+Model Disconnected {+ Units: mm+ BodyState Base {+ Size: [100mm, 80mm, 20mm]+ Hole H1 { Center: [-20mm, -12mm]+ Diameter: 4mm }+ Hole H2 { Center: [20mm, -12mm]+ Diameter: 4mm }+ Hole H3 { Center: [20mm, 12mm]+ Diameter: 4mm }+ Hole H4 { Center: [-20mm, 12mm]+ Diameter: 4mm }+ }+ SculptState CrownRaised {+ Input: Base+ OffsetRegion {+ Target: HousingCrown+ Offset: 6mm+ Region: [120mm, 40mm]+ InfluenceEnvelope: [-50mm, -40mm, 20mm, 50mm, 40mm, 26mm]+ Boundary: G0+ }+ MayModify: [HousingCrown, CrownTransitionZone]+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ Output: CrownRaised+}+diff --git a/fixtures/Invalid/Sculpting/sculpt-outside-authorized-region.firmament b/fixtures/Invalid/Sculpting/sculpt-outside-authorized-region.firmamentnew file mode 100644index 00000000..ba372acf--- /dev/null+++ b/fixtures/Invalid/Sculpting/sculpt-outside-authorized-region.firmament@@ -0,0 +1,29 @@+Model OutsideAuthorized {+ Units: mm+ BodyState Base {+ Size: [100mm, 80mm, 20mm]+ Hole H1 { Center: [-20mm, -12mm]+ Diameter: 4mm }+ Hole H2 { Center: [20mm, -12mm]+ Diameter: 4mm }+ Hole H3 { Center: [20mm, 12mm]+ Diameter: 4mm }+ Hole H4 { Center: [-20mm, 12mm]+ Diameter: 4mm }+ }+ SculptState CrownRaised {+ Input: Base+ OffsetRegion {+ Target: HousingCrown+ Offset: 6mm+ Region: [60mm, 40mm]+ InfluenceEnvelope: [-50mm, -40mm, 21mm, 50mm, 40mm, 26mm]+ Boundary: G0+ }+ MayModify: [HousingCrown, CrownTransitionZone]+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ Output: CrownRaised+}+diff --git a/fixtures/Invalid/Sculpting/sculpt-self-intersection.firmament b/fixtures/Invalid/Sculpting/sculpt-self-intersection.firmamentnew file mode 100644index 00000000..454e8faa--- /dev/null+++ b/fixtures/Invalid/Sculpting/sculpt-self-intersection.firmament@@ -0,0 +1,29 @@+Model SelfIntersect {+ Units: mm+ BodyState Base {+ Size: [100mm, 80mm, 20mm]+ Hole H1 { Center: [-20mm, -12mm]+ Diameter: 4mm }+ Hole H2 { Center: [20mm, -12mm]+ Diameter: 4mm }+ Hole H3 { Center: [20mm, 12mm]+ Diameter: 4mm }+ Hole H4 { Center: [-20mm, 12mm]+ Diameter: 4mm }+ }+ SculptState CrownRaised {+ Input: Base+ OffsetRegion {+ Target: HousingCrown+ Offset: -25mm+ Region: [60mm, 40mm]+ InfluenceEnvelope: [-50mm, -40mm, 20mm, 50mm, 40mm, 26mm]+ Boundary: G0+ }+ MayModify: [HousingCrown, CrownTransitionZone]+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ Output: CrownRaised+}+