Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add display mesh and STEP export support for standalone parts

Yuechen Li2f5cba0e2247
diff --git a/Aetheris.CLI.Tests/PartDisplayMeshCommandTests.cs b/Aetheris.CLI.Tests/PartDisplayMeshCommandTests.cs
new file mode 100644
index 00000000..682f42d8
--- /dev/null
+++ b/Aetheris.CLI.Tests/PartDisplayMeshCommandTests.cs
@@ -0,0 +1,43 @@
+using System.Text.Json;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class PartDisplayMeshCommandTests
+{
+ [Fact]
+ public void DisplayAndExactStepComeFromTheAdmittedPartAndRejectWithoutReplacingArtifacts()
+ {
+ var root = new DirectoryInfo(AppContext.BaseDirectory);
+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx"))) root = root.Parent;
+ Assert.NotNull(root);
+ var directory = Path.Combine(root!.FullName, "artifacts/local/tests/part-display", Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(directory);
+ var fixture = Path.Combine(root.FullName, "fixtures/Canonical/Learn/01-plate.firmament");
+ var display = Path.Combine(directory, "part.json");
+ var step = Path.Combine(directory, "part.step");
+ var stdout = new StringWriter(); var stderr = new StringWriter();
+ int Run(string source) => CliRunner.Run(["mesh", source, "--format", "display-json", "--output", display, "--step-output", step, "--json"], stdout, stderr);
+ Assert.True(Run(fixture) == 0, stdout + stderr.ToString());
+ using var document = JsonDocument.Parse(File.ReadAllText(display));
+ var definition = Assert.Single(document.RootElement.GetProperty("definitions").EnumerateArray());
+ Assert.Equal("mm", document.RootElement.GetProperty("units").GetString());
+ var positions = definition.GetProperty("positions").EnumerateArray().Select(v => v.GetDouble()).ToArray();
+ Assert.Equal(positions.Length, definition.GetProperty("normals").GetArrayLength());
+ Assert.True(definition.GetProperty("indices").GetArrayLength() > 0);
+ Assert.Equal(-40, positions.Where((_, i) => i % 3 == 0).Min(), 8);
+ Assert.Equal(40, positions.Where((_, i) => i % 3 == 0).Max(), 8);
+ Assert.Equal(8, positions.Where((_, i) => i % 3 == 2).Max(), 8);
+ var imported = Step242Importer.ImportBody(File.ReadAllText(step));
+ Assert.True(imported.IsSuccess);
+ Assert.Equal(7, imported.Value.Topology.Faces.Count());
+ var acceptedDisplay = File.ReadAllBytes(display); var acceptedStep = File.ReadAllBytes(step);
+ var invalid = Path.Combine(directory, "invalid.firmament");
+ File.WriteAllText(invalid, File.ReadAllText(fixture).Replace("diameter: 8mm", "diameter: -8mm"));
+ Assert.NotEqual(0, Run(invalid));
+ Assert.Equal(acceptedDisplay, File.ReadAllBytes(display));
+ Assert.Equal(acceptedStep, File.ReadAllBytes(step));
+ Assert.NotEqual(0, CliRunner.Run(["mesh", fixture, "--format", "obj", "--step-output", step], stdout, stderr));
+ Assert.Equal(acceptedStep, File.ReadAllBytes(step));
+ }
+}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index df452aff..e022e288 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>] [--locked] [--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 MeshUsage = "Usage: aetheris mesh <file.firmament|file.firmfixture|file.firmasm|file.step> [--format stl|obj|glb|assembly-json|display-json] [--output <path>] [--step-output <path> (display-json only)] [--debug-ir <path>] [--json] (glb: MeshState sources)";
private const string ValidateUsage = "Usage: aetheris validate <file.firmament|file.firmfixture> [--locked] [--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";
@@ -1379,7 +1379,7 @@ Model CanonicalPanel {
private static int RunMesh(string[] args, TextWriter stdout, TextWriter stderr)
{
if (args.Length == 0 || IsHelpFlag(args[0])) { CommandHelp.Write(stdout, MeshUsage, "Build or import a part and export a display mesh. The target format must be admitted by the compiled product.", "aetheris mesh bracket.firmament --format stl --output bracket.stl"); return args.Length == 0 ? 1 : 0; }
- var input = args[0]; var format = "stl"; string? output = null; string? debugIr = null; var json = false;
+ var input = args[0]; var format = "stl"; string? output = null; string? debugIr = null; string? stepOutput = null; var json = false;
for (var i = 1; i < args.Length; i++)
{
switch (args[i])
@@ -1387,10 +1387,17 @@ Model CanonicalPanel {
case "--format" when i + 1 < args.Length: format = args[++i]; break;
case "--output" when i + 1 < args.Length: output = args[++i]; break;
case "--debug-ir" when i + 1 < args.Length: debugIr = args[++i]; break;
+ case "--step-output" when i + 1 < args.Length: stepOutput = args[++i]; break;
case "--json": json = true; break;
default: stderr.WriteLine($"Unknown mesh option '{args[i]}'."); stderr.WriteLine(MeshUsage); return 1;
}
}
+ if (string.Equals(format, "display-json", StringComparison.OrdinalIgnoreCase))
+ {
+ if (debugIr is not null) { stderr.WriteLine("display-json does not support --debug-ir."); return 1; }
+ return PartDisplayMeshCommand.Run(input, output, stepOutput, stdout);
+ }
+ if (stepOutput is not null) { stderr.WriteLine("--step-output requires --format display-json."); return 1; }
if (string.Equals(format, "assembly-json", StringComparison.OrdinalIgnoreCase))
{
if (debugIr is not null) { stderr.WriteLine("assembly-json does not support --debug-ir."); return 1; }
diff --git a/Aetheris.CLI/PartDisplayMeshCommand.cs b/Aetheris.CLI/PartDisplayMeshCommand.cs
new file mode 100644
index 00000000..045d5947
--- /dev/null
+++ b/Aetheris.CLI/PartDisplayMeshCommand.cs
@@ -0,0 +1,66 @@
+using System.Text;
+using System.Text.Json;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament;
+using Aetheris.Kernel.Firmament.Assembly;
+
+namespace Aetheris.CLI;
+
+/// <summary>One admitted standalone part, projected through the existing display tessellator.
+/// STEP and display derive from the same build; a DCC client never reconstructs engineering geometry.</summary>
+internal static class PartDisplayMeshCommand
+{
+ public static int Run(string input, string? output, string? stepOutput, TextWriter stdout)
+ {
+ int Fail(IEnumerable<string> diagnostics)
+ {
+ stdout.WriteLine(JsonSerializer.Serialize(new { success = false, command = "mesh", diagnostics }));
+ return 1;
+ }
+ if (!Path.GetExtension(input).Equals(".firmament", StringComparison.OrdinalIgnoreCase))
+ return Fail(["display-json requires a standalone Firmament part (.firmament). Use assembly-json for assemblies."]);
+ var destination = Path.GetFullPath(output ?? Path.Combine("artifacts", "local", "mesh", Path.GetFileNameWithoutExtension(input) + ".display.json"));
+ if (stepOutput is not null && Path.GetFullPath(stepOutput).Equals(destination, StringComparison.OrdinalIgnoreCase))
+ return Fail(["Display JSON and STEP need different output paths."]);
+ var temporary = Path.Combine(Path.GetTempPath(), "aetheris-display-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(temporary);
+ try
+ {
+ var build = FirmamentBuildAndExport.Run(input, Path.Combine(temporary, "part.step"));
+ if (!build.IsSuccess) return Fail(build.Diagnostics.Select(d => d.Message));
+ var export = build.Value.Export;
+ var body = export.RuntimeBody;
+ if (body is null)
+ {
+ var imported = Step242Importer.ImportBody(export.StepText);
+ if (!imported.IsSuccess || imported.Value is null) return Fail(imported.Diagnostics.Select(d => d.Message));
+ body = imported.Value;
+ }
+ var entity = export.RuntimeCorrespondence?.BodyStableId ?? export.ExportedFeatureId;
+ if (string.IsNullOrWhiteSpace(entity)) entity = Path.GetFileNameWithoutExtension(input);
+ var definition = AssemblyDisplayMeshExporter.PrepareDefinition("definition:" + entity, entity, body,
+ externalStep: export.ExportedBodyCategory == "inline-step");
+ var display = new AssemblyDisplayMeshDocument("aetheris/display-mesh/1", Path.GetFileNameWithoutExtension(input), "mm",
+ [definition], [new(entity + ":occurrence", entity, null, definition.Id,
+ [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1], entity)]);
+ // Finish compilation and tessellation before replacing any caller artifact.
+ var serialized = AssemblyDisplayMeshExporter.Serialize(display);
+ Directory.CreateDirectory(Path.GetDirectoryName(destination)!);
+ if (stepOutput is not null)
+ {
+ stepOutput = Path.GetFullPath(stepOutput);
+ Directory.CreateDirectory(Path.GetDirectoryName(stepOutput)!);
+ File.WriteAllText(stepOutput, export.StepText, new UTF8Encoding(false));
+ }
+ File.WriteAllText(destination, serialized, new UTF8Encoding(false));
+ stdout.WriteLine(JsonSerializer.Serialize(new { success = true, output = destination, stepOutput, schema = display.Schema,
+ units = display.Units, definitions = 1, occurrences = 1, triangles = definition.Indices.Length / 3 }));
+ return 0;
+ }
+ catch (Exception error) when (error is InvalidOperationException or IOException or ArgumentException)
+ {
+ return Fail([error.Message]);
+ }
+ finally { Directory.Delete(temporary, true); }
+ }
+}
diff --git a/docs/development/reports/2026-10/blender-cad-addon.md b/docs/development/reports/2026-10/blender-cad-addon.md
new file mode 100644
index 00000000..c9826703
--- /dev/null
+++ b/docs/development/reports/2026-10/blender-cad-addon.md
@@ -0,0 +1,85 @@
+# Blender CAD extension, 2026-10-31
+
+## Change
+
+Added a Windows x64 Blender 5.2 extension with a bundled self-contained CLI.
+Firmament text and explicitly selected dependencies persist inside `.blend`;
+each successful build retains exact STEP and installs the existing kernel
+display tessellation. Blender owns placement, materials, modifiers, rendering
+and independent welded mesh copies. No second parser, geometry kernel or
+long-lived server was added.
+
+The new `mesh --format display-json --step-output` CLI path admits standalone
+parts through `FirmamentBuildAndExport` and reuses
+`AssemblyDisplayMeshExporter.PrepareDefinition`. Existing `assembly-json`
+requires an assembly root, so it could not provide this standalone seam.
+Both artifacts derive from one compilation. The extension publishes only a
+complete successful process result from its private snapshot directory.
+
+Builds poll a short-lived subprocess through Blender's modal operator timer.
+Failed/cancelled builds retain accepted geometry; stale source snapshots and
+modified stored STEP are rejected. Direct generated-mesh edits require an
+explicit restore after offering an independent copy. Rebuilds preserve object
+identity, transforms, modifiers and material slots. Face assignments persist
+only when connectivity matches. Source navigation starts at the first line.
+
+## Evidence
+
+- Full Release solution build: zero errors, 38 warnings.
+- Fast core lane: 1,168 passed. Full solution lane: 6,317 passed, zero failed,
+ two existing DrawingNotes tests skipped; FrictionLab reports no discovered
+ tests. Includes the new real-CLI display/STEP preservation regression.
+- Installed and validated the complete ZIP in isolated Blender 5.2.2 LTS
+ profiles, with no developer compiler override. Qualified actual source
+ builds, parameter updates, last-good geometry retention, stale STEP refusal,
+ source changes during compilation, mesh-copy independence/manifold seams,
+ managed-mesh edit refusal/restore, scene unit conversion and rendering.
+- Saved and reopened the actual `.blend`, removed original include files,
+ rebuilt both the main part and the packed-include part, and exported STEP.
+ Independent bundled CLI reimport measured exactly
+ `39597.87614034051 mm³` for the 100 × 50 × 8 mm plate with an 8 mm through hole;
+ bounds are `[-50,-25,0]` to `[50,25,8]` mm.
+- Native desktop pass: sidebar controls, Fit CAD Part, source/view split,
+ Text Editor modification from 100 to 120 mm and asynchronous header rebuild
+ visibly updated the body while keeping its material/placement. Undo restored
+ accepted geometry and correctly marked the edited source stale. Source
+ opening initially appeared blank at EOF; fixed initial cursor/scroll position
+ before the final package run. Automated qualification uses real Blender
+ operators in background mode; interactive cancellation/redo are not claimed
+ as separately qualified.
+- Repository layout guard and `git diff --check` passed.
+
+Local evidence lives under `artifacts/local/blender-addon/`: full build/test
+logs, `final-qualification/qualification.json`, `qualified.blend`, STEP
+artifacts and `cad-in-blender.png`. Generated files remain ignored.
+
+Final ZIP: `aetheris_cad-0.1.0-windows-x64.zip`, 49,649,592 bytes,
+SHA-256 `a2ae3df02a25f2460ddec13b7616af1d4f60153c4c0a917ceb69526c2b021ab9`.
+Its `package-info.json` records the bundled runtime version and file hashes.
+
+## Reproduce
+
+Run from the repository root, with Python, .NET 10 and Blender 5.2 available:
+
+```powershell
+dotnet build Aetheris.slnx -c Release -m:1 -nr:false -p:UseSharedCompilation=false
+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build --filter 'Category!=SlowCorpus'
+dotnet test Aetheris.slnx -c Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1
+python scripts/package-blender-addon.py
+python scripts/qualify-blender-addon.py --blender 'C:\Program Files\Blender Foundation\Blender 5.2\blender.exe' --output artifacts/local/blender-addon/final-qualification
+```
+
+The qualification script installs into its own `BLENDER_USER_RESOURCES`,
+checks subprocess exit status using `--python-exit-code 1`, runs create/reopen
+phases, then independently measures exported STEP. Use `--runtime-dir` with
+the packager only to reuse an already published current CLI after Python-only
+changes. User installation and workflow are in `docs/public/blender.md`.
+
+## Verdict and limits
+
+Success for a first packaged source-authored CAD workflow inside Blender.
+The extension supports multiple independent standalone BRep parts. Assembly
+and Scene roots, interactive CAD face/edge feature editing, mesh-to-BRep
+conversion and non-Windows packages are outside this version. Exact STEP is
+exported in source coordinates; Blender placement/modifiers are presentation.
+No manufacturing accuracy claim is made for the display mesh or its copy.
diff --git a/docs/public/README.md b/docs/public/README.md
index 0db3a52c..7f81d485 100644
--- a/docs/public/README.md
+++ b/docs/public/README.md
@@ -85,6 +85,7 @@ cannot honour.
### Tools and integration
+- [Aetheris CAD for Blender](blender.md): exact Firmament parts, editable mesh copies and STEP export
- Helios: [sketching](firmament/sketcher.md), [AI author](firmament/ai-author.md),
[engineering references](firmament/engineering-assistance.md)
- Cadmata: [overview](cadmata/overview.md), [measurement](cadmata/measurement.md),
diff --git a/docs/public/blender.md b/docs/public/blender.md
new file mode 100644
index 00000000..9f7b2c8c
--- /dev/null
+++ b/docs/public/blender.md
@@ -0,0 +1,109 @@
+# Aetheris CAD for Blender
+
+Aetheris CAD adds exact, code-authored parts to Blender. Edit Firmament in
+Blender's Text Editor, build a BRep with the bundled local Aetheris compiler,
+and use Blender for placement, materials, mesh modeling and rendering. The
+source and accepted exact STEP body travel with the `.blend` file.
+
+## Install and build a first part
+
+The extension ZIP targets **Blender 5.2 on Windows x64**. In Preferences,
+open **Get Extensions**, use its menu to **Install from Disk**, select the
+complete `aetheris_cad-0.1.0-windows-x64.zip`, and enable Aetheris CAD.
+The ZIP includes the compiler runtime; no .NET SDK, account or server is needed.
+
+1. In the 3D View, choose **Add → Aetheris CAD Part**. This creates a CAD
+ container and opens its Firmament source in a Text Editor beside the view.
+2. Click **Build CAD** in the Text Editor header. The first successful build
+ frames the part in the viewport. The **Aetheris** tab in the sidebar
+ (toggle the sidebar with `N`) contains the same build and export controls.
+3. Change a dimension in the source and click **Build CAD** again. Use this
+ command for Firmament; Blender's **Run Script** command runs Python.
+4. Save the `.blend` normally. Reopen it with the extension enabled to continue
+ editing, rebuilding or exporting the exact body.
+
+The starter is the complete [plate lesson](../../fixtures/Canonical/Learn/01-plate.firmament):
+
+```firmament
+Model Plate {
+ units: mm
+ Box stock { size: [80mm, 50mm, 8mm] }
+ Modify stock {
+ Hole<Shaft> mount {
+ on: +Z
+ center: Point2(0mm, 0mm)
+ diameter: 8mm
+ end: ThroughAll
+ }
+ }
+}
+```
+
+## Editing and mesh modeling
+
+The Firmament source owns the exact part. A successful build updates the
+managed display mesh in place, preserving its Blender object, placement,
+modifiers and material slots. Per-face material assignments survive when
+triangle connectivity is unchanged; otherwise faces return to material slot
+zero and the build status reports the reset.
+
+Use **Create Editable Mesh Copy** for Blender vertex editing, sculpting or
+mesh booleans. This creates an independent mesh with welded seams. Changes
+to it do not change the Firmament source or exact STEP body. If you edit the
+managed mesh directly, the next build refuses to overwrite those edits.
+Create a mesh copy to keep them, then choose **Restore CAD Mesh** explicitly.
+
+**Fit CAD Part** frames the selected CAD part. Selecting either its container,
+its managed mesh or its associated source in the Text Editor identifies the
+part for build/export commands. A scene may contain multiple independent CAD
+parts.
+
+## Existing source and dependencies
+
+Use **Open Firmament Part** in the Aetheris sidebar to copy a `.firmament`
+document into the scene. Use **Add Project File** for each include, STEP
+asset or other dependency. Files below the original source folder keep their
+relative paths; files selected elsewhere use their filename. The project file
+list lets you change the relative path to match the source reference.
+
+The extension packs only explicitly selected files, never a whole directory.
+Paths must be relative, unique ignoring case, and must not contain `..`.
+A selected dependency may be at most 32 MiB; a build snapshot may total at
+most 64 MiB. Source, text dependencies and encoded binary dependencies are
+saved as Blender Text datablocks. **Unlink Project File** removes the project
+reference but retains its Text datablock. Reopening and rebuilding does not
+require the original files on disk.
+
+## Builds and exact export
+
+Builds use a short-lived local compiler process and keep the UI responsive.
+Press `Esc` to cancel. An invalid source, missing dependency or failed build
+keeps the last accepted geometry; **Open Diagnostics** shows the error.
+Changing the source during a build prevents that older result from replacing
+the part.
+
+**Export Exact STEP** writes the accepted BRep in **Firmament source
+coordinates**. Blender placement, scale, modifiers, material changes and
+editable mesh copies are presentation changes and are not baked into STEP.
+Export is refused when the source/dependencies have changed since the last
+successful build or the stored STEP has been altered.
+
+Firmament millimetres are converted using the scene's unit scale at build
+time. Rebuild after changing the scene unit scale. Source dimensions and
+STEP dimensions retain their physical units.
+
+## Limits
+
+Each CAD part builds one standalone BRep model through the existing compiler.
+Assembly and Scene roots and mesh-only model results are not supported by this
+extension. Geometry support is the same as the Aetheris compiler; incomplete
+display tessellation is rejected. There is no mesh-to-BRep conversion,
+interactive face/edge CAD feature editing, or Firmament completion/highlighting
+in Blender's Text Editor.
+
+The compiler override in extension preferences is for developers. Leave it
+empty to use the runtime included in the package.
+
+See [Learn Firmament](learn/README.md), [geometry and features](firmament/geometry.md)
+and [STEP import](firmament/step-import.md) for source modeling and supported
+operations.
diff --git a/docs/public/reference/cli.md b/docs/public/reference/cli.md
index 8c1bf2c8..e4d41937 100644
--- a/docs/public/reference/cli.md
+++ b/docs/public/reference/cli.md
@@ -71,6 +71,14 @@ retaining the structured polygon representation.
## Assembly display meshes
+For a standalone BRep part, use
+`aetheris mesh part.firmament --format display-json --output artifacts/local/part.display.json --step-output artifacts/local/part.step --json`.
+This exports the shared display schema in millimetres with one definition and
+one identity-frame occurrence. The optional `--step-output` writes the exact
+body from the same compilation. Compilation and tessellation finish before
+either output is written; filesystem write errors may still leave one output.
+This is the transport used by [Aetheris CAD for Blender](../blender.md).
+
`aetheris mesh <assembly.firmament|assembly.firmasm> --format assembly-json --output <file.mesh.json> --json` exports shared local definition meshes and stable world-space occurrences. Failed geometry is not omitted. The default destination is `artifacts/local/mesh/<name>.mesh.json`. See [editable mechanisms](../firmament/editable-mechanisms.md) for the schema and a working consumer.
## Generate engineering drawings
diff --git a/fixtures/Regression/BlenderAddon/packed-plate.firmament b/fixtures/Regression/BlenderAddon/packed-plate.firmament
new file mode 100644
index 00000000..f0bc0390
--- /dev/null
+++ b/fixtures/Regression/BlenderAddon/packed-plate.firmament
@@ -0,0 +1,5 @@
+include "parameters.firmament";
+Model PackedPlate {
+ units: mm
+ Box stock { size: [40mm, 30mm, Depth] }
+}
diff --git a/fixtures/Regression/BlenderAddon/parameters.firmament b/fixtures/Regression/BlenderAddon/parameters.firmament
new file mode 100644
index 00000000..0b186b52
--- /dev/null
+++ b/fixtures/Regression/BlenderAddon/parameters.firmament
@@ -0,0 +1 @@
+Static Depth: Length = 8mm
diff --git a/scripts/package-blender-addon.py b/scripts/package-blender-addon.py
new file mode 100644
index 00000000..35e58d64
--- /dev/null
+++ b/scripts/package-blender-addon.py
@@ -0,0 +1,46 @@
+"""Build a self-contained Windows Blender extension. Output stays under artifacts/local."""
+import argparse
+import hashlib
+import json
+from pathlib import Path
+import subprocess
+import zipfile
+
+
+def main():
+ repo = Path(__file__).resolve().parent.parent
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--output", type=Path, default=repo / "artifacts/local/blender-addon/aetheris_cad-0.1.0-windows-x64.zip")
+ parser.add_argument("--runtime-dir", type=Path, help="Reuse an already published self-contained CLI directory")
+ args = parser.parse_args()
+ output = args.output.resolve()
+ output.parent.mkdir(parents=True, exist_ok=True)
+ runtime = args.runtime_dir.resolve() if args.runtime_dir else output.parent / "runtime-win-x64"
+ if not args.runtime_dir:
+ subprocess.run(["dotnet", "publish", str(repo / "Aetheris.CLI"), "-c", "Release", "-r", "win-x64", "--self-contained", "true",
+ "-p:UseAppHost=true", "-p:PublishSingleFile=true", "-p:IncludeNativeLibrariesForSelfExtract=true", "-p:EnableCompressionInSingleFile=true",
+ "-p:UseSharedCompilation=false", "-p:DebugType=None", "-p:DebugSymbols=false",
+ "-m:1", "-nr:false", "-o", str(runtime)], check=True)
+ executable = runtime / "aetheris.exe"
+ if not executable.is_file():
+ raise SystemExit("The runtime directory must contain the published aetheris.exe.")
+ version = subprocess.check_output([str(executable), "--version"], text=True).strip()
+ source = repo / "tools/blender-aetheris/aetheris_cad"
+ files = {p.relative_to(source).as_posix(): p for p in source.rglob("*") if p.is_file() and "__pycache__" not in p.parts and p.suffix != ".pyc"}
+ files.update({"runtime/" + p.relative_to(runtime).as_posix(): p for p in runtime.rglob("*") if p.is_file() and p.suffix not in (".pdb", ".xml")})
+ files["starter.firmament"] = repo / "fixtures/Canonical/Learn/01-plate.firmament"
+ files["LICENSE"] = repo / "LICENSE"
+ files["THIRD_PARTY_NOTICES.md"] = repo / "THIRD_PARTY_NOTICES.md"
+ inventory = {name: hashlib.sha256(path.read_bytes()).hexdigest() for name, path in sorted(files.items())}
+ metadata = json.dumps({"runtime": version, "platform": "windows-x64", "files": inventory}, indent=2).encode()
+ with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
+ for name, path in sorted(files.items()):
+ info = zipfile.ZipInfo(name, date_time=(2026, 1, 1, 0, 0, 0))
+ info.compress_type = zipfile.ZIP_DEFLATED
+ archive.writestr(info, path.read_bytes())
+ archive.writestr("package-info.json", metadata)
+ print(json.dumps({"zip": str(output), "bytes": output.stat().st_size, "sha256": hashlib.sha256(output.read_bytes()).hexdigest(), "runtime": version}, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/qualify-blender-addon.py b/scripts/qualify-blender-addon.py
new file mode 100644
index 00000000..ddf3d6e4
--- /dev/null
+++ b/scripts/qualify-blender-addon.py
@@ -0,0 +1,54 @@
+"""Install the packaged extension in an isolated profile and exercise the real Blender/CLI path."""
+import argparse
+import json
+import math
+import os
+from pathlib import Path
+import subprocess
+
+
+def main():
+ repo = Path(__file__).resolve().parent.parent
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--blender", type=Path, required=True)
+ parser.add_argument("--package", type=Path, default=repo / "artifacts/local/blender-addon/aetheris_cad-0.1.0-windows-x64.zip")
+ parser.add_argument("--output", type=Path, default=repo / "artifacts/local/blender-addon/package-qualification")
+ args = parser.parse_args()
+ output = args.output.resolve()
+ output.mkdir(parents=True, exist_ok=True)
+ profile = output / "profile"
+ env = dict(os.environ, BLENDER_USER_RESOURCES=str(profile))
+ blender = str(args.blender.resolve())
+
+ def run(name, arguments):
+ with (output / (name + ".log")).open("w", encoding="utf-8") as log:
+ subprocess.run([blender, "--background", "--python-exit-code", "1", *map(str, arguments)], env=env,
+ cwd=output, stdout=log, stderr=subprocess.STDOUT, check=True)
+
+ run("repo", ["--command", "extension", "repo-add", "aetheris_test", "--name", "Aetheris qualification",
+ "--directory", profile / "extensions/aetheris_test", "--clear-all"])
+ run("manifest", ["--command", "extension", "validate", args.package.resolve()])
+ run("install", ["--command", "extension", "install-file", args.package.resolve(), "--repo", "aetheris_test", "--enable"])
+ script = repo / "test-support/blender-addon/qualify.py"
+ run("create", ["--python", script, "--", "--repo", repo, "--output", output, "--phase", "create"])
+ run("reopen", [output / "qualified.blend", "--python", script, "--", "--repo", repo, "--output", output, "--phase", "reopen"])
+ create = json.loads((output / "create.json").read_text())
+ reopened = json.loads((output / "reopen.json").read_text())
+ assert create["success"] and reopened["success"]
+ assert not create["compiler_override"] and not reopened["compiler_override"], "Qualification must use the bundled compiler"
+ compiler = profile / "extensions/aetheris_test/aetheris_cad/runtime/aetheris.exe"
+ volume = json.loads(subprocess.check_output([str(compiler), "analyze", "volume", str(output / "reopened.step"), "--json"], text=True))
+ assert volume["success"] and volume["exact"]
+ expected = 100 * 50 * 8 - math.pi * 4 * 4 * 8
+ assert abs(volume["volume"] - expected) < 1e-8, volume
+ assert volume["boundingBox"]["min"] == {"x": -50, "y": -25, "z": 0}
+ assert volume["boundingBox"]["max"] == {"x": 50, "y": 25, "z": 8}
+ (output / "exact-step-analysis.json").write_text(json.dumps(volume, indent=2))
+ report = {"success": True, "package": str(args.package.resolve()), "create": create, "reopen": reopened,
+ "exact_volume_mm3": volume["volume"], "expected_volume_mm3": expected}
+ (output / "qualification.json").write_text(json.dumps(report, indent=2))
+ print(json.dumps({"success": True, "report": str(output / "qualification.json"), "blend": str(output / "qualified.blend")}, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test-support/blender-addon/qualify.py b/test-support/blender-addon/qualify.py
new file mode 100644
index 00000000..6f02579c
--- /dev/null
+++ b/test-support/blender-addon/qualify.py
@@ -0,0 +1,256 @@
+"""Run with Blender's Python against an installed extension and the real local compiler."""
+import argparse
+import hashlib
+import importlib
+import json
+from pathlib import Path
+import sys
+
+import addon_utils
+import bpy
+import bmesh
+from mathutils import Vector
+
+parser = argparse.ArgumentParser()
+parser.add_argument("--module", default="bl_ext.aetheris_test.aetheris_cad")
+parser.add_argument("--source-addon", type=Path)
+parser.add_argument("--compiler", type=Path)
+parser.add_argument("--output", required=True, type=Path)
+parser.add_argument("--repo", required=True, type=Path)
+parser.add_argument("--phase", choices=("create", "reopen"), default="create")
+args = parser.parse_args(sys.argv[sys.argv.index("--") + 1:])
+out = args.output.resolve()
+out.mkdir(parents=True, exist_ok=True)
+if args.source_addon:
+ sys.path.insert(0, str(args.source_addon.resolve()))
+addon_utils.enable(args.module, default_set=True, persistent=True)
+addon = importlib.import_module(args.module)
+if args.compiler:
+ bpy.context.preferences.addons[args.module].preferences.executable_path = str(args.compiler.resolve())
+state = addon.state
+
+
+def select(root):
+ for obj in bpy.context.selected_objects:
+ obj.select_set(False)
+ root.select_set(True)
+ bpy.context.view_layer.objects.active = root
+
+
+def build(root, **kwargs):
+ select(root)
+ result = bpy.ops.aetheris.build(**kwargs)
+ assert result == {"FINISHED"}, root.aetheris.diagnostics.as_string() if root.aetheris.diagnostics else root.aetheris.status
+ return state.body_of(root)
+
+
+def dimensions(root):
+ body = state.body_of(root)
+ xs = [v.co.x for v in body.data.vertices]
+ ys = [v.co.y for v in body.data.vertices]
+ zs = [v.co.z for v in body.data.vertices]
+ return [max(xs) - min(xs), max(ys) - min(ys), max(zs) - min(zs)]
+
+
+def expect_dimensions(root, values):
+ for actual, expected in zip(dimensions(root), values):
+ # Blender stores float32 mesh positions; compare physical metres, including unit scale.
+ assert abs(actual - expected) * bpy.context.scene.unit_settings.scale_length < 1e-7, (actual, expected)
+
+
+def replace(text, source):
+ text.clear()
+ text.write(source)
+
+
+def export(root, filename):
+ select(root)
+ path = out / filename
+ assert bpy.ops.aetheris.export_step(filepath=str(path)) == {"FINISHED"}
+ return path
+
+
+if args.phase == "reopen":
+ root = bpy.data.objects["CAD Plate"]
+ select(root)
+ accepted = root.aetheris.accepted_hash
+ assert state.current_hash(root) == accepted
+ assert state.accepted_step(root).startswith("ISO-10303-21;")
+ expect_dimensions(root, [.1, .05, .008])
+ material = state.body_of(root).data.materials[0]
+ build(root)
+ assert state.body_of(root).data.materials[0] == material
+ assert abs(root.location.x - .025) < 1e-8
+ assert abs(state.body_of(root).location.x - .003) < 1e-8
+ packed = bpy.data.objects["Packed Plate"]
+ assert len(packed.aetheris.resources) == 1
+ build(packed)
+ expect_dimensions(packed, [.04, .03, .012])
+ export(root, "reopened.step")
+ export(packed, "reopened-packed.step")
+ (out / "reopen.json").write_text(json.dumps({"success": True, "saved_source": True, "saved_dependencies": True,
+ "compiler_override": bool(args.compiler), "dimensions": dimensions(root)}, indent=2))
+ print("AETHERIS_BLENDER_REOPEN_OK")
+else:
+ # Only this factory-startup test scene is modified.
+ for obj in list(bpy.data.objects):
+ bpy.data.objects.remove(obj, do_unlink=True)
+ assert bpy.ops.aetheris.new_part() == {"FINISHED"}
+ root = bpy.context.active_object
+ root.name = "CAD Plate"
+ body = build(root)
+ expect_dimensions(root, [.08, .05, .008])
+ identity = body.as_pointer()
+ source = root.aetheris.source.as_string()
+ material = bpy.data.materials.new("Qualification brass")
+ material.diffuse_color = (.55, .28, .07, 1)
+ material.use_nodes = True
+ shader = material.node_tree.nodes["Principled BSDF"]
+ shader.inputs["Base Color"].default_value = material.diffuse_color
+ shader.inputs["Metallic"].default_value = .7
+ shader.inputs["Roughness"].default_value = .3
+ body.data.materials.clear()
+ body.data.materials.append(material)
+ root.location = (.025, -.025, .005)
+ root.rotation_euler.z = .15
+ body.location.x = .003
+ transform = body.matrix_basis.copy()
+ replace(root.aetheris.source, source.replace("80mm", "100mm"))
+ body = build(root)
+ assert body.as_pointer() == identity
+ assert body.matrix_basis == transform
+ assert body.data.materials[0] == material
+ expect_dimensions(root, [.1, .05, .008])
+ good = root.aetheris.source.as_string()
+ accepted_mesh = state.mesh_hash(body.data)
+ accepted_step = state.accepted_step(root)
+ replace(root.aetheris.source, good.replace("diameter: 8mm", "diameter: -8mm"))
+ assert bpy.ops.aetheris.build() == {"CANCELLED"}
+ assert state.mesh_hash(body.data) == accepted_mesh
+ assert root.aetheris.step.as_string() == accepted_step
+ assert root.aetheris.diagnostics.as_string()
+ try:
+ state.accepted_step(root)
+ raise AssertionError("A stale source exported STEP")
+ except addon.BuildError:
+ pass
+ replace(root.aetheris.source, good)
+ build(root)
+ # Native mesh editing remains independent of exact CAD.
+ assert bpy.ops.aetheris.mesh_copy() == {"FINISHED"}
+ copy = bpy.context.active_object
+ assert copy.data != body.data and copy.parent is None
+ editable = bmesh.new()
+ try:
+ editable.from_mesh(copy.data)
+ assert all(edge.is_manifold for edge in editable.edges), "Mesh copy has open display seams"
+ volume_mm3 = abs(editable.calc_volume()) * 1e9
+ import math
+ assert abs(volume_mm3 - (100 * 50 * 8 - math.pi * 4 * 4 * 8)) < 5, volume_mm3
+ finally:
+ editable.free()
+ copy.data.vertices[0].co.x += .001
+ copy.hide_render = True
+ copy.hide_set(True)
+ select(root)
+ body.data.vertices[0].co.x += .001
+ assert bpy.ops.aetheris.build() == {"CANCELLED"}
+ assert "vertex edits" in root.aetheris.status
+ build(root, replace_edited=True)
+ assert not state.mesh_edited(root)
+ assert copy.data != body.data
+ assert state.body_of(root).data.materials[0] == material
+ export(root, "plate.step")
+ # Build from packed dependencies, then take the original files away before reopening.
+ external = out / "original-project"
+ external.mkdir(exist_ok=True)
+ fixture_dir = args.repo / "fixtures/Regression/BlenderAddon"
+ for name in ("packed-plate.firmament", "parameters.firmament"):
+ (external / name).write_bytes((fixture_dir / name).read_bytes())
+ assert bpy.ops.aetheris.import_source(filepath=str(external / "packed-plate.firmament")) == {"FINISHED"}
+ packed = bpy.context.active_object
+ packed.name = "Packed Plate"
+ assert bpy.ops.aetheris.build() == {"CANCELLED"}
+ assert state.body_of(packed) is None
+ assert bpy.ops.aetheris.add_resource(filepath=str(external / "parameters.firmament")) == {"FINISHED"}
+ build(packed)
+ expect_dimensions(packed, [.04, .03, .008])
+ replace(packed.aetheris.resources[0].text, "Static Depth: Length = 12mm\n")
+ build(packed)
+ expect_dimensions(packed, [.04, .03, .012])
+ packed.location = (-.055, .035, .005)
+ # Source edits during an asynchronous compiler job cannot replace accepted geometry.
+ select(root)
+ files, main = state.project_files(root)
+ job = addon.BuildJob(addon.executable(bpy.context), files, main)
+ replace(root.aetheris.source, good.replace("100mm", "110mm"))
+ try:
+ import time
+ while job.poll() is None:
+ time.sleep(.02)
+ mesh, step = job.result()
+ try:
+ state.install_result(root, mesh, step, job.digest, bpy.context.scene)
+ raise AssertionError("A stale asynchronous result replaced the accepted part")
+ except addon.BuildError as error:
+ assert "Source changed" in str(error)
+ finally:
+ job.close()
+ replace(root.aetheris.source, good)
+ expect_dimensions(root, [.1, .05, .008])
+ # Different Blender unit scales still represent the same millimetre geometry.
+ bpy.context.scene.unit_settings.scale_length = .001
+ body = build(root)
+ expect_dimensions(root, [100, 50, 8])
+ bpy.context.scene.unit_settings.scale_length = 1
+ body = build(root)
+ expect_dimensions(root, [.1, .05, .008])
+ export(root, "plate.step")
+ # A real Blender render of the compiler's geometry, alongside a native Blender floor.
+ scene = bpy.context.scene
+ scene.render.engine = "BLENDER_EEVEE"
+ scene.render.resolution_x, scene.render.resolution_y = 1200, 800
+ scene.render.resolution_percentage = 100
+ scene.world = bpy.data.worlds.new("CAD studio")
+ scene.world.use_nodes = True
+ scene.world.node_tree.nodes["Background"].inputs[0].default_value = (.14, .17, .22, 1)
+ scene.world.node_tree.nodes["Background"].inputs[1].default_value = .4
+ floor_mesh = bpy.data.meshes.new("Blender floor")
+ floor_mesh.from_pydata([(-1,-1,0), (1,-1,0), (1,1,0), (-1,1,0)], [], [(0,1,2,3)])
+ floor = bpy.data.objects.new("Native Blender floor", floor_mesh)
+ scene.collection.objects.link(floor)
+ floor_material = bpy.data.materials.new("Studio floor")
+ floor_material.diffuse_color = (.07, .09, .12, 1)
+ floor_material.use_nodes = True
+ floor_material.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = floor_material.diffuse_color
+ floor_mesh.materials.append(floor_material)
+ camera_data = bpy.data.cameras.new("CAD camera")
+ camera = bpy.data.objects.new("CAD camera", camera_data)
+ scene.collection.objects.link(camera)
+ camera.location = (.19, -.23, .21)
+ camera.rotation_euler = (Vector((0,0,.005)) - camera.location).to_track_quat("-Z", "Y").to_euler()
+ camera_data.lens = 50
+ camera_data.clip_start = .001
+ scene.camera = camera
+ for name, location, energy, size in [("Key", (.1,-.1,.2), 2, .15), ("Fill", (-.12,.05,.15), 1, .12)]:
+ light = bpy.data.lights.new(name, "AREA")
+ light.energy, light.shape, light.size = energy, "DISK", size
+ obj = bpy.data.objects.new(name, light)
+ scene.collection.objects.link(obj)
+ obj.location = location
+ obj.rotation_euler = (-obj.location).to_track_quat("-Z", "Y").to_euler()
+ select(root)
+ bpy.context.view_layer.update()
+ scene.render.filepath = str(out / "cad-in-blender.png")
+ bpy.ops.render.render(write_still=True)
+ bpy.ops.wm.save_as_mainfile(filepath=str(out / "qualified.blend"))
+ for path in external.iterdir():
+ if path.suffix != ".unavailable":
+ path.replace(path.with_suffix(path.suffix + ".unavailable"))
+ (out / "create.json").write_text(json.dumps({"success": True, "module": args.module, "compiler_override": bool(args.compiler),
+ "revision": root.aetheris.revision, "dimensions": dimensions(root), "triangles": len(body.data.polygons),
+ "identity_preserved": True, "material_preserved": True, "placement_preserved": True, "failed_build_retained": True,
+ "stale_result_refused": True, "mesh_copy_independent": True, "unit_scale_qualified": True,
+ "packed_dependency": True, "original_dependency_removed": True,
+ "step_sha256": hashlib.sha256((out / "plate.step").read_bytes()).hexdigest()}, indent=2))
+ print("AETHERIS_BLENDER_CREATE_OK")
diff --git a/tools/blender-aetheris/.gitignore b/tools/blender-aetheris/.gitignore
new file mode 100644
index 00000000..7a60b85e
--- /dev/null
+++ b/tools/blender-aetheris/.gitignore
@@ -0,0 +1,2 @@
+__pycache__/
+*.pyc
diff --git a/tools/blender-aetheris/aetheris_cad/__init__.py b/tools/blender-aetheris/aetheris_cad/__init__.py
new file mode 100644
index 00000000..c62ade21
--- /dev/null
+++ b/tools/blender-aetheris/aetheris_cad/__init__.py
@@ -0,0 +1,478 @@
+"""Aetheris CAD: exact Firmament parts in Blender, with local compiler transport."""
+import base64
+from pathlib import Path
+import time
+
+import bpy
+import bmesh
+from bpy.app.handlers import persistent
+from bpy.props import BoolProperty, CollectionProperty, IntProperty, PointerProperty, StringProperty
+from bpy_extras.io_utils import ExportHelper, ImportHelper
+
+from .bridge import BuildError, BuildJob
+from . import state
+
+_jobs = {}
+
+
+class AETHERIS_Resource(bpy.types.PropertyGroup):
+ relative_path: StringProperty(name="Project path")
+ text: PointerProperty(type=bpy.types.Text)
+ binary: BoolProperty(default=False)
+
+
+class AETHERIS_Part(bpy.types.PropertyGroup):
+ is_part: BoolProperty(default=False)
+ uid: StringProperty()
+ source: PointerProperty(name="Firmament source", type=bpy.types.Text)
+ main_file: StringProperty(name="Main file", default="part.firmament")
+ resources: CollectionProperty(type=AETHERIS_Resource)
+ import_directory: StringProperty(subtype="DIR_PATH")
+ step: PointerProperty(type=bpy.types.Text)
+ diagnostics: PointerProperty(type=bpy.types.Text)
+ accepted_hash: StringProperty()
+ step_hash: StringProperty()
+ revision: IntProperty(default=0)
+ status: StringProperty(default="Ready to build")
+
+
+class AETHERIS_Preferences(bpy.types.AddonPreferences):
+ bl_idname = __package__
+ executable_path: StringProperty(name="Compiler override", description="Leave empty to use the bundled local runtime", subtype="FILE_PATH")
+
+ def draw(self, context):
+ self.layout.label(text="The complete extension ZIP includes its local Aetheris runtime.")
+ self.layout.prop(self, "executable_path")
+ self.layout.label(text="Developer override accepts aetheris.exe or aetheris.dll.")
+
+
+def executable(context):
+ addon = context.preferences.addons.get(__package__)
+ override = addon.preferences.executable_path if addon else ""
+ return Path(bpy.path.abspath(override)).resolve() if override else Path(__file__).parent / "runtime" / "aetheris.exe"
+
+
+def show_text(context, text):
+ if not text or not context.screen:
+ return
+ area = next((a for a in context.screen.areas if a.type == "TEXT_EDITOR"), None)
+ if area is None:
+ current = context.area
+ if not current or current.type != "VIEW_3D":
+ return
+ before = {a.as_pointer() for a in context.screen.areas}
+ with context.temp_override(area=current):
+ bpy.ops.screen.area_split(direction="VERTICAL", factor=.5)
+ area = next((a for a in context.screen.areas if a.as_pointer() not in before), None)
+ if area is None:
+ return
+ area.type = "TEXT_EDITOR"
+ area.spaces.active.text = text
+ area.spaces.active.show_line_numbers = True
+ area.spaces.active.show_word_wrap = True
+ text.cursor_set(0)
+ area.spaces.active.top = 0
+
+
+def fit_part(context, root):
+ body = state.body_of(root)
+ if not body or not context.screen:
+ return
+ for selected in context.selected_objects:
+ selected.select_set(False)
+ body.select_set(True)
+ context.view_layer.objects.active = body
+ for area in context.screen.areas:
+ if area.type == "VIEW_3D":
+ region = next((r for r in area.regions if r.type == "WINDOW"), None)
+ if region:
+ with context.temp_override(area=area, region=region):
+ bpy.ops.view3d.view_selected(use_all_regions=False)
+
+
+class AETHERIS_OT_fit(bpy.types.Operator):
+ bl_idname = "aetheris.fit_part"
+ bl_label = "Fit CAD Part"
+
+ def execute(self, context):
+ root = state.find_part(context)
+ if not root:
+ return {"CANCELLED"}
+ fit_part(context, root)
+ return {"FINISHED"}
+
+
+class AETHERIS_OT_new(bpy.types.Operator):
+ bl_idname = "aetheris.new_part"
+ bl_label = "New CAD Part"
+ bl_description = "Create a Firmament source and an exact CAD part in this scene"
+ bl_options = {"REGISTER", "UNDO"}
+
+ def execute(self, context):
+ root = state.new_part(context)
+ if not bpy.app.background:
+ show_text(context, root.aetheris.source)
+ return {"FINISHED"}
+
+
+class AETHERIS_OT_import(bpy.types.Operator, ImportHelper):
+ bl_idname = "aetheris.import_source"
+ bl_label = "Open Firmament Part"
+ bl_description = "Copy a .firmament document into this .blend; add its dependencies explicitly"
+ bl_options = {"REGISTER", "UNDO"}
+ filename_ext = ".firmament"
+ filter_glob: StringProperty(default="*.firmament", options={"HIDDEN"})
+
+ def execute(self, context):
+ try:
+ path = Path(self.filepath)
+ root = state.new_part(context, path.read_text(encoding="utf-8-sig"), path.name, str(path.parent))
+ if not bpy.app.background:
+ show_text(context, root.aetheris.source)
+ return {"FINISHED"}
+ except (OSError, UnicodeError) as error:
+ self.report({"ERROR"}, str(error))
+ return {"CANCELLED"}
+
+
+class AETHERIS_OT_source(bpy.types.Operator):
+ bl_idname = "aetheris.open_source"
+ bl_label = "Open Source"
+ diagnostic: BoolProperty(default=False, options={"SKIP_SAVE"})
+
+ def execute(self, context):
+ root = state.find_part(context)
+ if not root:
+ return {"CANCELLED"}
+ show_text(context, root.aetheris.diagnostics if self.diagnostic else root.aetheris.source)
+ return {"FINISHED"}
+
+
+class AETHERIS_OT_resource(bpy.types.Operator, ImportHelper):
+ bl_idname = "aetheris.add_resource"
+ bl_label = "Add Project File"
+ bl_description = "Pack an explicitly selected include, STEP asset, or lock file into this .blend"
+ bl_options = {"REGISTER", "UNDO"}
+
+ def execute(self, context):
+ root = state.find_part(context)
+ if not root:
+ return {"CANCELLED"}
+ try:
+ path = Path(self.filepath).resolve()
+ data = path.read_bytes()
+ if len(data) > 32 * 1024 * 1024:
+ raise BuildError("A project file may be at most 32 MiB.")
+ directory = root.aetheris.import_directory
+ name = path.relative_to(Path(directory).resolve()).as_posix() if directory and path.is_relative_to(Path(directory).resolve()) else path.name
+ if name.casefold() in {root.aetheris.main_file.casefold(), *(r.relative_path.casefold() for r in root.aetheris.resources)}:
+ raise BuildError("This project already contains " + name)
+ try:
+ content = data.decode("utf-8")
+ binary = False
+ except UnicodeError:
+ content, binary = base64.b64encode(data).decode("ascii"), True
+ text = state.text_block(name, content)
+ resource = root.aetheris.resources.add()
+ resource.relative_path, resource.text, resource.binary = name, text, binary
+ return {"FINISHED"}
+ except (OSError, ValueError, BuildError) as error:
+ self.report({"ERROR"}, str(error))
+ return {"CANCELLED"}
+
+
+class AETHERIS_OT_remove_resource(bpy.types.Operator):
+ bl_idname = "aetheris.remove_resource"
+ bl_label = "Unlink Project File"
+ bl_options = {"REGISTER", "UNDO"}
+ index: IntProperty()
+
+ def execute(self, context):
+ root = state.find_part(context)
+ if root and 0 <= self.index < len(root.aetheris.resources):
+ root.aetheris.resources.remove(self.index)
+ return {"FINISHED"}
+ return {"CANCELLED"}
+
+
+class AETHERIS_OT_build(bpy.types.Operator):
+ bl_idname = "aetheris.build"
+ bl_label = "Build CAD Part"
+ bl_description = "Compile the saved source snapshot locally; retain accepted geometry on failure"
+ bl_options = {"REGISTER", "UNDO"}
+ replace_edited: BoolProperty(default=False, options={"SKIP_SAVE"})
+ _timer = None
+ _job = None
+ _uid = ""
+
+ @classmethod
+ def poll(cls, context):
+ root = state.find_part(context)
+ return root is not None and context.mode == "OBJECT" and root.aetheris.uid not in _jobs
+
+ def execute(self, context):
+ root = state.find_part(context)
+ self._uid = root.aetheris.uid
+ try:
+ if state.mesh_edited(root) and not self.replace_edited:
+ raise BuildError("The generated mesh has vertex edits. Create a Mesh Copy to retain them, then use Restore CAD Mesh.")
+ files, main = state.project_files(root)
+ self._job = BuildJob(executable(context), files, main)
+ _jobs[self._uid] = self
+ root.aetheris.status = "Building locally… Esc cancels"
+ if bpy.app.background:
+ while self._job.poll() is None:
+ time.sleep(.02)
+ return self.finish(context)
+ self._timer = context.window_manager.event_timer_add(.1, window=context.window)
+ context.window_manager.modal_handler_add(self)
+ return {"RUNNING_MODAL"}
+ except Exception as error:
+ state.diagnostic(root, str(error))
+ self.cleanup(context)
+ self.report({"WARNING"}, "Build refused. Open Diagnostics for the compiler message.")
+ return {"CANCELLED"}
+
+ def modal(self, context, event):
+ if event.type == "ESC":
+ root = state.find_part(context, self._uid)
+ if root:
+ root.aetheris.status = "Build cancelled · last accepted geometry retained"
+ self.cleanup(context)
+ return {"CANCELLED"}
+ if event.type == "TIMER":
+ try:
+ if self._job.poll() is not None:
+ return self.finish(context)
+ except Exception as error:
+ root = state.find_part(context, self._uid)
+ if root:
+ state.diagnostic(root, str(error))
+ self.cleanup(context)
+ return {"CANCELLED"}
+ return {"PASS_THROUGH"}
+
+ def finish(self, context):
+ try:
+ root = state.find_part(context, self._uid)
+ if not root:
+ raise BuildError("The target CAD part was removed or duplicated while building.")
+ mesh, step = self._job.result()
+ first = root.aetheris.revision == 0
+ state.install_result(root, mesh, step, self._job.digest, context.scene)
+ if first and not bpy.app.background:
+ fit_part(context, root)
+ self.report({"INFO"}, root.aetheris.status)
+ return {"FINISHED"}
+ except Exception as error:
+ root = state.find_part(context, self._uid)
+ if root:
+ state.diagnostic(root, str(error))
+ self.report({"WARNING"}, "Build refused. Last accepted geometry retained; open Diagnostics.")
+ return {"CANCELLED"}
+ finally:
+ self.cleanup(context)
+
+ def cleanup(self, context):
+ if self._job:
+ self._job.close()
+ self._job = None
+ if self._timer:
+ context.window_manager.event_timer_remove(self._timer)
+ self._timer = None
+ _jobs.pop(self._uid, None)
+ if context.screen:
+ for area in context.screen.areas:
+ area.tag_redraw()
+
+ def cancel(self, context):
+ self.cleanup(context)
+
+
+class AETHERIS_OT_step(bpy.types.Operator, ExportHelper):
+ bl_idname = "aetheris.export_step"
+ bl_label = "Export Exact STEP (Source Frame)"
+ bl_description = "Export the accepted source BRep; Blender placement, modifiers, and mesh copies are presentation only"
+ filename_ext = ".step"
+ filter_glob: StringProperty(default="*.step;*.stp", options={"HIDDEN"})
+
+ @classmethod
+ def poll(cls, context):
+ root = state.find_part(context)
+ return root is not None and bool(root.aetheris.step) and root.aetheris.uid not in _jobs
+
+ def execute(self, context):
+ try:
+ root = state.find_part(context)
+ data = state.accepted_step(root)
+ Path(self.filepath).write_text(data, encoding="utf-8", newline="")
+ self.report({"INFO"}, "Exact STEP exported in Firmament source coordinates")
+ return {"FINISHED"}
+ except (OSError, BuildError) as error:
+ self.report({"ERROR"}, str(error))
+ return {"CANCELLED"}
+
+
+class AETHERIS_OT_bake(bpy.types.Operator):
+ bl_idname = "aetheris.mesh_copy"
+ bl_label = "Create Editable Mesh Copy"
+ bl_description = "Make an independent Blender mesh for sculpting, booleans, or vertex editing"
+ bl_options = {"REGISTER", "UNDO"}
+
+ @classmethod
+ def poll(cls, context):
+ root = state.find_part(context)
+ return root is not None and state.body_of(root) is not None and root.aetheris.uid not in _jobs
+
+ def execute(self, context):
+ root = state.find_part(context)
+ body = state.body_of(root)
+ obj = body.copy()
+ obj.data = body.data.copy()
+ # Display faces retain split vertices for exact normals. Weld only the
+ # independent presentation copy so Blender mesh operations get shared seams.
+ editable = bmesh.new()
+ try:
+ editable.from_mesh(obj.data)
+ bmesh.ops.remove_doubles(editable, verts=list(editable.verts), dist=1e-8 / context.scene.unit_settings.scale_length)
+ editable.normal_update()
+ editable.to_mesh(obj.data)
+ obj.data.update()
+ finally:
+ editable.free()
+ obj.name = root.name + " Mesh Copy"
+ transform = body.matrix_world.copy()
+ obj.parent = None
+ obj.matrix_world = transform
+ for key in ("aetheris_owner", "aetheris_mesh_hash"):
+ if key in obj:
+ del obj[key]
+ context.collection.objects.link(obj)
+ for selected in context.selected_objects:
+ selected.select_set(False)
+ obj.select_set(True)
+ context.view_layer.objects.active = obj
+ return {"FINISHED"}
+
+
+def draw_part(layout, context):
+ root = state.find_part(context)
+ if not root:
+ layout.operator("aetheris.new_part", icon="ADD")
+ layout.operator("aetheris.import_source", icon="FILE_FOLDER")
+ layout.label(text="Select a CAD part or its source to rebuild.")
+ return
+ part = root.aetheris
+ busy = part.uid in _jobs
+ layout.label(text=root.name, icon="MESH_CUBE")
+ column = layout.column()
+ column.enabled = not busy
+ column.prop(part, "source")
+ column.prop(part, "main_file")
+ column.operator("aetheris.open_source", icon="TEXT")
+ column.operator("aetheris.fit_part", icon="VIEWZOOM")
+ row = column.row()
+ row.enabled = context.mode == "OBJECT"
+ row.operator("aetheris.build", icon="FILE_REFRESH")
+ try:
+ stale = state.current_hash(root) != part.accepted_hash
+ edited = part.status.startswith("The generated mesh has vertex edits")
+ except BuildError:
+ stale, edited = True, False
+ layout.label(text="Building locally…" if busy else "Source changed · rebuild required" if stale else "Source matches accepted CAD", icon="TIME" if busy else "ERROR" if stale else "CHECKMARK")
+ if edited:
+ box = layout.box()
+ box.alert = True
+ box.label(text="Generated mesh has vertex edits")
+ box.operator("aetheris.mesh_copy")
+ box.operator("aetheris.build", text="Restore CAD Mesh").replace_edited = True
+ layout.label(text=part.status[:90])
+ if part.diagnostics and part.diagnostics.as_string():
+ box = layout.box()
+ box.alert = True
+ box.label(text="Build refused · accepted part retained", icon="ERROR")
+ box.operator("aetheris.open_source", text="Open Diagnostics").diagnostic = True
+ column = layout.column()
+ column.enabled = not busy
+ column.operator("aetheris.mesh_copy", icon="DUPLICATE")
+ row = column.row()
+ row.enabled = not stale
+ row.operator("aetheris.export_step", text="Export Exact STEP", icon="EXPORT")
+ layout.label(text="STEP uses source coordinates")
+ box = layout.box()
+ box.label(text="Project files · saved inside .blend")
+ for i, resource in enumerate(part.resources):
+ row = box.row(align=True)
+ row.enabled = not busy
+ row.prop(resource, "relative_path", text="")
+ row.operator("aetheris.remove_resource", text="", icon="X").index = i
+ row = box.row()
+ row.enabled = not busy
+ row.operator("aetheris.add_resource", icon="FILE_NEW")
+
+
+class AETHERIS_PT_view(bpy.types.Panel):
+ bl_label = "Aetheris CAD"
+ bl_space_type = "VIEW_3D"
+ bl_region_type = "UI"
+ bl_category = "Aetheris"
+
+ def draw(self, context):
+ draw_part(self.layout, context)
+
+
+class AETHERIS_PT_text(bpy.types.Panel):
+ bl_label = "Aetheris CAD"
+ bl_space_type = "TEXT_EDITOR"
+ bl_region_type = "UI"
+ bl_category = "Aetheris"
+
+ def draw(self, context):
+ draw_part(self.layout, context)
+
+
+def draw_add(self, context):
+ self.layout.operator("aetheris.new_part", text="Aetheris CAD Part", icon="MESH_CUBE")
+
+
+def draw_text_header(self, context):
+ root = state.find_part(context)
+ if root:
+ self.layout.operator("aetheris.build", text="Build CAD", icon="FILE_REFRESH")
+ self.layout.operator("aetheris.export_step", text="STEP", icon="EXPORT")
+
+
+@persistent
+def loaded(_):
+ for operator in list(_jobs.values()):
+ operator.cleanup(bpy.context)
+ for obj in bpy.data.objects:
+ if obj.aetheris.is_part and obj.aetheris.status.startswith("Building"):
+ obj.aetheris.status = "Build interrupted · rebuild to continue"
+
+
+_classes = (AETHERIS_Resource, AETHERIS_Part, AETHERIS_Preferences, AETHERIS_OT_fit, AETHERIS_OT_new, AETHERIS_OT_import,
+ AETHERIS_OT_source, AETHERIS_OT_resource, AETHERIS_OT_remove_resource, AETHERIS_OT_build,
+ AETHERIS_OT_step, AETHERIS_OT_bake, AETHERIS_PT_view, AETHERIS_PT_text)
+
+
+def register():
+ for cls in _classes:
+ bpy.utils.register_class(cls)
+ bpy.types.Object.aetheris = PointerProperty(type=AETHERIS_Part)
+ bpy.types.VIEW3D_MT_add.append(draw_add)
+ bpy.types.TEXT_HT_header.append(draw_text_header)
+ bpy.app.handlers.load_pre.append(loaded)
+ bpy.app.handlers.load_post.append(loaded)
+
+
+def unregister():
+ for operator in list(_jobs.values()):
+ operator.cleanup(bpy.context)
+ bpy.app.handlers.load_pre.remove(loaded)
+ bpy.app.handlers.load_post.remove(loaded)
+ bpy.types.TEXT_HT_header.remove(draw_text_header)
+ bpy.types.VIEW3D_MT_add.remove(draw_add)
+ del bpy.types.Object.aetheris
+ for cls in reversed(_classes):
+ bpy.utils.unregister_class(cls)
diff --git a/tools/blender-aetheris/aetheris_cad/blender_manifest.toml b/tools/blender-aetheris/aetheris_cad/blender_manifest.toml
new file mode 100644
index 00000000..30d04af8
--- /dev/null
+++ b/tools/blender-aetheris/aetheris_cad/blender_manifest.toml
@@ -0,0 +1,17 @@
+schema_version = "1.0.0"
+id = "aetheris_cad"
+version = "0.1.0"
+name = "Aetheris CAD"
+tagline = "Exact Firmament CAD parts with Blender modeling and rendering"
+maintainer = "Aetheris"
+type = "add-on"
+blender_version_min = "5.2.0"
+license = ["SPDX:AGPL-3.0-only"]
+platforms = ["windows-x64"]
+tags = ["Modeling", "Import-Export"]
+
+[permissions]
+files = "Read project files, run the local compiler, and export STEP"
+
+[build]
+paths_exclude_pattern = ["__pycache__/", "*.pyc"]
diff --git a/tools/blender-aetheris/aetheris_cad/bridge.py b/tools/blender-aetheris/aetheris_cad/bridge.py
new file mode 100644
index 00000000..23f606db
--- /dev/null
+++ b/tools/blender-aetheris/aetheris_cad/bridge.py
@@ -0,0 +1,131 @@
+"""Transport and display-contract admission only. All engineering belongs to Aetheris."""
+import hashlib
+import json
+import math
+from pathlib import Path, PurePosixPath
+import subprocess
+import tempfile
+import time
+
+
+class BuildError(Exception):
+ pass
+
+
+def relative_path(value):
+ value = value.replace("\\", "/")
+ if not value or value.startswith("/") or ":" in value or "\0" in value or any(p in ("", ".", "..") for p in value.split("/")):
+ raise BuildError("Project files need distinct relative paths without '..', for example parts/profile.firmament.")
+ return str(PurePosixPath(value))
+
+
+def source_hash(files, main_file):
+ relative_path(main_file)
+ keys = set()
+ for name in files:
+ clean = relative_path(name)
+ if clean.casefold() in keys:
+ raise BuildError("Duplicate project path: " + clean)
+ keys.add(clean.casefold())
+ if main_file not in files:
+ raise BuildError("The main Firmament document is missing.")
+ if sum(len(data) for data in files.values()) > 64 * 1024 * 1024:
+ raise BuildError("This project exceeds the add-on's 64 MiB snapshot limit.")
+ manifest = [main_file, [(name, hashlib.sha256(data).hexdigest()) for name, data in sorted(files.items())]]
+ return hashlib.sha256(json.dumps(manifest, ensure_ascii=True).encode()).hexdigest()
+
+
+def validate_display(document):
+ if document.get("schema") != "aetheris/display-mesh/1" or document.get("units") != "mm":
+ raise BuildError("The compiler returned an unsupported display schema or unit.")
+ definitions, occurrences = document.get("definitions", []), document.get("occurrences", [])
+ if len(definitions) != 1 or len(occurrences) != 1:
+ raise BuildError("This version accepts one standalone BRep part per CAD object.")
+ mesh = definitions[0]
+ positions, normals, indices = mesh.get("positions", []), mesh.get("normals", []), mesh.get("indices", [])
+ if not positions or len(positions) % 3 or len(normals) != len(positions) or not indices or len(indices) % 3:
+ raise BuildError("Incomplete display mesh returned by the compiler.")
+ if any(not isinstance(v, (int, float)) or not math.isfinite(v) for v in positions + normals):
+ raise BuildError("Non-finite display coordinates returned by the compiler.")
+ if any(type(i) is not int or i < 0 or i >= len(positions) // 3 for i in indices):
+ raise BuildError("Invalid display triangle index returned by the compiler.")
+ if any(d.get("code") == "display-external-face-unmeshed" for d in mesh.get("diagnostics", [])):
+ raise BuildError("This BRep has faces the display route cannot tessellate; no partial preview was installed.")
+ if occurrences[0].get("definitionId") != mesh.get("id"):
+ raise BuildError("The compiler returned an unresolved display occurrence.")
+ if occurrences[0].get("transform") != [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]:
+ raise BuildError("A standalone CAD part must use its source coordinate frame.")
+ return mesh
+
+
+class BuildJob:
+ """One short-lived CLI process; files are private to this immutable build snapshot."""
+ def __init__(self, executable, files, main_file, timeout=180):
+ self.digest = source_hash(files, main_file)
+ self.timeout = timeout
+ self.started = time.monotonic()
+ self.process = None
+ self.temp = tempfile.TemporaryDirectory(prefix="aetheris-blender-")
+ self.directory = Path(self.temp.name)
+ self.log = None
+ try:
+ source = self.directory / "source"
+ for name, data in files.items():
+ path = source / relative_path(name)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(data)
+ self.display = self.directory / "display.json"
+ self.step = self.directory / "part.step"
+ self.log = (self.directory / "compiler.log").open("wb")
+ executable = Path(executable)
+ if not executable.is_file():
+ raise BuildError("Aetheris runtime is missing. Install the complete extension ZIP or choose a compiler in add-on preferences.")
+ command = (["dotnet", str(executable)] if executable.suffix.lower() == ".dll" else [str(executable)])
+ command += ["mesh", str(source / main_file), "--format", "display-json", "--output", str(self.display), "--step-output", str(self.step), "--json"]
+ self.process = subprocess.Popen(command, stdout=self.log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
+ except Exception:
+ self.close()
+ raise
+
+ def poll(self):
+ code = self.process.poll()
+ if code is None and time.monotonic() - self.started > self.timeout:
+ self.close()
+ raise BuildError("The compiler exceeded the 180 second build limit. The last accepted CAD part is unchanged.")
+ return code
+
+ def result(self):
+ if self.poll() is None:
+ raise BuildError("The compiler is still running.")
+ self.log.flush()
+ log = (self.directory / "compiler.log").read_text(encoding="utf-8", errors="replace")
+ if self.process.returncode:
+ try:
+ report = json.loads(log)
+ diagnostics = report.get("diagnostics", [])
+ log = "\n".join(d if isinstance(d, str) else d.get("message", str(d)) for d in diagnostics) or log
+ except ValueError:
+ pass
+ raise BuildError(log[-16000:] or "The Aetheris compiler failed without a diagnostic.")
+ if not self.display.is_file() or not self.step.is_file():
+ raise BuildError("The compiler did not produce both the display mesh and exact STEP.")
+ document = json.loads(self.display.read_text(encoding="utf-8-sig"))
+ mesh = validate_display(document)
+ step = self.step.read_text(encoding="utf-8-sig")
+ if not step.startswith("ISO-10303-21;") or "END-ISO-10303-21;" not in step:
+ raise BuildError("The compiler returned an incomplete STEP artifact.")
+ return mesh, step
+
+ def close(self):
+ if self.process and self.process.poll() is None:
+ self.process.terminate()
+ try:
+ self.process.wait(timeout=2)
+ except subprocess.TimeoutExpired:
+ self.process.kill()
+ self.process.wait()
+ if self.log:
+ self.log.close()
+ self.log = None
+ self.temp.cleanup()
diff --git a/tools/blender-aetheris/aetheris_cad/state.py b/tools/blender-aetheris/aetheris_cad/state.py
new file mode 100644
index 00000000..01475979
--- /dev/null
+++ b/tools/blender-aetheris/aetheris_cad/state.py
@@ -0,0 +1,196 @@
+"""Blender data ownership. Source and accepted STEP live in .blend text datablocks."""
+import base64
+import hashlib
+from pathlib import Path
+import struct
+import uuid
+
+import bpy
+
+from .bridge import BuildError, relative_path, source_hash
+
+
+def find_part(context, uid=""):
+ if uid:
+ parts = [o for o in context.scene.objects if o.aetheris.is_part and o.aetheris.uid == uid]
+ return parts[0] if len(parts) == 1 else None
+ area = context.area
+ if area and area.type == "TEXT_EDITOR":
+ text = area.spaces.active.text
+ parts = [o for o in context.scene.objects if o.aetheris.is_part and text and
+ (o.aetheris.source == text or o.aetheris.diagnostics == text or any(r.text == text for r in o.aetheris.resources))]
+ if len(parts) == 1:
+ return parts[0]
+ return None
+ obj = context.active_object
+ if obj and obj.aetheris.is_part:
+ return obj
+ if obj and obj.parent and obj.parent.aetheris.is_part and obj.get("aetheris_owner") == obj.parent.aetheris.uid:
+ return obj.parent
+ return None
+
+
+def body_of(root):
+ bodies = [o for o in root.children if o.type == "MESH" and o.get("aetheris_owner") == root.aetheris.uid]
+ if len(bodies) > 1:
+ raise BuildError("This CAD part has multiple managed meshes. Use New CAD Part or Create Mesh Copy to make independent objects.")
+ return bodies[0] if bodies else None
+
+
+def project_files(root):
+ part = root.aetheris
+ if not part.source:
+ raise BuildError("Select a Firmament source text first.")
+ main = relative_path(part.main_file)
+ if not main.lower().endswith(".firmament"):
+ raise BuildError("The main document needs a .firmament file name.")
+ files = {main: part.source.as_string().encode("utf-8")}
+ paths = {main.casefold()}
+ for resource in part.resources:
+ path = relative_path(resource.relative_path)
+ if path.casefold() in paths:
+ raise BuildError("Duplicate project file: " + path)
+ if not resource.text:
+ raise BuildError("Missing packed project text: " + path)
+ paths.add(path.casefold())
+ try:
+ files[path] = base64.b64decode(resource.text.as_string(), validate=True) if resource.binary else resource.text.as_string().encode("utf-8")
+ except ValueError as error:
+ raise BuildError("Invalid packed binary resource: " + path) from error
+ source_hash(files, main)
+ return files, main
+
+
+def current_hash(root):
+ files, main = project_files(root)
+ return source_hash(files, main)
+
+
+def text_block(name, value):
+ text = bpy.data.texts.new(name)
+ text.use_fake_user = True
+ text.write(value)
+ return text
+
+
+def new_part(context, source=None, main_file="part.firmament", directory=""):
+ root = bpy.data.objects.new("Aetheris Part", None)
+ context.collection.objects.link(root)
+ root.location = context.scene.cursor.location
+ root.empty_display_type = "PLAIN_AXES"
+ root.empty_display_size = .025 / context.scene.unit_settings.scale_length
+ part = root.aetheris
+ part.is_part = True
+ part.uid = uuid.uuid4().hex
+ part.main_file = main_file
+ part.import_directory = directory
+ starter = source if source is not None else (Path(__file__).parent / "starter.firmament").read_text(encoding="utf-8")
+ part.source = text_block(main_file, starter)
+ for obj in context.selected_objects:
+ obj.select_set(False)
+ root.select_set(True)
+ context.view_layer.objects.active = root
+ return root
+
+
+def mesh_hash(mesh):
+ digest = hashlib.sha256()
+ for vertex in mesh.vertices:
+ digest.update(struct.pack("<fff", *vertex.co))
+ for polygon in mesh.polygons:
+ digest.update(struct.pack("<I", len(polygon.vertices)))
+ digest.update(struct.pack("<" + "I" * len(polygon.vertices), *polygon.vertices))
+ return digest.hexdigest()
+
+
+def mesh_edited(root):
+ body = body_of(root)
+ return bool(body and body.get("aetheris_mesh_hash") != mesh_hash(body.data))
+
+
+def diagnostic(root, message):
+ part = root.aetheris
+ if not part.diagnostics:
+ part.diagnostics = text_block("Aetheris diagnostics " + part.uid[:8], "")
+ part.diagnostics.clear()
+ part.diagnostics.write(message)
+ part.status = message.splitlines()[0][:200] if message else "Ready"
+
+
+def install_result(root, mesh_data, step, digest, scene):
+ """Stage a complete new mesh before swapping one object's data. Keep object-owned presentation."""
+ if current_hash(root) != digest:
+ raise BuildError("Source changed while the compiler was running. Rebuild the current source; the last accepted part is unchanged.")
+ body = body_of(root)
+ factor = .001 / scene.unit_settings.scale_length
+ positions, indices = mesh_data["positions"], mesh_data["indices"]
+ vertices = [tuple(v * factor for v in positions[i:i + 3]) for i in range(0, len(positions), 3)]
+ faces = [indices[i:i + 3] for i in range(0, len(indices), 3)]
+ normals = [mesh_data["normals"][i:i + 3] for i in range(0, len(positions), 3)]
+ mesh = bpy.data.meshes.new(root.name + " CAD display")
+ try:
+ mesh.from_pydata(vertices, [], faces)
+ mesh.update()
+ if mesh.validate(verbose=False, clean_customdata=False):
+ raise BuildError("Blender rejected the compiler display topology. No repaired or partial mesh was installed.")
+ for polygon in mesh.polygons:
+ polygon.use_smooth = True
+ mesh.normals_split_custom_set_from_vertices(normals)
+ old = body.data if body else None
+ reset_faces = False
+ if old:
+ for material in old.materials:
+ mesh.materials.append(material)
+ same_topology = len(old.polygons) == len(mesh.polygons) and all(tuple(a.vertices) == tuple(b.vertices) for a, b in zip(old.polygons, mesh.polygons))
+ if same_topology:
+ for new_polygon, old_polygon in zip(mesh.polygons, old.polygons):
+ new_polygon.material_index = old_polygon.material_index
+ else:
+ reset_faces = any(p.material_index != 0 for p in old.polygons)
+ if not mesh.materials:
+ material = bpy.data.materials.get("Aetheris CAD")
+ if material is None:
+ material = bpy.data.materials.new("Aetheris CAD")
+ material.diffuse_color = (.16, .38, .55, 1)
+ material.use_nodes = True
+ shader = material.node_tree.nodes.get("Principled BSDF")
+ shader.inputs["Base Color"].default_value = material.diffuse_color
+ shader.inputs["Roughness"].default_value = .35
+ mesh.materials.append(material)
+ except Exception:
+ bpy.data.meshes.remove(mesh)
+ raise
+ if body is None:
+ body = bpy.data.objects.new(root.name + " · CAD", mesh)
+ root.users_collection[0].objects.link(body)
+ body.parent = root
+ body["aetheris_owner"] = root.aetheris.uid
+ else:
+ body.data = mesh
+ body["aetheris_mesh_hash"] = mesh_hash(mesh)
+ part = root.aetheris
+ if not part.step:
+ part.step = text_block(".Aetheris STEP " + part.uid[:8], "")
+ part.step.clear()
+ part.step.write(step)
+ part.step_hash = hashlib.sha256(step.encode()).hexdigest()
+ part.accepted_hash = digest
+ part.revision += 1
+ part.status = f"Built revision {part.revision} · {len(faces):,} display triangles"
+ if reset_faces:
+ part.status += " · topology changed: face materials reset; slots retained"
+ if part.diagnostics:
+ part.diagnostics.clear()
+ if old and old.users == 0:
+ bpy.data.meshes.remove(old)
+ return body
+
+
+def accepted_step(root):
+ part = root.aetheris
+ if not part.step or current_hash(root) != part.accepted_hash:
+ raise BuildError("Build the current source successfully before exporting STEP.")
+ step = part.step.as_string()
+ if hashlib.sha256(step.encode()).hexdigest() != part.step_hash:
+ raise BuildError("The saved STEP text changed. Rebuild before exporting.")
+ return step