Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Support MeshState exports through the CLI

Yuechen Lid9e14691db68
diff --git a/Aetheris.CLI.Tests/GenericSculptingCliTests.cs b/Aetheris.CLI.Tests/GenericSculptingCliTests.cs
new file mode 100644
index 00000000..4eda0876
--- /dev/null
+++ b/Aetheris.CLI.Tests/GenericSculptingCliTests.cs
@@ -0,0 +1,107 @@
+using System.Text.Json;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class GenericSculptingCliTests
+{
+ [Theory]
+ [InlineData("box-cage", "stl")]
+ [InlineData("sphere-cage", "stl")]
+ [InlineData("box-cage", "glb")]
+ [InlineData("sphere-cage", "glb")]
+ public void RealMeshExportsCarryActualGeometryAndReplayableProvenance(string fixture, string format)
+ {
+ WithSource(fixture, s => s, (source, directory) =>
+ {
+ var output = Path.Combine(directory, "sculpt." + format); var stdout = new StringWriter(); var stderr = new StringWriter();
+ Assert.True(CliRunner.Run(["validate", source, "--json"], stdout, stderr) == 0, stdout + stderr.ToString());
+ using (var validation = JsonDocument.Parse(stdout.ToString()))
+ {
+ var v = validation.RootElement.GetProperty("firmamentV2Validation"); Assert.Equal("MeshBuilt", v.GetProperty("validationLevel").GetString()); Assert.False(v.GetProperty("stepExportAvailable").GetBoolean());
+ }
+ stdout.GetStringBuilder().Clear();
+ Assert.True(CliRunner.Run(["mesh", source, "--format", format, "--output", output, "--json"], stdout, stderr) == 0, stdout + stderr.ToString());
+ using var report = JsonDocument.Parse(stdout.ToString()); var root = report.RootElement; Assert.True(root.GetProperty("success").GetBoolean());
+ var triangleCount = root.GetProperty("triangles").GetInt32(); Assert.True(triangleCount > 12); Assert.False(root.GetProperty("stepExportAvailable").GetBoolean());
+ using var provenance = JsonDocument.Parse(File.ReadAllText(output + ".sculpt.json"));
+ var replay = Aetheris.Surfacing.MeshConstructionReplayer.Replay(provenance.RootElement.GetProperty("construction").GetRawText());
+ Assert.Equal(root.GetProperty("stateId").GetString(), replay.StateId);
+ if (format == "stl")
+ {
+ var bytes = File.ReadAllBytes(output); Assert.Equal(triangleCount, BitConverter.ToInt32(bytes, 80)); Assert.Equal(84 + 50 * triangleCount, bytes.Length);
+ var indices = new List<int>(); var positions = new List<Point3D>(); var ids = new Dictionary<Point3D, int>();
+ for (var i = 0; i < triangleCount; i++) for (var j = 0; j < 3; j++)
+ {
+ var at = 84 + 50 * i + 12 + 12 * j; var p = new Point3D(BitConverter.ToSingle(bytes, at), BitConverter.ToSingle(bytes, at + 4), BitConverter.ToSingle(bytes, at + 8));
+ if (!ids.TryGetValue(p, out var id)) { id = positions.Count; ids.Add(p, id); positions.Add(p); }
+ indices.Add(id);
+ }
+ var mesh = new TriangleMesh(positions, [], indices, new HashSet<(int, int)>(), "");
+ Assert.True(TriangleMeshValidator.TryValidateClosed(mesh, out var topology, out var failure), failure); Assert.True(topology.SignedVolume > 0);
+ }
+ else
+ {
+ var bytes = File.ReadAllBytes(output); Assert.Equal(0x46546C67u, BitConverter.ToUInt32(bytes, 0)); Assert.Equal(bytes.Length, BitConverter.ToInt32(bytes, 8));
+ using var gltf = JsonDocument.Parse(bytes.AsMemory(20, BitConverter.ToInt32(bytes, 12)));
+ Assert.Equal("2.0", gltf.RootElement.GetProperty("asset").GetProperty("version").GetString());
+ Assert.Contains(gltf.RootElement.GetProperty("accessors").EnumerateArray(), a => a.GetProperty("count").GetInt32() == triangleCount * 3);
+ var positionIndex = gltf.RootElement.GetProperty("meshes")[0].GetProperty("primitives")[0].GetProperty("attributes").GetProperty("POSITION").GetInt32();
+ var accessor = gltf.RootElement.GetProperty("accessors")[positionIndex];
+ var points = replay.Cage.Vertices.Select(v => v.Position).ToArray();
+ Assert.Equal(points.Min(p => p.X), accessor.GetProperty("min")[0].GetDouble(), 4);
+ Assert.Equal(points.Max(p => p.Z), accessor.GetProperty("max")[2].GetDouble(), 4);
+ }
+ });
+ }
+
+ [Theory]
+ [InlineData("preserve: [v1]", "preserve: [v0]", "mesh-preservation-failed")]
+ [InlineData("vertices: [v0]", "vertices: [typo]", "mesh-vertex-unresolved")]
+ [InlineData("levels: 2", "levels: 99", "mesh-subdivision-budget-invalid")]
+ [InlineData("maximumDeviation: 0.01mm", "maximumDeviation: 0.01mm; heigth: 3mm", "field-unknown")]
+ [InlineData("mode: Smooth", "mode: Jelly", "mesh-crease-mode-invalid")]
+ [InlineData("output: edited", "MeshState wide { input: edited; Scale { vertices: [All]; factor: [1e40, 1e40, 1e40]; origin: [0mm, 0mm, 0mm] } } output: wide", "mesh-export-precision-exhausted")]
+ [InlineData("output: edited", "MeshState wide { input: edited; Scale { vertices: [All]; factor: [1e8, 1e8, 1e8]; origin: [0mm, 0mm, 0mm] } } output: wide", "mesh-export-precision-budget-exceeded")]
+ [InlineData("Move {", "Relax {", "mesh-operation-cardinality")]
+ [InlineData("offset: [0mm, 0mm, 1mm]", "offset: [0mm, 0mm, 100mm]", "mesh-local-foldover")]
+ [InlineData("input: refined; preserve:", "input: exact; preserve:", "mesh-predecessor-unresolved")]
+ public void InvalidMeshIntentRejectsInValidateAndBuildWithoutArtifacts(string old, string replacement, string code)
+ {
+ WithSource("box-cage", s => s.Replace(old, replacement), (source, directory) =>
+ {
+ var output = Path.Combine(directory, "rejected.glb");
+ foreach (var args in new[] { new[] { "validate", source, "--json" }, new[] { "build", source, "--out", output, "--json" } })
+ {
+ var stdout = new StringWriter(); var stderr = new StringWriter(); Assert.True(CliRunner.Run(args, stdout, stderr) == 1, stdout + stderr.ToString());
+ using var json = JsonDocument.Parse(stdout.ToString()); var root = json.RootElement; if (args[0] == "validate") root = root.GetProperty("firmamentV2Validation");
+ Assert.Contains(root.GetProperty("diagnostics").EnumerateArray(), d => d.GetProperty("code").GetString()!.Contains(code, StringComparison.Ordinal) && d.GetProperty("line").GetInt32() > 1);
+ }
+ Assert.False(File.Exists(output)); Assert.False(File.Exists(output + ".sculpt.json"));
+ });
+ }
+
+ [Fact]
+ public void AValidMeshCannotBeExportedAsStepOrOverwriteItsSource()
+ {
+ WithSource("box-cage", s => s, (source, directory) =>
+ {
+ var original = File.ReadAllText(source);
+ foreach (var output in new[] { Path.Combine(directory, "invalid.step"), source })
+ {
+ var stdout = new StringWriter(); Assert.Equal(1, CliRunner.Run(["build", source, "--out", output, "--json"], stdout, new StringWriter()));
+ using var json = JsonDocument.Parse(stdout.ToString()); Assert.False(json.RootElement.GetProperty("success").GetBoolean());
+ }
+ Assert.Equal(original, File.ReadAllText(source)); Assert.False(File.Exists(Path.Combine(directory, "invalid.step")));
+ });
+ }
+
+ private static void WithSource(string fixture, Func<string, string> transform, Action<string, string> assertion)
+ {
+ var p = new DirectoryInfo(AppContext.BaseDirectory); while (p is not null && !File.Exists(Path.Combine(p.FullName, "Aetheris.slnx"))) p = p.Parent;
+ var directory = Path.Combine(p!.FullName, "artifacts/local/tests/generic-sculpting", Guid.NewGuid().ToString("N")); Directory.CreateDirectory(directory);
+ try { var source = Path.Combine(directory, "source.firmament"); File.WriteAllText(source, transform(File.ReadAllText(Path.Combine(p.FullName, "fixtures/Regression/GenericSculpting/" + fixture + ".firmament")))); assertion(source, directory); }
+ finally { Directory.Delete(directory, true); }
+ }
+}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index aa873c6a..9009b420 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -135,7 +135,7 @@ public static class CliRunner
int? RigidRootCount = null);
private const string TopLevelUsage = "Usage: aetheris <command> [options]";
private const string BuildUsage = "Usage: aetheris build <file.firmament|file.firmasm> [--output <path>] [--json]";
- private const string MeshUsage = "Usage: aetheris mesh <file.firmament|file.firmfixture|file.firmasm|file.step> [--format stl|obj|assembly-json] [--output <path>] [--debug-ir <path>] [--json]";
+ private const string MeshUsage = "Usage: aetheris mesh <file.firmament|file.firmfixture|file.firmasm|file.step> [--format stl|obj|glb|assembly-json] [--output <path>] [--debug-ir <path>] [--json] (glb: MeshState sources)";
private const string ValidateUsage = "Usage: aetheris validate <file.firmament|file.firmfixture> [--forge-pack <path>] [--parse-only] [--explain] [--shadow [--ast]] [--json]";
private const string InspectProfileUsage = "Usage: aetheris inspect-profile <file.firmament> [--json]";
private const string InspectSpansUsage = "Usage: aetheris inspect-spans <file.firmament> --json";
@@ -326,6 +326,7 @@ public static class CliRunner
else if (SculptingAuthoring.IsSculptingSource(sourceText))
{
var sculpt = SculptingAuthoring.Compile(sourceText);
+ if (sculpt.OutputMesh is not null) return MeshSculptCommand.Write(sculpt, stepPath, null, "step", "verify", json, stdout, stderr);
var sculptExport = sculpt.OutputState is null ? null : SculptStepExporter.Export(sculpt.OutputState, sculpt.ModelName);
if (!sculpt.IsSuccess || sculptExport?.IsSuccess != true || sculptExport.Step is null)
{
@@ -808,6 +809,8 @@ public static class CliRunner
private static int RunSculptingBuild(string sourcePath, string? outPath, bool json, TextWriter stdout, TextWriter stderr)
{
var compile = SculptingAuthoring.CompileFile(sourcePath);
+ if (compile.OutputMesh is not null)
+ return MeshSculptCommand.Write(compile, sourcePath, outPath, Path.GetExtension(outPath ?? ".step").TrimStart('.').ToLowerInvariant(), "build", json, stdout, stderr);
var sourceText=File.ReadAllText(sourcePath);
var presented=SculptingAuthoring.KernelDiagnostics(compile).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,sourceText)).ToArray();
if (!compile.IsSuccess || compile.OutputState is null)
@@ -903,7 +906,12 @@ public static class CliRunner
})
},
realizedHousingEvidence = state.Construction is {} housing ? new { housing.Width, housing.Depth, housing.BaseHeight, housing.CrownWidth, housing.CrownDepth, housing.CrownOffset, housing.FinalHeight } : null,
- semanticInventory = state.SemanticInventory.Values, surfacePatches = state.SurfacePatches, blendJudgment = state.BlendJudgment, hasDelta = state.Delta is not null
+ semanticInventory = state.SemanticInventory.Values, geometryAssociations = state.GeometryAssociations,
+ faceBoundaries = state.Construction is null ? state.Body.Topology.Faces.Select(f => new { handle = "Face" + f.Id.Value,
+ loops = f.LoopIds.Select(l => state.Body.GetCoedgeIds(l).Select(state.Body.Topology.GetCoedge).Select(c => {
+ var edge = state.Body.Topology.GetEdge(c.EdgeId); state.Body.TryGetVertexPoint(edge.StartVertexId, out var start); state.Body.TryGetVertexPoint(edge.EndVertexId, out var end);
+ return new { handle = "Edge" + c.EdgeId.Value, start, end }; }).ToArray()).ToArray() }).ToArray() : null,
+ surfacePatches = state.SurfacePatches, blendJudgment = state.BlendJudgment, hasDelta = state.Delta is not null
};
private static int RunSheetMetalAuthoredBuild(string sourcePath, string? outPath, bool json, TextWriter stdout, TextWriter stderr)
@@ -1335,6 +1343,19 @@ Model CanonicalPanel {
}
catch (InvalidOperationException error) { return WriteMeshFailure([error.Message], json, input, stdout, stderr); }
}
+ string? sculptStep = null;
+ if (File.Exists(input) && Path.GetExtension(input).Equals(".firmament", StringComparison.OrdinalIgnoreCase) && SculptingAuthoring.IsSculptingSource(File.ReadAllText(input)))
+ {
+ var sculpt = SculptingAuthoring.CompileFile(input);
+ if (sculpt.OutputMesh is not null || !sculpt.IsSuccess)
+ {
+ if (debugIr is not null) sculpt = sculpt with { IsSuccess = false, Diagnostics = [..sculpt.Diagnostics, new("mesh-sculpt-debug-ir-unsupported", "Use inspect --json for cage identities and provenance; SurfaceMeshIR debug output belongs to BRep tessellation.")] };
+ return MeshSculptCommand.Write(sculpt, input, output, format.ToLowerInvariant(), "mesh", json, stdout, stderr);
+ }
+ var exact = SculptStepExporter.Export(sculpt.OutputState!, sculpt.ModelName);
+ if (!exact.IsSuccess) return WriteMeshFailure(exact.Diagnostics.Select(d => d.Code + ": " + d.Message), json, input, stdout, stderr);
+ sculptStep = exact.Step;
+ }
if (!string.Equals(format, "stl", StringComparison.OrdinalIgnoreCase) && !string.Equals(format, "obj", StringComparison.OrdinalIgnoreCase))
{
stderr.WriteLine("Mesh supports binary STL, topology-preserving OBJ, and assembly-json definition/occurrence meshes.");
@@ -1342,7 +1363,8 @@ Model CanonicalPanel {
}
var fullInput = Path.GetFullPath(input);
string stepText;
- if (string.Equals(Path.GetExtension(fullInput), ".firmament", StringComparison.OrdinalIgnoreCase) || string.Equals(Path.GetExtension(fullInput), ".firmfixture", StringComparison.OrdinalIgnoreCase))
+ if (sculptStep is not null) stepText = sculptStep;
+ else if (string.Equals(Path.GetExtension(fullInput), ".firmament", StringComparison.OrdinalIgnoreCase) || string.Equals(Path.GetExtension(fullInput), ".firmfixture", StringComparison.OrdinalIgnoreCase))
{
var build = FirmamentBuildAndExport.Run(fullInput);
if (!build.IsSuccess) return WriteMeshFailure(build.Diagnostics.Select(d => d.Message), json, fullInput, stdout, stderr);
@@ -1499,9 +1521,9 @@ Model CanonicalPanel {
var sculpt = SculptingAuthoring.Compile(source,fullPath);
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 = SculptingAuthoring.KernelDiagnostics(sculpt).Select(d=>FirmamentBuildAdmissionValidation.Present(d,fullPath,source)).ToArray() };
+ outputState = sculpt.OutputState?.StateId, meshStates = sculpt.MeshStates, outputMesh = sculpt.OutputMesh, timingsMilliseconds = sculpt.Timings, diagnostics = SculptingAuthoring.KernelDiagnostics(sculpt).Select(d=>FirmamentBuildAdmissionValidation.Present(d,fullPath,source)).ToArray() };
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 if (sculpt.IsSuccess) { stdout.WriteLine($"Sculpting model {sculpt.ModelName}: output {sculpt.OutputState?.AuthoredName ?? sculpt.OutputMesh!.Name} ({sculpt.OutputState?.StateId.Value ?? sculpt.OutputMesh!.StateId})"); foreach (var state in sculpt.States.Values) stdout.WriteLine($"State {state.AuthoredName}: {state.StateId} <- {state.PredecessorStateId?.Value ?? "<initial>"}"); }
else WriteFrontendDiagnostics(SculptingAuthoring.KernelDiagnostics(sculpt).Select(d=>FirmamentBuildAdmissionValidation.Present(d,fullPath,source)),stderr);
return sculpt.IsSuccess ? 0 : 1;
}
@@ -1859,6 +1881,7 @@ Model CanonicalPanel {
if (SculptingAuthoring.IsSculptingSource(viewSource))
{
var sculpt = SculptingAuthoring.Compile(viewSource); var export = sculpt.OutputState is null ? null : SculptStepExporter.Export(sculpt.OutputState, sculpt.ModelName);
+ if (sculpt.OutputMesh is not null) return MeshSculptCommand.Write(sculpt, fullInput, null, "step", "view", json, stdout, stderr);
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();
@@ -2491,7 +2514,7 @@ Model CanonicalPanel {
{
if (parseOnly) return RejectParseOnly("Sculpting");
var sculpt = SculptingAuthoring.Compile(validationSource,Path.GetFullPath(sourcePath));
- var payload = new { source = sourcePath, status = sculpt.IsSuccess ? "valid" : "invalid", domain = "Sculpting", validationLevel=sculpt.IsSuccess?"Built":"BuildRejected", parserRoute="UnifiedSculpting", summary = new { fatalDiagnosticCount = sculpt.Diagnostics.Count, warningDiagnosticCount = 0, states = sculpt.States.Count }, diagnostics = SculptingAuthoring.KernelDiagnostics(sculpt).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,authoredValidationSource)).ToArray() };
+ var payload = new { source = sourcePath, status = sculpt.IsSuccess ? "valid" : "invalid", domain = "Sculpting", validationLevel=sculpt.IsSuccess?(sculpt.OutputMesh is null?"Built":"MeshBuilt"):"BuildRejected", artifactKind=sculpt.OutputMesh?.ArtifactKind ?? "BRep", stepExportAvailable=sculpt.OutputMesh is null, parserRoute="UnifiedSculpting", summary = new { fatalDiagnosticCount = sculpt.Diagnostics.Count, warningDiagnosticCount = 0, states = sculpt.States.Count + sculpt.MeshStates.Count }, diagnostics = SculptingAuthoring.KernelDiagnostics(sculpt).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,authoredValidationSource)).ToArray() };
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)");WriteFrontendDiagnostics(payload.diagnostics,stderr);}
return sculpt.IsSuccess ? 0 : 1;
diff --git a/Aetheris.CLI/MeshSculptCommand.cs b/Aetheris.CLI/MeshSculptCommand.cs
new file mode 100644
index 00000000..c715846c
--- /dev/null
+++ b/Aetheris.CLI/MeshSculptCommand.cs
@@ -0,0 +1,77 @@
+using System.Text.Json;
+using Aetheris.Surfacing;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.CLI;
+
+internal static class MeshSculptCommand
+{
+ internal static int Write(SculptingCompileResult compile, string source, string? output, string format, string command, bool json, TextWriter stdout, TextWriter stderr)
+ {
+ var diagnostics = compile.Diagnostics.ToList();
+ if (format is not ("stl" or "glb")) diagnostics.Add(new("sculpt-mesh-export-format-unsupported", "MeshState outputs are mesh-only. Use mesh --format stl|glb, or build --out <file.stl|file.glb>; STEP export cannot retain this representation.", compile.OutputMesh?.Name));
+ if (!compile.IsSuccess || compile.OutputMesh is null || diagnostics.Count != 0) return Failure();
+ var state = compile.OutputMesh;
+ var path = Path.GetFullPath(output ?? Path.Combine("artifacts", "local", "mesh-sculpt", Path.GetFileNameWithoutExtension(source) + "." + format));
+ var sidecar = path + ".sculpt.json";
+ if (path.Equals(Path.GetFullPath(source), StringComparison.OrdinalIgnoreCase) || sidecar.Equals(Path.GetFullPath(source), StringComparison.OrdinalIgnoreCase) || !Path.GetExtension(path).Equals("." + format, StringComparison.OrdinalIgnoreCase))
+ { diagnostics.Add(new("mesh-export-path-invalid", "Output must differ from source and have the selected .stl or .glb extension.")); return Failure(); }
+ var prepared = SubdivisionSculptor.PrepareExport(state.Cage, state.Construction.MaximumDeviationMm);
+ var mesh = prepared.NativeMesh;
+ var topology = prepared.Topology;
+ var maximumFloatQuantizationMm = prepared.MaximumFloatQuantizationMm;
+ // Serialize/validate all payloads before creating any output.
+ var recipe = MeshConstructionReplayer.Serialize(state.Construction);
+ using var packet = JsonDocument.Parse(recipe);
+ var metadata = JsonSerializer.Serialize(new
+ {
+ schema = SubdivisionSculptor.Schema,
+ state.StateId,
+ state.PredecessorStateId,
+ state.SourceBodyStateId,
+ state.ArtifactKind,
+ state.StepExportAvailable,
+ state.SelfIntersectionStatus,
+ state.ConversionDeviationMm,
+ state.ConversionEvidence,
+ maximumFloatQuantizationMm,
+ cage = state.Cage,
+ edges = state.Edges,
+ construction = packet.RootElement,
+ topology
+ }, CliRunner.JsonOptions);
+ byte[]? glb = format == "glb" ? MeshSculptExport.Glb(state) : null;
+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);
+ if (glb is not null) File.WriteAllBytes(path, glb); else BinaryStlExporter.Export(path, mesh);
+ File.WriteAllText(sidecar, metadata);
+ var report = new
+ {
+ command,
+ success = true,
+ output = path,
+ format,
+ domain = "Sculpting",
+ artifactKind = state.ArtifactKind,
+ stepExportAvailable = false,
+ state.StateId,
+ state.SourceBodyStateId,
+ state.SelfIntersectionStatus,
+ maximumFloatQuantizationMm,
+ vertices = mesh.Positions.Count,
+ triangles = mesh.TriangleIndices.Count / 3,
+ topology,
+ provenance = sidecar
+ };
+ if (json) stdout.WriteLine(JsonSerializer.Serialize(report, CliRunner.JsonOptions)); else stdout.WriteLine($"Built {state.Name}: {path}; {report.triangles} triangles; mesh-only; global self-intersection not certified.");
+ return 0;
+
+ int Failure()
+ {
+ var presented = SculptingAuthoring.KernelDiagnostics(compile with { Diagnostics = diagnostics }).Select(d => FirmamentBuildAdmissionValidation.Present(d, source, File.ReadAllText(source))).ToArray();
+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command, success = false, domain = "Sculpting", diagnostics = presented }, CliRunner.JsonOptions));
+ else foreach (var d in presented) stderr.WriteLine($"{d.SourceFile}:{d.Line}:{d.Column}: {d.Severity} {d.Code}: {d.Message}");
+ return 1;
+ }
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
index 3dd02e35..c596f505 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
@@ -64,7 +64,7 @@ public static class FirmamentLanguageAnalysisService
var assembly = new AssemblyM0Parser().Parse(source, document);
return new(document, revision, tokens, assembly.Diagnostics.Select(d => new FirmamentLanguageDiagnostic(d.Severity == AssemblyDiagnosticSeverity.Error ? "error" : "information", d.Code, d.Message, 0, 0)).ToArray());
}
- if(Syntax.FirmamentSyntaxTraversal.Declarations(documentSyntax).FirstOrDefault(d=>d.Type.Name.Text is "PlasticShell" or "BodyState" or "SculptState"
+ if(Syntax.FirmamentSyntaxTraversal.Declarations(documentSyntax).FirstOrDefault(d=>d.Type.Name.Text is "PlasticShell" or "BodyState" or "SculptState" or "MeshState"
|| d.Type.Name.Text=="LinearElastic" && d.Modifiers.Any(m=>m.Name.Text is "Analysis" or "analysis")) is {} externalDomain)
{
// Editor analysis never materializes sculpt states or runs engineering.
diff --git a/Aetheris.Kernel.Firmament/Surfacing/EngineeringBodyStateConstruction.cs b/Aetheris.Kernel.Firmament/Surfacing/EngineeringBodyStateConstruction.cs
index 3d008578..6d235513 100644
--- a/Aetheris.Kernel.Firmament/Surfacing/EngineeringBodyStateConstruction.cs
+++ b/Aetheris.Kernel.Firmament/Surfacing/EngineeringBodyStateConstruction.cs
@@ -12,7 +12,7 @@ namespace Aetheris.Surfacing;
internal static class EngineeringBodyStateConstruction
{
internal static bool IsStateDeclaration(StatementSyntax statement) => statement is DeclarationSyntax d
- && d.Type.Name.Text is "BodyState" or "SculptState" or "SurfacePatch" or "SectionChain";
+ && d.Type.Name.Text is "BodyState" or "SculptState" or "MeshState" or "SurfacePatch" or "SectionChain";
internal static SculptResult Realize(EngineeringSourceConstruction recipe)
{
@@ -79,6 +79,12 @@ internal static class EngineeringBodyStateConstruction
[bodyId] = new(bodyId, SculptEntityKind.Body, id.Value, "Admitted engineering body; no prototype regions inferred.")
};
var associations = new List<PersistentGeometryAssociation>();
+ foreach (var face in realized.Topology.Faces)
+ {
+ var handle = "Face" + face.Id.Value;
+ if (inventory.TryAdd(handle, new(handle, SculptEntityKind.Region, id.Value + ":" + handle, "Current body face handle; inspect EdgeN boundary identities before grafting.")))
+ associations.Add(new(handle, PersistentAssociationState.Preserved, [face.Id.Value], "Exact topology identity; no proximity lookup."));
+ }
foreach (var group in export.RuntimeCorrespondence?.Descendants.GroupBy(d => d.SourceStableId) ?? [])
{
var faces = group.Where(d => d.Face is not null).Select(d => d.Face!.Value.Value).Distinct().Order().ToArray();
@@ -96,6 +102,7 @@ internal static class EngineeringBodyStateConstruction
var authority = new ConstructionState(ConstructionState.CurrentSchemaId, ConstructionState.CurrentSchemaVersion, recipe, []);
return new(true, new(id, null, bodyId, recipe.BaseId, realized, null, inventory, null, evidence,
associations, ConstructionAuthority: authority, RealizedStepText: export.StepText)
- { RealizedStepProductName = export.DocumentName ?? model.Name?.Text }, null, evidence, []);
+ { RealizedStepProductName = export.DocumentName ?? model.Name?.Text,
+ HasImportedEngineeringSource = FirmamentV2Parser.MechanicalDeclarations(model.Body?.Statements ?? []).Any(d => d.Type.Name.Text == "InlineStep") }, null, evidence, []);
}
}
diff --git a/Aetheris.Kernel.Firmament/Surfacing/MeshConstructionReplayer.cs b/Aetheris.Kernel.Firmament/Surfacing/MeshConstructionReplayer.cs
new file mode 100644
index 00000000..40df8d34
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Surfacing/MeshConstructionReplayer.cs
@@ -0,0 +1,31 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Aetheris.Surfacing;
+
+/// <summary>Reuse exact construction replay, then execute the typed cage program.</summary>
+public static class MeshConstructionReplayer
+{
+ private sealed record SavedMesh(string Schema, string SourceJson, string Cage, int Segments, double MaximumDeviationMm, IReadOnlyList<MeshSculptOperation> Operations);
+ private static readonly JsonSerializerOptions Options = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow };
+ public static string Serialize(MeshConstruction construction)
+ {
+ var source = ConstructionStateSerializer.Serialize(construction.Source);
+ if (!source.IsSuccess) throw new InvalidOperationException(string.Join(";", source.Diagnostics.Select(d => d.Message)));
+ return JsonSerializer.Serialize(new SavedMesh(construction.Schema, source.Json!, construction.Cage, construction.Segments, construction.MaximumDeviationMm, construction.Operations), Options);
+ }
+ public static MeshSculptState Replay(string json, string name = "Replayed")
+ {
+ var saved = JsonSerializer.Deserialize<SavedMesh>(json, Options) ?? throw new InvalidOperationException("mesh-replay-invalid: Empty mesh recipe.");
+ if (saved.Schema != SubdivisionSculptor.Schema || saved.Operations is null || saved.Operations.Count > 64 || saved.Operations.Any(o => o is null))
+ throw new InvalidOperationException("mesh-replay-version-unsupported: Unknown schema or exceeded operation budget.");
+ var source = ConstructionStateSerializer.Deserialize(saved.SourceJson);
+ if (!source.IsSuccess) throw new InvalidOperationException(string.Join(";", source.Diagnostics.Select(d => d.Message)));
+ var replay = ConstructionStateReplayer.Replay(source.ConstructionState!);
+ if (!replay.IsSuccess || replay.OutputState is null) throw new InvalidOperationException(string.Join(";", replay.Diagnostics.Select(d => d.Message)));
+ var state = SubdivisionSculptor.Convert(replay.OutputState, name, saved.Cage, saved.Segments, saved.MaximumDeviationMm);
+ foreach (var operation in saved.Operations) state = SubdivisionSculptor.Apply(state, name, operation);
+ SubdivisionSculptor.PrepareExport(state.Cage, state.Construction.MaximumDeviationMm);
+ return state;
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Surfacing/MeshSculptExport.cs b/Aetheris.Kernel.Firmament/Surfacing/MeshSculptExport.cs
new file mode 100644
index 00000000..22badc7d
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Surfacing/MeshSculptExport.cs
@@ -0,0 +1,24 @@
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Firmament.Assembly;
+
+namespace Aetheris.Surfacing;
+
+public static class MeshSculptExport
+{
+ public static byte[] Glb(MeshSculptState state)
+ {
+ var mesh = SubdivisionSculptor.PrepareExport(state.Cage, state.Construction.MaximumDeviationMm).NativeMesh;
+ // Flat per-triangle render normals retain every crease. Render vertex
+ // duplication is a projection; the authoritative cage stays welded.
+ var positions = new List<double>(); var normals = new List<double>();
+ for (var i = 0; i < mesh.TriangleIndices.Count; i += 3)
+ {
+ var a = mesh.Positions[mesh.TriangleIndices[i]]; var b = mesh.Positions[mesh.TriangleIndices[i + 1]]; var c = mesh.Positions[mesh.TriangleIndices[i + 2]];
+ var n = (b - a).Cross(c - a); n /= n.Length;
+ foreach (var p in new[] { a, b, c }) { positions.AddRange([p.X, p.Y, p.Z]); normals.AddRange([n.X, n.Y, n.Z]); }
+ }
+ var definition = new AssemblyDisplayMeshDefinition("mesh", state.StateId, positions.ToArray(), normals.ToArray(), Enumerable.Range(0, positions.Count / 3).ToArray(), "SubdivisionCage");
+ var occurrence = new AssemblyDisplayMeshOccurrence(state.Name, state.Name, null, "mesh", [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+ return AssemblyGlbExporter.Serialize(new("aetheris.assembly.display-mesh.v1", state.Name, "mm", [definition], [occurrence]));
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Surfacing/MeshSculptingAuthoring.cs b/Aetheris.Kernel.Firmament/Surfacing/MeshSculptingAuthoring.cs
new file mode 100644
index 00000000..16dd5c93
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Surfacing/MeshSculptingAuthoring.cs
@@ -0,0 +1,69 @@
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using Aetheris.Kernel.Core.Math;
+using Block = Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxScope;
+
+namespace Aetheris.Surfacing;
+
+public static partial class SculptingAuthoring
+{
+ private static Dictionary<string, MeshSculptState> BindMeshStates(Block model, IReadOnlyDictionary<string, BodyState> bodies, List<SculptDiagnostic> diagnostics)
+ {
+ var states = new Dictionary<string, MeshSculptState>(StringComparer.Ordinal);
+ var blocks = Blocks(model, "MeshState");
+ if (blocks.Count > 64) { diagnostics.Add(new("mesh-state-budget-exceeded", "At most 64 mesh states are admitted per model.")); return states; }
+ foreach (var block in blocks)
+ {
+ var inputName = block.Word("Input"); var kind = block.Word("Cage");
+ var subdivide = Single(block, "Subdivide", diagnostics); var move = Single(block, "Move", diagnostics);
+ var scale = Single(block, "Scale", diagnostics); var crease = Single(block, "Crease", diagnostics);
+ try
+ {
+ if (bodies.ContainsKey(block.Name) || states.ContainsKey(block.Name)) throw new InvalidOperationException("mesh-state-duplicate: State names must be unique across exact and mesh states.");
+ MeshSculptState result;
+ var operations = new[] { subdivide, move, scale, crease }.Count(b => b is not null);
+ if (kind is not null)
+ {
+ if (operations != 0) throw new InvalidOperationException("mesh-conversion-operation-mixed: Conversion is one explicit state; put edits in successor states.");
+ if (inputName is null || !bodies.TryGetValue(inputName, out var body)) throw new InvalidOperationException("mesh-source-unresolved: Conversion input must name a previously admitted exact BodyState or SculptState.");
+ var segments = Integer(block, "Segments") ?? (kind == "Box" ? 1 : 4);
+ var deviation = Length(block, "MaximumDeviation", diagnostics);
+ if (deviation is null) continue;
+ result = SubdivisionSculptor.Convert(body, block.Name, kind, segments, deviation.Value);
+ }
+ else
+ {
+ if (operations != 1) throw new InvalidOperationException("mesh-operation-cardinality: A mesh successor requires exactly one Subdivide, Move, Scale or Crease operation.");
+ if (inputName is null || !states.TryGetValue(inputName, out var input)) throw new InvalidOperationException("mesh-predecessor-unresolved: Mesh edits require one previously admitted MeshState.");
+ MeshSculptOperation operation;
+ if (subdivide is not null) operation = new SubdivideCage(block.Name, Integer(subdivide, "Levels") ?? 0);
+ else if (move is not null)
+ {
+ var offset = Vector(move, "Offset", 3, diagnostics); var vertices = List(move, "Vertices"); if (offset is null) continue;
+ operation = new MoveCageVertices(block.Name, vertices, new(offset[0], offset[1], offset[2]));
+ }
+ else if (scale is not null)
+ {
+ var factor = NumberVector(scale, "Factor", 3, diagnostics); var origin = Vector(scale, "Origin", 3, diagnostics); var vertices = List(scale, "Vertices");
+ if (factor is null || origin is null) continue;
+ operation = new ScaleCageVertices(block.Name, vertices, new(factor[0], factor[1], factor[2]), new(origin[0], origin[1], origin[2]));
+ }
+ else
+ {
+ var mode = crease!.Word("Mode"); var edges = List(crease, "Edges");
+ if (mode is not ("Sharp" or "Smooth")) throw new InvalidOperationException("mesh-crease-mode-invalid: Crease mode must be Sharp or Smooth.");
+ operation = new CreaseCageEdges(block.Name, edges, mode == "Sharp");
+ }
+ operation = operation with { Preserve = List(block, "Preserve") };
+ result = SubdivisionSculptor.Apply(input, block.Name, operation);
+ }
+ states.Add(block.Name, result);
+ }
+ catch (InvalidOperationException error)
+ {
+ var split = error.Message.IndexOf(':');
+ diagnostics.Add(new(split > 0 ? error.Message[..split] : "mesh-sculpt-failed", error.Message, block.Name));
+ }
+ }
+ return states;
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Surfacing/SculptingAuthoring.cs b/Aetheris.Kernel.Firmament/Surfacing/SculptingAuthoring.cs
index e9430509..dba22a33 100644
--- a/Aetheris.Kernel.Firmament/Surfacing/SculptingAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/Surfacing/SculptingAuthoring.cs
@@ -8,11 +8,11 @@ using Aetheris.Kernel.Core.Math;
namespace Aetheris.Surfacing;
-public static class SculptingAuthoring
+public static partial class SculptingAuthoring
{
- public static bool IsSculptingSource(string source) => (source.Contains("BodyState", StringComparison.Ordinal) || source.Contains("SculptState", StringComparison.Ordinal))
- && FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document).Any(d => d.Type.Name.Text is "BodyState" or "SculptState");
- public static SculptingCompileResult CompileFile(string path) => Compile(File.ReadAllText(path), path);
+ public static bool IsSculptingSource(string source) => (source.Contains("BodyState", StringComparison.Ordinal) || source.Contains("SculptState", StringComparison.Ordinal) || source.Contains("MeshState", StringComparison.Ordinal))
+ && FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document).Any(d => d.Type.Name.Text is "BodyState" or "SculptState" or "MeshState");
+ public static SculptingCompileResult CompileFile(string path) => Compile(File.ReadAllText(path), Path.GetFullPath(path));
public static IReadOnlyList<Aetheris.Kernel.Core.Diagnostics.KernelDiagnostic> KernelDiagnostics(SculptingCompileResult result) =>
result.Diagnostics.Select(d=>new Aetheris.Kernel.Core.Diagnostics.KernelDiagnostic(
@@ -172,7 +172,7 @@ public static class SculptingAuthoring
var replaceOperation = new ReplaceRegionOperation(block.Name + ".ReplaceRegion", replaceTarget, patch, replaceMayModify,
new(replaceEnvelope[0], replaceEnvelope[1], replaceEnvelope[2], replaceEnvelope[3], replaceEnvelope[4], replaceEnvelope[5]), replaceContracts, replaceRequirements);
var replaceApplyClock = Stopwatch.StartNew(); var replaceResult = ReplaceRegionSculptor.Apply(input, block.Name, replaceOperation); replaceApplyClock.Stop(); verification += replaceApplyClock.Elapsed;
- if (!replaceResult.IsSuccess || replaceResult.OutputState is null) diagnostics.AddRange(replaceResult.Diagnostics);
+ if (!replaceResult.IsSuccess || replaceResult.OutputState is null) diagnostics.AddRange(replaceResult.Diagnostics.Select(d => d with { Entity = block.Name }));
else if (!states.TryAdd(block.Name, replaceResult.OutputState)) diagnostics.Add(new("sculpt-state-duplicate", $"State '{block.Name}' is declared more than once."));
continue;
}
@@ -220,12 +220,24 @@ public static class SculptingAuthoring
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 meshStates = BindMeshStates(model, states, diagnostics);
var outputName = ScalarText(model, "Output");
BodyState? output = null;
- if (outputName is null || !states.TryGetValue(outputName, out output))
+ MeshSculptState? outputMesh = null;
+ if (outputName is not null) meshStates.TryGetValue(outputName, out outputMesh);
+ if (outputMesh is not null)
+ {
+ try { SubdivisionSculptor.PrepareExport(outputMesh.Cage, outputMesh.Construction.MaximumDeviationMm); }
+ catch (InvalidOperationException error)
+ {
+ var separator = error.Message.IndexOf(':');
+ diagnostics.Add(new(separator > 0 ? error.Message[..separator] : "mesh-export-preflight-failed", error.Message, outputMesh.Name));
+ }
+ }
+ if ((outputName is null || !states.TryGetValue(outputName, out output)) && outputMesh is null)
{
var failedDeclaration = models[0].Body?.Statements.OfType<DeclarationSyntax>()
- .Any(d => d.Type.Name.Text is "BodyState" or "SculptState" && d.Name?.Text == outputName) == true;
+ .Any(d => d.Type.Name.Text is "BodyState" or "SculptState" or "MeshState" && d.Name?.Text == outputName) == true;
if (outputName is null || !failedDeclaration || diagnostics.Count == 0)
diagnostics.Add(new("sculpt-output-unresolved", "Output must name one accepted BodyState or SculptState."));
}
@@ -241,8 +253,9 @@ public static class SculptingAuthoring
{ LocationNote = "Location identifies the enclosing declaration; the domain operation supplied no finer original-source span." } };
}
total.Stop();
- return new(diagnostics.Count == 0 && output is not null, model.Name, output, states, diagnostics,
- new(baseClock.Elapsed.TotalMilliseconds, opConstruction.TotalMilliseconds, verification.TotalMilliseconds, brep.TotalMilliseconds, 0d));
+ return new(diagnostics.Count == 0 && (output is not null || outputMesh is not null), model.Name, output, states, diagnostics,
+ new(baseClock.Elapsed.TotalMilliseconds, opConstruction.TotalMilliseconds, verification.TotalMilliseconds, brep.TotalMilliseconds, 0d))
+ { OutputMesh = outputMesh, MeshStates = meshStates };
SculptingCompileResult Fail(string name, string code, string message) => new(false, name, null, states, [new(code, message)], new(0, 0, 0, 0, 0));
}
diff --git a/Aetheris.Modules.Tests/GenericSculptingTests.cs b/Aetheris.Modules.Tests/GenericSculptingTests.cs
new file mode 100644
index 00000000..c48f4a75
--- /dev/null
+++ b/Aetheris.Modules.Tests/GenericSculptingTests.cs
@@ -0,0 +1,135 @@
+using Aetheris.Surfacing;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Step242;
+using Xunit;
+
+namespace Aetheris.Modules.Tests;
+
+public sealed class GenericSculptingTests
+{
+ [Fact]
+ public void ExactFaceGraftRetainsNeighborsAndReplaysItsActualPatch()
+ {
+ var result = Compile("exact-face"); var before = result.States["exact"]; var after = result.OutputState!;
+ Assert.Null(after.Construction); Assert.Same(before.Body.Topology, after.Body.Topology);
+ Assert.Null(after.Body.SafeBooleanComposition);
+ Assert.Equal(before.Body.Geometry.Curves, after.Body.Geometry.Curves);
+ foreach (var face in before.Body.Topology.Faces.Where(f => f.Id.Value != 2))
+ {
+ Assert.True(before.Body.TryGetFaceSurfaceGeometry(face.Id, out var oldSupport));
+ Assert.True(after.Body.TryGetFaceSurfaceGeometry(face.Id, out var support)); Assert.Equal(oldSupport, support);
+ }
+ Assert.True(after.Body.TryGetFaceSurfaceGeometry(new(2), out var crown));
+ Assert.Equal(8.5625, crown!.BSplineSurfaceWithKnots!.Evaluate(.5, .5).Z, 7);
+ Assert.True(after.Body.Bindings.TryGetFaceBinding(new(2), out var crownBinding));
+ Assert.True(crownBinding.Orientation.IsAlignedWithSurface);
+ Assert.False(after.SemanticInventory.ContainsKey("Face2"));
+ Assert.Contains(after.GeometryAssociations!, a => a.SemanticTarget == "crown" && a.FaceIds.SequenceEqual(new[] { 2 }));
+ Assert.True(BrepPcurveValidator.Validate(after.Body, 1e-6, true).IsValid);
+ var saved = ConstructionStateSerializer.Serialize(after.ConstructionAuthority!); Assert.True(saved.IsSuccess);
+ var loaded = ConstructionStateSerializer.Deserialize(saved.Json!); Assert.True(loaded.IsSuccess);
+ var replay = ConstructionStateReplayer.Replay(loaded.ConstructionState!);
+ Assert.True(replay.IsSuccess, string.Join(";", replay.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(after.StateId, replay.OutputState!.StateId);
+ var export = SculptStepExporter.Export(after, result.ModelName); Assert.True(export.IsSuccess);
+ Assert.Equal(export.Step, SculptStepExporter.Export(replay.OutputState, result.ModelName).Step);
+ Assert.True(Step242Importer.ImportBody(export.Step!).IsSuccess);
+ var stale = (ReplaceRegionOperation)after.ConstructionAuthority!.Operations.Single().Payload;
+ var refused = ReplaceRegionSculptor.Apply(after, "stale", stale);
+ Assert.False(refused.IsSuccess); Assert.Null(refused.OutputState);
+ }
+
+ [Theory]
+ [InlineData("preserve: [Face1]", "preserve: [Face2]", "sculpt-preserve-conflict")]
+ [InlineData("existing: Edge2", "existing: Edge5", "surf-face-boundary-mismatch")]
+ [InlineData("continuity: G0", "continuity: G1", "surf-face-continuity-unsupported")]
+ [InlineData("ClosedManifold, OrientationConsistency", "ClosedManifold, NoSelfIntersection", "surf-face-global-intersection-unqualified")]
+ [InlineData("10mm, 8mm, 9mm", "10mm, 8mm, 8mm", "sculpt-envelope-exceeded")]
+ public void ExactGraftRejectsUnprovenIntentAtomically(string old, string replacement, string code)
+ {
+ var result = SculptingAuthoring.Compile(Source("exact-face").Replace(old, replacement));
+ Assert.False(result.IsSuccess); Assert.Null(result.OutputState); Assert.Single(result.States);
+ Assert.Contains(result.Diagnostics, d => d.Code == code);
+ }
+
+ [Fact]
+ public void RawPmiCannotDisappearThroughAnExactEdit()
+ {
+ var result = Compile("exact-face"); var operation = (ReplaceRegionOperation)result.OutputState!.ConstructionAuthority!.Operations.Single().Payload;
+ var pmiPath = Path.Combine(Root(), "fixtures/Regression/BodyStateDebt/explicit-pmi.firmament");
+ var pmi = SculptingAuthoring.CompileFile(pmiPath); Assert.True(pmi.IsSuccess);
+ var original = pmi.OutputState!; var step = SculptStepExporter.Export(original, pmi.ModelName).Step;
+ var refused = ReplaceRegionSculptor.Apply(original, "edited", operation);
+ Assert.False(refused.IsSuccess); Assert.Contains(refused.Diagnostics, d => d.Code == "surf-face-pmi-projection-unsupported");
+ Assert.Equal(step, SculptStepExporter.Export(original, pmi.ModelName).Step);
+ }
+
+ [Fact]
+ public void CreasedBoxRefinementRetainsTheExactStockBoundary()
+ {
+ var result = Compile("box-cage"); var cage = result.MeshStates["cage"]; var source = result.States["exact"];
+ var before = SubdivisionSculptor.Evaluate(cage.Cage);
+ var refined = SubdivisionSculptor.Apply(cage, "refined", new SubdivideCage("refine", 2));
+ var mesh = SubdivisionSculptor.Evaluate(refined.Cage);
+ Assert.True(TriangleMeshValidator.TryValidateClosed(mesh, out var topology, out _));
+ Assert.Equal(2560, topology.SignedVolume, 6); Assert.Equal(2560, Volume(before), 6);
+ Assert.Equal(96, refined.Cage.Faces.Count); Assert.Equal(98, refined.Cage.Vertices.Count);
+ Assert.All(refined.Cage.Faces, f => Assert.Single(f.SourceFaceIds));
+ Assert.Equal(source.StateId.Value, refined.SourceBodyStateId);
+ Assert.Equal(source.RealizedStepText, SculptStepExporter.Export(source, result.ModelName).Step);
+ Assert.True(Volume(SubdivisionSculptor.Evaluate(result.MeshStates["refined"].Cage)) < 2560);
+ Assert.NotEqual(SubdivisionSculptor.Fingerprint(result.MeshStates["refined"].Cage), SubdivisionSculptor.Fingerprint(result.OutputMesh!.Cage));
+ }
+
+ [Theory]
+ [InlineData("box-cage")]
+ [InlineData("sphere-cage")]
+ public void CageProgramSerializesAndReplaysDeterministically(string fixture)
+ {
+ var result = Compile(fixture); var state = result.OutputMesh!;
+ var json = MeshConstructionReplayer.Serialize(state.Construction);
+ var replay = MeshConstructionReplayer.Replay(json, state.Name);
+ Assert.Equal(state.StateId, replay.StateId);
+ Assert.Equal(SubdivisionSculptor.Fingerprint(state.Cage), SubdivisionSculptor.Fingerprint(replay.Cage));
+ Assert.Equal(MeshSculptExport.Glb(state), MeshSculptExport.Glb(replay));
+ Assert.Equal("NotCertified", state.SelfIntersectionStatus); Assert.False(state.StepExportAvailable);
+ Assert.True(TriangleMeshValidator.TryValidateClosed(SubdivisionSculptor.Evaluate(replay.Cage), out _, out _));
+ }
+
+ [Fact]
+ public void SphereConversionHasABoundedDeclaredErrorAndScalingIsExplicit()
+ {
+ var result = Compile("sphere-cage"); var root = result.MeshStates["cage"];
+ Assert.InRange(root.ConversionDeviationMm, 0, 1);
+ Assert.All(root.Cage.Vertices, v => Assert.Equal(10, (v.Position - Point3D.Origin).Length, 8));
+ var refined = result.MeshStates["refined"]; var stretched = result.OutputMesh!;
+ for (var i = 0; i < refined.Cage.Vertices.Count; i++)
+ {
+ var a = refined.Cage.Vertices[i].Position; var b = stretched.Cage.Vertices[i].Position;
+ Assert.Equal(a.X * 1.5, b.X, 8); Assert.Equal(a.Y, b.Y, 8); Assert.Equal(a.Z * .75, b.Z, 8);
+ }
+ var tighter = SculptingAuthoring.Compile(Source("sphere-cage").Replace("maximumDeviation: 1mm", "maximumDeviation: 0.001mm"));
+ Assert.False(tighter.IsSuccess); Assert.Contains(tighter.Diagnostics, d => d.Code == "mesh-conversion-deviation-exceeded");
+ }
+
+ [Fact]
+ public void CreaseSuccessionAndRefinementBudgetsCannotSilentlyRebindOrOverallocate()
+ {
+ var result = Compile("box-cage"); var cage = result.MeshStates["cage"];
+ var oldEdge = Assert.Single(cage.Edges.Take(1)).Id;
+ var next = SubdivisionSculptor.Apply(cage, "next", new SubdivideCage("next", 1));
+ var stale = Assert.Throws<InvalidOperationException>(() => SubdivisionSculptor.Apply(next, "stale", new CreaseCageEdges("stale", [oldEdge], true)));
+ Assert.StartsWith("mesh-edge-unresolved:", stale.Message);
+ var maximum = SubdivisionSculptor.Apply(cage, "maximum", new SubdivideCage("maximum", 4));
+ var refused = Assert.Throws<InvalidOperationException>(() => SubdivisionSculptor.Apply(maximum, "over", new SubdivideCage("over", 4)));
+ Assert.StartsWith("mesh-subdivision-budget-exceeded:", refused.Message);
+ Assert.Equal(1536, maximum.Cage.Faces.Count);
+ }
+
+ private static double Volume(TriangleMesh mesh) { Assert.True(TriangleMeshValidator.TryValidateClosed(mesh, out var report, out _)); return report.SignedVolume; }
+ private static SculptingCompileResult Compile(string fixture) { var r = SculptingAuthoring.CompileFile(Path.Combine(Root(), "fixtures/Regression/GenericSculpting/" + fixture + ".firmament")); Assert.True(r.IsSuccess, string.Join(";", r.Diagnostics.Select(d => d.Message))); return r; }
+ private static string Source(string fixture) => File.ReadAllText(Path.Combine(Root(), "fixtures/Regression/GenericSculpting/" + fixture + ".firmament"));
+ private static string Root() { var p = new DirectoryInfo(AppContext.BaseDirectory); while (p is not null && !File.Exists(Path.Combine(p.FullName, "Aetheris.slnx"))) p = p.Parent; return p!.FullName; }
+}
diff --git a/Aetheris.Surfacing/BoundedFaceGraft.cs b/Aetheris.Surfacing/BoundedFaceGraft.cs
new file mode 100644
index 00000000..1abac5bf
--- /dev/null
+++ b/Aetheris.Surfacing/BoundedFaceGraft.cs
@@ -0,0 +1,39 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Surfacing;
+
+/// <summary>One support replacement with retained topology/curves. No housing reconstruction.</summary>
+public static class BoundedFaceGraft
+{
+ public sealed record Result(BrepBody? Body, BrepPcurveEvidence? Pcurves, IReadOnlyList<SculptDiagnostic> Diagnostics);
+
+ public static Result Apply(BrepBody input, FaceId face, BSplineSurfacePatch patch, double tolerance, ResolvedFaceOrientation orientation)
+ {
+ var diagnostics = patch.Validate();
+ if (diagnostics.Count != 0) return new(null, null, diagnostics);
+ if (!input.Topology.TryGetFace(face, out _)) return new(null, null, [new("surf-face-unresolved", "Face handle is not in the current body.")]);
+ var geometry = new BrepGeometryStore();
+ foreach (var item in input.Geometry.Curves) geometry.AddCurve(item.Key, item.Value);
+ foreach (var item in input.Geometry.Surfaces) geometry.AddSurface(item.Key, item.Value);
+ var surface = new SurfaceGeometryId(input.Geometry.Surfaces.Select(i => i.Key.Value).DefaultIfEmpty().Max() + 1);
+ geometry.AddSurface(surface, patch.Support);
+ var bindings = new BrepBindingModel();
+ foreach (var item in input.Bindings.EdgeBindings) bindings.AddEdgeBinding(item);
+ foreach (var item in input.Bindings.FaceBindings)
+ bindings.AddFaceBinding(item.FaceId == face ? new(item.FaceId, surface, orientation, item.SourceStepEntityId) : item);
+ var points = input.Topology.Vertices.ToDictionary(v => v.Id, v =>
+ input.TryGetVertexPoint(v.Id, out var p) ? p : throw new InvalidOperationException("Unbound graft vertex."));
+ // A support edit invalidates any cached analytic Boolean decomposition.
+ // Shell membership is unchanged; the edited BRep is the new authority.
+ var body = new BrepBody(input.Topology, geometry, bindings, points, null, input.ShellRepresentation);
+ var built = BoundedPcurveBuilder.Populate(body.Topology, geometry, bindings, tolerance);
+ if (!built.IsSuccess) return new(null, null, built.Diagnostics);
+ var pcurves = BrepPcurveValidator.Validate(body, tolerance, requireEveryCoedge: true);
+ if (!pcurves.IsValid) return new(null, pcurves, [new("surf-pcurve-invalid", string.Join(" | ", pcurves.Diagnostics))]);
+ var preflight = BrepExportPreflight.Validate(body);
+ if (!preflight.IsValid) return new(null, pcurves, [new("surf-face-graft-invalid", string.Join(" | ", preflight.Diagnostics.Where(d => d.Severity == BrepExportPreflightSeverity.Error).Select(d => d.Message)))]);
+ return new(body, pcurves, []);
+ }
+}
diff --git a/Aetheris.Surfacing/EngineeringFaceRegionReplacer.cs b/Aetheris.Surfacing/EngineeringFaceRegionReplacer.cs
new file mode 100644
index 00000000..e49e147d
--- /dev/null
+++ b/Aetheris.Surfacing/EngineeringFaceRegionReplacer.cs
@@ -0,0 +1,126 @@
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Core.Brep;
+
+namespace Aetheris.Surfacing;
+
+/// <summary>Current-state association authority around the shared bounded graft.</summary>
+public static class EngineeringFaceRegionReplacer
+{
+ public static SculptResult Apply(BodyState input, string name, ReplaceRegionOperation operation)
+ {
+ SculptResult Fail(string code, string message) => SculptResult.Failure([new(code, message, operation.TargetRegion)]);
+ if (input.HasImportedEngineeringSource)
+ return Fail("surf-face-import-metadata-unqualified", "The source-level graft is qualified for native engineering sources. Imported product metadata requires a complete successor projection; use the existing bounded imported-face API for its qualified contract.");
+ if (operation.Requirements.Contains(SculptRequirement.NoSelfIntersection))
+ return Fail("surf-face-global-intersection-unqualified", "This bounded graft checks trims, pcurves and enclosure; it cannot prove global NoSelfIntersection.");
+ if (input.RealizedStepText is { } step)
+ {
+ var pmi = Step242SemanticPmiInspector.Inspect(step);
+ if (!pmi.Success || pmi.Items.Count != 0)
+ return Fail("surf-face-pmi-projection-unsupported", "Retained STEP PMI has no complete editable projection. The exact predecessor and its PMI remain unchanged; this edit cannot discard them.");
+ }
+ var associations = input.GeometryAssociations ?? [];
+ var target = associations.SingleOrDefault(a => a.SemanticTarget == operation.TargetRegion && a.State != PersistentAssociationState.Removed);
+ if (target is null || target.FaceIds.Count != 1)
+ return Fail("surf-face-target-unresolved", "ReplaceRegion requires one current face association. Inspect the BodyState for explicit FaceN handles or select its replacement patch name.");
+ var faceId = target.FaceIds[0];
+ if ((input.SemanticPmi ?? []).Any(p => p.GeometricFaceIds.Contains(faceId)) || (input.AssemblyInterfaces ?? []).Any(a => a.FaceIds.Contains(faceId)))
+ return Fail("surf-face-associated-target-unsupported", "The selected face carries PMI or an assembly interface whose successor meaning is not qualified. Unaffected associations remain retained.");
+ if (!operation.MayModify.Contains(operation.TargetRegion, StringComparer.Ordinal))
+ return Fail("sculpt-target-not-authorized", "The current face target must be listed in mayModify.");
+ foreach (var contract in operation.Preserves)
+ {
+ var preserved = associations.SingleOrDefault(a => a.SemanticTarget == contract.EntityId);
+ if (preserved is null || preserved.FaceIds.Contains(faceId))
+ return Fail("sculpt-preserve-conflict", $"Cannot preserve '{contract.EntityId}': it is unresolved or includes the replaced face.");
+ }
+ if (operation.ReplacementPatch is not BSplineSurfacePatch patch)
+ return Fail("surf-face-patch-unsupported", "The exact face graft requires a non-rational BSpline SurfacePatch.");
+ if (input.ConstructionAuthority is null)
+ return Fail("surf-face-replay-authority-missing", "Exact face editing requires a replayable source body.");
+ if (patch.BoundaryLoop.Boundaries.Any(b => b.Continuity != PatchBoundaryContinuity.G0))
+ return Fail("surf-face-continuity-unsupported", "The bounded exact-face graft currently qualifies G0 boundaries only.");
+ var face = input.Body.Topology.GetFace(new(faceId));
+ var edges = face.LoopIds.Count == 1 ? input.Body.GetCoedgeIds(face.LoopIds[0]).Select(input.Body.Topology.GetCoedge).Select(c => c.EdgeId).ToArray() : [];
+ if (edges.Length != 4 || patch.BoundaryLoop.Boundaries.Count != 4)
+ return Fail("surf-face-boundary-unsupported", "This exact-edit adapter requires one four-line outer loop and no holes.");
+ var rows = patch.Spline.ControlPoints;
+ var spline = patch.Spline; var domain = patch.ParameterDomain;
+ if (spline.IsRational || spline.DegreeU != 3 || spline.DegreeV != 3 || rows.Count != 4 || rows.Any(r => r.Count != 4)
+ || spline.KnotMultiplicitiesU.Count != 2 || spline.KnotMultiplicitiesV.Count != 2
+ || spline.KnotMultiplicitiesU.Any(m => m != 4) || spline.KnotMultiplicitiesV.Any(m => m != 4)
+ || domain.UMin != spline.DomainStartU || domain.UMax != spline.DomainEndU || domain.VMin != spline.DomainStartV || domain.VMax != spline.DomainEndV
+ || !input.Body.TryGetFaceSurfaceGeometry(new(faceId), out var original) || original?.Plane is not { } sourcePlane)
+ return Fail("surf-face-patch-family-unsupported", "This adapter admits a full-domain non-rational bicubic Bezier graph over one planar four-line face.");
+ input.Body.Bindings.TryGetFaceBinding(new(faceId), out var sourceBinding);
+ var normal = sourcePlane.Normal.ToVector() * (sourceBinding.Orientation.IsAlignedWithSurface ? 1 : -1);
+ var u = rows[^1][0] - rows[0][0]; var v = rows[0][^1] - rows[0][0];
+ var alignment = !patch.ReversedOrientation;
+ if (u.Cross(v).Dot(normal) * (alignment ? 1 : -1) <= 0)
+ return Fail("surf-face-orientation-invalid", "Patch parameter orientation must retain the selected face's outward material side.");
+ for (var i = 0; i < 4; i++) for (var j = 0; j < 4; j++)
+ {
+ var expected = rows[0][0] + u * (i / 3d) + v * (j / 3d);
+ var displacement = rows[i][j] - expected; var height = displacement.Dot(normal);
+ if ((displacement - normal * height).Length > operation.GeometricTolerance || height < -operation.GeometricTolerance)
+ return Fail("surf-face-graph-unsupported", "Control points must retain the face's affine parameter grid and displace outward along its normal; broader deformation belongs to MeshState.");
+ }
+ foreach (var boundary in patch.BoundaryLoop.Boundaries)
+ {
+ var edge = edges.SingleOrDefault(e => boundary.ExistingBoundary == "Edge" + e.Value);
+ if (!edges.Contains(edge) || !input.Body.TryGetEdgeCurveGeometry(edge, out var curve) || curve?.Line3 is not { } line)
+ return Fail("surf-face-boundary-unresolved", "Each patch side must explicitly name its current straight EdgeN handle.");
+ var controls = boundary.PatchSide switch
+ {
+ PatchBoundarySide.South => rows.Select(r => r[0]).ToArray(),
+ PatchBoundarySide.North => rows.Select(r => r[^1]).ToArray(),
+ PatchBoundarySide.West => rows[0].ToArray(),
+ _ => rows[^1].ToArray()
+ };
+ var topologyEdge = input.Body.Topology.GetEdge(edge);
+ input.Body.TryGetVertexPoint(topologyEdge.StartVertexId, out var a); input.Body.TryGetVertexPoint(topologyEdge.EndVertexId, out var b);
+ var tol = operation.GeometricTolerance;
+ if (controls.Any(p => (p - line.Origin).Cross(line.Direction.ToVector()).Length > tol) ||
+ !(((controls[0] - a).Length <= tol && (controls[^1] - b).Length <= tol) || ((controls[0] - b).Length <= tol && (controls[^1] - a).Length <= tol)))
+ return Fail("surf-face-boundary-mismatch", $"Patch side {boundary.PatchSide} does not retain its named edge endpoints/support.");
+ }
+ if (patch.BoundaryLoop.Boundaries.Select(b => b.ExistingBoundary).Distinct().Count() != 4)
+ return Fail("surf-face-boundary-duplicate", "Each outer edge must be bound once.");
+ var points = patch.Spline.ControlPoints.SelectMany(r => r).ToArray();
+ var bounds = new SpatialInfluenceEnvelope(points.Min(p => p.X), points.Min(p => p.Y), points.Min(p => p.Z), points.Max(p => p.X), points.Max(p => p.Y), points.Max(p => p.Z));
+ if (!operation.InfluenceEnvelope.Contains(bounds, operation.GeometricTolerance))
+ return Fail("sculpt-envelope-exceeded", "The non-rational patch control hull exceeds the authorized influenceEnvelope.");
+ var graft = BoundedFaceGraft.Apply(input.Body, new(faceId), patch, operation.GeometricTolerance, new(alignment));
+ if (graft.Body is null) return SculptResult.Failure(graft.Diagnostics);
+ var affected = associations.Where(a => a.FaceIds.Contains(faceId)).Select(a => a.SemanticTarget).ToHashSet(StringComparer.Ordinal);
+ var inventory = input.SemanticInventory.Where(p => !affected.Contains(p.Key)).ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal);
+ if (inventory.ContainsKey(patch.PatchId)) return Fail("surf-face-successor-duplicate", "The replacement patch identity already belongs to another current entity.");
+ inventory[patch.PatchId] = new(patch.PatchId, SculptEntityKind.Surface, patch.GeometryFingerprint, "Explicit bounded face successor.");
+ var id = BodyStateId.Derive(input.StateId.Value + "|ExactFaceGraft|" + operation.Canonical);
+ inventory[input.BodyStableId] = new(input.BodyStableId, SculptEntityKind.Body, id.Value, "Exact body after bounded face graft.");
+ var correspondence = associations.Select(a => new GeometricDeltaEntry(a.SemanticTarget,
+ affected.Contains(a.SemanticTarget) ? GeometricChangeKind.Replaced : GeometricChangeKind.Preserved,
+ affected.Contains(a.SemanticTarget) ? [patch.PatchId] : [a.SemanticTarget], "Retained topology; explicit face-support succession.")).ToArray();
+ var delta = new GeometricDelta(input.StateId, id, operation.Reads,
+ associations.Where(a => !affected.Contains(a.SemanticTarget)).Select(a => a.SemanticTarget).ToArray(), affected.ToArray(), [], [patch.PatchId], operation.MayModify,
+ operation.InfluenceEnvelope, correspondence);
+ var remapped = associations.Where(a => !affected.Contains(a.SemanticTarget)).Append(new(patch.PatchId, PersistentAssociationState.ReplacedBy, [faceId], "Retained face identity; explicitly replaced support.")).ToArray();
+ var evidence = new SculptValidationEvidence[] { new("ExactFaceGraft", true, LocalityEvidenceLevel.CertifiedBounded,
+ graft.Pcurves!.MaximumReconstructionDeviation, operation.GeometricTolerance, "Topology/edges/vertices and all neighboring supports retained. Pcurves and export preflight passed; global self-intersection is unqualified.") };
+ var output = input with
+ {
+ StateId = id,
+ PredecessorStateId = input.StateId,
+ AuthoredName = name,
+ Body = graft.Body,
+ SemanticInventory = inventory,
+ GeometryAssociations = remapped,
+ Delta = delta,
+ ValidationEvidence = evidence,
+ RealizedStepText = null,
+ ExactFacePatches = [.. input.ExactFacePatches.Where(p => !affected.Contains(p.PatchId)), SurfacePatchMetadata.From(patch, 1)],
+ ConstructionAuthority = ConstructionAuthorityEvolution.Append(input, name, operation, id, delta, evidence)
+ };
+ return new(true, output, delta, evidence, []);
+ }
+}
diff --git a/Aetheris.Surfacing/ImportedFaceRegionReplacer.cs b/Aetheris.Surfacing/ImportedFaceRegionReplacer.cs
index de128b3b..e4a30db7 100644
--- a/Aetheris.Surfacing/ImportedFaceRegionReplacer.cs
+++ b/Aetheris.Surfacing/ImportedFaceRegionReplacer.cs
@@ -61,28 +61,11 @@ public static class ImportedFaceRegionReplacer
var face = importedState.Body.Topology.GetFace(selected.FaceId);
if (face.LoopIds.Count == 0) return Failure("surf-inner-loop-invalid", "Selected imported face has no outer loop.");
- var geometry = new BrepGeometryStore();
- foreach (var curve in importedState.Body.Geometry.Curves) geometry.AddCurve(curve.Key, curve.Value);
- foreach (var surface in importedState.Body.Geometry.Surfaces) geometry.AddSurface(surface.Key, surface.Value);
- var newSurfaceId = new Aetheris.Kernel.Core.Geometry.SurfaceGeometryId(importedState.Body.Geometry.Surfaces.Select(item => item.Key.Value).DefaultIfEmpty().Max() + 1);
- geometry.AddSurface(newSurfaceId, replacementPatch.Support);
-
- var bindings = new BrepBindingModel();
- foreach (var edge in importedState.Body.Bindings.EdgeBindings) bindings.AddEdgeBinding(edge);
- foreach (var binding in importedState.Body.Bindings.FaceBindings)
- bindings.AddFaceBinding(binding.FaceId == selected.FaceId
- ? new FaceGeometryBinding(binding.FaceId, newSurfaceId, replacementPatch.ReversedOrientation, binding.SourceStepEntityId)
- : binding);
- var vertexPoints = importedState.Body.Topology.Vertices.Where(vertex => importedState.Body.TryGetVertexPoint(vertex.Id, out _))
- .ToDictionary(vertex => vertex.Id, vertex => { importedState.Body.TryGetVertexPoint(vertex.Id, out var point); return point; });
- var body = new BrepBody(importedState.Body.Topology, geometry, bindings, vertexPoints,
- importedState.Body.SafeBooleanComposition, importedState.Body.ShellRepresentation);
- var pcurveBuild = BoundedPcurveBuilder.Populate(body.Topology, geometry, bindings, tolerance);
- if (!pcurveBuild.IsSuccess) return new(false, null, null, pcurveBuild.Diagnostics);
- var pcurveEvidence = BrepPcurveValidator.Validate(body, tolerance, requireEveryCoedge: true);
- if (!pcurveEvidence.IsValid) return Failure("surf-pcurve-invalid", string.Join(" | ", pcurveEvidence.Diagnostics));
- var preflight = BrepExportPreflight.Validate(body);
- if (!preflight.IsValid) return Failure("surf-imported-replacement-invalid", string.Join(" | ", preflight.Diagnostics.Where(item => item.Severity == BrepExportPreflightSeverity.Error).Select(item => item.Message)));
+ // Preserve this compatibility API's historical resolved-orientation contract.
+ var graft = BoundedFaceGraft.Apply(importedState.Body, selected.FaceId, replacementPatch, tolerance, new(replacementPatch.ReversedOrientation));
+ if (graft.Body is null) return new(false, null, null, graft.Diagnostics);
+ var body = graft.Body;
+ var pcurveEvidence = graft.Pcurves!;
var construction = importedState.Construction with
{
@@ -108,7 +91,7 @@ public static class ImportedFaceRegionReplacer
if (!associationRemap.IsSuccess) return new(false, null, null, associationRemap.Diagnostics);
var associations = associationRemap.Associations;
var evidence = new ImportedFaceReplacementEvidence(sourceStepFaceEntityId, selected.FaceId.Value,
- bindings.FaceBindings.Where(binding => binding.FaceId != selected.FaceId && binding.SourceStepEntityId.HasValue).Select(binding => binding.SourceStepEntityId!.Value).Order().ToArray(),
+ body.Bindings.FaceBindings.Where(binding => binding.FaceId != selected.FaceId && binding.SourceStepEntityId.HasValue).Select(binding => binding.SourceStepEntityId!.Value).Order().ToArray(),
face.LoopIds.Count - 1, pcurveEvidence);
var validations = SculptedHousingFactory.ValidateBody(body, tolerance).Append(new SculptValidationEvidence("ImportedFaceReplacement", true,
LocalityEvidenceLevel.CertifiedBounded, 0d, tolerance, $"Retained topology and {evidence.PreservedNeighborSourceStepEntityIds.Count} neighboring imported face provenances; replaced support on current face {selected.FaceId.Value}.")).ToArray();
diff --git a/Aetheris.Surfacing/SculptingAuthoringResults.cs b/Aetheris.Surfacing/SculptingAuthoringResults.cs
index 1b79b84b..6eb8b6e7 100644
--- a/Aetheris.Surfacing/SculptingAuthoringResults.cs
+++ b/Aetheris.Surfacing/SculptingAuthoringResults.cs
@@ -1,5 +1,9 @@
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 sealed record SculptingCompileResult(bool IsSuccess, string ModelName, BodyState? OutputState, IReadOnlyDictionary<string, BodyState> States, IReadOnlyList<SculptDiagnostic> Diagnostics, SculptingTimingEvidence Timings)
+{
+ public MeshSculptState? OutputMesh { get; init; }
+ public IReadOnlyDictionary<string, MeshSculptState> MeshStates { get; init; } = new Dictionary<string, MeshSculptState>();
+}
diff --git a/Aetheris.Surfacing/SculptingExecution.cs b/Aetheris.Surfacing/SculptingExecution.cs
index 0693abbf..0b391839 100644
--- a/Aetheris.Surfacing/SculptingExecution.cs
+++ b/Aetheris.Surfacing/SculptingExecution.cs
@@ -241,7 +241,7 @@ public static class ReplaceRegionSculptor
private static SculptResult ApplyCore(BodyState input, string outputName, ReplaceRegionOperation operation, SpatialInfluenceEnvelope? certifiedBounds)
{
ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(operation);
- if (input.Construction is null) return SculptResult.Failure([BodyStateCapabilities.HousingRequired(input, operation.OperationKind)]);
+ if (input.Construction is null) return EngineeringFaceRegionReplacer.Apply(input, outputName, operation);
if (BodyStateCapabilities.ImportedReconstruction(input, operation.OperationKind) is {} imported) return SculptResult.Failure([imported]);
if (BodyStateCapabilities.UnretainedSectionChain(input, operation.OperationKind) is {} history) return SculptResult.Failure([history]);
var diagnostics = operation.ReplacementPatch.Validate().ToList();
diff --git a/Aetheris.Surfacing/SculptingState.cs b/Aetheris.Surfacing/SculptingState.cs
index 90c92e11..598f3d2e 100644
--- a/Aetheris.Surfacing/SculptingState.cs
+++ b/Aetheris.Surfacing/SculptingState.cs
@@ -174,9 +174,11 @@ public sealed record BodyState(
string? RealizedStepText = null)
{
public string? RealizedStepProductName { get; init; }
+ public bool HasImportedEngineeringSource { get; init; }
+ public IReadOnlyList<SurfacePatchMetadata> ExactFacePatches { get; init; } = [];
public IReadOnlyList<SurfacePatchMetadata> SurfacePatches => Construction?.ReplacementPatch is { } patch
? [SurfacePatchMetadata.From(patch, Body.Topology.Faces.FirstOrDefault(face =>
- Body.TryGetFaceSurfaceGeometry(face.Id, out var support) && Equals(support, patch.Support))?.LoopIds.Count ?? 1)] : [];
+ Body.TryGetFaceSurfaceGeometry(face.Id, out var support) && Equals(support, patch.Support))?.LoopIds.Count ?? 1)] : ExactFacePatches;
}
public sealed record OffsetRegionOperation(
diff --git a/Aetheris.Surfacing/SubdivisionSculpting.cs b/Aetheris.Surfacing/SubdivisionSculpting.cs
new file mode 100644
index 00000000..3c255d80
--- /dev/null
+++ b/Aetheris.Surfacing/SubdivisionSculpting.cs
@@ -0,0 +1,307 @@
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json.Serialization;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Surfacing;
+
+public sealed record CageVertex(string Id, Point3D Position, IReadOnlyList<string> Parents);
+public sealed record CageFace(string Id, IReadOnlyList<string> Vertices, IReadOnlyList<int> SourceFaceIds);
+public sealed record CageEdge(string Id, string A, string B, IReadOnlyList<int> Faces);
+public sealed record MeshExportPreparation(TriangleMesh NativeMesh, TriangleMesh EncodedMesh, TriangleMeshTopologyReport Topology, double MaximumFloatQuantizationMm);
+public sealed record SubdivisionCage(IReadOnlyList<CageVertex> Vertices, IReadOnlyList<CageFace> Faces, IReadOnlyList<string> Creases);
+
+[JsonPolymorphic(TypeDiscriminatorPropertyName = "$operation")]
+[JsonDerivedType(typeof(SubdivideCage), "Subdivide")]
+[JsonDerivedType(typeof(MoveCageVertices), "Move")]
+[JsonDerivedType(typeof(ScaleCageVertices), "Scale")]
+[JsonDerivedType(typeof(CreaseCageEdges), "Crease")]
+public abstract record MeshSculptOperation(string Id)
+{
+ public IReadOnlyList<string> Preserve { get; init; } = [];
+}
+public sealed record SubdivideCage(string Id, int Levels) : MeshSculptOperation(Id);
+public sealed record MoveCageVertices(string Id, IReadOnlyList<string> Vertices, Vector3D Offset) : MeshSculptOperation(Id);
+public sealed record ScaleCageVertices(string Id, IReadOnlyList<string> Vertices, Vector3D Factor, Point3D Origin) : MeshSculptOperation(Id);
+public sealed record CreaseCageEdges(string Id, IReadOnlyList<string> Edges, bool Sharp) : MeshSculptOperation(Id);
+public sealed record MeshConstruction(string Schema, ConstructionState Source, string Cage, int Segments, double MaximumDeviationMm, IReadOnlyList<MeshSculptOperation> Operations);
+public sealed record MeshSculptState(string StateId, string? PredecessorStateId, string Name, string SourceBodyStateId,
+ SubdivisionCage Cage, MeshConstruction Construction, double ConversionDeviationMm, string ConversionEvidence)
+{
+ public string ArtifactKind => "SubdivisionMesh";
+ public bool StepExportAvailable => false;
+ public string SelfIntersectionStatus => "NotCertified";
+ public IReadOnlyList<CageEdge> Edges => SubdivisionSculptor.Edges(Cage);
+}
+
+/// <summary>Finite Catmull-Clark refinement over a real closed quad cage. No BRep fitting/fallback.</summary>
+public static class SubdivisionSculptor
+{
+ public const string Schema = "aetheris.mesh-sculpt.v1";
+ public const int MaximumFaces = 24576;
+ public static string Hash(string value) => System.Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value))).ToLowerInvariant();
+ public static string EdgeId(string a, string b) => "e" + Hash(string.CompareOrdinal(a, b) < 0 ? a + "|" + b : b + "|" + a)[..20];
+
+ public static IReadOnlyList<CageEdge> Edges(SubdivisionCage cage)
+ {
+ var edges = new Dictionary<string, (string A, string B, List<int> Faces)>(StringComparer.Ordinal);
+ for (var i = 0; i < cage.Faces.Count; i++)
+ {
+ var v = cage.Faces[i].Vertices;
+ for (var j = 0; j < v.Count; j++)
+ {
+ var a = v[j]; var b = v[(j + 1) % v.Count]; var id = EdgeId(a, b);
+ if (!edges.TryGetValue(id, out var edge)) edges.Add(id, edge = (a, b, []));
+ edge.Faces.Add(i);
+ }
+ }
+ return edges.OrderBy(e => e.Key, StringComparer.Ordinal).Select(e => new CageEdge(e.Key, e.Value.A, e.Value.B, e.Value.Faces.ToArray())).ToArray();
+ }
+
+ public static MeshSculptState Convert(BodyState source, string name, string kind, int segments = 4, double maximumDeviationMm = 1)
+ {
+ if (source.ConstructionAuthority is null) throw Error("mesh-source-not-replayable", "Conversion requires a source construction recipe.");
+ if (kind is not ("Box" or "Sphere")) throw Error("mesh-cage-unsupported", "Explicit cage must be Box or Sphere; arbitrary BRep retopology is not implemented.");
+ if (segments is < 1 or > 16 || !double.IsFinite(maximumDeviationMm) || maximumDeviationMm <= 0)
+ throw Error("mesh-conversion-budget-invalid", "Segments must be 1..16 and maximumDeviation must be positive and finite.");
+ var body = source.Body;
+ var vertices = body.Topology.Vertices.Select(v => body.TryGetVertexPoint(v.Id, out var p) ? p : throw Error("mesh-source-unbound", "Unbound source vertex.")).ToArray();
+ var surfaces = body.Topology.Faces.Select(f => body.TryGetFaceSurfaceGeometry(f.Id, out var s) ? s! : throw Error("mesh-source-unbound", "Unbound source face.")).ToArray();
+ Func<int, int, int, Point3D> Map = (x, y, z) => new(x, y, z);
+ double radius = 0; Point3D center = Point3D.Origin;
+ if (kind == "Box")
+ {
+ if (vertices.Length != 8 || body.Topology.Faces.Count() != 6 || surfaces.Any(s => s.Plane is null) || body.Topology.Faces.Any(f => f.LoopIds.Count != 1))
+ throw Error("mesh-box-cage-source-unsupported", "Box cage conversion requires a pure axis-aligned box with eight vertices and six planar faces.");
+ var lo = new Point3D(vertices.Min(p => p.X), vertices.Min(p => p.Y), vertices.Min(p => p.Z));
+ var hi = new Point3D(vertices.Max(p => p.X), vertices.Max(p => p.Y), vertices.Max(p => p.Z));
+ if (vertices.Any(p => (p.X != lo.X && p.X != hi.X) || (p.Y != lo.Y && p.Y != hi.Y) || (p.Z != lo.Z && p.Z != hi.Z)) || vertices.Distinct().Count() != 8)
+ throw Error("mesh-box-cage-source-unsupported", "A bounding box is not a box conversion; every source corner must match.");
+ Map = (x, y, z) => new(lo.X + (hi.X - lo.X) * (x + segments) / (2d * segments), lo.Y + (hi.Y - lo.Y) * (y + segments) / (2d * segments), lo.Z + (hi.Z - lo.Z) * (z + segments) / (2d * segments));
+ }
+ else
+ {
+ var spheres = surfaces.Select(s => s.Sphere).ToArray();
+ if (spheres.Length == 0 || spheres.Any(s => s is null) || spheres.Distinct().Count() != 1)
+ throw Error("mesh-sphere-cage-source-unsupported", "Sphere cage conversion requires one common exact spherical support and no other surface family.");
+ radius = spheres[0]!.Value.Radius; center = spheres[0]!.Value.Center;
+ Map = (x, y, z) => center + new Vector3D(x, y, z) * (radius / Math.Sqrt(x * x + y * y + z * z));
+ }
+ var vs = new List<CageVertex>(); var fs = new List<CageFace>(); var ids = new Dictionary<(int, int, int), string>();
+ string Vertex(int x, int y, int z)
+ {
+ if (ids.TryGetValue((x, y, z), out var id)) return id;
+ id = "v" + vs.Count; ids.Add((x, y, z), id); vs.Add(new(id, Map(x, y, z), [source.StateId.Value])); return id;
+ }
+ // Six consistently outward cube parameterizations, welded by lattice key.
+ (int X, int Y, int Z) Grid(int side, int u, int v) => side switch
+ {
+ 0 => (segments, u, v),
+ 1 => (-segments, v, u),
+ 2 => (v, segments, u),
+ 3 => (u, -segments, v),
+ 4 => (u, v, segments),
+ _ => (v, u, -segments)
+ };
+ var sourceFaces = body.Topology.Faces.Select(f => f.Id.Value).ToArray();
+ for (var side = 0; side < 6; side++) for (var i = 0; i < segments; i++) for (var j = 0; j < segments; j++)
+ {
+ var u = -segments + 2 * i; var v = -segments + 2 * j;
+ var keys = new[] { Grid(side, u, v), Grid(side, u + 2, v), Grid(side, u + 2, v + 2), Grid(side, u, v + 2) };
+ var quad = keys.Select(p => Vertex(p.X, p.Y, p.Z)).ToArray();
+ var owners = kind == "Sphere" ? sourceFaces : body.Topology.Faces.Where(f =>
+ body.TryGetFaceSurfaceGeometry(f.Id, out var s) && s?.Plane is { } plane &&
+ quad.All(id => Math.Abs((vs.Single(vertex => vertex.Id == id).Position - plane.Origin).Dot(plane.Normal.ToVector())) <= 1e-8)).Select(f => f.Id.Value).ToArray();
+ if (kind == "Box" && owners.Length != 1) throw Error("mesh-box-face-correspondence-unsupported", "A cage face must have one proven source plane; no nearest-face projection.");
+ fs.Add(new("q" + fs.Count, quad, owners));
+ }
+ var cage = new SubdivisionCage(vs.ToArray(), fs.ToArray(), []);
+ if (kind == "Box")
+ {
+ var byId = vs.ToDictionary(v => v.Id, v => v.Position, StringComparer.Ordinal);
+ var crease = Edges(cage).Where(e =>
+ {
+ var a = byId[e.A]; var b = byId[e.B]; var lo = vertices.Aggregate((p, q) => new(Math.Min(p.X, q.X), Math.Min(p.Y, q.Y), Math.Min(p.Z, q.Z))); var hi = vertices.Aggregate((p, q) => new(Math.Max(p.X, q.X), Math.Max(p.Y, q.Y), Math.Max(p.Z, q.Z)));
+ return (a.X == b.X && (a.X == lo.X || a.X == hi.X) ? 1 : 0) + (a.Y == b.Y && (a.Y == lo.Y || a.Y == hi.Y) ? 1 : 0) + (a.Z == b.Z && (a.Z == lo.Z || a.Z == hi.Z) ? 1 : 0) >= 2;
+ }).Select(e => e.Id).ToArray();
+ cage = cage with { Creases = crease };
+ }
+ var prepared = PrepareExport(cage, maximumDeviationMm);
+ var deviation = kind == "Sphere"
+ ? Math.Max(RadialBound(prepared.NativeMesh, center, radius), RadialBound(prepared.EncodedMesh, center, radius))
+ : prepared.MaximumFloatQuantizationMm;
+ if (deviation > maximumDeviationMm) throw Error("mesh-conversion-deviation-exceeded", $"Finite cage radial deviation {deviation:R}mm exceeds maximumDeviation {maximumDeviationMm:R}mm; increase segments or authorize a larger conversion budget.");
+ var recipe = new MeshConstruction(Schema, source.ConstructionAuthority, kind, segments, maximumDeviationMm, []);
+ return new(Hash(source.StateId.Value + "|" + Schema + "|" + kind + "|" + segments + "|" + maximumDeviationMm.ToString("R", CultureInfo.InvariantCulture) + "|" + Fingerprint(cage)), source.StateId.Value, name, source.StateId.Value, cage, recipe, deviation,
+ kind == "Box" ? "Exact native box cage; sharp edges retained, with output quantization inside the declared budget." : "Finite cube-sphere cage; conservative triangle-plane radial bound, including output quantization, relative to the exact source sphere. Not a limit-surface certificate.");
+ }
+
+ public static MeshSculptState Apply(MeshSculptState input, string name, MeshSculptOperation operation)
+ {
+ if (input.Construction.Operations.Count >= 64) throw Error("mesh-operation-budget-exceeded", "At most 64 operations are admitted per mesh recipe.");
+ var cage = input.Cage;
+ var preserved = operation.Preserve.Count == 0 ? new HashSet<string>() : Selection(cage, operation.Preserve);
+ switch (operation)
+ {
+ case SubdivideCage subdivide:
+ if (subdivide.Levels is < 1 or > 4) throw Error("mesh-subdivision-budget-invalid", "Subdivide levels must be 1..4, within the cumulative face budget.");
+ for (var i = 0; i < subdivide.Levels; i++) cage = Refine(cage);
+ break;
+ case MoveCageVertices move:
+ if (!Finite(move.Offset)) throw Error("mesh-edit-nonfinite", "Move offset must be finite.");
+ var moved = Selection(cage, move.Vertices);
+ cage = cage with { Vertices = cage.Vertices.Select(v => moved.Contains(v.Id) ? v with { Position = v.Position + move.Offset } : v).ToArray() };
+ break;
+ case ScaleCageVertices scale:
+ if (!Finite(scale.Factor) || scale.Factor.X <= 0 || scale.Factor.Y <= 0 || scale.Factor.Z <= 0 || !Finite(new(scale.Origin.X, scale.Origin.Y, scale.Origin.Z))) throw Error("mesh-scale-invalid", "Scale factors must be positive and finite, with a finite explicit origin.");
+ var scaled = Selection(cage, scale.Vertices);
+ cage = cage with { Vertices = cage.Vertices.Select(v => scaled.Contains(v.Id) ? v with { Position = scale.Origin + new Vector3D((v.Position.X - scale.Origin.X) * scale.Factor.X, (v.Position.Y - scale.Origin.Y) * scale.Factor.Y, (v.Position.Z - scale.Origin.Z) * scale.Factor.Z) } : v).ToArray() };
+ break;
+ case CreaseCageEdges crease:
+ var edges = Edges(cage).Select(e => e.Id).ToHashSet(StringComparer.Ordinal);
+ var selected = crease.Edges.SequenceEqual(new[] { "All" }) ? edges : crease.Edges.ToHashSet(StringComparer.Ordinal);
+ if (selected.Count == 0 || selected.Count != crease.Edges.Count && !crease.Edges.SequenceEqual(new[] { "All" }) || selected.Any(e => !edges.Contains(e))) throw Error("mesh-edge-unresolved", "Crease requires unique current edge handles, or [All].");
+ var creases = cage.Creases.ToHashSet(StringComparer.Ordinal);
+ if (crease.Sharp) creases.UnionWith(selected); else creases.ExceptWith(selected);
+ cage = cage with { Creases = creases.Order(StringComparer.Ordinal).ToArray() };
+ break;
+ default: throw Error("mesh-operation-unsupported", "Unknown mesh operation.");
+ }
+ Evaluate(cage); // Validate the successor before publishing it.
+ var current = cage.Vertices.ToDictionary(v => v.Id, v => v.Position, StringComparer.Ordinal);
+ if (input.Cage.Vertices.Any(v => preserved.Contains(v.Id) && (!current.TryGetValue(v.Id, out var p) || p != v.Position)))
+ throw Error("mesh-preservation-failed", "An explicitly preserved cage vertex moved or disappeared; no successor was published.");
+ if (operation is MoveCageVertices or ScaleCageVertices)
+ {
+ var old = input.Cage.Vertices.ToDictionary(v => v.Id, v => v.Position, StringComparer.Ordinal);
+ foreach (var face in cage.Faces) for (var i = 1; i < 3; i++)
+ {
+ var a = face.Vertices[0]; var b = face.Vertices[i]; var c = face.Vertices[i + 1];
+ if ((old[b] - old[a]).Cross(old[c] - old[a]).Dot((current[b] - current[a]).Cross(current[c] - current[a])) <= 0)
+ throw Error("mesh-local-foldover", "The edit reverses a face triangle relative to its predecessor. Global self-intersection remains separately unqualified.");
+ }
+ }
+ var recipe = input.Construction with { Operations = [.. input.Construction.Operations, operation] };
+ return input with { StateId = Hash(input.StateId + "|" + System.Text.Json.JsonSerializer.Serialize<MeshSculptOperation>(operation) + "|" + Fingerprint(cage)), PredecessorStateId = input.StateId, Name = name, Cage = cage, Construction = recipe };
+ }
+
+ private static HashSet<string> Selection(SubdivisionCage cage, IReadOnlyList<string> requested)
+ {
+ var all = cage.Vertices.Select(v => v.Id).ToHashSet(StringComparer.Ordinal);
+ if (requested.SequenceEqual(new[] { "All" })) return all;
+ var result = requested.ToHashSet(StringComparer.Ordinal);
+ if (result.Count == 0 || result.Count != requested.Count || result.Any(v => !all.Contains(v))) throw Error("mesh-vertex-unresolved", "Use unique current cage vertex handles or [All]. Stale handles are not rebound by proximity.");
+ return result;
+ }
+
+ private static SubdivisionCage Refine(SubdivisionCage cage)
+ {
+ if (cage.Faces.Count > MaximumFaces / 4) throw Error("mesh-subdivision-budget-exceeded", $"Refinement exceeds {MaximumFaces} faces.");
+ var edges = Edges(cage); var points = cage.Vertices.ToDictionary(v => v.Id, v => v.Position, StringComparer.Ordinal);
+ var incident = cage.Vertices.ToDictionary(v => v.Id, _ => new List<CageEdge>(), StringComparer.Ordinal);
+ foreach (var e in edges) { incident[e.A].Add(e); incident[e.B].Add(e); }
+ var facePoints = cage.Faces.Select(f => Average(f.Vertices.Select(v => points[v]))).ToArray();
+ var sharp = cage.Creases.ToHashSet(StringComparer.Ordinal); var output = new List<CageVertex>();
+ foreach (var vertex in cage.Vertices)
+ {
+ var adjacent = incident[vertex.Id].ToArray();
+ var creased = adjacent.Where(e => sharp.Contains(e.Id)).ToArray(); var p = vertex.Position;
+ Point3D position;
+ // Infinite sharpness: corners stay fixed; a two-edge crease uses
+ // the cubic B-spline 6P/8 + (P0+P1)/8 rule. A dart stays smooth.
+ if (creased.Length >= 3) position = p;
+ else if (creased.Length == 2) position = Average([p, p, p, p, p, p, points[Other(creased[0], vertex.Id)], points[Other(creased[1], vertex.Id)]]);
+ else
+ {
+ // Standard Catmull-Clark vertex rule: (F + 2R + (n-3)P)/n.
+ var faces = adjacent.SelectMany(e => e.Faces).Distinct().ToArray(); var n = faces.Length;
+ var f = Average(faces.Select(i => facePoints[i])); var r = Average(adjacent.Select(e => Average([points[e.A], points[e.B]])));
+ position = new((f.X + 2 * r.X + (n - 3) * p.X) / n, (f.Y + 2 * r.Y + (n - 3) * p.Y) / n, (f.Z + 2 * r.Z + (n - 3) * p.Z) / n);
+ }
+ output.Add(vertex with { Position = position });
+ }
+ // A sharp edge splits at its midpoint; a smooth edge also averages
+ // both adjacent face centers. The old edge ID names its new vertex.
+ foreach (var edge in edges) output.Add(new(edge.Id, sharp.Contains(edge.Id) ? Average([points[edge.A], points[edge.B]]) : Average([points[edge.A], points[edge.B], facePoints[edge.Faces[0]], facePoints[edge.Faces[1]]]), [edge.A, edge.B]));
+ for (var i = 0; i < cage.Faces.Count; i++) output.Add(new("f" + Hash(cage.Faces[i].Id)[..20], facePoints[i], cage.Faces[i].Vertices.ToArray()));
+ var facesOut = new List<CageFace>();
+ for (var i = 0; i < cage.Faces.Count; i++)
+ {
+ var face = cage.Faces[i]; var v = face.Vertices; var center = "f" + Hash(face.Id)[..20];
+ for (var j = 0; j < 4; j++) facesOut.Add(new(face.Id + "_" + j, [v[j], EdgeId(v[j], v[(j + 1) % 4]), center, EdgeId(v[(j + 3) % 4], v[j])], face.SourceFaceIds));
+ }
+ var childCreases = edges.Where(e => sharp.Contains(e.Id)).SelectMany(e => new[] { EdgeId(e.A, e.Id), EdgeId(e.Id, e.B) }).Order(StringComparer.Ordinal).ToArray();
+ return new(output.ToArray(), facesOut.ToArray(), childCreases);
+ }
+
+ public static TriangleMesh Evaluate(SubdivisionCage cage)
+ {
+ if (cage.Faces.Count == 0 || cage.Faces.Count > MaximumFaces || cage.Vertices.Select(v => v.Id).Distinct().Count() != cage.Vertices.Count || cage.Vertices.Any(v => !Finite(new(v.Position.X, v.Position.Y, v.Position.Z)))) throw Error("mesh-cage-invalid", "Invalid cage size, identities or coordinates.");
+ var indices = cage.Vertices.Select((v, i) => (v.Id, i)).ToDictionary(v => v.Id, v => v.i, StringComparer.Ordinal);
+ if (cage.Faces.Any(f => f.Vertices.Count != 4 || f.Vertices.Distinct().Count() != 4 || f.Vertices.Any(v => !indices.ContainsKey(v)))) throw Error("mesh-cage-invalid", "Every cage face must be a quad with four distinct current vertices.");
+ var edges = Edges(cage);
+ var edgeIds = edges.Select(e => e.Id).ToHashSet(StringComparer.Ordinal);
+ if (edges.Any(e => e.Faces.Count != 2) || cage.Creases.Any(c => !edgeIds.Contains(c))) throw Error("mesh-cage-nonmanifold", "Cage must be closed with current crease handles.");
+ var links = cage.Vertices.ToDictionary(v => v.Id, _ => new List<CageEdge>(), StringComparer.Ordinal);
+ foreach (var e in edges) { links[e.A].Add(e); links[e.B].Add(e); }
+ foreach (var vertex in cage.Vertices)
+ {
+ var incident = links[vertex.Id]; var faces = incident.SelectMany(e => e.Faces).ToHashSet();
+ if (faces.Count < 3) throw Error("mesh-cage-vertex-link-invalid", "Every cage vertex needs a closed connected face fan.");
+ var seen = new HashSet<int>(); var pending = new Stack<int>(); pending.Push(faces.First());
+ while (pending.Count > 0) { var f = pending.Pop(); if (!seen.Add(f)) continue; foreach (var e in incident.Where(e => e.Faces.Contains(f))) foreach (var next in e.Faces) if (!seen.Contains(next)) pending.Push(next); }
+ if (seen.Count != faces.Count) throw Error("mesh-cage-vertex-link-invalid", "Disconnected face fans cannot share one vertex identity.");
+ }
+ var triangles = cage.Faces.SelectMany(f => new[] { indices[f.Vertices[0]], indices[f.Vertices[1]], indices[f.Vertices[2]], indices[f.Vertices[0]], indices[f.Vertices[2]], indices[f.Vertices[3]] }).ToArray();
+ var positions = cage.Vertices.Select(v => v.Position).ToArray(); var normals = new Vector3D[positions.Length];
+ for (var i = 0; i < triangles.Length; i += 3)
+ {
+ var a = triangles[i]; var b = triangles[i + 1]; var c = triangles[i + 2]; var n = (positions[b] - positions[a]).Cross(positions[c] - positions[a]);
+ normals[a] += n; normals[b] += n; normals[c] += n;
+ }
+ for (var i = 0; i < normals.Length; i++) if (normals[i].Length > 0) normals[i] /= normals[i].Length;
+ var creaseIds = cage.Creases.ToHashSet(StringComparer.Ordinal);
+ var hard = edges.Where(e => creaseIds.Contains(e.Id)).Select(e => (indices[e.A], indices[e.B])).ToHashSet();
+ var mesh = new TriangleMesh(positions, normals, triangles, hard, Fingerprint(cage));
+ if (!TriangleMeshValidator.TryValidateClosed(mesh, out var topology, out var failure) || !double.IsFinite(topology.SignedVolume) || normals.Any(n => !Finite(n))) throw Error("mesh-successor-invalid", failure ?? "Mesh numeric range exhausted.");
+ // Existing validator checks incidence/volume, not directed edge winding.
+ var uses = new Dictionary<(int, int), int>();
+ for (var i = 0; i < triangles.Length; i += 3) for (var j = 0; j < 3; j++) { var a = triangles[i + j]; var b = triangles[i + (j + 1) % 3]; var key = a < b ? (a, b) : (b, a); uses[key] = uses.GetValueOrDefault(key) + (a < b ? 1 : -1); }
+ if (uses.Any(e => e.Value != 0)) throw Error("mesh-winding-invalid", "Adjacent faces must traverse shared edges in opposite directions.");
+ return mesh;
+ }
+
+ /// <summary>Shared compiler/export admission for the current 32-bit GLB/STL boundary.</summary>
+ public static MeshExportPreparation PrepareExport(SubdivisionCage cage, double maximumQuantizationMm)
+ {
+ var mesh = Evaluate(cage);
+ var encoded = mesh with { Positions = mesh.Positions.Select(p => new Point3D((float)p.X, (float)p.Y, (float)p.Z)).ToArray() };
+ if (encoded.Positions.Any(p => !Finite(new(p.X, p.Y, p.Z)))
+ || !TriangleMeshValidator.TryValidateClosed(encoded, out var topology, out _) || !double.IsFinite(topology.SignedVolume))
+ throw Error("mesh-export-precision-exhausted", "The 32-bit output coordinates cannot retain a finite closed mesh. No artifact is admitted.");
+ var deviation = mesh.Positions.Zip(encoded.Positions, (a, b) => (a - b).Length).Max();
+ if (!double.IsFinite(maximumQuantizationMm) || maximumQuantizationMm <= 0 || deviation > maximumQuantizationMm)
+ throw Error("mesh-export-precision-budget-exceeded", $"Output quantization {deviation:R}mm exceeds the inherited maximumDeviation budget {maximumQuantizationMm:R}mm. Reduce the coordinate scale or explicitly authorize a larger budget.");
+ return new(mesh, encoded, topology, deviation);
+ }
+
+ public static string Fingerprint(SubdivisionCage cage) => Hash(string.Join(";", cage.Vertices.Select(v => v.Id + ":" + v.Position.X.ToString("R", CultureInfo.InvariantCulture) + "," + v.Position.Y.ToString("R", CultureInfo.InvariantCulture) + "," + v.Position.Z.ToString("R", CultureInfo.InvariantCulture))) + "|" + string.Join(";", cage.Faces.Select(f => f.Id + ":" + string.Join(",", f.Vertices))) + "|" + string.Join(",", cage.Creases.Order(StringComparer.Ordinal)));
+ private static Point3D Average(IEnumerable<Point3D> values) { var p = values.ToArray(); return new(p.Average(x => x.X), p.Average(x => x.Y), p.Average(x => x.Z)); }
+ private static string Other(CageEdge e, string v) => e.A == v ? e.B : e.A;
+ private static bool Finite(Vector3D v) => double.IsFinite(v.X) && double.IsFinite(v.Y) && double.IsFinite(v.Z);
+ private static double RadialBound(TriangleMesh mesh, Point3D center, double radius)
+ {
+ var lower = radius; var upper = 0d;
+ for (var i = 0; i < mesh.TriangleIndices.Count; i += 3)
+ {
+ var a = mesh.Positions[mesh.TriangleIndices[i]] - center; var b = mesh.Positions[mesh.TriangleIndices[i + 1]] - center; var c = mesh.Positions[mesh.TriangleIndices[i + 2]] - center;
+ var n = (b - a).Cross(c - a); var d = a.Dot(n) / n.Length;
+ if (d <= 0) throw Error("mesh-sphere-cage-invalid", "Sphere cage triangle is not outward relative to its source center.");
+ lower = Math.Min(lower, d); upper = Math.Max(upper, Math.Max(a.Length, Math.Max(b.Length, c.Length)));
+ }
+ return Math.Max(radius - lower, Math.Abs(upper - radius));
+ }
+ private static InvalidOperationException Error(string code, string message) => new(code + ": " + message);
+}
diff --git a/docs/development/FIRMAMENT-GENERIC-SCULPTING-2026-10-18.md b/docs/development/FIRMAMENT-GENERIC-SCULPTING-2026-10-18.md
new file mode 100644
index 00000000..7d1c81ba
--- /dev/null
+++ b/docs/development/FIRMAMENT-GENERIC-SCULPTING-2026-10-18.md
@@ -0,0 +1,243 @@
+# Native exact face edits and explicit subdivision sculpting
+
+## Scope and result
+
+This pass provides a small working foundation for two distinct artifact types:
+exact native-body face grafts, and explicitly converted editable subdivision
+meshes. A failed exact operation never silently switches to a mesh. A mesh
+successor never pretends to support STEP. **Success for the bounded foundation**:
+the real CLI, serialized replay, exact STEP graft and both mesh exporters work,
+with the qualification and remaining boundaries recorded below.
+
+Source witnesses live in
+[`fixtures/Regression/GenericSculpting`](../../fixtures/Regression/GenericSculpting/README.md).
+Generated run evidence is ignored under `artifacts/local/generic-sculpting/`.
+No canonical source or existing geometry golden is rewritten for this pass.
+
+## Exact-edit ownership repair
+
+The existing imported-face adapter contained a useful bounded support graft,
+but coupled its successor to `HousingConstruction`, mounting-hole PMI and
+housing interfaces. Engineering-source BodyStates already retained arbitrary
+admitted native bodies and their source recipes; their edit owner could only
+reject or reconstruct an unrelated housing.
+
+`BoundedFaceGraft` now owns the shared geometry operation: retain topology,
+vertices, edge curves, source face bindings and shell membership; replace one
+support; reconstruct/validate pcurves; run export preflight. An edited support
+invalidates cached Boolean-composition evidence, so that evidence is cleared.
+The old imported-face API calls this same owner and retains its established
+resolved-orientation convention and housing compatibility projection.
+
+`EngineeringFaceRegionReplacer` provides a separate semantic adapter around
+that shared geometry operation, without housing reconstruction. Its admitted
+family is intentionally bounded:
+
+- One native planar four-line face, no inner loop.
+- One full-domain, non-rational bicubic Bezier patch.
+- The original affine parameter grid is retained; controls displace outward
+ along the original face normal. The selected material-side orientation is
+ checked explicitly rather than inferring it from the misleading historical
+ `ReversedOrientation` Boolean convention.
+- Every patch side explicitly names its current `EdgeN` boundary, with retained
+ endpoint/support geometry. The entire control hull fits the authored envelope.
+- `mayModify`, current face selection and unaffected preservation contracts bind
+ before emission. Neighboring supports, curves, vertices and topology remain
+ unchanged. No nearest-face or bounding-box reconstruction is used.
+
+The native source adopter exposes current face handles and authoritative face
+associations. `inspect --json` also reports edge handles and endpoint positions.
+After a graft, every alias covering the selected face is explicitly replaced by
+the named SurfacePatch. A historical face alias cannot be reused as though the
+old support were still current. The existing typed `ReplaceRegionOperation`
+and ConstructionState serializer/replayer own the operation; there is no second
+exact-edit history engine. File-based compilation retains an absolute source
+path for subsequent relative-resource replay.
+
+The exact witness starts with a 20 × 16 × 8 mm box. Its top center becomes
+8.5625 mm after the graft. Tests verify that actual surface value, unchanged
+neighbor supports and edge curves, retained topology, source correspondence,
+explicit outward orientation, STEP reimport and identical STEP after typed
+serialization/replay. It is not an unchanged box reported as a successful edit.
+
+### Metadata admission
+
+The source-level adapter rejects imported engineering sources, raw STEP PMI
+without a complete editable projection, and edits to faces carrying PMI or an
+assembly interface whose successor meaning is unqualified. Their predecessor
+retains its complete geometry and metadata. Unaffected projected associations
+are retained by exact face identity. It does not drop annotations, reuse housing
+PMI, or claim that old dimensions remain valid on a changed face.
+
+G1/G2 face grafts, arbitrary control nets, holes in the selected face and global
+`NoSelfIntersection` proof remain explicit rejections. The historical imported
+graft remains available through its own bounded C# contract; this pass does not
+claim unrestricted imported-product editing.
+
+## Explicit mesh representation
+
+`MeshState` is owned by the existing Sculpting frontend and existing unified
+AST/field-consumption infrastructure. Conversion takes an exact BodyState or
+SculptState. A successor takes a MeshState. Mesh states never enter the BRep
+state dictionary, and no exact operation implicitly converts them back.
+
+The editable authority is a welded quad cage with stable vertex/face identities,
+sharp edges and derivation provenance. It is not a smoothed copy of display
+triangles. The initial constructors are:
+
+| Constructor | Admission and conversion evidence |
+| --- | --- |
+| `Box` | Eight actual axis-aligned stock corners, six planar faces, one proven source plane per cage face. Original sharp stock edges are marked. The native cage retains the exact box boundary; output quantization must fit the budget. |
+| `Sphere` | A common exact spherical support. A welded cube-sphere lattice places controls on that sphere. A conservative finite triangle-plane radial bound must fit the explicitly authored `maximumDeviation`. |
+
+Segments are 1..16 per side. Sphere conversion is a finite approximation; its
+budget is not a certificate for an infinite subdivision limit surface. Scaling
+the resulting mesh produces an ellipsoid-like mesh, while the original exact
+sphere remains unchanged. Arbitrary BRep retopology, imported sculpt cages and
+automatic cage fitting are not implemented.
+
+Successors contain exactly one typed operation: `Subdivide`, `Move`, `Scale` or
+`Crease`. Subdivision implements finite Catmull-Clark face/edge/vertex rules,
+including fixed corners, two-edge crease stencils and inherited crease child
+edges. Existing vertex identities survive refinement; new points retain parent
+identities, and child faces retain source-face derivation. Selected edits use
+current handles, not ordering or proximity. Optional protected vertices must
+retain their exact coordinates and identities.
+
+There are hard budgets of 64 mesh states/operations, four refinement levels per
+operation and 24,576 cage faces. Refinement checks its cumulative face budget
+before allocation. Manifold admission checks edge incidence, connected vertex
+fans, directed winding, enclosure, connectedness, finite range and nondegenerate
+triangles. Move/Scale reject local face-triangle reversal relative to their
+predecessor. These checks are not a global self-intersection certificate:
+`selfIntersectionStatus` remains `NotCertified`.
+
+`MeshConstruction` retains the existing exact ConstructionState as its source
+authority and typed mesh operations under `aetheris.mesh-sculpt.v1`. Persistence
+reuses the exact serializer, with a closed mesh envelope and operation
+discriminators. Replay realizes the exact source through its existing owner,
+rebuilds the cage and applies the typed operations. Cage snapshots are evidence,
+not executable replay authority. No source macro or renderer-only deformation
+path was introduced.
+
+## Validation, exports and host boundaries
+
+The shared `PrepareExport` owner preflights the selected mesh output for the
+current 32-bit GLB/STL boundary. Precision overflow, topology collapse or
+quantization beyond the inherited `maximumDeviation` budget rejects
+in both validation and build. This check lives in the compiler/export owner,
+not a CLI-specific validator. Sphere conversion also includes encoded-coordinate
+radial deviation in its conversion bound. Explicit deformations are not required
+to remain close to the original source body; the inherited export budget bounds
+precision loss relative to the requested deformed cage. A valid mesh reports:
+
+```text
+validationLevel: MeshBuilt
+artifactKind: SubdivisionMesh
+stepExportAvailable: false
+selfIntersectionStatus: NotCertified
+```
+
+GLB reuses `AssemblyGlbExporter` with the existing mm/Z-up → m/Y-up root
+projection. It exports finite, flat-shaded triangles so sharp boundaries remain
+visible. STL reuses `BinaryStlExporter`. Both have a `.sculpt.json` sidecar with
+the cage, current edge handles, source state identity, replayable construction,
+conversion evidence and float-quantization report. STL itself carries none of
+those semantics. PMI/interfaces stay attached to the exact source; mesh
+derivation is not an assertion that engineering dimensions apply to deformation.
+
+`mesh --format stl|glb` and `build --out <file.stl|file.glb>` execute this path.
+A default STEP build rejects a mesh-only output. The retained exact state can
+be selected explicitly for STEP. STEP-based `view` and `verify` reject mesh
+outputs with a useful format diagnostic. `inspect` exposes the new states;
+editor analysis retains the existing compiler-context notice and does not
+materialize meshes on keystrokes. Interactive Helios integration is not claimed.
+
+## Qualification
+
+The frozen-code Release build, focused suites and full regression gates are
+run serially with .NET SDK 10.0.401, node reuse/shared compilation disabled and
+process-local `DOTNET_PROCESSOR_COUNT=2`. No test category or deadline changes.
+
+| Gate | Result |
+| --- | --- |
+| Release solution build | 0 errors; 30 existing dependency/nullable/WASM warnings |
+| Focused generic/existing body-state/imported-face tests | 37 passed |
+| Focused CLI tests | 15 passed |
+| Fast Core lane (`Category!=SlowCorpus`) | 1,076 passed |
+| Complete solution suite | 5,586 passed, 0 failed, 0 skipped; 20 nonempty test assemblies |
+| Recent Structural/Sculpting/BodyState/PlasticShell STEP parity | 30/30 byte-identical to the prior qualified artifacts; baseline artifact SHA verified before comparison |
+| Historical frontend geometry gate | 37/37 matched: 35 byte-identical STEP files and 2 expected rejections |
+| Canonical owner/consumer gate | 369 records: 296 owner operations, 69 consumed modules, 4 expected external-body boundaries |
+| Claude FrontendX4 | 32/32, including unchanged Chimera baseline geometry |
+| SheetMetalSyntax | 26/26; formed STEP / flat parity true |
+| SheetMetalSemantics | 29/29 |
+| New source witnesses | All three validate/inspect; exact face builds and reimports through CLI analyze; both cage sources export actual GLB and STL with provenance sidecars |
+
+The earlier complete run passed before the final precision-budget regression
+was added; it is retained as `full-before-precision-budget.log`, not substituted
+for the final gate.
+
+The final complete run includes 1,209 Core, 2,905 Firmament, 600 CLI and 150
+Modules tests. FrictionLab advertises no tests and is not counted as a passed
+test assembly. Canonical qualification exercises the actual domain owner; an
+assembly/scene inspection is not an independent mesh or STEP-hash comparison.
+The recent 30-artifact and historical 37-record gates provide the explicit
+byte-parity evidence. Their source fixtures and recorded expected hashes were
+not changed. This is local qualification, not remote CI or interactive Helios
+certification. Frozen Zig was not run because no legacy Zig compiler or build
+infrastructure changed.
+
+| New output | Vertices | Triangles | Artifact checks |
+| --- | ---: | ---: | --- |
+| Box cage, refined and edited | 98 | 192 | GLB and STL; connected, outward, watertight |
+| Sphere cage, refined and scaled | 386 | 768 | GLB and STL; connected, outward, watertight |
+| Exact face graft STEP | 8 | n/a | Reimport: 1 body, 1 shell, 6 faces, 12 edges; top-center value 8.5625 mm asserted independently in tests |
+
+CLI tests parse the emitted GLB header/accessors/bounds and reconstruct the STL
+triangles from its binary coordinates. They replay the actual persisted sidecar
+construction and check state/geometry identity. Negative cases assert both
+validate/build rejection and absence of artifacts. Protected vertices, stale
+edges, unknown fields/statements, local foldover, cumulative refinement limits,
+float overflow and excessive finite quantization all have regression evidence.
+The original 20 × 16 × 8 mm box is retained unchanged; its sharp-cage refinement
+retains volume 2,560 mm³. Removing creases and moving a selected vertex produces
+a demonstrably different finite mesh.
+
+Reproduce from the repository root using the freshly built CLI:
+
+```powershell
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll build fixtures/Regression/GenericSculpting/exact-face.firmament --out artifacts/local/generic-sculpting/exact-face.step --json
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll mesh fixtures/Regression/GenericSculpting/box-cage.firmament --format glb --output artifacts/local/generic-sculpting/box-cage.glb --json
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll mesh fixtures/Regression/GenericSculpting/sphere-cage.firmament --format stl --output artifacts/local/generic-sculpting/sphere-cage.stl --json
+```
+
+Final evidence includes `release-build.log`, `focused.log`, `cli-focused.log`,
+`fast.log`, `full.log`, `test-summary.json`, `domain-parity.json`,
+`historical/comparison.json`, `canonical/qualification.json`, the authoring-corpus
+logs, `mesh-summary.json` and the actual new artifacts/sidecars. The local
+`qualify-corpus.ps1` records the serial corpus commands and baseline comparisons.
+All task .NET hosts exited after qualification; no background service, scheduled
+task or persistent compiler host was created.
+
+## Code-quality review and remaining work
+
+Review covered representation boundaries, source ownership, closed field and
+statement consumption, exact predecessor retention, material-side orientation,
+PMI refusal, stale handles, protection contracts, topology, typed persistence,
+finite allocation budgets, output precision, artifact paths and runtime hosts.
+Whitespace formatting was limited to this pass's new C# files. No new regex
+dispatch, source rewrite, diagnostic allowlist, parallel parser, background
+service or runtime state-machine framework was added. Cage kinds and operations
+are explicit deterministic choices, so ordinary dispatch does not use Judgment.
+
+The next exact-edit prerequisite is complete editable PMI/import metadata
+projection and qualification of additional face/support families. The next mesh
+extension can add deliberately authored cages or another qualified constructor;
+automatic arbitrary-BRep retopology needs a separate design and proof. General
+global self-intersection certification and new editor tools are separate work.
+None is silently substituted into this bounded pass.
+
+No user decision is needed to use this foundation. The pass does not declare
+general imported BRep editing, arbitrary retopology, complete mesh/PMI projection
+or broader X2 closure.
diff --git a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
index 22761339..0efad37f 100644
--- a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
+++ b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
@@ -450,3 +450,17 @@ a new structural collection language or complete expansion source maps. Those
remain explicit capability/consolidation boundaries under the no-new-features
constraint. See the report for qualification, compatibility changes and the
concrete remaining housing-materializer coupling.
+
+## Exact face and subdivision representation follow-up (2026-10-18)
+
+The [generic sculpting foundation](FIRMAMENT-GENERIC-SCULPTING-2026-10-18.md)
+separates exact BRep successors from explicitly requested mesh successors.
+This extends the bounded DOMAIN-02 capability disposition; it does not erase
+the remaining imported-product/PMI projection prerequisite.
+
+| Decision | Disposition |
+| --- | --- |
+| Native exact face editing | Reuse the shared bounded support graft with current face/edge bindings, a bicubic graph, preservation contracts and typed replay. No housing reconstruction. Unsupported metadata/continuity/intersection claims reject. |
+| `MeshState` | Explicit box/sphere cage conversion and finite Catmull-Clark editing under the existing Sculpting AST owner. One operation per successor, stable parent-derived handles and protected vertices. |
+| Output and precision | Mesh successors are STL/GLB artifacts, never implicit STEP. Validation reports `MeshBuilt` and unavailable STEP output. `maximumDeviation` bounds conversion and inherited output quantization; deformations remain explicit. |
+| Future boundaries | Arbitrary BRep retopology, new cage constructors, full PMI/import metadata succession, global mesh self-intersection proof and interactive editing remain separate qualification work. No silent fallback or implied X2 closure. |
diff --git a/docs/public/firmament/sculpting.md b/docs/public/firmament/sculpting.md
index 2249f6fc..be1f874d 100644
--- a/docs/public/firmament/sculpting.md
+++ b/docs/public/firmament/sculpting.md
@@ -16,6 +16,14 @@ Sculpting is a lower-authority escape hatch for geometry that an engineering fea
## Body states
+There are now two explicit representations. `BodyState` / `SculptState` retain
+exact BRep authority and can export STEP within their admitted capabilities.
+`MeshState` converts a qualified box or sphere into a real subdivision control
+cage, then supports finite Catmull-Clark refinement, creases, vertex movement
+and positive scaling. It exports STL or GLB with a replay/provenance sidecar;
+it cannot export STEP. The source exact body remains unchanged. See the
+[complete syntax and examples](syntax.md#exact-face-editing-and-explicit-mesh-sculpting).
+
Every accepted operation consumes exactly one immutable semantic `BodyState` and produces a new one:
```text
@@ -56,13 +64,41 @@ ordinary engineering source for production annotation policy.
| HoleFeature | Housing top/footprint frame; retains an existing east-attached SectionChain across repeated holes. |
| AddSectionChain / RemoveSectionChain | One qualified housing attachment or through-duct construction. |
-These materializers do not yet graft arbitrary operations onto arbitrary BReps.
+These housing materializers do not graft arbitrary operations onto arbitrary BReps.
They reject engineering-source bodies with
`bodystate-operation-capability-unsupported`. A reconstruction that cannot
retain an earlier SectionChain rejects with
`bodystate-history-capability-unsupported`; the predecessor remains authoritative.
No operation may silently remove an earlier attachment or duct.
+The engineering-source `ReplaceRegion` adapter has a bounded exact graft owner.
+It admits a full-domain non-rational bicubic Bezier graph over one native planar
+four-line face, with outward displacement on its unchanged affine parameter
+grid. `inspect --json` reports current `FaceN` handles, `EdgeN` boundaries and
+endpoint positions. Bind all four patch boundaries explicitly, authorize the
+target with `mayModify`, and name unaffected face associations in `preserve`.
+The [complete example](../../../fixtures/Regression/GenericSculpting/exact-face.firmament)
+retains all edge curves, vertices, topology, neighboring supports and source face
+provenance. Its replaced face alias becomes stale; the named patch is the
+current successor. Replay uses the existing typed `ReplaceRegion` operation.
+
+This source-level adapter rejects imported engineering sources, raw STEP PMI
+without an editable projection, and edits to faces carrying qualified PMI or
+assembly interfaces. The predecessor keeps its complete source/PMI. It does not
+pretend to preserve associations by proximity or by changing a dimension's
+meaning. The older bounded imported-face API retains its separate compatibility
+contract. G1/G2 face grafts, holes in the edited face, arbitrary control-net
+deformation and global `NoSelfIntersection` proof are outside this adapter;
+those requests reject explicitly. Exact graph edits check control-hull locality,
+boundary correspondence, pcurves, orientation and BRep export preflight.
+
+Mesh sculpting likewise reports `selfIntersectionStatus: NotCertified`.
+Enclosure, directed winding, connected vertex fans and local foldover checks
+are useful checks, not a global collision certificate. Protected cage vertices
+are exact successor contracts. Finite evaluated quads become triangles at
+export; GLB uses flat per-triangle normals so crease boundaries remain visible.
+No source is silently reconstructed as a housing or converted to a mesh.
+
The direct C# imported-face adapter retains imported topology/provenance and
supports its bounded support-surface graft. It does not carry a replayable
source recipe and exposes no `ConstructionAuthority`; whole-housing edits on
diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.md
index 2f03b7ab..fb050e73 100644
--- a/docs/public/firmament/syntax.md
+++ b/docs/public/firmament/syntax.md
@@ -976,6 +976,96 @@ The existing surface-edit materializers still have explicit topology/support
requirements. An unsupported edit or history combination rejects before it can
replace earlier geometry. See the [operation boundaries](sculpting.md).
+### Exact face editing and explicit mesh sculpting
+
+`ReplaceRegion` can now graft a bounded patch onto an engineering-source
+BodyState. Inspect the state for current `FaceN` and `EdgeN` handles, then bind
+every patch side explicitly. The initial adapter admits an outward, non-rational
+bicubic Bezier graph over a planar four-line face. It retains all topology,
+edge curves, vertices and neighboring supports. A replaced face handle becomes
+stale; its named SurfacePatch is the successor. Raw STEP PMI that lacks a complete
+editable projection rejects before editing. See the complete
+[exact-face example](../../../fixtures/Regression/GenericSculpting/exact-face.firmament).
+Imported engineering sources and edits to PMI/interface-bearing faces remain
+outside this native adapter's qualified contract.
+
+Use `MeshState` for explicit conversion to an editable subdivision control cage.
+It produces a mesh artifact, not an exact BodyState. There is no automatic
+mesh fallback when an exact edit fails.
+
+**Complete file — convert a box, soften its creases and edit its cage:**
+
+```firmament
+Model CageSculpt {
+ units: mm
+ Box stock { size: [20mm, 16mm, 8mm] }
+ BodyState exact { input: stock }
+ MeshState cage {
+ input: exact
+ cage: Box
+ segments: 1
+ maximumDeviation: 0.01mm
+ }
+ MeshState smooth {
+ input: cage
+ Crease { edges: [All]; mode: Smooth }
+ }
+ MeshState refined { input: smooth; Subdivide { levels: 2 } }
+ MeshState edited {
+ input: refined
+ preserve: [v1]
+ Move { vertices: [v0]; offset: [0mm, 0mm, 1mm] }
+ }
+ output: edited
+}
+```
+
+`cage: Box` requires a pure axis-aligned box, and starts with sharp stock edges.
+`cage: Sphere` requires a pure exact spherical support; it creates a welded
+cube-sphere quad cage. `segments` is 1..16 per cube side (default 1 for Box,
+4 for Sphere). Required `maximumDeviation` bounds the finite conversion's
+radial error for Sphere, including output quantization; the native Box cage
+retains its exact boundary. The same budget limits 32-bit coordinate
+quantization for every selected mesh successor. It does not constrain an
+explicit Move/Scale to stay near the original body. A tighter
+sphere budget may require more segments. This is not arbitrary BRep retopology
+or a certificate for the infinite subdivision limit surface.
+
+Each successor has exactly one operation:
+
+| Operation | Fields | Meaning |
+| --- | --- | --- |
+| `Subdivide` | `levels: 1` | Finite Catmull-Clark refinement, 1..4 levels per operation |
+| `Move` | `vertices: [v0]`, `offset: [0mm, 0mm, 1mm]` | Move selected current cage vertices in world space |
+| `Scale` | `vertices: [All]`, `factor: [1.5, 1, 0.75]`, `origin: [0mm, 0mm, 0mm]` | Explicit positive scale about a required origin; factors are dimensionless |
+| `Crease` | `edges: [All]`, `mode: Sharp` or `Smooth` | Mark or unmark current cage edges as sharp |
+
+Use `inspect --json` for current vertex/edge identities; edge handles are
+derived from their endpoint identities. `[All]` is an explicit whole-cage
+selection. Existing vertex IDs survive refinement; new edge/face points have
+parent-derived IDs. Old edge handles are replaced by their child edges.
+Optional `preserve: [v1]` requires those input vertices to retain their exact
+coordinates and identities in that successor. A conflict rejects atomically.
+There are at most 64 mesh states/operations and 24,576 cage faces.
+
+The [sphere example](../../../fixtures/Regression/GenericSculpting/sphere-cage.firmament)
+uses `Scale` to create an ellipsoid-like subdivision mesh. Its original sphere
+remains an unchanged exact BodyState. Mesh states carry their source body,
+conversion evidence, typed construction recipe and edit history. Finite meshes
+are checked for enclosure, directed winding and local edit foldover. Global
+self-intersection is **not certified**; unsupported requirements are errors.
+
+Export a mesh output with `aetheris mesh part.firmament --format glb` or
+`--format stl`, or `build --out artifacts/local/part.glb`. GLB is binary glTF 2.0.
+Each output has a `.sculpt.json` sidecar with the cage and replayable construction.
+STL does not embed those semantics, so retain its sidecar. GLB uses the existing
+millimeter/Z-up to meter/Y-up projection and finite, flat-shaded triangles.
+Both formats use 32-bit coordinates; export reports quantization and rejects
+precision collapse. `validate` reports `MeshBuilt`, `SubdivisionMesh` and
+`stepExportAvailable: false`. A normal STEP build of that output rejects;
+select the retained exact state as `output` when STEP is required. The existing
+STEP-based `view`/`verify` commands explicitly reject mesh-only outputs.
+
### Inventory: organize module dependencies
Use a short `include "parts/bolt";` when shared declarations are convenient. For
diff --git a/docs/public/reference/diagnostics.md b/docs/public/reference/diagnostics.md
index 8a760954..102ca161 100644
--- a/docs/public/reference/diagnostics.md
+++ b/docs/public/reference/diagnostics.md
@@ -4,6 +4,32 @@ Generic V2 build/validation errors use structured objects with `code`, `severity
Unknown canonical statements and Box fields are errors. `profile-layout-placement-unsupported` rejects unsupported Concept Struct layout planes instead of substituting XY. Use a traced Construction Plane for supported oriented profile workflows. `SemanticSourceNotFound` preserves the missing source and the provenance explanation. An accidental through-depth Pocket fails; explicit `end: ThroughAll` selects the admitted through cut. Box top-boundary Fillet with disjoint ThroughAll shaft/counterbore holes is supported; `CombinedFeatureInteractionUnsupported` identifies a hole touching the finish band or another hole. Unsupported combined selectors retain `CombinedFeatureSelectionLost` at the EdgeFinish declaration.
+## Exact face grafts and subdivision meshes
+
+- `surf-face-pmi-projection-unsupported` / `surf-face-associated-target-unsupported`:
+ this edit cannot retain the required PMI/interface meaning. The predecessor
+ remains authoritative; no metadata is silently dropped.
+- `surf-face-boundary-mismatch` / `surf-face-graph-unsupported`: retain the named
+ four-line boundary and affine parameter grid, or use explicit mesh sculpting
+ for the broader deformation. `FaceN` handles become stale after replacement.
+- `mesh-conversion-deviation-exceeded`: increase sphere cage segments or
+ explicitly authorize a larger finite conversion budget.
+- `mesh-vertex-unresolved` / `mesh-edge-unresolved`: inspect the current cage;
+ historical handles are not rebound by proximity.
+- `mesh-preservation-failed` / `mesh-local-foldover`: the edit violates its
+ protected vertex contract or reverses a predecessor face triangle.
+- `mesh-subdivision-budget-exceeded`: refinement exceeds 24,576 faces.
+- `sculpt-mesh-export-format-unsupported`: the selected MeshState produces STL
+ or GLB, not STEP. Validation reports `MeshBuilt` and
+ `stepExportAvailable: false`; select an exact state for STEP.
+- `mesh-export-precision-exhausted`: 32-bit coordinates cannot retain a finite
+ closed output mesh. No new artifact is emitted.
+- `mesh-export-precision-budget-exceeded`: coordinate quantization exceeds the
+ inherited `maximumDeviation` budget, even though topology may remain closed.
+
+Global mesh self-intersection remains `NotCertified`, independent of successful
+topology and local foldover checks.
+
## Profile rim finishes
- `ProfileBoundaryEdgeFinishSequenceUnsupported`: this Profile/Compose owner
diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.md
index 9ddf88ef..9b72db1e 100644
--- a/docs/public/reference/supported-features.md
+++ b/docs/public/reference/supported-features.md
@@ -31,6 +31,7 @@
| Edge finishes/hollow/lattice | Bounded | Documented admitted chamfer/fillet, hollow, and cubic-truss routes; not arbitrary topology |
| Templates/Records/Static/Tables | Supported | Typed compile-time specialization, finite data, `with`, and `Require` |
| STEP AP242 export | Bounded | Deterministic single-body routes plus semantic PMI; unsupported intent fails loudly |
+| Exact face graft / subdivision sculpting | Bounded | Native planar four-line face replacement by an outward bicubic graph; explicit box/sphere quad cages, Catmull-Clark refinement, creases, protected vertices, movement and scaling. MeshState exports STL/GLB with replay/provenance sidecars, never STEP; arbitrary BRep retopology and global mesh self-intersection proof are not implemented. See [sculpting](../firmament/sculpting.md). |
| STEP import / inlineSTEP | Bounded | Canonical single-body topology and recognized identities; arbitrary containment and multi-root bodies are not native-part promises |
| PMI authoring and presentation | Bounded | Model authoring qualifies plane Datum and toleranced shaft HoleDiameter; manufacturing AP242 workflows additionally qualify documented dimensions, position controls, annotations, and geometry associations; this is not general PMI authoring |
| Sheet Metal authoring | Bounded | Base/flanges/bends and planar circular holes/cuts, formed STEP, flat STEP/SVG, K-factor, DFM, semantic regions; Model `Hole<Counterbore>` / `Hole<Countersink>` syntax is rejected |
diff --git a/fixtures/Regression/GenericSculpting/README.md b/fixtures/Regression/GenericSculpting/README.md
new file mode 100644
index 00000000..9983ecfa
--- /dev/null
+++ b/fixtures/Regression/GenericSculpting/README.md
@@ -0,0 +1,18 @@
+# Exact face graft and explicit subdivision sculpting
+
+- `exact-face.firmament`: a native engineering box with one bicubic graph graft.
+ The top center is 8.5625 mm rather than 8 mm. All input topology, curves,
+ vertices and neighboring supports remain retained; the output is exact STEP.
+- `box-cage.firmament`: exact box conversion, explicit crease removal, two finite
+ Catmull-Clark levels and one selected-vertex movement with a protected neighbor.
+- `sphere-cage.firmament`: budgeted cube-sphere cage conversion, refinement and
+ explicit scaling into an ellipsoid-like mesh. The exact source sphere remains
+ retained and unchanged. The output is GLB/STL, not STEP.
+
+`GenericSculptingTests` checks shape changes, exact preservation, stale handles,
+crease succession, bounded resources and serialized replay. CLI tests validate
+actual GLB/STL geometry, float precision, provenance sidecars, validation levels,
+unknown fields/statements, protected vertices, local foldover, incompatible
+formats and atomic rejection. No global self-intersection certification is claimed.
+
+Generated evidence belongs under `artifacts/local/generic-sculpting/`.
diff --git a/fixtures/Regression/GenericSculpting/box-cage.firmament b/fixtures/Regression/GenericSculpting/box-cage.firmament
new file mode 100644
index 00000000..17ebd682
--- /dev/null
+++ b/fixtures/Regression/GenericSculpting/box-cage.firmament
@@ -0,0 +1,10 @@
+Model CageSculpt {
+ units: mm
+ Box stock { size: [20mm, 16mm, 8mm] }
+ BodyState exact { input: stock }
+ MeshState cage { input: exact; cage: Box; segments: 1; maximumDeviation: 0.01mm }
+ MeshState smooth { input: cage; Crease { edges: [All]; mode: Smooth } }
+ MeshState refined { input: smooth; Subdivide { levels: 2 } }
+ MeshState edited { input: refined; preserve: [v1]; Move { vertices: [v0]; offset: [0mm, 0mm, 1mm] } }
+ output: edited
+}
diff --git a/fixtures/Regression/GenericSculpting/exact-face.firmament b/fixtures/Regression/GenericSculpting/exact-face.firmament
new file mode 100644
index 00000000..aefe9310
--- /dev/null
+++ b/fixtures/Regression/GenericSculpting/exact-face.firmament
@@ -0,0 +1,27 @@
+Model ExactFaceGraft {
+ units: mm
+ Box stock { size: [20mm, 16mm, 8mm] }
+ BodyState exact { input: stock }
+ SurfacePatch crown {
+ degree: [3, 3]
+ domain: [0, 1, 0, 1]
+ knotsU: [0, 0, 0, 0, 1, 1, 1, 1]
+ knotsV: [0, 0, 0, 0, 1, 1, 1, 1]
+ controlRow: [[-10mm, -8mm, 8mm], [-10mm, -2.6666666666666665mm, 8mm], [-10mm, 2.6666666666666665mm, 8mm], [-10mm, 8mm, 8mm]]
+ controlRow: [[-3.3333333333333335mm, -8mm, 8mm], [-3.3333333333333335mm, -2.6666666666666665mm, 9mm], [-3.3333333333333335mm, 2.6666666666666665mm, 9mm], [-3.3333333333333335mm, 8mm, 8mm]]
+ controlRow: [[3.3333333333333335mm, -8mm, 8mm], [3.3333333333333335mm, -2.6666666666666665mm, 9mm], [3.3333333333333335mm, 2.6666666666666665mm, 9mm], [3.3333333333333335mm, 8mm, 8mm]]
+ controlRow: [[10mm, -8mm, 8mm], [10mm, -2.6666666666666665mm, 8mm], [10mm, 2.6666666666666665mm, 8mm], [10mm, 8mm, 8mm]]
+ Boundary South { existing: Edge2; continuity: G0 }
+ Boundary East { existing: Edge5; continuity: G0 }
+ Boundary North { existing: Edge8; continuity: G0 }
+ Boundary West { existing: Edge11; continuity: G0 }
+ }
+ SculptState raised {
+ input: exact
+ ReplaceRegion { target: Face2; patch: crown; influenceEnvelope: [-10mm, -8mm, 8mm, 10mm, 8mm, 9mm] }
+ mayModify: [Face2]
+ preserve: [Face1]
+ require: [ClosedManifold, OrientationConsistency]
+ }
+ output: raised
+}
diff --git a/fixtures/Regression/GenericSculpting/sphere-cage.firmament b/fixtures/Regression/GenericSculpting/sphere-cage.firmament
new file mode 100644
index 00000000..730f8dc2
--- /dev/null
+++ b/fixtures/Regression/GenericSculpting/sphere-cage.firmament
@@ -0,0 +1,12 @@
+Model EllipsoidSculpt {
+ units: mm
+ Sphere stock { radius: 10mm }
+ BodyState exact { input: stock }
+ MeshState cage { input: exact; cage: Sphere; segments: 4; maximumDeviation: 1mm }
+ MeshState refined { input: cage; Subdivide { levels: 1 } }
+ MeshState stretched {
+ input: refined
+ Scale { vertices: [All]; factor: [1.5, 1, 0.75]; origin: [0mm, 0mm, 0mm] }
+ }
+ output: stretched
+}