Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Improve WebGPU viewport rendering and shader loading

Yuechen Li8e8a080e9911
diff --git a/Aetheris.Kernel.Firmament.Tests/DisplayProjectionTests.cs b/Aetheris.Kernel.Firmament.Tests/DisplayProjectionTests.cs
new file mode 100644
index 00000000..314f85cb
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/DisplayProjectionTests.cs
@@ -0,0 +1,157 @@
+using System.Text.Json;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Kernel.Firmament.Scene;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class DisplayProjectionTests
+{
+ private static string PathFor(string relative) => FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/"+relative);
+ [Theory]
+ [InlineData("Basics/box.firmament")]
+ [InlineData("Basics/cylinder.firmament")]
+ [InlineData("DisplayProjection/sphere.firmament")]
+ [InlineData("DisplayProjection/cone.firmament")]
+ [InlineData("DisplayProjection/torus.firmament")]
+ public void V2RetainsQualifiedEvaluableCirBesideBrepAndSerializesOnlySafeMetadata(string fixture)
+ {
+ var source = File.ReadAllText(PathFor(fixture));
+ var built = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(built.IsSuccess, string.Join("\n", built.Diagnostics));
+ Assert.NotNull(built.Value.RuntimeBody);
+ var cir = Assert.IsType<FirmamentCirRetention>(built.Value.Cir);
+ Assert.Equal("cir-qualified", cir.Qualification);
+ Assert.NotNull(cir.RuntimeRoot);
+ Assert.Equal(cir.DefinitionId, FirmamentBuildAndExport.CompileSource(source).Value.Cir!.DefinitionId);
+ Assert.Contains("function Field", cir.FieldSource);
+ Assert.DoesNotContain("RuntimeRoot", JsonSerializer.Serialize(cir));
+ Assert.DoesNotContain("RuntimeBody", JsonSerializer.Serialize(built.Value));
+ var outside = new Point3D(cir.MaximumMm![0]+100, cir.MaximumMm[1]+100, cir.MaximumMm[2]+100);
+ Assert.True(cir.RuntimeRoot!.Evaluate(outside)>0);
+ var shader = CirShaderArtifactProvider.Resolve(cir);
+ Assert.Equal("shader-artifact-bound", shader.Status);
+ Assert.NotNull(shader.Artifact);
+ Assert.Equal(cir.StructuralIdentity, shader.Artifact.SourceIdentity);
+ Assert.Contains("@fragment", shader.Artifact.Wgsl);
+ Assert.Equal(32, Assert.Single(shader.Artifact.Bindings).ByteSize);
+ Assert.True(CirShaderArtifactProvider.Resolve(cir).CacheHit);
+ var roundtrip = JsonSerializer.Deserialize<DisplayShaderArtifact>(JsonSerializer.Serialize(shader.Artifact))!;
+ Assert.Equal(shader.Artifact.ShaderId, roundtrip.ShaderId);
+ Assert.Equal(shader.Artifact.Wgsl, roundtrip.Wgsl);
+ }
+
+ [Fact]
+ public void ExistingBoundedCsgMirrorRetainsItsEvaluableRootWithoutSerializingAst()
+ {
+ var compilation = FirmamentCorpusHarness.Compile(FirmamentCorpusHarness.ReadFixtureText("fixtures/Compatibility/LegacyV1/Examples/w2_cylinder_root_blind_bore_semantic.firmament"));
+ Assert.True(compilation.Compilation.IsSuccess);
+ var mirror = compilation.Compilation.Value.PrimitiveExecutionResult!.NativeGeometryState.CirMirror;
+ Assert.NotNull(mirror.RuntimeRoot);
+ Assert.DoesNotContain("RuntimeRoot", JsonSerializer.Serialize(mirror));
+ var retained = FirmamentCirRetention.FromRoot(mirror.RuntimeRoot, "compatibility-csg-test");
+ Assert.Equal("cir-qualified",retained.Qualification);
+ Assert.Equal("shader-artifact-bound",CirShaderArtifactProvider.Resolve(retained).Status);
+ var normal = FirmamentBuildAndExport.CompileSource(FirmamentCorpusHarness.ReadFixtureText("fixtures/Compatibility/LegacyV1/Examples/w2_cylinder_root_blind_bore_semantic.firmament"));
+ Assert.False(normal.IsSuccess);
+ Assert.Contains(normal.Diagnostics,d=>d.Message.StartsWith("firmament-v2-source-required",StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void HouseProjectsTheSameOwnedEnvironmentMaterialsAndCamerasFromSnapshot()
+ {
+ var root = PathFor("Scene/WarmModernHouse/house.firmament");
+ var documents = Directory.GetFiles(Path.GetDirectoryName(root)!, "*.firmament")
+ .ToDictionary(p => Path.GetFileName(p), File.ReadAllText);
+ using var session = new FirmamentSceneSession();
+ var result = session.CompileProject(new("house.firmament", documents!));
+ Assert.True(result.IsSuccess, string.Join("\n",result.Diagnostics));
+ var compiled = result.Scene!;
+ var display = DisplayProjection.Project(compiled);
+ Assert.Equal(94,display.Definitions.Count);
+ Assert.Equal(254,display.Occurrences.Count);
+ Assert.Equal(3,display.Cameras.Count);
+ Assert.Equal(compiled.MinimumMm, display.MinimumMm);
+ Assert.Equal(compiled.Appearances.Count, display.Occurrences.Count(o=>o.Material is not null));
+ Assert.Contains(display.Occurrences,o=>o.Kind=="WindowFinish" && o.Material?.Opacity<1);
+ Assert.Contains(display.Occurrences,o=>o.Kind=="EnvironmentPanel");
+ Assert.Throws<ArgumentException>(()=>DisplayProjection.Project(compiled,["main.notABoundary"]));
+ var repeated = session.CompileProject(new("house.firmament", documents!));
+ Assert.Equal(0,repeated.Scene!.Performance.RebuiltEngineeringDefinitions);
+ Assert.Equal(display.Occurrences.Select(o=>o.Id), repeated.Scene.Display.Occurrences.Select(o=>o.Id));
+ var changedDocuments = new Dictionary<string,string>(documents!)
+ { ["house.firmament"] = documents["house.firmament"].Replace("[.55, .35, .18]", "[.25, .35, .18]")
+ .Replace("[2500mm, 1450mm]", "[2600mm, 1450mm]")
+ .Replace("[8.1m, .65m, 1.65m]", "[8.2m, .65m, 1.65m]") };
+ var edited = session.CompileProject(new("house.firmament",changedDocuments));
+ Assert.True(edited.IsSuccess, string.Join("\n",edited.Diagnostics));
+ var next = DisplayProjection.Project(edited.Scene!);
+ Assert.Equal(0,edited.Scene!.Performance.RebuiltEngineeringDefinitions);
+ Assert.Equal(display.Definitions.Select(d=>d.GeometryRevision),next.Definitions.Select(d=>d.GeometryRevision));
+ Assert.NotEqual(display.Occurrences.Single(o=>o.Path=="WarmModernHouse.main.floor.panel0").Material!.BaseColor[0],
+ next.Occurrences.Single(o=>o.Path=="WarmModernHouse.main.floor.panel0").Material!.BaseColor[0]);
+ Assert.NotEqual(display.Occurrences.Single(o=>o.Path=="WarmModernHouse.living").Transform[12],next.Occurrences.Single(o=>o.Path=="WarmModernHouse.living").Transform[12]);
+ Assert.NotEqual(display.Cameras.Single(c=>c.Name=="Hero").Transform[12], next.Cameras.Single(c=>c.Name=="Hero").Transform[12]);
+ }
+
+ [Fact]
+ public void MissingSnapshotDependencyNeverFallsBackToDisk()
+ {
+ var source = File.ReadAllText(PathFor("Scene/WarmModernHouse/house.firmament"));
+ using var session = new FirmamentSceneSession();
+ var result = session.CompileProject(new("house.firmament", new Dictionary<string,string>{{"house.firmament",source}}));
+ Assert.False(result.IsSuccess);
+ Assert.Contains(result.Diagnostics,d=>d.Code=="scene-assembly-file-missing");
+ }
+
+ [Fact]
+ public void ShaderIdentityFollowsGeometryAndRejectsCorruptTransport()
+ {
+ var source = File.ReadAllText(PathFor("Basics/cylinder.firmament"));
+ var first = FirmamentBuildAndExport.CompileSource(source).Value.Cir!;
+ var changed = FirmamentBuildAndExport.CompileSource(source.Replace("12mm", "14mm")).Value.Cir!;
+ Assert.NotEqual(CirShaderArtifactProvider.Resolve(first).Artifact!.ShaderId, CirShaderArtifactProvider.Resolve(changed).Artifact!.ShaderId);
+ Assert.Equal(CirShaderArtifactProvider.Resolve(first).Artifact!.ShaderId, CirShaderArtifactProvider.Resolve(first with { DefinitionId = "another-definition" }).Artifact!.ShaderId);
+ var failure = CirShaderArtifactProvider.Resolve(first with { FieldSource = "corrupt" });
+ Assert.Null(failure.Artifact);
+ Assert.Equal("shader-artifact-generation-failed", failure.Status);
+ }
+
+ [Fact]
+ public void NormalAssemblySharesBoundArtifactAcrossOccurrencesAndKeepsMeshFallback()
+ {
+ var compilation = new AssemblyM1Pipeline().CompileFile(PathFor("DisplayProjection/mixed.firmament"));
+ Assert.True(compilation.IsSuccess, string.Join("\n",compilation.Diagnostics));
+ var display = AssemblyDisplayMeshExporter.Export(compilation);
+ Assert.Contains(display.Definitions, d=>d.Shader?.Artifact is not null);
+ Assert.Contains(display.Definitions, d=>d.DisplayPath=="mesh");
+ var field = Assert.Single(display.Definitions, d=>d.Shader?.Artifact is not null);
+ Assert.Equal(2,display.Occurrences.Count(o=>o.DefinitionId==field.Id));
+ Assert.NotEmpty(field.Edges);
+ Assert.All(field.Ranges!,range=>Assert.Null(range.SemanticEntityId));
+ Assert.Contains(display.Occurrences,o=>o.Material?.Metallic==.7);
+ }
+
+ [Fact]
+ public void SceneMaterialAndPlacementEditsReuseAutomaticShaderArtifact()
+ {
+ var root = PathFor("DisplayProjection/scene.firmament");
+ var assembly = File.ReadAllText(PathFor("DisplayProjection/mixed.firmament"));
+ var documents = new Dictionary<string,string> { ["scene.firmament"]=File.ReadAllText(root), ["mixed.firmament"]=assembly };
+ using var session = new FirmamentSceneSession();
+ var first = session.CompileProject(new("scene.firmament",documents));
+ Assert.True(first.IsSuccess,string.Join("\n",first.Diagnostics));
+ var display = DisplayProjection.Project(first.Scene!);
+ var shader = Assert.Single(display.Definitions,d=>d.Shader?.Artifact is not null).Shader!.Artifact!;
+ documents["mixed.firmament"] = assembly.Replace("[.55,.18,.06]","[.1,.5,.2]");
+ documents["scene.firmament"] = documents["scene.firmament"].Replace("[0mm,0mm,0mm]","[10mm,0mm,0mm]");
+ var edited = session.CompileProject(new("scene.firmament",documents));
+ Assert.True(edited.IsSuccess,string.Join("\n",edited.Diagnostics));
+ var next = DisplayProjection.Project(edited.Scene!);
+ var retained = Assert.Single(next.Definitions,d=>d.Shader?.Artifact is not null).Shader!;
+ Assert.Equal(shader.ShaderId,retained.Artifact!.ShaderId);
+ Assert.True(retained.CacheHit);
+ Assert.Contains(next.Occurrences,o=>o.Material?.BaseColor[0]==.1);
+ Assert.NotEqual(display.Occurrences.Last().Transform[12],next.Occurrences.Last().Transform[12]);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj b/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj
index ed724c37..20c6a9e3 100644
--- a/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj
+++ b/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj
@@ -9,6 +9,7 @@
</PropertyGroup>
<ItemGroup>
+ <PackageReference Include="Copeland.TS.Backend.Wgsl" Version="0.1.0-preview.1-a3.7329cf8ff04d504a" />
<PackageReference Include="Machina.Typography.OpenFont" Version="1.0.0" />
<ProjectReference Include="..\Aetheris.Firmament.SchemaGenerator\Aetheris.Firmament.SchemaGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<ProjectReference Include="..\Aetheris.Continuum\Aetheris.Continuum.csproj" />
@@ -21,6 +22,7 @@
</ItemGroup>
<ItemGroup>
+ <EmbeddedResource Include="Display\telos-field.v.ts" LogicalName="Aetheris.Display.TelosField.v.ts" />
<EmbeddedResource Include="Resources\Inter-Regular.ttf" LogicalName="Aetheris.Drawing.Inter.ttf" />
<EmbeddedResource Include="Resources\ProfileModifications.firmament" />
<EmbeddedResource Include="Standard\StandardProducts.firmament" LogicalName="Aetheris.Standard.StandardProducts.firmament" />
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
index b7b51375..0afc533a 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs
@@ -4,13 +4,35 @@ using Aetheris.Kernel.Core.Geometry;
namespace Aetheris.Kernel.Firmament.Assembly;
-public sealed record AssemblyDisplayMeshRange(int StartTriangle, int TriangleCount, string FaceId, string SemanticEntityId);
+public sealed record AssemblyDisplayMeshRange(int StartTriangle, int TriangleCount, string FaceId, string? SemanticEntityId);
+public sealed record DisplayProjectionDiagnostic(string Code, string Message, string? FaceId = null);
+public sealed record DisplayProjectionEdge(string EdgeId, double[][] Points, bool Closed);
public sealed record AssemblyDisplayMeshDefinition(string Id, string Identity, double[] Positions, double[] Normals, int[] Indices,
- string MeshPipeline = "LegacyTessellator", IReadOnlyList<AssemblyDisplayMeshRange>? Ranges = null);
+ string MeshPipeline = "LegacyTessellator", IReadOnlyList<AssemblyDisplayMeshRange>? Ranges = null)
+{
+ public FirmamentCirRetention? Cir { get; init; }
+ public string? GeometryRevision { get; init; }
+ public CirShaderBinding? Shader { get; init; }
+ public IReadOnlyList<DisplayProjectionEdge> Edges { get; init; } = [];
+ public string DisplayPath => Shader?.Artifact is not null ? "cir" : "mesh";
+ public string? FallbackReason => Shader?.Artifact is not null ? null : Shader?.Reason ?? DisplayProjection.FallbackReason(Cir);
+ public IReadOnlyList<DisplayProjectionDiagnostic> Diagnostics { get; init; } = [];
+}
public sealed record AssemblyDisplayMeshOccurrence(string Id, string Path, string? ParentId, string? DefinitionId, double[] Transform,
- string? SemanticEntityId = null);
+ string? SemanticEntityId = null)
+{
+ public ResolvedDisplayMaterial? Material { get; init; }
+ public string? Kind { get; init; }
+}
+public sealed record ResolvedDisplayMaterial(double[] BaseColor, double Roughness, double Metallic, double Opacity, double[] Emissive);
public sealed record AssemblyDisplayMeshDocument(string Schema, string Name, string Units,
- IReadOnlyList<AssemblyDisplayMeshDefinition> Definitions, IReadOnlyList<AssemblyDisplayMeshOccurrence> Occurrences);
+ IReadOnlyList<AssemblyDisplayMeshDefinition> Definitions, IReadOnlyList<AssemblyDisplayMeshOccurrence> Occurrences)
+{
+ public IReadOnlyList<DisplayCamera> Cameras { get; init; } = [];
+ public double[]? MinimumMm { get; init; }
+ public double[]? MaximumMm { get; init; }
+ public IReadOnlyList<Aetheris.Kernel.Firmament.Scene.SceneBoundary> Boundaries { get; init; } = [];
+}
/// <summary>Deterministic local-definition meshes plus world occurrence frames. Never drops failed geometry.</summary>
public static class AssemblyDisplayMeshExporter
@@ -48,7 +70,10 @@ public static class AssemblyDisplayMeshExporter
var definitions = new List<AssemblyDisplayMeshDefinition>();
foreach (var (identity, body) in geometry.DefinitionBodies.OrderBy(p => p.Key, StringComparer.Ordinal))
{
- definitions.Add(PrepareDefinition(ids[identity], identity, body, options));
+ var artifact = geometry.Artifact.Definitions.Single(d => d.DefinitionIdentity == identity);
+ var externalStep = artifact.Provenance.Any(p => p.Stage == "imported-step-definition");
+ definitions.Add(PrepareDefinition(ids[identity], identity, body, options, externalStep) with
+ { Cir = geometry.DefinitionCir.GetValueOrDefault(identity), Shader = CirShaderArtifactProvider.Resolve(geometry.DefinitionCir.GetValueOrDefault(identity)), GeometryRevision = artifact.StepSha256 });
}
var occurrences = (pose?.Instances ?? compilation.Ir.Instances).OrderBy(i => i.Path.ToString(), StringComparer.Ordinal).Select(instance =>
{
@@ -56,21 +81,25 @@ public static class AssemblyDisplayMeshExporter
? ids.GetValueOrDefault(instance.DefinitionIdentity) ?? throw new InvalidOperationException($"assembly-mesh-missing-definition:{instance.Path}") : null;
if (instance.ResolvedTransform is null || instance.ResolvedTransform.Matrix.Length != 16 || instance.ResolvedTransform.Matrix.Any(v => !double.IsFinite(v)))
throw new InvalidOperationException($"assembly-mesh-unresolved-transform:{instance.Path}");
- return new AssemblyDisplayMeshOccurrence(instance.StableId, instance.Path.ToString(), instance.ParentStableId, id, instance.ResolvedTransform.Matrix.ToArray(), instance.StableId);
+ return new AssemblyDisplayMeshOccurrence(instance.StableId, instance.Path.ToString(), instance.ParentStableId, id, instance.ResolvedTransform.Matrix.ToArray(), instance.StableId)
+ { Material = DisplayProjection.Material(instance.Appearance), Kind = instance.Kind.ToString() };
}).ToArray();
return new("aetheris/assembly-display-mesh/1", compilation.Ir.Name, "mm", definitions, occurrences);
}
- internal static AssemblyDisplayMeshDefinition PrepareDefinition(string id, string identity, Aetheris.Kernel.Core.Brep.BrepBody body, DisplayTessellationOptions? options = null)
+ public static AssemblyDisplayMeshDefinition PrepareDefinition(string id, string identity, Aetheris.Kernel.Core.Brep.BrepBody body,
+ DisplayTessellationOptions? options = null, bool externalStep = false)
{
var effectiveOptions = options ?? new DisplayTessellationOptions(double.Pi / 16, .3, 6, 64);
// Reuse the OBJ export's shared-boundary mesher for planar/cylindrical
// and formed-wire torus parts. A failure on this admitted family must remain visible; do not
// silently replace a failed cap or bore with the legacy mesh.
- var useSurfaceMeshIr = body.Topology.Faces.All(face =>
+ // External STEP provenance does not admit arbitrary trims to the authored
+ // shared-boundary family. Preserve its existing bounded display route.
+ var useSurfaceMeshIr = !externalStep && body.Topology.Faces.All(face =>
body.TryGetFaceSurfaceGeometry(face.Id, out var surface)
&& surface?.Kind is SurfaceGeometryKind.Plane or SurfaceGeometryKind.Cylinder or SurfaceGeometryKind.Torus);
- var structuredSpline = !useSurfaceMeshIr && RectangularSplineDisplayTessellator.TryTessellate(body, effectiveOptions, out var splineMesh)
+ var structuredSpline = !externalStep && !useSurfaceMeshIr && RectangularSplineDisplayTessellator.TryTessellate(body, effectiveOptions, out var splineMesh)
? splineMesh : null;
var tessellation = structuredSpline is not null
? Aetheris.Kernel.Core.Results.KernelResult<DisplayTessellationResult>.Success(structuredSpline)
@@ -81,11 +110,19 @@ public static class AssemblyDisplayMeshExporter
throw new InvalidOperationException($"assembly-mesh-definition-failed:{identity}:" + string.Join(";", tessellation.Diagnostics.Select(d => d.Message)));
var positions = new List<double>(); var normals = new List<double>(); var indices = new List<int>();
var ranges = new List<AssemblyDisplayMeshRange>();
+ var diagnostics = tessellation.Diagnostics.Select(d => new DisplayProjectionDiagnostic(d.Source ?? d.Code.ToString(), d.Message)).ToList();
foreach (var rawFace in tessellation.Value.FacePatches.OrderBy(p => p.FaceId.Value))
{
// Both tessellation paths emit canonically oriented patches. Assembly placement transforms
// positions and normals but never reinterprets interchange orientation evidence.
var face = rawFace;
+ if (externalStep && face.Positions.Count == 0 && face.Normals.Count == 0 && face.TriangleIndices.Count == 0)
+ {
+ var faceId = $"face:{face.FaceId.Value}";
+ ranges.Add(new(indices.Count / 3, 0, faceId, null));
+ diagnostics.Add(new("display-external-face-unmeshed", "The bounded importer display route supplied no triangles for this face; engineering BRep remains retained.", faceId));
+ continue;
+ }
if (face.Positions.Count == 0 || face.Normals.Count != face.Positions.Count || face.TriangleIndices.Count == 0
|| face.TriangleIndices.Count % 3 != 0 || face.TriangleIndices.Any(i => i < 0 || i >= face.Positions.Count))
throw new InvalidOperationException($"assembly-mesh-face-invalid:{identity}:{face.FaceId}:positions={face.Positions.Count};normals={face.Normals.Count};indices={face.TriangleIndices.Count};" + string.Join(";", tessellation.Diagnostics.Select(d => d.Message)));
@@ -94,12 +131,16 @@ public static class AssemblyDisplayMeshExporter
positions.AddRange(face.Positions.SelectMany(p => new[] { p.X, p.Y, p.Z }));
normals.AddRange(face.Normals.SelectMany(p => new[] { p.X, p.Y, p.Z }));
indices.AddRange(face.TriangleIndices.Select(i => i + offset));
- ranges.Add(new(startTriangle, face.TriangleIndices.Count / 3, $"face:{face.FaceId.Value}", id));
+ // Shared faces own topology, not one occurrence's semantic node.
+ // The SDK resolves an unbound range through the selected occurrence.
+ ranges.Add(new(startTriangle, face.TriangleIndices.Count / 3, $"face:{face.FaceId.Value}", null));
}
if (positions.Concat(normals).Any(v => !double.IsFinite(v)))
throw new InvalidOperationException($"assembly-mesh-nonfinite:{identity}");
return new(id, identity, positions.ToArray(), normals.ToArray(), indices.ToArray(),
- tessellation.Value.MeshPipeline.ToString(), ranges);
+ tessellation.Value.MeshPipeline.ToString(), ranges) { Diagnostics = diagnostics,
+ Edges = tessellation.Value.EdgePolylines.Select(e=>new DisplayProjectionEdge($"edge:{e.EdgeId.Value}",
+ e.Points.Select(p=>new[]{p.X,p.Y,p.Z}).ToArray(),e.IsClosed)).ToArray() };
}
public static string Serialize(AssemblyDisplayMeshDocument document)
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
index 0e3da4db..b2db70bb 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
@@ -17,7 +17,10 @@ namespace Aetheris.Kernel.Firmament.Assembly;
public sealed record AssemblyExecutedGeometry(
AssemblyGeometryArtifactIr Artifact,
IReadOnlyDictionary<string, BrepBody> DefinitionBodies,
- IReadOnlyDictionary<string, BrepBody> InstanceBodies);
+ IReadOnlyDictionary<string, BrepBody> InstanceBodies)
+{
+ public IReadOnlyDictionary<string, FirmamentCirRetention> DefinitionCir { get; init; } = new Dictionary<string, FirmamentCirRetention>();
+}
public sealed record AssemblyM1CompilationResult(
AssemblyIr? Ir,
@@ -53,7 +56,8 @@ internal sealed record MaterializedAssemblyDefinition(
BrepBody Body,
IReadOnlyList<SemanticValue> Semantics,
AssemblyDefinitionArtifactIr Artifact,
- string? CanonicalStep = null);
+ string? CanonicalStep = null,
+ FirmamentCirRetention? Cir = null);
/// <summary>
/// M1's definition seam: specialize through the ordinary Firmament compiler, then
@@ -263,7 +267,7 @@ internal static class AssemblyDefinitionMaterializer
var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(build.Value.StepText)));
var stableId = "assembly-definition:" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(definitionIdentity)))[..16];
var artifact = new AssemblyDefinitionArtifactIr(stableId, definitionIdentity, specialization, hash, Metrics(import.Value), provenance);
- return new(definitionIdentity, specialization, import.Value, semantics, artifact, build.Value.StepText);
+ return new(definitionIdentity, specialization, import.Value, semantics, artifact, build.Value.StepText, build.Value.Cir);
}
private static IEnumerable<SemanticValue> WindingSemantics(FirmamentWireFormReport? wire,
@@ -473,7 +477,11 @@ public sealed class AssemblyM1Pipeline
var canonical = JsonSerializer.Serialize(new { definitions = definitionsIr, instances = instanceArtifacts, residuals });
var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(canonical)));
var artifact = new AssemblyGeometryArtifactIr("aetheris/assembly-geometry/m1", definitionsIr, instanceArtifacts, residuals, hash, datumSeats);
- return new(artifact, definitions.ToDictionary(pair => pair.Key, pair => pair.Value.Body, StringComparer.Ordinal), instances);
+ return new(artifact, definitions.ToDictionary(pair => pair.Key, pair => pair.Value.Body, StringComparer.Ordinal), instances)
+ {
+ DefinitionCir = definitions.Where(p => p.Value.Cir is not null)
+ .ToDictionary(p => p.Key, p => p.Value.Cir! with { DefinitionId = p.Value.Artifact.StableId }, StringComparer.Ordinal)
+ };
}
private static void ValidateSolidInterference(AssemblyIr ir, IReadOnlyDictionary<string, BrepBody> instances, List<AssemblyDiagnostic> diagnostics)
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyUsdExporter.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyUsdExporter.cs
index d5ce721e..9402a7fb 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyUsdExporter.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyUsdExporter.cs
@@ -14,7 +14,10 @@ public sealed record AssemblyUsdOptions(IReadOnlyDictionary<string, double>? Sta
IReadOnlyList<AssemblyUsdSample>? Samples = null,
IReadOnlyDictionary<string, AssemblyUsdMaterial>? DefinitionMaterials = null);
-public sealed record DisplayCamera(string Name, double[] Transform, double FovDegrees);
+public sealed record DisplayCamera(string Name, double[] Transform, double FovDegrees)
+{
+ public double[]? LookAtMm { get; init; }
+}
public sealed record SpatialUsdMetadata(IReadOnlyDictionary<string,string> DefinitionIdentities,
IReadOnlyDictionary<string,AssemblyAppearanceBinding> Appearances,
IReadOnlyDictionary<string,IReadOnlyDictionary<string,string>> Properties,
diff --git a/Aetheris.Kernel.Firmament/Assembly/CirShaderArtifactProvider.cs b/Aetheris.Kernel.Firmament/Assembly/CirShaderArtifactProvider.cs
new file mode 100644
index 00000000..cdcbaf90
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Assembly/CirShaderArtifactProvider.cs
@@ -0,0 +1,65 @@
+using System.Diagnostics;
+using System.Reflection;
+using System.Security.Cryptography;
+using System.Text;
+using Copeland.TS.Gpu;
+using Copeland.TS.Gpu.Wgsl;
+using Copeland.TS.Gpu.VdMir;
+
+namespace Aetheris.Kernel.Firmament.Assembly;
+
+public sealed record DisplayShaderBinding(int Group, int Binding, string Kind, int ByteSize);
+public sealed record DisplayShaderArtifact(string ShaderId, string Wgsl, string VertexEntryPoint,
+ string FragmentEntryPoint, IReadOnlyList<DisplayShaderBinding> Bindings, IReadOnlyList<string> Capabilities,
+ string SourceIdentity, string CompilerVersion, string Schema = "aetheris/display-shader/1");
+public sealed record CirShaderBinding(DisplayShaderArtifact? Artifact, string Status, string? Reason,
+ bool CacheHit, double GenerationMilliseconds);
+
+/// <summary>Bounded display-only compilation over compiler-retained CIR. No GPU or product state.</summary>
+public static class CirShaderArtifactProvider
+{
+ private static readonly object Gate = new();
+ private static readonly Dictionary<string, CirShaderBinding> Cache = new(StringComparer.Ordinal);
+ private static readonly Queue<string> Order = new();
+ private static readonly string Template = ReadTemplate();
+ private static readonly string Compiler = WgslGraphicsBackend.CompatibilityVersion + ":" +
+ typeof(WgslGraphicsBackend).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
+ private static readonly string Contract = Compiler + ":" + Hash(Template);
+ private static string Hash(string text) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant();
+ private static string ReadTemplate()
+ {
+ using var stream = typeof(CirShaderArtifactProvider).Assembly.GetManifestResourceStream("Aetheris.Display.TelosField.v.ts")!;
+ using var reader = new StreamReader(stream);
+ return reader.ReadToEnd().Replace("\r\n", "\n", StringComparison.Ordinal);
+ }
+ public static CirShaderBinding Resolve(FirmamentCirRetention? cir)
+ {
+ if (cir?.Qualification != "cir-qualified")
+ return new(null, "mesh-fallback", cir?.FallbackReason ?? "no-field-representation", false, 0);
+ if (cir.FieldSource is null || cir.StructuralIdentity is null ||
+ Hash(Aetheris.Continuum.Backends.Sdf.CirVisualTsLowerer.CompatibilityVersion + "\n" + cir.FieldSource) != cir.StructuralIdentity)
+ return new(null, "shader-artifact-generation-failed", "Retained field source/structural identity mismatch.", false, 0);
+ var key = Contract + ":" + cir.StructuralIdentity;
+ lock (Gate)
+ {
+ if (Cache.TryGetValue(key, out var cached)) return cached with { CacheHit = true, GenerationMilliseconds = 0 };
+ var timer = Stopwatch.StartNew();
+ var result = WgslGraphicsBackend.Compile(new GpuCompilationRequest([new GpuSourceFile("TelosField.v.ts", cir.FieldSource + Template)]));
+ CirShaderBinding binding;
+ if (!result.Success)
+ binding = new(null, "shader-artifact-generation-failed", string.Join("; ", result.Diagnostics.Select(d => d.Code + ": " + d.Message)), false, timer.Elapsed.TotalMilliseconds);
+ else
+ {
+ var program = result.Program!;
+ var artifact = new DisplayShaderArtifact(Hash(Contract + ":" + program.SemanticHash), program.Code,
+ program.VertexEntryPoint, program.FragmentEntryPoint,
+ [new(0, 0, "uniform", program.Semantics.Material!.Size)],
+ ["fragment-depth", "telos-field-rays/2", "rigid-occurrence"], cir.StructuralIdentity, Compiler);
+ binding = new(artifact, "shader-artifact-bound", null, false, timer.Elapsed.TotalMilliseconds);
+ }
+ if (Cache.Count == 256) Cache.Remove(Order.Dequeue());
+ Cache.Add(key, binding); Order.Enqueue(key);
+ return binding;
+ }
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Assembly/DisplayProjection.cs b/Aetheris.Kernel.Firmament/Assembly/DisplayProjection.cs
new file mode 100644
index 00000000..a98ef546
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Assembly/DisplayProjection.cs
@@ -0,0 +1,31 @@
+using Aetheris.Kernel.Firmament.Scene;
+
+namespace Aetheris.Kernel.Firmament.Assembly;
+
+/// <summary>Product-neutral display state over already compiled geometry and resolved appearance.</summary>
+public static class DisplayProjection
+{
+ public static string FallbackReason(FirmamentCirRetention? cir) => cir?.Qualification == "cir-qualified"
+ ? "shader-artifact-not-bound" : cir?.FallbackReason ?? "no-field-representation";
+ public static ResolvedDisplayMaterial? Material(AssemblyAppearanceBinding? appearance) => appearance is null ? null :
+ new([appearance.Preview.Red, appearance.Preview.Green, appearance.Preview.Blue], appearance.Preview.Roughness,
+ appearance.Preview.Metallic, appearance.Preview.Opacity,
+ [appearance.Preview.EmissiveRed, appearance.Preview.EmissiveGreen, appearance.Preview.EmissiveBlue]);
+
+ public static AssemblyDisplayMeshDocument Project(CompiledScene scene, IReadOnlyCollection<string>? hiddenBoundaries = null)
+ {
+ var display = SceneExport.Project(scene, hiddenBoundaries);
+ var nodes = scene.Nodes.ToDictionary(n => n.Path, StringComparer.Ordinal);
+ return display with
+ {
+ Definitions = display.Definitions.Select(d => d with { Shader = d.Shader ?? CirShaderArtifactProvider.Resolve(d.Cir) }).ToArray(),
+ Occurrences = display.Occurrences.Select(o => o with
+ {
+ Material = Material(scene.Appearances.GetValueOrDefault(o.Id)) ?? o.Material,
+ Kind = nodes.GetValueOrDefault(o.Path)?.Kind ?? o.Kind
+ }).ToArray(),
+ Cameras = scene.Source.Cameras.Select(c => new DisplayCamera(c.Name, c.WorldTransform(), c.FovDegrees) { LookAtMm = c.LookAtMm.ToArray() }).ToArray(),
+ MinimumMm = scene.MinimumMm.ToArray(), MaximumMm = scene.MaximumMm.ToArray(), Boundaries = scene.Boundaries
+ };
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Assembly/FirmamentCompilationSession.cs b/Aetheris.Kernel.Firmament/Assembly/FirmamentCompilationSession.cs
index 8e5dab35..8d5222ed 100644
--- a/Aetheris.Kernel.Firmament/Assembly/FirmamentCompilationSession.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/FirmamentCompilationSession.cs
@@ -168,6 +168,8 @@ internal sealed class AssemblyDefinitionCache(int capacity)
private static MaterializedAssemblyDefinition CopyMetadata(MaterializedAssemblyDefinition definition) => definition with
{
+ Cir = definition.Cir is null ? null : definition.Cir with
+ { MinimumMm = definition.Cir.MinimumMm?.ToArray(), MaximumMm = definition.Cir.MaximumMm?.ToArray() },
Semantics = definition.Semantics.Select(Copy).ToArray(),
Artifact = definition.Artifact with
{
diff --git a/Aetheris.Kernel.Firmament/Assembly/FirmamentProjectSnapshot.cs b/Aetheris.Kernel.Firmament/Assembly/FirmamentProjectSnapshot.cs
index 6c4b15c5..8f24a476 100644
--- a/Aetheris.Kernel.Firmament/Assembly/FirmamentProjectSnapshot.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/FirmamentProjectSnapshot.cs
@@ -2,7 +2,7 @@ using System.Collections.Frozen;
namespace Aetheris.Kernel.Firmament.Assembly;
-/// <summary>An immutable, project-relative source set for an assembly build.</summary>
+/// <summary>An immutable, project-relative source set for a Firmament Part, Assembly or Scene build.</summary>
public sealed class FirmamentProjectSnapshot
{
private readonly IReadOnlyDictionary<string, string> documents;
@@ -14,8 +14,8 @@ public sealed class FirmamentProjectSnapshot
{
ArgumentNullException.ThrowIfNull(documents);
RootDocument = NormalizePath(rootDocument);
- if (!RootDocument.EndsWith(".firmasm", StringComparison.OrdinalIgnoreCase))
- throw new ArgumentException("The project root must be a .firmasm document.", nameof(rootDocument));
+ if (!RootDocument.EndsWith(".firmasm", StringComparison.OrdinalIgnoreCase) && !RootDocument.EndsWith(".firmament", StringComparison.OrdinalIgnoreCase))
+ throw new ArgumentException("The project root must be a Firmament document.", nameof(rootDocument));
var normalized = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var (path, source) in documents)
{
diff --git a/fixtures/three-telos/field-pass.v.ts b/Aetheris.Kernel.Firmament/Display/telos-field.v.ts
similarity index 69%
rename from fixtures/three-telos/field-pass.v.ts
rename to Aetheris.Kernel.Firmament/Display/telos-field.v.ts
index a65d1dd1..42712bfa 100644
--- a/fixtures/three-telos/field-pass.v.ts
+++ b/Aetheris.Kernel.Firmament/Display/telos-field.v.ts
@@ -9,6 +9,7 @@ stream Input {
@location(3) depthRow: float4;
@location(4) wRow: float4;
@location(5) epsilon: f32;
+ @location(6) metallic: f32;
}
stream Varyings {
@builtin(position) position: ClipPosition;
@@ -17,10 +18,11 @@ stream Varyings {
@location(2) depthRow: float4;
@location(3) wRow: float4;
@location(4) epsilon: f32;
+ @location(5) metallic: f32;
}
stream Output { @target(0) color: float4; @builtin(frag_depth) depth: f32; }
@vertex function VertexMain(input: Input): Varyings {
- return { position: float4(input.position, 1.0), origin: input.origin, delta: input.delta, depthRow: input.depthRow, wRow: input.wRow, epsilon: input.epsilon };
+ return { position: float4(input.position, 1.0), origin: input.origin, delta: input.delta, depthRow: input.depthRow, wRow: input.wRow, epsilon: input.epsilon, metallic: input.metallic };
}
@pixel function PixelMain(input: Varyings, resources: Resources): Output {
const length: f32 = Sqrt(input.delta.x * input.delta.x + input.delta.y * input.delta.y + input.delta.z * input.delta.z);
@@ -39,10 +41,19 @@ stream Output { @target(0) color: float4; @builtin(frag_depth) depth: f32; }
const gy: f32 = Field(x,y+h,z)-Field(x,y-h,z);
const gz: f32 = Field(x,y,z+h)-Field(x,y,z-h);
const n: f32 = Max(Sqrt(gx*gx+gy*gy+gz*gz),0.00000001);
- const light: f32 = 0.28 + 0.72 * Abs((gx*0.3+gy*0.8+gz*0.6)/n);
+ const light: f32 = 0.28 + 0.72 * Abs((gx*0.287347886+gy*0.766261029+gz*0.574695772)/n);
+ const s: f32 = Min(Abs((gx*0.161+gy*0.432+gz*0.887)/n),1.0);
+ const s2: f32 = s*s;
+ const s4: f32 = s2*s2;
+ const s8: f32 = s4*s4;
+ const s16: f32 = s8*s8;
+ const s32: f32 = s16*s16;
+ const s64: f32 = s32*s32;
+ const rough: f32 = Min(Max(resources.frame.roughness,0.04),1.0);
+ const spec: f32 = (s64*(1.0-rough)+s2*rough)*(0.05+Min(Max(input.metallic,0.0),1.0)*0.2);
const clipZ: f32 = input.depthRow.x*x+input.depthRow.y*y+input.depthRow.z*z+input.depthRow.w;
const clipW: f32 = input.wRow.x*x+input.wRow.y*y+input.wRow.z*z+input.wRow.w;
- return { color: float4(resources.frame.tint.x*light,resources.frame.tint.y*light,resources.frame.tint.z*light,resources.frame.tint.w), depth: clipZ/clipW };
+ return { color: float4(Sqrt(Max(resources.frame.tint.x*light+spec,0.0)),Sqrt(Max(resources.frame.tint.y*light+spec,0.0)),Sqrt(Max(resources.frame.tint.z*light+spec,0.0)),resources.frame.tint.w), depth: clipZ/clipW };
}
t = t + Abs(d) * 0.9;
if (t > length) { break; }
diff --git a/Aetheris.Kernel.Firmament/Execution/FirmamentPrimitiveExecutor.cs b/Aetheris.Kernel.Firmament/Execution/FirmamentPrimitiveExecutor.cs
index 9dfbea72..fb43eb94 100644
--- a/Aetheris.Kernel.Firmament/Execution/FirmamentPrimitiveExecutor.cs
+++ b/Aetheris.Kernel.Firmament/Execution/FirmamentPrimitiveExecutor.cs
@@ -367,7 +367,7 @@ internal static class FirmamentPrimitiveExecutor
analysis.Volume.Approximate,
analysis.Volume.Resolution);
- return new NativeGeometryCirMirrorState(CirMirrorStatus.Available, summary, []);
+ return new NativeGeometryCirMirrorState(CirMirrorStatus.Available, summary, []) { RuntimeRoot = lower.Value.Root };
}
private static KernelResult<NativeGeometryState> TryBuildCirOnlyFallback(
diff --git a/Aetheris.Kernel.Firmament/Execution/NativeGeometryState.cs b/Aetheris.Kernel.Firmament/Execution/NativeGeometryState.cs
index 9d6dede9..81598a61 100644
--- a/Aetheris.Kernel.Firmament/Execution/NativeGeometryState.cs
+++ b/Aetheris.Kernel.Firmament/Execution/NativeGeometryState.cs
@@ -88,7 +88,11 @@ public sealed record NativeGeometryCirMirrorSummary(
public sealed record NativeGeometryCirMirrorState(
CirMirrorStatus Status,
NativeGeometryCirMirrorSummary? Summary,
- IReadOnlyList<NativeGeometryCirMirrorDiagnostics> Diagnostics);
+ IReadOnlyList<NativeGeometryCirMirrorDiagnostics> Diagnostics)
+{
+ [System.Text.Json.Serialization.JsonIgnore]
+ public Aetheris.Continuum.Backends.Sdf.SdfNode? RuntimeRoot { get; init; }
+}
public sealed record NativeGeometryState(
NativeGeometryExecutionMode ExecutionMode,
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index 624cdd83..c73bea4b 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -608,7 +608,11 @@ public static class FirmamentBuildAndExport
"primitive",
v2Parse.Document.Solid.RecordType.ToLowerInvariant(),
DatumInspection: v2Parse.Document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.DatumPlane).Select(p => new FirmamentPmiInspectionDatum(p.Name, "planar", p.Target)).ToArray() ?? [],
- DimensionInspection: []);
+ DimensionInspection: [])
+ {
+ RuntimeBody = executedPrimitive.Body,
+ Cir = FirmamentCirRetention.FromRoot(execution.Value.NativeGeometryState.CirMirror.RuntimeRoot, step.Value)
+ };
if (executedPrimitive.Kind == FirmamentLoweredPrimitiveKind.Box
&& executedPrimitive.BoxConstructionTopology is { } boxTopology
&& v2Parse.Document.Solids.Count == 1
diff --git a/Aetheris.Kernel.Firmament/FirmamentCirRetention.cs b/Aetheris.Kernel.Firmament/FirmamentCirRetention.cs
new file mode 100644
index 00000000..7e9d2954
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentCirRetention.cs
@@ -0,0 +1,28 @@
+using System.Text.Json.Serialization;
+using System.Security.Cryptography;
+using System.Text;
+using Aetheris.Continuum.Backends.Sdf;
+
+namespace Aetheris.Kernel.Firmament;
+
+/// <summary>Compiler-owned display eligibility. The field never owns engineering topology.</summary>
+public sealed record FirmamentCirRetention(string DefinitionId, string Qualification, string? FallbackReason,
+ string? StructuralIdentity, string? FieldSource, double[]? MinimumMm, double[]? MaximumMm)
+{
+ public const string Version = "aetheris/cir-retention/1";
+ public string Schema => Version;
+ [JsonIgnore] public SdfNode? RuntimeRoot { get; init; }
+
+ internal static FirmamentCirRetention FromRoot(SdfNode? root, string step)
+ {
+ var definition = "definition:" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step)))[..16].ToLowerInvariant();
+ if (root is null) return new(definition, "mesh", "no-qualified-cir-mirror", null, null, null, null);
+ var display = CirVisualTsLowerer.Lower(root);
+ if (!display.Success) return new(definition, "mesh", display.FallbackReason, null, null, null, null)
+ { RuntimeRoot = root };
+ var program = display.Program!;
+ return new(definition, "cir-qualified", null, program.StructuralHash, program.FieldSource,
+ [program.Bounds.Min.X, program.Bounds.Min.Y, program.Bounds.Min.Z],
+ [program.Bounds.Max.X, program.Bounds.Max.Y, program.Bounds.Max.Z]) { RuntimeRoot = root };
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
index e864ce16..8b7deced 100644
--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
@@ -41,6 +41,7 @@ public sealed record FirmamentStepExportResult(
// It is intentionally absent from CLI/JSON artifact serialization.
[JsonIgnore] public BrepBody? RuntimeBody { get; init; }
[JsonIgnore] public SemanticTopologyCorrespondence? RuntimeCorrespondence { get; init; }
+ public FirmamentCirRetention? Cir { get; init; }
}
public sealed record FirmamentThreadReport(
diff --git a/Aetheris.Kernel.Firmament/Scene/SceneCompilation.cs b/Aetheris.Kernel.Firmament/Scene/SceneCompilation.cs
index ceecb4c9..55d8f0ba 100644
--- a/Aetheris.Kernel.Firmament/Scene/SceneCompilation.cs
+++ b/Aetheris.Kernel.Firmament/Scene/SceneCompilation.cs
@@ -31,7 +31,10 @@ public sealed class FirmamentSceneSession : IDisposable
private readonly Dictionary<string,FirmamentCompilationSession> assemblies = new(StringComparer.OrdinalIgnoreCase);
private bool disposed;
public SceneCompilationResult CompileFile(string path) => Compile(File.ReadAllText(path),Path.GetFullPath(path));
- public SceneCompilationResult Compile(string source, string sourceIdentity = "<memory>")
+ public SceneCompilationResult CompileProject(FirmamentProjectSnapshot project) => project.TryResolve(project.RootDocument, out var source)
+ ? Compile(source, project.RootDocument, project)
+ : new(null, [new("scene-project-root-missing", project.RootDocument)]);
+ public SceneCompilationResult Compile(string source, string sourceIdentity = "<memory>", FirmamentProjectSnapshot? project = null)
{
lock (gate)
{
@@ -53,28 +56,32 @@ public sealed class FirmamentSceneSession : IDisposable
{
var match=Regex.Match(item.Definition,"^AssemblyFile<\\s*\"(?<path>[^\"]+)\"\\s*>$");
if (!match.Success) { Error("scene-assembly-definition-invalid","X0 assembly occurrences require AssemblyFile<\"relative.firmament\">; their document compiles independently."); continue; }
- var path=Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Path.GetFullPath(sourceIdentity))!,match.Groups["path"].Value));
- var allowedRoot=AssemblyM0Parser.FindAllowedSourceRoot(Path.GetFullPath(sourceIdentity));
- var allowedPrefix=Path.TrimEndingDirectorySeparator(allowedRoot)+Path.DirectorySeparatorChar;
- if (!path.StartsWith(allowedPrefix,StringComparison.OrdinalIgnoreCase))
- { Error("scene-assembly-file-outside-root","AssemblyFile must stay inside the existing allowed source root."); continue; }
+ var path=AssemblyPathFor(match.Groups["path"].Value);
+ if (path is null) continue;
+ if (project is null)
+ {
+ var allowedRoot=AssemblyM0Parser.FindAllowedSourceRoot(Path.GetFullPath(sourceIdentity));
+ var allowedPrefix=Path.TrimEndingDirectorySeparator(allowedRoot)+Path.DirectorySeparatorChar;
+ if (!path.StartsWith(allowedPrefix,StringComparison.OrdinalIgnoreCase))
+ { Error("scene-assembly-file-outside-root","AssemblyFile must stay inside the existing allowed source root."); continue; }
+ }
if (!path.EndsWith(".firmament",StringComparison.OrdinalIgnoreCase)) { Error("scene-assembly-file-invalid","AssemblyFile requires a .firmament source document."); continue; }
if (!compiledAssemblies.ContainsKey(path))
{
- if (!File.Exists(path)) { Error("scene-assembly-file-missing",path); continue; }
+ if (project is null ? !File.Exists(path) : !project.TryResolve(path, out _)) { Error("scene-assembly-file-missing",path); continue; }
if (!assemblies.TryGetValue(path,out var session))
{
if (assemblies.Count >= 256) { Error("scene-definition-session-capacity-exceeded","The retained Scene session supports at most 256 independent Assembly sources; start a fresh session."); continue; }
assemblies[path]=session=new();
}
- var assembly=session.CompileFile(path); compiledAssemblies.Add(path,assembly);
+ var assembly=project is null ? session.CompileFile(path) : session.CompileProject(new FirmamentProjectSnapshot(path, project.Documents)); compiledAssemblies.Add(path,assembly);
diagnostics.AddRange(assembly.Diagnostics);
}
}
else if (!materializedParts.ContainsKey(item.Definition))
{
- var part=parts.Materialize(item.Definition,s.DefinitionSource,sourceIdentity,diagnostics,null,
- () => AssemblyDefinitionMaterializer.TryMaterialize(item.Definition,s.DefinitionSource,sourceIdentity,diagnostics));
+ var part=parts.Materialize(item.Definition,s.DefinitionSource,sourceIdentity,diagnostics,project,
+ () => AssemblyDefinitionMaterializer.TryMaterialize(item.Definition,s.DefinitionSource,sourceIdentity,diagnostics,project));
if (part is not null) materializedParts.Add(item.Definition,part);
}
}
@@ -155,13 +162,13 @@ public sealed class FirmamentSceneSession : IDisposable
if (item.From != "Origin") { Error("scene-part-source-frame-unsupported","X0 Part Scene placement starts at Origin; assembly published source frames are supported."); continue; }
var part=materializedParts[item.Definition]; var id=Id("part:"+item.Definition);
if (!definitions.ContainsKey(id))
- { var preparation=Stopwatch.StartNew(); definitions.Add(id,AssemblyDisplayMeshExporter.PrepareDefinition(id,item.Definition,part.Body)); displayMs+=preparation.Elapsed.TotalMilliseconds; }
+ { var preparation=Stopwatch.StartNew(); definitions.Add(id,AssemblyDisplayMeshExporter.PrepareDefinition(id,item.Definition,part.Body, externalStep: part.Artifact.Provenance.Any(p => p.Stage == "imported-step-definition")) with { Cir = part.Cir is null ? null : part.Cir with { DefinitionId = id }, GeometryRevision = part.Artifact.StepSha256 }); displayMs+=preparation.Elapsed.TotalMilliseconds; }
AddNode(item.Path,"Part",item.Definition,parent,world.ToRowMajor(),id,item.Span,item.PatternKey); ApplyLook(item.Path,item.Appearance);
}
else
{
var match=Regex.Match(item.Definition,"\"(?<path>[^\"]+)\"");
- var path=Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Path.GetFullPath(sourceIdentity))!,match.Groups["path"].Value));
+ var path=AssemblyPathFor(match.Groups["path"].Value)!;
var assembly=compiledAssemblies[path];
if (!preparedAssemblies.TryGetValue(path,out var mesh))
{ var preparation=Stopwatch.StartNew(); preparedAssemblies[path]=mesh=AssemblyDisplayMeshExporter.Export(assembly); displayMs+=preparation.Elapsed.TotalMilliseconds; }
@@ -177,7 +184,7 @@ public sealed class FirmamentSceneSession : IDisposable
foreach (var d in mesh.Definitions)
{
var id=prefix+":"+d.Id;
- if (!definitions.ContainsKey(id)) definitions.Add(id,d with { Id=id, Identity=path+"::"+d.Identity });
+ if (!definitions.ContainsKey(id)) definitions.Add(id,d with { Id=id, Identity=path+"::"+d.Identity, Cir = d.Cir is null ? null : d.Cir with { DefinitionId = id } });
}
foreach (var o in mesh.Occurrences)
{
@@ -214,6 +221,16 @@ public sealed class FirmamentSceneSession : IDisposable
}
}
void Error(string code,string message) => diagnostics.Add(new(code,message));
+ string? AssemblyPathFor(string relative)
+ {
+ try
+ {
+ return project is null
+ ? Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Path.GetFullPath(sourceIdentity))!, relative))
+ : FirmamentProjectSnapshot.NormalizePath((Path.GetDirectoryName(sourceIdentity)?.Replace('\\','/') is { Length: > 0 } directory ? directory+"/" : "")+relative);
+ }
+ catch (ArgumentException exception) { Error("scene-assembly-file-outside-root", exception.Message); return null; }
+ }
void AddNode(string path,string kind,string definition,string? parent,double[] transform,string? def,SemanticSourceSpan span,string? key=null)
{ occurrences.Add(new(Id(path),path,parent is null ? null : Id(parent),def,transform,path)); nodes.Add(new(path,kind,definition,"SceneFrame",span,key)); }
void ApplyLook(string path,string? look)
@@ -264,7 +281,7 @@ public sealed class FirmamentSceneSession : IDisposable
double[][] normals=[[0,0,-1],[0,0,1],[0,-1,0],[0,1,0],[-1,0,0],[1,0,0]];
var positions=new List<double>(); var ns=new List<double>(); var indices=new List<int>();
for(var f=0;f<6;f++) { var start=positions.Count/3; foreach(var v in faces[f]) { positions.AddRange(p[v]); ns.AddRange(normals[f]); } indices.AddRange([start,start+1,start+2,start,start+2,start+3]); }
- return new(id,identity,positions.ToArray(),ns.ToArray(),indices.ToArray(),"SceneRectangularBoundary");
+ return new(id,identity,positions.ToArray(),ns.ToArray(),indices.ToArray(),"SceneRectangularBoundary") { GeometryRevision = identity };
}
private static (double[] Min,double[] Max) WorldBounds(AssemblyDisplayMeshDocument d)
{
diff --git a/Aetheris.Kernel.Firmament/Scene/SceneExport.cs b/Aetheris.Kernel.Firmament/Scene/SceneExport.cs
index 598456c5..8d0ddc1f 100644
--- a/Aetheris.Kernel.Firmament/Scene/SceneExport.cs
+++ b/Aetheris.Kernel.Firmament/Scene/SceneExport.cs
@@ -7,7 +7,7 @@ public static class SceneExport
{
/// <summary>A presentation projection over owned Room boundaries. Geometry and
/// authored room validity remain unchanged; unknown boundaries fail closed.</summary>
- private static AssemblyDisplayMeshDocument Project(CompiledScene scene,IReadOnlyCollection<string>? hiddenBoundaries)
+ public static AssemblyDisplayMeshDocument Project(CompiledScene scene,IReadOnlyCollection<string>? hiddenBoundaries = null)
{
if (hiddenBoundaries is null || hiddenBoundaries.Count == 0) return scene.Display;
var known=scene.Boundaries.Select(b => b.Path).ToHashSet(StringComparer.Ordinal);
diff --git a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
index 2558c0bd..52dad6ea 100644
--- a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
+++ b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
@@ -951,6 +951,10 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFact
Assert.Equal(18, envelope.Data.Occurrences.Count(occurrence => occurrence.Kind == "Part"));
Assert.All(envelope.Data.Occurrences.Where(occurrence => occurrence.Kind == "Part"), occurrence => Assert.Equal("LegacyExplicit", occurrence.PlacementAuthority));
Assert.True(envelope.Data.Bounds.Maximum[0] > envelope.Data.Bounds.Minimum[0]);
+ Assert.NotNull(envelope.Data.Display);
+ Assert.Equal(5, envelope.Data.Display.Definitions.Count);
+ Assert.All(envelope.Data.Display.Definitions, definition => Assert.Equal("LegacyTessellator", definition.MeshPipeline));
+ Assert.Contains(envelope.Data.Display.Definitions, definition => definition.Diagnostics.Any(d => d.Code == "display-external-face-unmeshed"));
}
[Fact]
@@ -967,6 +971,8 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFact
Assert.Equal(18, envelope.Data.Occurrences.Count(occurrence => occurrence.Kind == "Part"));
Assert.Equal(10, envelope.Data.Occurrences.Count(occurrence => occurrence.Kind == "Assembly"));
Assert.Equal(27, envelope.Data.Occurrences.Count(occurrence => occurrence.PlacementAuthority == "ImportedOccurrence"));
+ Assert.NotNull(envelope.Data.Display);
+ Assert.Equal(28, envelope.Data.Display.Occurrences.Count);
Assert.Empty(envelope.Data.Mates);
Assert.Equal(-10, envelope.Data.Bounds.Minimum[0], 8);
Assert.Equal(190, envelope.Data.Bounds.Maximum[0], 8);
diff --git a/Aetheris.Server/Api/AssemblyDisplayService.cs b/Aetheris.Server/Api/AssemblyDisplayService.cs
index cfa63891..7dfd2560 100644
--- a/Aetheris.Server/Api/AssemblyDisplayService.cs
+++ b/Aetheris.Server/Api/AssemblyDisplayService.cs
@@ -3,6 +3,7 @@ using Aetheris.Kernel.Core.Brep.Tessellation;
using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Step242;
using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Kernel.Firmament;
using Aetheris.Server.Contracts;
namespace Aetheris.Server.Api;
@@ -74,6 +75,33 @@ public static class AssemblyDisplayService
{
packet = null; error = string.Empty;
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) { error = $"Assembly source '{path}' was not found."; return false; }
+ var source = File.ReadAllText(path);
+ if (Aetheris.Kernel.Firmament.Scene.SceneAuthoring.HasRoot(source))
+ {
+ using var session = new Aetheris.Kernel.Firmament.Scene.FirmamentSceneSession();
+ var scene = session.CompileFile(path);
+ if (!scene.IsSuccess || scene.Scene is null) { error = string.Join(Environment.NewLine, scene.Diagnostics.Select(d => d.Code+": "+d.Message)); return false; }
+ packet = FromDisplay(DisplayProjection.Project(scene.Scene));
+ return true;
+ }
+ if (!path.EndsWith(".firmasm", StringComparison.OrdinalIgnoreCase) &&
+ !System.Text.RegularExpressions.Regex.IsMatch(source, @"(?m)^\s*Assembly\s+"))
+ {
+ var part = FirmamentBuildAndExport.CompileSource(source, Path.GetDirectoryName(Path.GetFullPath(path)));
+ if (!part.IsSuccess) { error = string.Join(Environment.NewLine, part.Diagnostics.Select(d => d.Message)); return false; }
+ var body = part.Value.RuntimeBody;
+ if (body is null)
+ {
+ var imported = Step242Importer.ImportBody(part.Value.StepText);
+ body = imported.IsSuccess ? imported.Value : null;
+ }
+ if (body is null) { error = "display-part-brep-unavailable"; return false; }
+ var id = part.Value.Cir?.DefinitionId ?? "part-definition:"+part.Value.ExportedFeatureId;
+ var definition = AssemblyDisplayMeshExporter.PrepareDefinition(id, part.Value.ExportedFeatureId, body) with { Cir = part.Value.Cir, Shader = CirShaderArtifactProvider.Resolve(part.Value.Cir), GeometryRevision = part.Value.Cir?.DefinitionId };
+ packet = FromDisplay(new("aetheris/display-mesh/1", Path.GetFileNameWithoutExtension(path), "mm", [definition],
+ [new("part", Path.GetFileNameWithoutExtension(path), null, id, Transform3D.Identity.ToRowMajor(), part.Value.ExportedFeatureId)]));
+ return true;
+ }
var watch = Stopwatch.StartNew();
var compilation = string.Equals(Path.GetExtension(path), ".firmasm", StringComparison.OrdinalIgnoreCase)
? new FirmamentAssemblyDocumentCompiler().CompileFile(path).Compilation
@@ -83,19 +111,11 @@ public static class AssemblyDisplayService
error = string.Join(Environment.NewLine, compilation.Diagnostics.Select(diagnostic => $"{diagnostic.Code}: {diagnostic.Message}"));
return false;
}
- var definitions = new List<AssemblyDisplayDefinitionDto>();
- var diagnostics = new List<DisplayDiagnosticDto>();
+ var display = AssemblyDisplayMeshExporter.Export(compilation);
+ var definitions = display.Definitions.Select(LegacyDefinition).ToList();
+ var diagnostics = display.Definitions.SelectMany(d => d.Diagnostics.Select(w =>
+ new DisplayDiagnosticDto(w.Code, w.Message, null, null, "definition-tessellation", d.Id + ":" + w.FaceId))).ToList();
var artifactByIdentity = compilation.Geometry.Artifact.Definitions.ToDictionary(item => item.DefinitionIdentity, item => item.StableId, StringComparer.Ordinal);
- foreach (var definition in compilation.Geometry.DefinitionBodies.OrderBy(item => item.Key, StringComparer.Ordinal))
- {
- var tessellation = BrepDisplayTessellator.TessellateBounded(definition.Value);
- if (!tessellation.IsSuccess)
- {
- diagnostics.Add(new("Viewer.Assembly.MissingDefinitionGeometry", $"Definition '{definition.Key}' could not be tessellated.", null, null, "definition-tessellation", "Inspect the definition diagnostic."));
- continue;
- }
- definitions.Add(new(artifactByIdentity[definition.Key], definition.Key, ApiMappings.ToTessellationResponse(tessellation.Value).FacePatches));
- }
var occurrences = compilation.Ir.Instances.OrderBy(item => item.Path.Segments.Count).ThenBy(item => item.Path.ToString(), StringComparer.Ordinal).Select(instance => new AssemblyDisplayOccurrenceDto(
instance.StableId, instance.Path.Segments[^1], instance.Path.ToString(), instance.ParentStableId,
instance.Kind == AssemblyInstanceKind.Part ? artifactByIdentity.GetValueOrDefault(instance.DefinitionIdentity)
@@ -119,7 +139,42 @@ public static class AssemblyDisplayService
var maximum = metrics.Length == 0 ? new[] { 0d,0d,0d } : new[] { metrics.Max(item => item.Maximum[0]), metrics.Max(item => item.Maximum[1]), metrics.Max(item => item.Maximum[2]) };
watch.Stop();
packet = new("aetheris/cadmata-assembly-display/m3", compilation.Ir.Name, compilation.Ir.RootInstanceStableId, definitions, occurrences, mates, tolerances,
- new(minimum, maximum), diagnostics, new Dictionary<string, double> { ["packetMilliseconds"] = watch.Elapsed.TotalMilliseconds, ["definitionCount"] = definitions.Count, ["moduleDefinitionCount"] = modules.Length, ["occurrenceCount"] = occurrences.Length }, modules);
+ new(minimum, maximum), diagnostics, new Dictionary<string, double> { ["packetMilliseconds"] = watch.Elapsed.TotalMilliseconds, ["definitionCount"] = definitions.Count, ["moduleDefinitionCount"] = modules.Length, ["occurrenceCount"] = occurrences.Length }, modules,
+ display);
return true;
}
+
+ private static AssemblyDisplayPacketDto FromDisplay(AssemblyDisplayMeshDocument display)
+ {
+ var vertices = display.Definitions.ToDictionary(d => d.Id, d => d.Positions, StringComparer.Ordinal);
+ var points = display.Occurrences.Where(o => o.DefinitionId is not null).SelectMany(o =>
+ {
+ var p = vertices[o.DefinitionId!]; var t = Transform3D.FromRowMajor(o.Transform);
+ return Enumerable.Range(0, p.Length/3).Select(i => t.Apply(new Point3D(p[i*3], p[i*3+1], p[i*3+2])));
+ });
+ var boundsPoints = display.MinimumMm is null || display.MaximumMm is null ? points.ToArray() : [];
+ var minimum = display.MinimumMm ?? (boundsPoints.Length == 0 ? [0d,0d,0d] : new[] { boundsPoints.Min(p=>p.X), boundsPoints.Min(p=>p.Y), boundsPoints.Min(p=>p.Z) });
+ var maximum = display.MaximumMm ?? (boundsPoints.Length == 0 ? [0d,0d,0d] : new[] { boundsPoints.Max(p=>p.X), boundsPoints.Max(p=>p.Y), boundsPoints.Max(p=>p.Z) });
+ var occurrences = display.Occurrences.Select(o => new AssemblyDisplayOccurrenceDto(o.Id, o.Path.Split('.').Last(), o.Path, o.ParentId,
+ o.DefinitionId, o.Kind ?? "Part", o.Transform, "CompiledDisplay")).ToArray();
+ return new("aetheris/cadmata-assembly-display/m3", display.Name, occurrences.Single(o=>o.ParentStableId is null).StableId,
+ display.Definitions.Select(LegacyDefinition).ToArray(), occurrences, [], [], new(minimum,maximum), [], new Dictionary<string,double>(), Display: display);
+ }
+
+ // Compatibility transport only: geometry and face ranges come from the shared projector.
+ private static AssemblyDisplayDefinitionDto LegacyDefinition(AssemblyDisplayMeshDefinition definition)
+ {
+ var ranges = definition.Ranges ?? [new(0, definition.Indices.Length/3, "face:0", definition.Id)];
+ var faces = ranges.Select(range =>
+ {
+ var indices = definition.Indices.Skip(range.StartTriangle*3).Take(range.TriangleCount*3).ToArray();
+ var vertices = indices.Distinct().Order().ToArray();
+ var local = vertices.Select((id,index)=>(id,index)).ToDictionary(v=>v.id,v=>v.index);
+ var positions = vertices.Select(i=>new Point3Dto(definition.Positions[i*3],definition.Positions[i*3+1],definition.Positions[i*3+2])).ToArray();
+ var normals = vertices.Select(i=>new Vector3Dto(definition.Normals[i*3],definition.Normals[i*3+1],definition.Normals[i*3+2])).ToArray();
+ return new FacePatchDto(int.Parse(range.FaceId.AsSpan("face:".Length), System.Globalization.CultureInfo.InvariantCulture),
+ positions,normals,indices.Select(i=>local[i]).ToArray(),definition.MeshPipeline,null);
+ }).ToArray();
+ return new(definition.Id,definition.Identity,faces);
+ }
}
diff --git a/Aetheris.Server/Contracts/ApiContracts.cs b/Aetheris.Server/Contracts/ApiContracts.cs
index 99461f1a..2e652418 100644
--- a/Aetheris.Server/Contracts/ApiContracts.cs
+++ b/Aetheris.Server/Contracts/ApiContracts.cs
@@ -230,7 +230,8 @@ public sealed record AssemblyDisplayOccurrenceDto(string StableId, string Name,
public sealed record AssemblyDisplayMateDto(string StableId, string Name, string InterfaceStableId, IReadOnlyList<string> Participants, IReadOnlyList<string> ConstraintIds, string ValidationStatus);
public sealed record AssemblyDisplayToleranceDto(string Name, bool Passed, double Nominal, double Minimum, double Maximum, string Unit, IReadOnlyList<string> Contributors, IReadOnlyList<string>? ExpandedContributors = null);
public sealed record AssemblyDisplayBoundsDto(IReadOnlyList<double> Minimum, IReadOnlyList<double> Maximum);
-public sealed record AssemblyDisplayPacketDto(string Schema, string Name, string RootOccurrenceStableId, IReadOnlyList<AssemblyDisplayDefinitionDto> Definitions, IReadOnlyList<AssemblyDisplayOccurrenceDto> Occurrences, IReadOnlyList<AssemblyDisplayMateDto> Mates, IReadOnlyList<AssemblyDisplayToleranceDto> ToleranceStackups, AssemblyDisplayBoundsDto Bounds, IReadOnlyList<DisplayDiagnosticDto> Diagnostics, IReadOnlyDictionary<string, double> Performance, IReadOnlyList<AssemblyDisplayModuleDefinitionDto>? ModuleDefinitions = null);
+public sealed record AssemblyDisplayPacketDto(string Schema, string Name, string RootOccurrenceStableId, IReadOnlyList<AssemblyDisplayDefinitionDto> Definitions, IReadOnlyList<AssemblyDisplayOccurrenceDto> Occurrences, IReadOnlyList<AssemblyDisplayMateDto> Mates, IReadOnlyList<AssemblyDisplayToleranceDto> ToleranceStackups, AssemblyDisplayBoundsDto Bounds, IReadOnlyList<DisplayDiagnosticDto> Diagnostics, IReadOnlyDictionary<string, double> Performance, IReadOnlyList<AssemblyDisplayModuleDefinitionDto>? ModuleDefinitions = null,
+ Aetheris.Kernel.Firmament.Assembly.AssemblyDisplayMeshDocument? Display = null);
public sealed record PickOptionsDto(bool? NearestOnly, bool? IncludeBackfaces, double? EdgeTolerance, double? SortTieTolerance, double? MaxDistance);
diff --git a/Aetheris.Server/Program.cs b/Aetheris.Server/Program.cs
index 7cb49e02..23f45be5 100644
--- a/Aetheris.Server/Program.cs
+++ b/Aetheris.Server/Program.cs
@@ -4,6 +4,7 @@ using Aetheris.Server.Documents;
using Aetheris.Server.Startup;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
+using Microsoft.AspNetCore.StaticFiles;
using System.Diagnostics;
CadmataLaunchOptions launchOptions;
@@ -66,7 +67,9 @@ app.MapPaperclipDemoApi();
app.MapStandardProductGalleryApi();
app.UseDefaultFiles();
-app.UseStaticFiles();
+var staticContentTypes = new FileExtensionContentTypeProvider();
+staticContentTypes.Mappings[".wgsl"] = "text/plain";
+app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = staticContentTypes });
app.MapFallbackToFile("index.html");
if (launchOptions.Step is null)
diff --git a/Aetheris.Web.Runtime/Program.cs b/Aetheris.Web.Runtime/Program.cs
index 59361e8c..2eed00af 100644
--- a/Aetheris.Web.Runtime/Program.cs
+++ b/Aetheris.Web.Runtime/Program.cs
@@ -12,6 +12,7 @@ using Aetheris.Kernel.Firmament;
using Aetheris.Kernel.Firmament.Assembly;
using Aetheris.Kernel.Firmament.FirmamentV2;
using Aetheris.Kernel.Firmament.Materializer;
+using Aetheris.Kernel.Firmament.Scene;
namespace Aetheris.Web.Runtime;
@@ -89,7 +90,7 @@ public static partial class Program
if (string.IsNullOrWhiteSpace(request.Source))
throw new WebRuntimeException("source-required", "compile requires Firmament source text.");
var id = $"model-{++_nextSession}";
- var session = new WebModelSession(id, request.Source, request.SourceName ?? "model.firmament");
+ var session = new WebModelSession(id, request.Source, request.SourceName ?? "model.firmament", request.ProjectDocuments);
var result = session.Rebuild();
if (result.Success) Sessions[id] = session;
else session.Dispose();
@@ -171,7 +172,7 @@ public static partial class Program
{
var session = Session(request);
if (request.Source is null) throw new WebRuntimeException("source-required", "setSource requires source text.");
- session.SetSource(request.Source, request.SourceName);
+ session.SetSource(request.Source, request.SourceName, request.ProjectDocuments);
return new { accepted = true, revision = session.Revision, dirty = true };
}
@@ -196,7 +197,7 @@ public static partial class Program
private static object ExportStep(WebRequest request)
{
var session = Session(request);
- if (session.StepText is null) throw new WebRuntimeException("model-not-built", "The model has no valid STEP artifact.");
+ if (session.StepText is null) throw new WebRuntimeException("step-export-unavailable", "The current document has no STEP product artifact.");
return new { mediaType = "model/step", fileName = session.Name + ".step", base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(session.StepText)), revision = session.Revision };
}
@@ -221,20 +222,22 @@ public static partial class Program
string? SourceName = null, string? PropertyId = null, WebPropertyValue? Value = null,
string? SourceRevision = null, int? Offset = null, string? ConstructSemanticId = null,
string? FieldId = null, FirmamentProjectedValue? FieldValue = null, int? BuildRevision = null,
- bool Performance = false);
+ bool Performance = false, IReadOnlyDictionary<string, string>? ProjectDocuments = null);
private sealed class WebRuntimeException(string code, string message) : Exception(message)
{
public string Code { get; } = code;
}
- private sealed class WebModelSession(string id, string source, string sourceName) : IDisposable
+ private sealed class WebModelSession(string id, string source, string sourceName, IReadOnlyDictionary<string, string>? projectDocuments) : IDisposable
{
private string _source = source;
private string _sourceName = sourceName;
+ private IReadOnlyDictionary<string, string>? _projectDocuments = projectDocuments;
private readonly FirmamentCompilationSession _compilationSession = new();
+ private readonly FirmamentSceneSession _sceneSession = new();
private AssemblyCompilationReuse? _lastReuse;
- public void Dispose() => _compilationSession.Dispose();
+ public void Dispose() { _compilationSession.Dispose(); _sceneSession.Dispose(); }
private IReadOnlyList<WebProperty> _properties = [];
private IReadOnlyList<FirmamentConstructProjection> _projections = [];
private readonly Dictionary<string, WebPropertyValue> _overrides = new(StringComparer.Ordinal);
@@ -245,8 +248,9 @@ public static partial class Program
public string? StepText { get; private set; }
public object Snapshot => _lastSnapshot ?? throw new WebRuntimeException("model-not-built", "The model has no valid snapshot.");
- public void SetSource(string nextSource, string? nextSourceName)
+ public void SetSource(string nextSource, string? nextSourceName, IReadOnlyDictionary<string, string>? documents = null)
{
+ if (documents is not null) _projectDocuments = documents;
_source = nextSource;
if (!string.IsNullOrWhiteSpace(nextSourceName)) _sourceName = nextSourceName;
_overrides.Clear();
@@ -321,7 +325,8 @@ public static partial class Program
if (index >= 0) nextProperties[index] = nextProperties[index] with { Value = value.Value };
}
var assembly = Regex.IsMatch(effective, @"(?m)^\s*Assembly\s+", RegexOptions.CultureInvariant);
- var compiled = assembly ? CompileAssembly(effective, nextProperties) : CompilePart(effective, nextProperties);
+ var scene = SceneAuthoring.HasRoot(effective);
+ var compiled = scene ? CompileScene(effective) : assembly ? CompileAssembly(effective, nextProperties) : CompilePart(effective, nextProperties);
if (!compiled.Success)
return compiled with { Revision = Revision, RetainedPreviousGeometry = _lastSnapshot is not null };
@@ -408,7 +413,7 @@ public static partial class Program
mappingPhase.Dispose();
var meshPhase = BuildPerfTrace.Phase("web.mesh-build");
var mesh = WebMeshBuilder.Build(Name, definitionId, entityId, displayBody,
- build.Value.RuntimeCorrespondence, boxSource, Revision + 1, featureSources);
+ build.Value.RuntimeCorrespondence, boxSource, Revision + 1, featureSources, build.Value.Cir);
meshPhase.Dispose();
var meshMs = watch.Elapsed.TotalMilliseconds;
var featureNodes = (build.Value.EngineeringFeatures ?? []).Select(feature => new WebTreeNode(feature.FeatureId, feature.Kind, feature.Name, entityId, [], true,
@@ -444,6 +449,30 @@ public static partial class Program
var tree = new { rootId = root.Id, nodes = nodes.Prepend(root).DistinctBy(node => node.Id).ToArray() };
return WebBuildResult.Passed(step.Value, tree, mesh, nodes.Select(node => node.Id).Prepend(root.Id).Distinct().ToArray(), compileMs, meshMs);
}
+
+ private WebBuildResult CompileScene(string effective)
+ {
+ var watch = System.Diagnostics.Stopwatch.StartNew();
+ // A project snapshot is explicit; missing resources never fall through to browser disk.
+ var documents = new Dictionary<string, string>(_projectDocuments ?? new Dictionary<string, string>(), StringComparer.Ordinal)
+ { [_sourceName] = effective };
+ var compilation = _sceneSession.CompileProject(new FirmamentProjectSnapshot(_sourceName, documents));
+ if (!compilation.IsSuccess || compilation.Scene is null)
+ return WebBuildResult.Failed(compilation.Diagnostics.Select(d => new WebDiagnostic("error", d.Code, d.Message)).ToArray(), watch.Elapsed.TotalMilliseconds);
+ var compiledScene = compilation.Scene;
+ var mesh = DisplayProjection.Project(compiledScene);
+ var sourceNodes = compiledScene.Nodes.ToDictionary(n => n.Path, StringComparer.Ordinal);
+ WebSourceRef? SceneSource(string path)
+ {
+ if (!sourceNodes.TryGetValue(path, out var node)) return null;
+ var text = documents.GetValueOrDefault(node.Span.Source);
+ return text is null ? null : SourceRefAt(node.Span.Source, text, node.Span.Start, node.Span.Length);
+ }
+ var nodes = mesh.Occurrences.Select(o => new WebTreeNode(o.Id, o.Kind ?? "SceneNode", o.Path.Split('.').Last(), o.ParentId,
+ mesh.Occurrences.Where(c => c.ParentId == o.Id).Select(c => c.Id).ToArray(), true, SceneSource(o.Path))).ToArray();
+ var tree = new { rootId = mesh.Occurrences.Single(o => o.ParentId is null).Id, nodes };
+ return WebBuildResult.Passed(null, tree, mesh, nodes.Select(n => n.Id).ToArray(), watch.Elapsed.TotalMilliseconds, compiledScene.Performance.DisplayPreparationMilliseconds);
+ }
}
private static string ApplyOverrides(string source, IReadOnlyList<WebProperty> properties, IReadOnlyDictionary<string, WebPropertyValue> overrides)
@@ -541,7 +570,8 @@ internal static class WebMeshBuilder
{
public static object Build(string name, string definitionId, string entityId, BrepBody body,
Aetheris.Kernel.Firmament.Materializer.SemanticTopologyCorrespondence? correspondence = null,
- WebSourceRef? source = null, int buildRevision = 0, IReadOnlyDictionary<string, WebSourceRef?>? featureSources = null)
+ WebSourceRef? source = null, int buildRevision = 0, IReadOnlyDictionary<string, WebSourceRef?>? featureSources = null,
+ FirmamentCirRetention? cir = null)
{
// Browser WASM has no blocking monitor wait. Use the existing synchronous
// tessellator authority; the Worker transport supplies UI responsiveness.
@@ -575,12 +605,14 @@ internal static class WebMeshBuilder
source = semanticFace is null ? null : faceSource, buildRevision });
}
mapPhase.Dispose();
+ var shader = CirShaderArtifactProvider.Resolve(cir);
return new
{
schema = "aetheris/display-mesh/1",
name,
units = "mm",
definitions = new[] { new { id = definitionId, identity = entityId, positions = positions.ToArray(), normals = normals.ToArray(), indices = indices.ToArray(), ranges,
+ cir, shader, geometryRevision = definitionId, displayPath = shader.Artifact is not null ? "cir" : "mesh", fallbackReason = shader.Reason,
edges = tessellation.Value.EdgePolylines.Select(edge =>
{
Aetheris.Kernel.Firmament.Materializer.SemanticTopologyDescendant? semanticEdge = null;
@@ -608,5 +640,5 @@ internal sealed record WebBuildResult(bool Success, int Revision, object? Model,
IReadOnlyList<FirmamentConstructProjection>? Projections = null, double CompileMilliseconds = 0, double MeshMilliseconds = 0)
{
public static WebBuildResult Failed(IReadOnlyList<WebDiagnostic> diagnostics, double compileMs) => new(false, 0, null, diagnostics, false, Timings: new { compileMilliseconds = compileMs }, CompileMilliseconds: compileMs);
- public static WebBuildResult Passed(string step, object tree, object mesh, IReadOnlyList<string> ids, double compileMs, double meshMs) => new(true, 0, null, [], false, tree, mesh, ids, new { compileMilliseconds = compileMs, meshMilliseconds = meshMs }, StepText: step, CompileMilliseconds: compileMs, MeshMilliseconds: meshMs);
+ public static WebBuildResult Passed(string? step, object tree, object mesh, IReadOnlyList<string> ids, double compileMs, double meshMs) => new(true, 0, null, [], false, tree, mesh, ids, new { compileMilliseconds = compileMs, meshMilliseconds = meshMs }, StepText: step, CompileMilliseconds: compileMs, MeshMilliseconds: meshMs);
}
diff --git a/Aetheris.Web.Runtime/sdk/README.md b/Aetheris.Web.Runtime/sdk/README.md
index d410054a..ebe6a117 100644
--- a/Aetheris.Web.Runtime/sdk/README.md
+++ b/Aetheris.Web.Runtime/sdk/README.md
@@ -21,3 +21,48 @@ For a single, unmodified Firmament `Box`, the Web runtime tessellates the canoni
`Aetheris.create({ worker: true })` hosts the same runtime in a dedicated module Worker. Its mesh arrays and STEP bytes cross the boundary as transferable buffers. `cad.workerTiming` and `model.workerTiming` expose the last Worker operation's execution time, message delay, and transferred buffer bytes. Terminate a wedged Worker with `cad.terminate()` and create a fresh instance; termination rejects outstanding and future requests on the old instance. The .NET 10 runtime needs a message event listener rather than an assigned `onmessage` handler during Worker initialization.
The preview package is AGPL-3.0-only. Contact the Aetheris project for commercial licensing; this statement is package metadata, not legal advice.
+
+## Scene and material projection
+
+Scene source compiles through the shared Scene owner. Supply all referenced
+dependency documents explicitly, using unique project-relative paths:
+
+```ts
+const { model, diagnostics } = await cad.compile(sceneSource, {
+ sourceName: 'house.firmament',
+ projectDocuments: {
+ 'components.firmament': componentSource,
+ 'living.firmament': livingAssemblySource,
+ },
+});
+```
+
+Missing resources fail with a named diagnostic and never fall through to native
+disk. `model.setSource` accepts the same `projectDocuments` option for resource
+updates and otherwise retains the existing resource set. Definitions are shared
+across occurrences, with stable geometry revisions. Occurrences carry world
+transforms and resolved materials; Scene output also carries millimetre bounds,
+environment boundaries and named cameras with poses/look-at/FOV. Scene is display
+composition and does not provide a synthetic engineering STEP export.
+
+Optional definition `cir` metadata carries compiler qualification, structural
+identity, typed field source and bounds. Runtime BRep and CIR ASTs do not cross
+JSON. Display projection lazily resolves qualified definitions through the managed
+Copeland VD-MIR/direct-WGSL backend. Optional `shader` contains the deterministic
+artifact, compiler/source identities and binding state. The shared Telos adapter
+automatically creates a field with an invisible engineering picking proxy and
+visual mesh fallback until GPU validation succeeds. Generation, missing transport
+and GPU failures remain separately inspectable; imported STEP and unsupported
+geometry keep the mesh path.
+
+The native and development WASM builds use one exact managed-backend package pin.
+Before restoring a fresh checkout, run `scripts/prepare-managed-wgsl.ps1` with an
+explicit `-CopelandRoot` matching `scripts/managed-wgsl-source-pin.txt`. This packs
+the existing producer into the ignored local feed; runtime execution has no
+sibling-checkout, DXC, Naga or subprocess requirement. No package publishing is
+required. Development Vite runtime assets use `no-store` and explicit lengths;
+production preview retains its existing fingerprint cache policy.
+
+Shared Assembly/Scene face ranges carry BRep face IDs. A range without an owned
+feature semantic ID uses `semanticEntityId: null`; selection resolves through the
+picked occurrence. This does not grant a source selector to a runtime-only face.
diff --git a/Aetheris.Web.Runtime/sdk/src/index.d.ts b/Aetheris.Web.Runtime/sdk/src/index.d.ts
index 38d5e088..31e48e13 100644
--- a/Aetheris.Web.Runtime/sdk/src/index.d.ts
+++ b/Aetheris.Web.Runtime/sdk/src/index.d.ts
@@ -7,19 +7,24 @@ export interface EditableProperty { readonly id: string; readonly ownerEntityId:
export interface ModelTreeNode { readonly id: string; readonly kind: string; readonly name: string; readonly parentId?: string; readonly children: readonly string[]; readonly visible: boolean; readonly source?: SourceReference; readonly holeDiameterMm?: number | null; readonly semanticConstruct?: string | null }
export interface ModelTree { readonly rootId: string; readonly nodes: readonly ModelTreeNode[] }
export type SourceAddressability = 'AuthoredStable' | 'DerivedStable' | 'ImportedStable' | 'RuntimeOnly' | 'Ambiguous' | 'Unstable';
-export interface MeshRange { readonly startTriangle: number; readonly triangleCount: number; readonly faceId: string; readonly semanticEntityId: string; readonly semanticTopologyId?: string | null; readonly topologyKind?: 'Face'; readonly outputRole?: string | null; readonly originFeature?: string | null; readonly sourceAddressability?: SourceAddressability; readonly selector?: string | null; readonly selectorReason?: string | null; readonly source?: SourceReference | null; readonly buildRevision?: number }
+export interface MeshRange { readonly startTriangle: number; readonly triangleCount: number; readonly faceId: string; readonly semanticEntityId: string | null; readonly semanticTopologyId?: string | null; readonly topologyKind?: 'Face'; readonly outputRole?: string | null; readonly originFeature?: string | null; readonly sourceAddressability?: SourceAddressability; readonly selector?: string | null; readonly selectorReason?: string | null; readonly source?: SourceReference | null; readonly buildRevision?: number }
export interface SelectionDescription { readonly semanticEntityId: string; readonly faceId: string; readonly occurrenceId: string; readonly definitionId: string; readonly semanticTopologyId: string | null; readonly topologyKind: string; readonly outputRole: string | null; readonly originFeature: string | null; readonly selector: string | null; readonly sourceAddressability: SourceAddressability; readonly selectorReason: string | null; readonly source: SourceReference | null; readonly buildRevision: number; readonly sourceAddressable: boolean }
export interface DisplayEdgePolyline { readonly edgeId: string; readonly points: readonly (readonly number[])[]; readonly closed: boolean; readonly semanticEntityId?: string; readonly semanticTopologyId?: string | null; readonly topologyKind?: 'Edge'; readonly outputRole?: string | null; readonly originFeature?: string | null; readonly sourceAddressability?: SourceAddressability; readonly selector?: string | null; readonly selectorReason?: string | null; readonly source?: SourceReference | null; readonly buildRevision?: number }
-export interface DisplayMeshDefinition { readonly id: string; readonly identity: string; readonly positions: Float64Array; readonly normals: Float64Array; readonly indices: Uint32Array; readonly ranges: readonly MeshRange[]; readonly edges?: readonly DisplayEdgePolyline[] }
-export interface DisplayMeshOccurrence { readonly id: string; readonly path: string; readonly parentId?: string; readonly definitionId?: string; readonly semanticEntityId: string; readonly transform: readonly number[] }
-export interface DisplayMesh { readonly schema: 'aetheris/display-mesh/1' | 'aetheris/assembly-display-mesh/1'; readonly name: string; readonly units: 'mm'; readonly definitions: readonly DisplayMeshDefinition[]; readonly occurrences: readonly DisplayMeshOccurrence[] }
+export interface CirRetention { readonly schema: 'aetheris/cir-retention/1'; readonly definitionId: string; readonly qualification: 'cir-qualified' | 'mesh'; readonly fallbackReason: string | null; readonly structuralIdentity: string | null; readonly fieldSource: string | null; readonly minimumMm: readonly number[] | null; readonly maximumMm: readonly number[] | null }
+export interface ResolvedDisplayMaterial { readonly baseColor: readonly number[]; readonly roughness: number; readonly metallic: number; readonly opacity: number; readonly emissive: readonly number[] }
+export interface DisplayShaderArtifact { readonly schema: 'aetheris/display-shader/1'; readonly shaderId: string; readonly wgsl: string; readonly vertexEntryPoint: string; readonly fragmentEntryPoint: string; readonly bindings: readonly { readonly group: number; readonly binding: number; readonly kind: 'uniform'; readonly byteSize: number }[]; readonly capabilities: readonly string[]; readonly sourceIdentity: string; readonly compilerVersion: string }
+export interface DisplayCamera { readonly name: string; readonly transform: readonly number[]; readonly lookAtMm?: readonly number[]; readonly fovDegrees: number }
+export interface DisplayMeshDefinition { readonly id: string; readonly identity: string; readonly positions: Float64Array; readonly normals: Float64Array; readonly indices: Uint32Array; readonly ranges: readonly MeshRange[]; readonly edges?: readonly DisplayEdgePolyline[]; readonly cir?: CirRetention | null; readonly displayPath?: 'mesh' | 'cir'; readonly fallbackReason?: string | null; readonly shader?: { readonly artifact: DisplayShaderArtifact | null; readonly status: string; readonly reason: string | null; readonly cacheHit: boolean; readonly generationMilliseconds: number }; readonly geometryRevision?: string | null; readonly diagnostics?: readonly { readonly code: string; readonly message: string; readonly faceId?: string | null }[] }
+export interface DisplayMeshOccurrence { readonly id: string; readonly path: string; readonly parentId?: string; readonly definitionId?: string; readonly semanticEntityId: string; readonly transform: readonly number[]; readonly material?: ResolvedDisplayMaterial | null; readonly kind?: string }
+export interface DisplayBoundary { readonly path: string; readonly room: string; readonly kind: string; readonly frame: readonly number[]; readonly widthMm: number; readonly heightMm: number; readonly openings: readonly string[] }
+export interface DisplayMesh { readonly schema: 'aetheris/display-mesh/1' | 'aetheris/assembly-display-mesh/1' | 'aetheris/scene-display-mesh/1'; readonly name: string; readonly units: 'mm'; readonly definitions: readonly DisplayMeshDefinition[]; readonly occurrences: readonly DisplayMeshOccurrence[]; readonly cameras?: readonly DisplayCamera[]; readonly minimumMm?: readonly number[]; readonly maximumMm?: readonly number[]; readonly boundaries?: readonly DisplayBoundary[] }
export interface ChangeSet { readonly changedEntityIds: readonly string[]; readonly addedEntityIds: readonly string[]; readonly removedEntityIds: readonly string[]; readonly meshChanged: boolean; readonly diagnosticsChanged: boolean }
export interface RebuildResult { readonly success: boolean; readonly revision: number; readonly diagnostics: readonly Diagnostic[]; readonly retainedPreviousGeometry: boolean; readonly changes?: ChangeSet }
export interface RuntimeCapabilities { readonly compile: boolean; readonly solidModeling: boolean; readonly assembly: boolean; readonly displayMesh: boolean; readonly propertyInspection: boolean; readonly parameterRebuild: boolean; readonly stepExport: boolean; readonly sheetMetal: boolean; readonly fea: boolean; readonly externalStepImport: boolean; readonly forgeSubprocess: boolean; readonly cancellation: boolean; readonly worker: boolean }
export interface RuntimeInfo { readonly packageVersion: string; readonly runtimeVersion: string; readonly contractVersion: 'aetheris/web-editor-contract/1'; readonly language: 'Firmament'; readonly capabilities: RuntimeCapabilities }
export interface WorkerTiming { readonly operation: string; readonly executionMilliseconds: number; readonly transportMilliseconds: number; readonly payloadBytes: number; readonly initialization?: { readonly moduleImportMilliseconds: number; readonly runtimeCreateMilliseconds: number; readonly assemblyExportsMilliseconds: number } | null }
export interface OperationOptions { readonly signal?: AbortSignal; readonly sourceRevision?: string; readonly performance?: boolean }
-export interface CompileOptions extends OperationOptions { readonly sourceName?: string }
+export interface CompileOptions extends OperationOptions { readonly sourceName?: string; readonly projectDocuments?: Readonly<Record<string, string>> }
export interface LanguageOptions { readonly sourceName?: string; readonly sourceRevision: string }
export interface LanguageField { readonly name: string; readonly type: string; readonly required: boolean; readonly meaning: string; readonly default?: string | null; readonly choices?: readonly string[] | null }
export interface LanguageEntry { readonly constructId: string; readonly name: string; readonly context: string; readonly source: string }
diff --git a/Aetheris.Web.Runtime/sdk/src/index.js b/Aetheris.Web.Runtime/sdk/src/index.js
index 57d0edb5..75ab6d5c 100644
--- a/Aetheris.Web.Runtime/sdk/src/index.js
+++ b/Aetheris.Web.Runtime/sdk/src/index.js
@@ -101,7 +101,7 @@ export class Aetheris {
async capabilities() { return (await this.info()).capabilities; }
async compile(source, options = {}) {
throwIfAborted(options.signal);
- const result = await this.transport.request({ operation: 'compile', source, sourceName: options.sourceName, sourceRevision: options.sourceRevision, performance: options.performance });
+ const result = await this.transport.request({ operation: 'compile', source, sourceName: options.sourceName, sourceRevision: options.sourceRevision, performance: options.performance, projectDocuments: options.projectDocuments });
this.diagnostics?.(result.diagnostics);
return { model: result.success ? new ModelSession(this.transport, result.model) : null, diagnostics: result.diagnostics };
}
@@ -143,7 +143,7 @@ export class ModelSession {
return this.serial(async () => { throwIfAborted(options.signal); await this.transport.request({ operation: 'setProperty', sessionId: this.id, propertyId, value }); return this.rebuild(options); });
}
async setSource(source, options = {}) {
- return this.serial(async () => { throwIfAborted(options.signal); await this.transport.request({ operation: 'setSource', sessionId: this.id, source, sourceName: options.sourceName, sourceRevision: options.sourceRevision }); return this.rebuild(options); });
+ return this.serial(async () => { throwIfAborted(options.signal); await this.transport.request({ operation: 'setSource', sessionId: this.id, source, sourceName: options.sourceName, sourceRevision: options.sourceRevision, projectDocuments: options.projectDocuments }); return this.rebuild(options); });
}
async describeConstruct(semanticId, options = {}) {
throwIfAborted(options.signal);
diff --git a/Aetheris.Web.Runtime/sdk/src/vite.js b/Aetheris.Web.Runtime/sdk/src/vite.js
index 92a938c1..2e381563 100644
--- a/Aetheris.Web.Runtime/sdk/src/vite.js
+++ b/Aetheris.Web.Runtime/sdk/src/vite.js
@@ -29,8 +29,15 @@ export function aetherisCad() {
const path = resolve(runtimeDirectory, relative);
const runtimeRoot = resolve(runtimeDirectory);
if (path !== runtimeRoot && !path.startsWith(runtimeRoot + sep)) return next();
- if (!existsSync(path) || !(await stat(path)).isFile()) return next();
+ if (!existsSync(path)) return next();
+ const file = await stat(path);
+ if (!file.isFile()) return next();
response.setHeader('Content-Type', mime.get(extname(path)) ?? 'application/octet-stream');
+ // Development packages are replaced at the same preview version. Avoid
+ // stale boot assets and Chromium private-context cache write failures
+ // for the larger managed compiler assemblies.
+ response.setHeader('Cache-Control', 'no-store');
+ response.setHeader('Content-Length', file.size);
createReadStream(path).pipe(response);
});
},
diff --git a/Aetheris.Web.Runtime/telos/README.md b/Aetheris.Web.Runtime/telos/README.md
index 4255a331..21cf1de5 100644
--- a/Aetheris.Web.Runtime/telos/README.md
+++ b/Aetheris.Web.Runtime/telos/README.md
@@ -8,6 +8,25 @@ Mesh and line shaders are standalone `src/shaders/*.wgsl` source files. The Type
This package owns the device, attachments, camera, ray query, raw mesh/field/line submission and lifetime. Three 0.183.2 supplies math and input adapters, never a GPU renderer. See `docs/release/THREE-TELOS-X0.md` and `docs/release/THREE-TELOS-X1.md` in the repository for qualification and product boundaries.
+`fromDisplayMesh` projects compiler-qualified definitions with matching generated
+shader artifacts into normal fields. It retains authoritative bounds, occurrence
+transforms, resolved material and an invisible BRep picking proxy. A visual mesh
+stays active while Telos validates the module and pipeline, and on rejection.
+Telos compiles WGSL for the GPU; it never compiles CIR or generates shader source.
+The shared typed field source lives in `Aetheris.Kernel.Firmament/Display/telos-field.v.ts`.
+
+`telos-field-rays/2` adds metallic at vertex location 6; tint/opacity and roughness
+keep the canonical 32-byte material uniform. The prior rays/1 substrate ABI remains
+supported. Field lighting is a bounded diffuse/specular approximation, rather than
+pixel-identical mesh shading or a PBR qualification. Rigid occurrences are admitted;
+non-rigid product occurrences retain their mesh fallback.
+
+`host.inspectDisplay()` and the canvas `data-telos-display`/`data-telos-field-draws`
+attributes expose definition/binding state, actual fields and mesh surfaces,
+separate picking-proxy counts, submitted fields and GPU cache counts. Shader source
+is not dumped. Obsolete field program references and draw buffers are released
+when geometry changes; unchanged occurrences/materials reuse program state.
+
World-space meshes and lines accept explicit `depthMode`: `depth-tested`, `depth-biased`, or `always-on-top`. Overlay meshes can be unlit with alpha blending and do not write depth. Line widths are CSS pixels. Products may project DOM text with `camera.project`/`unproject`; `beforeFrame` supplies the host-owned projection cadence after camera matrices update and before GPU drawing. No React or font engine lives here.
`setDynamicLines` updates a bounded set of world-space lines identified by stable IDs. An unchanged ID, segment count and depth state retain vertex and uniform buffers. Call it within `beforeFrame`, or request `invalidate()` after an external update. Removing an ID releases its resources. `setScene` similarly retains unchanged draw/proxy resources across selection and filter updates. Immutable geometry arrays remain the definition identity contract.
@@ -16,7 +35,7 @@ World-space meshes and lines accept explicit `depthMode`: `depth-tested`, `depth
## Experimental temporal AA
-`host.setAA("TAA")` enables a fixed-weight, depth-rejected, neighborhood-clamped baseline; `host.setAA("TAAUtility")` enables the generated Copeland utility policy. `None`/`SpatialOnly` retain local primitive/line coverage without temporal jitter or resolve. Spatial AA is still the default: X0's supersampled witness found both temporal modes worse than spatial-only at silhouettes. See `docs/release/TELOS-TAA-X0.md` for the exact bounded blocker and evidence.
+`SpatialOnly` is the production default: four-sample MSAA shares one multisampled color/depth pair across surfaces, topology and overlays, then resolves once to the canvas. Lines also retain derivative coverage. Field shaders execute their existing center-ray ABI; MSAA does not qualify analytic field silhouette coverage. `None` uses one sample. `host.setAA("TAA")` enables a single-sample fixed-weight temporal experiment; `host.setAA("TAAUtility")` enables its generated Copeland utility policy. Both remain disabled by default. See `docs/release/TELOS-TAA-X0.md` for the temporal silhouette blocker and `docs/release/VIEWPORT-FINISH-X0.md` for product qualification.
Optional debug values are `policy`, `confidence`, `motion` and `depth`; seed a color view first. Debug reads frozen color history and never accumulates its visualization. The shared host owns eight bounded physical-pixel Halton samples, surface color/depth history, reprojection and invalidation. Picking, PMI and overlay projection use the logical camera. Scene/appearance/occurrence updates through `setScene` reset history; object-transform reprojection is not claimed. Topology and authoring overlays render after resolve. Temporal textures remain allocated after switching back to spatial mode until resize/disposal.
diff --git a/Aetheris.Web.Runtime/telos/src/adapters.ts b/Aetheris.Web.Runtime/telos/src/adapters.ts
index 1ca80a42..84fc0a3e 100644
--- a/Aetheris.Web.Runtime/telos/src/adapters.ts
+++ b/Aetheris.Web.Runtime/telos/src/adapters.ts
@@ -7,11 +7,14 @@ import type {
TelosLine,
DisplayPacket,
TelosMaterial,
+ TelosField,
} from "./contracts.js";
export const identityTransform = () => new Matrix4().elements;
/** Clear colors are display encoded; mesh material colors are linear lighting inputs. */
-export const clearColor = (color: string | number): [number, number, number, number] => {
+export const clearColor = (
+ color: string | number,
+): [number, number, number, number] => {
const encoded = new Color(color).convertLinearToSRGB();
return [encoded.r, encoded.g, encoded.b, 1];
};
@@ -46,6 +49,7 @@ export function fromDisplayMesh(
);
const meshes: TelosMesh[] = [],
lines: TelosLine[] = [];
+ const fields: TelosField[] = [];
for (const occurrence of packet.occurrences) {
const definition = occurrence.definitionId
? definitions.get(occurrence.definitionId)
@@ -56,17 +60,39 @@ export function fromDisplayMesh(
bodyId: occurrence.semanticEntityId,
definitionId: definition.id,
};
- meshes.push({
+ const mesh: TelosMesh = {
definition,
identity,
transform: occurrence.transform,
- material: materialFromAppearance(appearance),
- });
+ material: occurrence.material ?? materialFromAppearance(appearance),
+ };
+ const cir = definition.cir,
+ artifact = definition.shader?.artifact;
+ if (
+ cir?.qualification === "cir-qualified" &&
+ artifact &&
+ artifact.sourceIdentity === cir.structuralIdentity &&
+ cir.minimumMm?.length === 3 &&
+ cir.maximumMm?.length === 3
+ ) {
+ fields.push({
+ artifact,
+ identity,
+ transform: occurrence.transform,
+ material: mesh.material,
+ proxy: definition,
+ fallback: mesh,
+ bounds: {
+ minimum: [...cir.minimumMm] as [number, number, number],
+ maximum: [...cir.maximumMm] as [number, number, number],
+ },
+ });
+ } else meshes.push(mesh);
for (const edge of definition.edges ?? []) {
const points = edge.points.flatMap((point) => Array.from(point));
if (edge.closed && edge.points.length > 2) points.push(...edge.points[0]);
lines.push({
- id: definition.id + ":" + edge.edgeId,
+ id: occurrence.id + ":" + edge.edgeId,
points,
transform: occurrence.transform,
widthPixels: 1.2,
@@ -75,7 +101,28 @@ export function fromDisplayMesh(
});
}
}
- return { meshes, lines, fields: [] };
+ const projected = new Set(fields.map((f) => f.identity.definitionId));
+ return {
+ meshes,
+ lines,
+ fields,
+ projectionDiagnostics: packet.definitions.map((d) => ({
+ definitionId: d.id,
+ qualification: d.cir?.qualification,
+ status:
+ d.cir?.qualification === "cir-qualified" && !projected.has(d.id)
+ ? d.shader?.status === "shader-artifact-generation-failed"
+ ? d.shader.status
+ : "shader-artifact-transport-missing"
+ : (d.shader?.status ?? "mesh-fallback"),
+ shaderId: d.shader?.artifact?.shaderId,
+ reason:
+ d.shader?.reason ??
+ (d.cir?.qualification === "cir-qualified" && !projected.has(d.id)
+ ? "Qualified definition has no matching executable artifact and retained bounds."
+ : null),
+ })),
+ };
}
/** Three hierarchy is an input, never Telos scene storage or renderer state. */
export function fromThree(
diff --git a/Aetheris.Web.Runtime/telos/src/camera.ts b/Aetheris.Web.Runtime/telos/src/camera.ts
index c11b5921..7b23ddb9 100644
--- a/Aetheris.Web.Runtime/telos/src/camera.ts
+++ b/Aetheris.Web.Runtime/telos/src/camera.ts
@@ -50,6 +50,28 @@ export class TelosCamera {
this.height = Math.max(1, height);
this.update();
}
+ /** Apply compiler-owned Scene presentation metadata through the existing camera authority. */
+ applyDisplayCamera(value: {
+ transform: readonly number[];
+ lookAtMm?: readonly number[];
+ fovDegrees: number;
+ }) {
+ const t = value.transform;
+ if (
+ t.length !== 16 ||
+ t.some((v) => !Number.isFinite(v)) ||
+ !(value.fovDegrees > 0 && value.fovDegrees < 180)
+ )
+ throw new Error("telos-scene-camera-invalid");
+ this.position.set(t[12], t[13], t[14]);
+ this.up.set(t[4], t[5], t[6]);
+ if (value.lookAtMm)
+ this.target.set(value.lookAtMm[0], value.lookAtMm[1], value.lookAtMm[2]);
+ else this.target.copy(this.position).add(new Vector3(-t[8], -t[9], -t[10]));
+ this.mode = "perspective";
+ this.fov = value.fovDegrees;
+ this.update();
+ }
update() {
if (!(this.near > 0 && this.far > this.near && this.span > 0))
throw new Error("telos-camera-clipping-invalid");
@@ -115,12 +137,21 @@ export class TelosCamera {
return;
this.target.copy(min).add(max).multiplyScalar(0.5);
const radius = Math.max(max.distanceTo(min) / 2, 1e-5);
- const distance = (radius / Math.sin((this.fov * Math.PI) / 360)) * 1.2;
+ const aspect = this.width / this.height;
+ const halfAngle = Math.atan(
+ Math.tan((this.fov * Math.PI) / 360) * Math.min(1, aspect),
+ );
+ const distance = (radius / Math.sin(halfAngle)) * 1.15;
+ // Respect each product's world-up convention instead of imposing a Y-up view.
+ const direction =
+ Math.abs(this.up.z) > 0.5
+ ? new Vector3(1, -1, 0.8)
+ : new Vector3(1, 0.8, 1);
this.position
.copy(this.target)
- .add(new Vector3(1, 0.8, 1).normalize().multiplyScalar(distance));
- this.span = radius * 2.5;
- this.near = Math.max(radius * 1e-4, 1e-8);
+ .add(direction.normalize().multiplyScalar(distance));
+ this.span = (radius * 2.3) / Math.min(1, aspect);
+ this.near = Math.max(radius * 0.01, 1e-8);
this.far = distance + radius * 20;
this.update();
}
diff --git a/Aetheris.Web.Runtime/telos/src/contracts.ts b/Aetheris.Web.Runtime/telos/src/contracts.ts
index 941cfb69..6118cc84 100644
--- a/Aetheris.Web.Runtime/telos/src/contracts.ts
+++ b/Aetheris.Web.Runtime/telos/src/contracts.ts
@@ -24,6 +24,8 @@ export interface MeshRange {
}
export interface TelosGeometry {
id: string;
+ /** Immutable geometry content identity supplied by the compiler/projector. */
+ geometryRevision?: string | null;
positions: NumericArray;
normals: NumericArray;
indices: NumericArray;
@@ -42,6 +44,8 @@ export interface TelosMesh {
unlit?: boolean;
}
export interface TelosLine {
+ /** Fade finite reference-grid endpoints without changing engineering edge coverage. */
+ fadeEnds?: boolean;
id: string;
points: NumericArray;
identity: TelosIdentity;
@@ -67,7 +71,8 @@ export interface TelosShaderArtifact {
capabilities: readonly string[];
sourceIdentity: string;
}
-/** X0 field ABI: clip, local near/delta, depth/w rows, epsilon; canonical 32-byte tint/roughness uniform. Rigid occurrences only. */
+/** Rays/1 uses 72-byte vertices; rays/2 adds metallic at location 6 (76 bytes).
+ * Both retain the canonical 32-byte tint/roughness uniform. Rigid occurrences only. */
export interface TelosField {
artifact: TelosShaderArtifact;
identity: TelosIdentity;
@@ -75,12 +80,22 @@ export interface TelosField {
transform?: NumericArray;
material: TelosMaterial;
proxy?: TelosGeometry;
+ visible?: boolean;
+ /** Normal mesh fallback while executable GPU state is pending or rejected. */
+ fallback?: TelosMesh;
selected?: boolean;
}
export interface TelosScene {
meshes: readonly TelosMesh[];
lines: readonly TelosLine[];
fields: readonly TelosField[];
+ projectionDiagnostics?: readonly {
+ definitionId: string;
+ qualification?: string;
+ status: string;
+ shaderId?: string;
+ reason?: string | null;
+ }[];
}
export interface TelosHit extends TelosIdentity {
triangleIndex?: number;
@@ -95,11 +110,23 @@ export interface DisplayPacket {
points: readonly (readonly number[])[];
closed: boolean;
}[];
+ cir?: {
+ qualification: string;
+ structuralIdentity?: string | null;
+ minimumMm?: readonly number[] | null;
+ maximumMm?: readonly number[] | null;
+ } | null;
+ shader?: {
+ artifact?: TelosShaderArtifact | null;
+ status: string;
+ reason?: string | null;
+ } | null;
})[];
occurrences: readonly {
id: string;
definitionId?: string;
semanticEntityId: string;
transform: NumericArray;
+ material?: TelosMaterial | null;
}[];
}
diff --git a/Aetheris.Web.Runtime/telos/src/device.ts b/Aetheris.Web.Runtime/telos/src/device.ts
index 2ddbe0a1..be0fbbe9 100644
--- a/Aetheris.Web.Runtime/telos/src/device.ts
+++ b/Aetheris.Web.Runtime/telos/src/device.ts
@@ -1,4 +1,5 @@
import { loadTelosShaders, type TelosShaderSources } from "./shaderSources.js";
+const contextOwners = new WeakMap<GPUCanvasContext, TelosDevice>();
export class TelosResources {
device: GPUDevice;
@@ -48,6 +49,13 @@ export class TelosResources {
if (!this.pipelines.has(key)) this.pipelines.set(key, create());
return this.pipelines.get(key)!;
}
+ /** Modules/pipelines have no destroy API. Drop owned references once a semantic
+ * program leaves the model; per-draw buffers are released by the host. */
+ releaseProgram(id: string) {
+ this.modules.delete(id);
+ for (const key of this.pipelines.keys())
+ if (JSON.parse(key)[0] === id) this.pipelines.delete(key);
+ }
dispose() {
for (const resource of [...this.buffers, ...this.textures])
resource.destroy();
@@ -59,6 +67,7 @@ export class TelosResources {
}
export class TelosDevice {
+ sampleCount: 1 | 4 = 4;
shaders: TelosShaderSources;
adapter: GPUAdapter;
device: GPUDevice;
@@ -74,6 +83,7 @@ export class TelosDevice {
static async create(
canvas: HTMLCanvasElement,
diagnostic: (message: string) => void = () => {},
+ signal?: AbortSignal,
) {
if (!navigator.gpu)
throw new Error(
@@ -85,17 +95,29 @@ export class TelosDevice {
// Timing is optional; neither viewport nor temporal startup depends on it.
let device: GPUDevice;
if (adapter.features.has("timestamp-query")) {
- device = await adapter.requestDevice({ requiredFeatures: ["timestamp-query"] })
+ device = await adapter
+ .requestDevice({ requiredFeatures: ["timestamp-query"] })
.catch(() => adapter.requestDevice());
} else {
device = await adapter.requestDevice();
}
+ if (signal?.aborted) {
+ device.destroy();
+ throw new DOMException("Viewport initialization cancelled", "AbortError");
+ }
const context = canvas.getContext("webgpu");
if (!context) {
device.destroy();
throw new Error("telos-context-unavailable");
}
- return new TelosDevice(adapter, device, context, canvas, diagnostic, shaders);
+ return new TelosDevice(
+ adapter,
+ device,
+ context,
+ canvas,
+ diagnostic,
+ shaders,
+ );
}
constructor(
adapter: GPUAdapter,
@@ -124,10 +146,11 @@ export class TelosDevice {
alphaMode: "opaque",
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
});
+ contextOwners.set(context, this);
device.lost.then((info) => {
+ const expected = this.stopped;
this.stopped = true;
- if (info.reason !== "destroyed")
- diagnostic("telos-device-lost: " + info.message);
+ if (!expected) diagnostic("telos-device-lost: " + info.message);
this.onLost?.();
});
this.onError = (event) => {
@@ -140,16 +163,21 @@ export class TelosDevice {
dispose() {
this.stopped = true;
this.resources.dispose();
- this.context.unconfigure();
+ if (contextOwners.get(this.context) === this) {
+ this.context.unconfigure();
+ contextOwners.delete(this.context);
+ }
this.device.removeEventListener("uncapturederror", this.onError);
this.device.destroy();
}
}
-/** Single sample, depth32float, clear=1, less; every drawing pass loads/stores this target. */
+/** One depth owner. Spatial rendering uses four samples; temporal experiments use one. */
export class TelosFrame {
owner: TelosDevice;
depth: GPUTexture | null;
+ color: GPUTexture | null = null;
+ private samples = 0;
depthView!: GPUTextureView;
colorView!: GPUTextureView;
target!: GPUTexture;
@@ -170,22 +198,43 @@ export class TelosFrame {
const limit = this.owner.device.limits.maxTextureDimension2D;
const w = Math.min(limit, Math.max(1, Math.round(width * this.dpr))),
h = Math.min(limit, Math.max(1, Math.round(height * this.dpr)));
- if (this.width === w && this.height === h) return;
+ if (
+ this.width === w &&
+ this.height === h &&
+ this.samples === this.owner.sampleCount
+ )
+ return;
if (this.depth) this.owner.resources.release(this.depth);
+ if (this.color) this.owner.resources.release(this.color);
+ this.samples = this.owner.sampleCount;
this.owner.canvas.width = this.width = w;
this.owner.canvas.height = this.height = h;
this.depth = this.owner.resources.texture({
label: "Telos authoritative depth",
size: [w, h],
format: "depth32float",
- usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC,
+ sampleCount: this.samples,
+ usage:
+ GPUTextureUsage.RENDER_ATTACHMENT |
+ GPUTextureUsage.TEXTURE_BINDING |
+ (this.samples === 1 ? GPUTextureUsage.COPY_SRC : 0),
});
+ this.color =
+ this.samples === 4
+ ? this.owner.resources.texture({
+ label: "Telos spatial color",
+ size: [w, h],
+ format: this.owner.format,
+ sampleCount: 4,
+ usage: GPUTextureUsage.RENDER_ATTACHMENT,
+ })
+ : null;
this.depthView = this.depth.createView();
this.generation++;
}
begin(background: GPUColor, source?: GPUTexture) {
this.target = this.owner.context.getCurrentTexture();
- this.colorView = (source ?? this.target).createView();
+ this.colorView = (this.color ?? source ?? this.target).createView();
this.encoder = this.owner.device.createCommandEncoder();
const pass = this.pass("Background", true, background);
pass.end();
@@ -210,10 +259,26 @@ export class TelosFrame {
});
}
end() {
+ if (this.color) {
+ // Resolve once, after topology and overlays; every pass shares the same depth.
+ const pass = this.encoder.beginRenderPass({
+ colorAttachments: [
+ {
+ view: this.colorView,
+ resolveTarget: this.target.createView(),
+ loadOp: "load",
+ storeOp: "discard",
+ },
+ ],
+ });
+ pass.end();
+ }
this.owner.device.queue.submit([this.encoder.finish()]);
}
dispose() {
if (this.depth) this.owner.resources.release(this.depth);
+ if (this.color) this.owner.resources.release(this.color);
+ this.color = null;
this.depth = null;
}
}
diff --git a/Aetheris.Web.Runtime/telos/src/host.ts b/Aetheris.Web.Runtime/telos/src/host.ts
index 3bacbb44..81058177 100644
--- a/Aetheris.Web.Runtime/telos/src/host.ts
+++ b/Aetheris.Web.Runtime/telos/src/host.ts
@@ -3,7 +3,11 @@ import { TelosCamera } from "./camera.js";
import { TelosDevice, TelosFrame } from "./device.js";
import { TelosPick } from "./pick.js";
import { attachNavigation } from "./navigation.js";
-import { TelosTemporal, type TelosAAMode, type TelosAADebug } from "./temporal.js";
+import {
+ TelosTemporal,
+ type TelosAAMode,
+ type TelosAADebug,
+} from "./temporal.js";
import { telosPipeline } from "./pipelines.js";
import type {
TelosScene,
@@ -11,6 +15,7 @@ import type {
TelosLine,
TelosField,
TelosGeometry,
+ TelosMaterial,
NumericArray,
} from "./contracts.js";
@@ -39,6 +44,20 @@ const meshKey = (item: TelosMesh) =>
const emptyScene = (): TelosScene => ({ meshes: [], lines: [], fields: [] });
const matrix = (values?: NumericArray) =>
values ? new Matrix4().fromArray(values) : new Matrix4();
+const surfaceColor = (
+ material: TelosMaterial,
+ selected?: boolean,
+ hovered?: boolean,
+) => {
+ const strength = selected ? 0.38 : hovered ? 0.16 : 0;
+ const accent = [0.8, 0.55, 0.12];
+ return [
+ ...material.baseColor
+ .slice(0, 3)
+ .map((value, axis) => value * (1 - strength) + accent[axis] * strength),
+ material.opacity,
+ ];
+};
export class TelosHost {
readonly camera = new TelosCamera();
@@ -58,13 +77,27 @@ export class TelosHost {
if (mode !== this.aaMode) this.temporal?.reset("mode");
this.aaMode = mode;
this.aaDebug = debug;
+ const samples = mode === "SpatialOnly" ? 4 : 1;
+ if (this.owner.sampleCount !== samples) {
+ this.owner.sampleCount = samples;
+ this.frame.resize(this.camera.width, this.camera.height, this.frame.dpr);
+ this.gridKey = "";
+ this.setScene(this.scene);
+ this.setDynamicLines(
+ [...this.dynamicLines.values()].map((draw) => draw.item),
+ );
+ }
this.invalidate();
}
private get temporalActive() {
- return this.temporal && (this.aaMode === "TAA" || this.aaMode === "TAAUtility");
+ return (
+ this.temporal && (this.aaMode === "TAA" || this.aaMode === "TAAUtility")
+ );
}
private get renderProjection() {
- return this.temporalActive ? this.temporal!.renderProjection : this.camera.viewProjection;
+ return this.temporalActive
+ ? this.temporal!.renderProjection
+ : this.camera.viewProjection;
}
gridPlane: "xy" | "xz" = "xz";
readonly geometry = new Map<string, GeometryBuffers>();
@@ -108,7 +141,7 @@ export class TelosHost {
}
if (!count) continue;
if (!draw) {
- draw = this.draw(item, pipeline, 160, count);
+ draw = this.draw(item, pipeline, 176, count);
draw.vertices = this.owner.resources.buffer(
new Float32Array(count * 6),
GPUBufferUsage.VERTEX,
@@ -136,10 +169,12 @@ export class TelosHost {
private disposed = false;
private detach?: () => void;
private observer?: ResizeObserver;
+ private detachDpr?: () => void;
metrics = {
meshUploadMs: 0,
lineUploadMs: 0,
fieldPipelineMs: 0,
+ fieldDraws: 0,
frameMs: 0,
frames: 0,
draws: 0,
@@ -149,10 +184,15 @@ export class TelosHost {
static async create(
canvas: HTMLCanvasElement,
diagnostic?: (message: string) => void,
+ signal?: AbortSignal,
) {
- const owner = await TelosDevice.create(canvas, diagnostic);
+ const owner = await TelosDevice.create(canvas, diagnostic, signal);
const host = new TelosHost(owner);
host.temporal = await TelosTemporal.create(owner);
+ if (signal?.aborted) {
+ host.dispose();
+ throw new DOMException("Viewport initialization cancelled", "AbortError");
+ }
return host;
}
constructor(readonly owner: TelosDevice) {
@@ -172,6 +212,35 @@ export class TelosHost {
);
this.observer = new ResizeObserver(() => this.invalidate());
this.observer.observe(container);
+ const rect = container.getBoundingClientRect();
+ this.resize(rect.width, rect.height, globalThis.devicePixelRatio || 1);
+ this.detachDpr?.();
+ let query: MediaQueryList;
+ const changed = () => {
+ query?.removeEventListener("change", changed);
+ query = matchMedia(
+ `(resolution: ${globalThis.devicePixelRatio || 1}dppx)`,
+ );
+ query.addEventListener("change", changed);
+ this.invalidate();
+ };
+ changed();
+ // Some browser/monitor transitions change DPR without a CSS resize or media event.
+ // Check only the scalar while idle; this never schedules an unchanged frame.
+ let lastDpr = globalThis.devicePixelRatio || 1;
+ const dprCheck = setInterval(() => {
+ const currentDpr = globalThis.devicePixelRatio || 1;
+ if (currentDpr !== lastDpr) {
+ lastDpr = currentDpr;
+ changed();
+ }
+ }, 500);
+ window.addEventListener("resize", changed);
+ this.detachDpr = () => {
+ clearInterval(dprCheck);
+ query.removeEventListener("change", changed);
+ window.removeEventListener("resize", changed);
+ };
this.invalidate();
}
resize(width: number, height: number, dpr = 1) {
@@ -212,7 +281,145 @@ export class TelosHost {
});
return { item, pipeline, uniform, binding, count };
}
+ private requestedScene: TelosScene = emptyScene();
+ private fieldStates = new Map<string, string>();
+ private fieldKey(field: TelosField) {
+ return (
+ field.artifact.shaderId +
+ ":" +
+ this.owner.sampleCount +
+ ":" +
+ (field.material.opacity < 1)
+ );
+ }
+ private async validateField(field: TelosField, key: string) {
+ try {
+ if (
+ field.artifact.bindings.length !== 1 ||
+ field.artifact.bindings[0].group !== 0 ||
+ field.artifact.bindings[0].binding !== 0 ||
+ field.artifact.bindings[0].byteSize !== 32 ||
+ !field.artifact.capabilities.some(
+ (c) => c === "telos-field-rays/1" || c === "telos-field-rays/2",
+ )
+ )
+ throw new Error("telos-field-abi-unsupported");
+ this.owner.device.pushErrorScope("validation");
+ let module: GPUShaderModule;
+ let moduleError: GPUError | null;
+ try {
+ module = this.owner.resources.module(
+ field.artifact.shaderId,
+ field.artifact.wgsl,
+ );
+ } finally {
+ moduleError = await this.owner.device.popErrorScope();
+ }
+ const info = await module.getCompilationInfo();
+ if (moduleError || info.messages.some((m) => m.type === "error"))
+ throw new Error(
+ moduleError?.message ??
+ info.messages
+ .filter((m) => m.type === "error")
+ .map((m) => m.message)
+ .join("; "),
+ );
+ this.owner.device.pushErrorScope("validation");
+ let pipelineError: GPUError | null;
+ try {
+ telosPipeline(
+ this.owner,
+ "mesh",
+ field.artifact,
+ undefined,
+ field.material.opacity < 1,
+ );
+ } finally {
+ pipelineError = await this.owner.device.popErrorScope();
+ }
+ if (pipelineError) throw new Error(pipelineError.message);
+ this.fieldStates.set(key, "shader-artifact-bound");
+ } catch (error) {
+ this.fieldStates.set(key, "shader-artifact-gpu-failed: " + String(error));
+ // Recoverable program rejection is inspectable without replacing the alive viewport.
+ console.warn(
+ "shader-artifact-gpu-failed: " +
+ field.artifact.shaderId +
+ ": " +
+ String(error),
+ );
+ }
+ if (!this.owner.stopped) this.setScene(this.requestedScene);
+ }
+ /** Developer inspection: CPU picking proxies are not visual mesh surfaces. */
+ inspectDisplay() {
+ return {
+ fields: this.fields.length,
+ meshSurfaces: this.meshes.filter((d) => !d.item.overlay).length,
+ proxies: this.requestedScene.fields.filter((f) => f.proxy).length,
+ shaders: [...this.fieldStates],
+ definitions: this.requestedScene.projectionDiagnostics,
+ occurrences: this.fields.map((d) => ({
+ identity: d.item.identity,
+ shaderId: d.item.artifact.shaderId,
+ material: d.item.material,
+ })),
+ modules: this.owner.resources.modules.size,
+ pipelines: this.owner.resources.pipelines.size,
+ };
+ }
setScene(scene: TelosScene) {
+ this.requestedScene = scene;
+ const fields: TelosField[] = [],
+ fallback: TelosMesh[] = [];
+ for (const field of scene.fields) {
+ // Standalone substrate callers retain the synchronous contract. Product
+ // fields carry their compiler-owned mesh fallback and are validated first.
+ if (!field.fallback) {
+ fields.push(field);
+ continue;
+ }
+ const e = matrix(field.transform).elements;
+ const axes = [
+ new Vector3(e[0], e[1], e[2]),
+ new Vector3(e[4], e[5], e[6]),
+ new Vector3(e[8], e[9], e[10]),
+ ];
+ if (
+ axes.some((a) => Math.abs(a.length() - 1) > 1e-6) ||
+ Math.abs(axes[0].dot(axes[1])) > 1e-6 ||
+ Math.abs(axes[0].dot(axes[2])) > 1e-6 ||
+ Math.abs(axes[1].dot(axes[2])) > 1e-6
+ ) {
+ fallback.push({
+ ...field.fallback,
+ material: field.material,
+ selected: field.selected,
+ visible: field.visible,
+ });
+ console.warn(
+ "mesh-fallback: telos-field-transform-not-rigid: " +
+ field.identity.occurrenceId,
+ );
+ continue;
+ }
+ const key = this.fieldKey(field);
+ if (this.fieldStates.get(key) === "shader-artifact-bound")
+ fields.push(field);
+ else {
+ fallback.push({
+ ...field.fallback,
+ material: field.material,
+ selected: field.selected,
+ visible: field.visible,
+ });
+ if (!this.fieldStates.has(key)) {
+ this.fieldStates.set(key, "shader-artifact-pending");
+ void this.validateField(field, key);
+ }
+ }
+ }
+ scene = { ...scene, meshes: [...scene.meshes, ...fallback], fields };
// No prior per-occurrence transforms are retained yet. Reset instead of assuming camera-only motion.
this.temporal?.reset("scene/appearance/occurrence");
const previous = [...this.meshes, ...this.lines, ...this.fields];
@@ -243,6 +450,10 @@ export class TelosHost {
let geometry = this.geometry.get(definition.id);
if (
geometry &&
+ !(
+ definition.geometryRevision &&
+ definition.geometryRevision === geometry.definition.geometryRevision
+ ) &&
(geometry.definition.positions !== definition.positions ||
geometry.definition.indices !== definition.indices ||
geometry.definition.normals !== definition.normals)
@@ -279,6 +490,7 @@ export class TelosHost {
item.overlay ? "overlay-mesh" : "mesh",
undefined,
item.depthMode,
+ item.material.opacity < 1,
);
const old = oldMeshes.get(meshKey(item));
const draw =
@@ -316,7 +528,7 @@ export class TelosHost {
old?.pipeline === pipeline && old.count === segments.length / 6;
const draw = reusable
? old
- : this.draw(item, pipeline, 160, segments.length / 6);
+ : this.draw(item, pipeline, 176, segments.length / 6);
if (!reusable)
draw.vertices = resources.buffer(
new Float32Array(segments),
@@ -340,7 +552,9 @@ export class TelosHost {
item.artifact.bindings[0].group !== 0 ||
item.artifact.bindings[0].binding !== 0 ||
item.artifact.bindings[0].byteSize !== 32 ||
- !item.artifact.capabilities.includes("telos-field-rays/1")
+ !item.artifact.capabilities.some(
+ (c) => c === "telos-field-rays/1" || c === "telos-field-rays/2",
+ )
)
throw new Error("telos-field-abi-unsupported");
const model = matrix(item.transform),
@@ -357,7 +571,13 @@ export class TelosHost {
Math.abs(axes[1].dot(axes[2])) > 1e-6
)
throw new Error("telos-field-transform-not-rigid");
- const pipeline = telosPipeline(this.owner, "mesh", item.artifact);
+ const pipeline = telosPipeline(
+ this.owner,
+ "mesh",
+ item.artifact,
+ undefined,
+ item.material.opacity < 1,
+ );
const old = oldFields.get(
item.identity.occurrenceId + ":" + item.artifact.shaderId,
);
@@ -365,7 +585,11 @@ export class TelosHost {
old?.pipeline === pipeline ? old : this.draw(item, pipeline, 32, 6);
if (draw !== old)
draw.vertices = resources.buffer(
- new Float32Array(108),
+ new Float32Array(
+ item.artifact.capabilities.includes("telos-field-rays/2")
+ ? 114
+ : 108,
+ ),
GPUBufferUsage.VERTEX,
);
draw.item = item;
@@ -378,13 +602,29 @@ export class TelosHost {
resources.release(draw.uniform);
if (draw.vertices) resources.release(draw.vertices);
}
+ const programs = new Set(
+ this.requestedScene.fields.map((f) => f.artifact.shaderId),
+ );
+ for (const key of this.fieldStates.keys()) {
+ const id = key.split(":").slice(0, -2).join(":");
+ if (!programs.has(id)) {
+ this.fieldStates.delete(key);
+ resources.releaseProgram(id);
+ }
+ }
this.picker.setScene(scene);
this.invalidate();
}
- fit() {
+ fit(occurrenceIds?: ReadonlySet<string>) {
const bounds = new Box3();
- const modelMeshes = this.scene.meshes.filter((item) => !item.overlay);
- for (const item of modelMeshes.length ? modelMeshes : this.scene.meshes) {
+ const modelMeshes = this.scene.meshes.filter(
+ (item) =>
+ !item.overlay &&
+ (!occurrenceIds || occurrenceIds.has(item.identity.occurrenceId)),
+ );
+ for (const item of modelMeshes.length || occurrenceIds
+ ? modelMeshes
+ : this.scene.meshes) {
const transform = matrix(item.transform),
p = item.definition.positions;
for (let i = 0; i < p.length; i += 3)
@@ -393,12 +633,13 @@ export class TelosHost {
);
}
for (const field of this.scene.fields)
- bounds.union(
- new Box3(
- new Vector3(...field.bounds.minimum),
- new Vector3(...field.bounds.maximum),
- ).applyMatrix4(matrix(field.transform)),
- );
+ if (!occurrenceIds || occurrenceIds.has(field.identity.occurrenceId))
+ bounds.union(
+ new Box3(
+ new Vector3(...field.bounds.minimum),
+ new Vector3(...field.bounds.maximum),
+ ).applyMatrix4(matrix(field.transform)),
+ );
if (!bounds.isEmpty())
this.camera.fit(bounds.min.toArray(), bounds.max.toArray());
this.invalidate();
@@ -406,18 +647,15 @@ export class TelosHost {
private updateMesh(draw: Draw<TelosMesh>) {
const model = matrix(draw.item.transform);
const data = new Float32Array(56);
- data.set(draw.item.overlay ? this.camera.viewProjection.elements : this.renderProjection.elements);
+ data.set(
+ draw.item.overlay
+ ? this.camera.viewProjection.elements
+ : this.renderProjection.elements,
+ );
data.set(model.elements, 16);
data.set(model.clone().invert().transpose().elements, 32);
const material = draw.item.material;
- data.set(
- draw.item.selected
- ? [0.8, 0.55, 0.12, 1]
- : draw.item.hovered
- ? [0.25, 0.65, 0.48, 1]
- : [...material.baseColor.slice(0, 3), material.opacity],
- 48,
- );
+ data.set(surfaceColor(material, draw.item.selected, draw.item.hovered), 48);
data.set(
[material.roughness, material.metallic, draw.item.unlit ? 1 : 0, 0],
52,
@@ -425,7 +663,7 @@ export class TelosHost {
this.owner.device.queue.writeBuffer(draw.uniform, 0, data);
}
private updateLine(draw: Draw<TelosLine>) {
- const data = new Float32Array(40);
+ const data = new Float32Array(44);
data.set(this.camera.viewProjection.elements);
data.set(matrix(draw.item.transform).elements, 16);
data.set(
@@ -445,6 +683,7 @@ export class TelosHost {
],
36,
);
+ data[40] = draw.item.fadeEnds ? 1 : 0;
this.owner.device.queue.writeBuffer(draw.uniform, 0, data);
}
private updateField(draw: Draw<TelosField>) {
@@ -469,11 +708,16 @@ export class TelosHost {
];
const vertices = new Float32Array(
corners.flatMap((pixel) => {
- const unproject = (depth: number) => new Vector3(
- (pixel[0] / this.camera.width) * 2 - 1,
- 1 - (pixel[1] / this.camera.height) * 2,
- depth,
- ).applyMatrix4(this.temporalActive ? this.temporal!.inverseRenderProjection : this.camera.inverseViewProjection);
+ const unproject = (depth: number) =>
+ new Vector3(
+ (pixel[0] / this.camera.width) * 2 - 1,
+ 1 - (pixel[1] / this.camera.height) * 2,
+ depth,
+ ).applyMatrix4(
+ this.temporalActive
+ ? this.temporal!.inverseRenderProjection
+ : this.camera.inverseViewProjection,
+ );
const origin = unproject(0).applyMatrix4(inverse),
far = unproject(1).applyMatrix4(inverse);
return [
@@ -491,20 +735,15 @@ export class TelosHost {
m[11],
m[15],
epsilon,
+ ...(draw.item.artifact.capabilities.includes("telos-field-rays/2")
+ ? [draw.item.material.metallic]
+ : []),
];
}),
);
this.owner.device.queue.writeBuffer(draw.vertices!, 0, vertices);
const data = new Float32Array(8);
- data.set(
- draw.item.selected
- ? [0.8, 0.55, 0.12, 1]
- : [
- ...draw.item.material.baseColor.slice(0, 3),
- draw.item.material.opacity,
- ],
- 0,
- );
+ data.set(surfaceColor(draw.item.material, draw.item.selected), 0);
data[4] = draw.item.material.roughness;
this.owner.device.queue.writeBuffer(draw.uniform, 0, data);
}
@@ -512,6 +751,7 @@ export class TelosHost {
const key = JSON.stringify([
this.grid,
this.gridPlane,
+ this.owner.sampleCount,
this.camera.viewProjection.elements,
this.camera.span,
this.camera.width,
@@ -547,7 +787,10 @@ export class TelosHost {
span * 20,
Math.max(span, ...points.map((p) => p.distanceTo(this.camera.target))),
);
- const step = Math.pow(10, Math.floor(Math.log10(extent / 12)));
+ const desired = span / 12;
+ const decade = Math.pow(10, Math.floor(Math.log10(desired)));
+ const step =
+ decade * (desired / decade < 2 ? 2 : desired / decade < 5 ? 5 : 10);
const centerX = Math.round(this.camera.target.x / step) * step;
const centerY =
Math.round(
@@ -555,7 +798,7 @@ export class TelosHost {
? this.camera.target.y
: this.camera.target.z) / step,
) * step;
- const count = Math.min(40, Math.ceil(extent / step));
+ const count = Math.min(32, Math.ceil(extent / step));
const segments: number[] = [];
const point = (x: number, y: number) =>
this.gridPlane === "xy" ? [x, y, 0] : [x, 0, y];
@@ -572,13 +815,14 @@ export class TelosHost {
this.gridDraw = this.draw(
{
id: "reference-grid",
+ fadeEnds: true,
points: segments,
identity: { occurrenceId: "reference-grid" },
widthPixels: 0.7,
color: [0.45, 0.48, 0.46, 0.18],
},
telosPipeline(this.owner, "line"),
- 160,
+ 176,
segments.length / 6,
);
this.gridDraw.vertices = this.owner.resources.buffer(
@@ -597,9 +841,15 @@ export class TelosHost {
this.metrics.overlayUpdateMs = performance.now() - overlayStart;
this.updateGrid();
const temporal = this.temporalActive ? this.temporal : undefined;
- const source = temporal?.prepare(this.frame, this.camera, this.aaMode, this.aaDebug);
+ const source = temporal?.prepare(
+ this.frame,
+ this.camera,
+ this.aaMode,
+ this.aaDebug,
+ );
this.frame.begin(this.background, source);
this.metrics.draws = 0;
+ this.metrics.fieldDraws = 0;
const drawGrid = () => {
if (!this.gridDraw) return;
const grid = this.frame.pass("ReferenceGrid");
@@ -622,19 +872,33 @@ export class TelosHost {
this.metrics.draws++;
};
let pass = this.frame.pass("MeshOpaque");
- for (const draw of this.meshes.filter((draw) => !draw.item.overlay))
+ for (const draw of this.meshes.filter(
+ (draw) => !draw.item.overlay && draw.item.material.opacity >= 1,
+ ))
drawMesh(pass, draw);
pass.end();
pass = this.frame.pass("Field");
for (const draw of this.fields) {
+ if (draw.item.visible === false) continue;
this.updateField(draw);
pass.setPipeline(draw.pipeline);
pass.setBindGroup(0, draw.binding);
pass.setVertexBuffer(0, draw.vertices!);
pass.draw(6);
+ this.metrics.fieldDraws++;
this.metrics.draws++;
}
pass.end();
+ pass = this.frame.pass("MeshTranslucent");
+ const distance = (draw: Draw<TelosMesh>) =>
+ new Vector3()
+ .applyMatrix4(matrix(draw.item.transform))
+ .distanceToSquared(this.camera.position);
+ for (const draw of this.meshes
+ .filter((draw) => !draw.item.overlay && draw.item.material.opacity < 1)
+ .sort((a, b) => distance(b) - distance(a)))
+ drawMesh(pass, draw);
+ pass.end();
temporal?.resolve(this.frame);
drawGrid();
pass = this.frame.pass("Topology");
@@ -666,6 +930,10 @@ export class TelosHost {
pass.end();
this.frame.end();
this.metrics.frames++;
+ this.owner.canvas.dataset.telosDisplay = JSON.stringify(
+ this.inspectDisplay(),
+ );
+ this.owner.canvas.dataset.telosFieldDraws = String(this.metrics.fieldDraws);
this.metrics.frameMs = performance.now() - started;
if (temporal?.needsFrame) this.invalidate();
}
@@ -718,6 +986,7 @@ export class TelosHost {
cancelAnimationFrame(this.raf);
this.raf = 0;
this.observer?.disconnect();
+ this.detachDpr?.();
this.detach?.();
this.picker.dispose();
this.setDynamicLines([]);
diff --git a/Aetheris.Web.Runtime/telos/src/pipelines.ts b/Aetheris.Web.Runtime/telos/src/pipelines.ts
index ad671e25..3d2b437a 100644
--- a/Aetheris.Web.Runtime/telos/src/pipelines.ts
+++ b/Aetheris.Web.Runtime/telos/src/pipelines.ts
@@ -11,6 +11,7 @@ export function telosPipeline(
kind: "mesh" | "line" | "overlay-mesh" | "overlay-line",
artifact?: TelosField["artifact"],
depthMode?: TelosDepthMode,
+ transparent = false,
) {
const format = owner.format,
resources = owner.resources;
@@ -30,13 +31,15 @@ export function telosPipeline(
resolvedDepth,
format,
"depth32float",
- 1,
+ owner.sampleCount,
+ transparent,
artifact?.vertexEntryPoint ?? "vertex",
artifact?.fragmentEntryPoint ?? "fragment",
]);
const shader = resources.module(
id,
- artifact?.wgsl ?? (kind.includes("mesh") ? owner.shaders.mesh : owner.shaders.line),
+ artifact?.wgsl ??
+ (kind.includes("mesh") ? owner.shaders.mesh : owner.shaders.line),
);
return resources.pipeline(key, () =>
owner.device.createRenderPipeline({
@@ -48,7 +51,11 @@ export function telosPipeline(
buffers: artifact
? [
{
- arrayStride: 72,
+ arrayStride: artifact.capabilities.includes(
+ "telos-field-rays/2",
+ )
+ ? 76
+ : 72,
attributes: [
...[0, 1, 2].map((i) => ({
shaderLocation: i,
@@ -58,6 +65,15 @@ export function telosPipeline(
{ shaderLocation: 3, offset: 36, format: "float32x4" },
{ shaderLocation: 4, offset: 52, format: "float32x4" },
{ shaderLocation: 5, offset: 68, format: "float32" },
+ ...(artifact.capabilities.includes("telos-field-rays/2")
+ ? [
+ {
+ shaderLocation: 6,
+ offset: 72,
+ format: "float32" as const,
+ },
+ ]
+ : []),
],
},
]
@@ -104,10 +120,11 @@ export function telosPipeline(
],
},
primitive: { topology: "triangle-list", cullMode: "none" },
+ multisample: { count: owner.sampleCount },
depthStencil: {
format: "depth32float",
depthWriteEnabled:
- !kind.includes("line") && !kind.startsWith("overlay"),
+ !transparent && !kind.includes("line") && !kind.startsWith("overlay"),
depthBias:
resolvedDepth === "depth-biased" && kind.includes("mesh") ? -1 : 0,
depthCompare:
diff --git a/Aetheris.Web.Runtime/telos/src/shaders/line.wgsl b/Aetheris.Web.Runtime/telos/src/shaders/line.wgsl
index ef7528dd..991cf7f5 100644
--- a/Aetheris.Web.Runtime/telos/src/shaders/line.wgsl
+++ b/Aetheris.Web.Runtime/telos/src/shaders/line.wgsl
@@ -1,15 +1,16 @@
-struct State { vp: mat4x4<f32>, model: mat4x4<f32>, color: vec4<f32>, viewport: vec4<f32> }
+struct State { vp: mat4x4<f32>, model: mat4x4<f32>, color: vec4<f32>, viewport: vec4<f32>, style: vec4<f32> }
@group(0) @binding(0) var<uniform> state: State;
struct LineOutput {
@builtin(position) position: vec4<f32>,
@location(0) lateral: f32,
+ @location(1) along: f32,
}
@vertex fn vertex(@builtin(vertex_index) vertex: u32, @location(0) start: vec3<f32>, @location(1) end: vec3<f32>) -> LineOutput {
var a = state.vp * state.model * vec4(start,1); var b = state.vp * state.model * vec4(end,1);
// Clip before dividing by w: segments crossing the near plane remain finite.
if (a.z < 0 && b.z >= 0) { a = mix(a,b, -a.z / (b.z-a.z)); }
if (b.z < 0 && a.z >= 0) { b = mix(b,a, -b.z / (a.z-b.z)); }
- if (a.z < 0 && b.z < 0) { return LineOutput(vec4<f32>(2,2,2,1), 0.0); }
+ if (a.z < 0 && b.z < 0) { return LineOutput(vec4<f32>(2,2,2,1), 0.0, 0.0); }
let delta = (b.xy/b.w-a.xy/a.w) * state.viewport.xy;
let direction = delta / max(length(delta), 0.00001);
let perpendicular = vec2(-direction.y, direction.x);
@@ -17,11 +18,12 @@ struct LineOutput {
let corner = corners[vertex]; var p = mix(a,b,corner.x);
let paddedHalfWidth = state.viewport.z * 0.5 + 1.0;
p = vec4(p.xy + perpendicular * corner.y * (2.0 * paddedHalfWidth) / state.viewport.xy * p.w, p.z - state.viewport.w * p.w, p.w);
- return LineOutput(p, corner.y * paddedHalfWidth);
+ return LineOutput(p, corner.y * paddedHalfWidth, corner.x);
}
@fragment fn fragment(input: LineOutput) -> @location(0) vec4<f32> {
let halfWidth = state.viewport.z * 0.5;
let filterWidth = max(fwidth(input.lateral), 0.0001);
let coverage = 1.0 - smoothstep(halfWidth - filterWidth * 0.5, halfWidth + filterWidth * 0.5, abs(input.lateral));
- return vec4<f32>(state.color.rgb, state.color.a * coverage);
+ let endFade = smoothstep(0.0, 0.16, input.along) * (1.0 - smoothstep(0.84, 1.0, input.along));
+ return vec4<f32>(state.color.rgb, state.color.a * coverage * select(1.0, endFade, state.style.x > 0.5));
}
diff --git a/Aetheris.Web.Runtime/telos/tests/browser-witness.ts b/Aetheris.Web.Runtime/telos/tests/browser-witness.ts
index 7721cfab..2ca2e7ee 100644
--- a/Aetheris.Web.Runtime/telos/tests/browser-witness.ts
+++ b/Aetheris.Web.Runtime/telos/tests/browser-witness.ts
@@ -235,6 +235,22 @@ try {
architecture: host.owner.adapter.info.architecture,
description: host.owner.adapter.info.description,
};
+ const modes: Record<string, unknown> = {};
+ for (const mode of ["None", "SpatialOnly", "TAA", "TAAUtility"] as const) {
+ host.setAA(mode);
+ host.render();
+ await host.readPixels();
+ modes[mode] = {
+ active: host.aaMode,
+ samples: host.owner.sampleCount,
+ depthGeneration: host.frame.generation,
+ };
+ check(
+ host.owner.sampleCount === (mode === "SpatialOnly" ? 4 : 1),
+ "AA attachment sample count mismatch",
+ );
+ }
+ results.aaTransitions = modes;
const resources = host.owner.resources;
host.dispose();
check(
diff --git a/Aetheris.Web.Runtime/telos/tests/camera.test.ts b/Aetheris.Web.Runtime/telos/tests/camera.test.ts
index a52a75c1..4a43647c 100644
--- a/Aetheris.Web.Runtime/telos/tests/camera.test.ts
+++ b/Aetheris.Web.Runtime/telos/tests/camera.test.ts
@@ -9,6 +9,74 @@ import {
} from "../dist/index.js";
import type { TelosScene } from "../dist/index.js";
+test("resolved occurrence materials retain shared geometry and camera metadata uses Telos authority", () => {
+ const definition = {
+ id: "shared",
+ positions: [0, 0, 0],
+ normals: [0, 0, 1],
+ indices: [],
+ };
+ const material = {
+ baseColor: [0.7, 0.2, 0.1],
+ roughness: 0.3,
+ metallic: 0.1,
+ opacity: 0.18,
+ };
+ const scene = fromDisplayMesh({
+ definitions: [definition],
+ occurrences: [
+ {
+ id: "glass",
+ definitionId: "shared",
+ semanticEntityId: "pane",
+ transform: new Matrix4().elements,
+ material,
+ },
+ {
+ id: "default",
+ definitionId: "shared",
+ semanticEntityId: "body",
+ transform: new Matrix4().elements,
+ },
+ ],
+ });
+ assert.equal(scene.meshes[0].material, material);
+ assert.equal(scene.meshes[0].definition, scene.meshes[1].definition);
+ assert.equal(scene.meshes[1].material.opacity, 1);
+ const camera = new TelosCamera();
+ camera.applyDisplayCamera({
+ transform: new Matrix4().makeTranslation(100, 200, 300).elements,
+ lookAtMm: [0, 0, 0],
+ fovDegrees: 67,
+ });
+ assert.deepEqual(camera.position.toArray(), [100, 200, 300]);
+ assert.deepEqual(camera.target.toArray(), [0, 0, 0]);
+ assert.equal(camera.fov, 67);
+});
+
+test("fit contains every bounds corner in narrow and wide product panes", () => {
+ for (const mode of ["perspective", "orthographic"] as const)
+ for (const [width, height] of [
+ [320, 900],
+ [1600, 500],
+ ])
+ for (const scale of [1e-5, 1, 1e6]) {
+ const camera = new TelosCamera();
+ camera.mode = mode;
+ camera.up.set(0, 0, 1);
+ camera.resize(width, height);
+ camera.fit([-scale, -scale, -scale], [scale, scale, scale]);
+ assert.ok(camera.position.z > camera.target.z);
+ for (const x of [-scale, scale])
+ for (const y of [-scale, scale])
+ for (const z of [-scale, scale]) {
+ const [px, py, depth] = camera.project([x, y, z]);
+ assert.ok(px > 0 && px < width && py > 0 && py < height);
+ assert.ok(depth > 0 && depth < 1);
+ }
+ }
+});
+
for (const mode of ["perspective", "orthographic"] as const)
test(`${mode}: project, unproject, ray, aspect and scale`, () => {
const camera = new TelosCamera();
@@ -111,4 +179,82 @@ test("SDK adapter preserves shared geometry and kernel edge identity", () => {
assert.equal(scene.meshes[0].definition, scene.meshes[1].definition);
assert.equal(scene.lines[1].identity.edgeId, "brep-edge");
assert.equal(scene.lines[1].identity.occurrenceId, "right");
+ assert.notEqual(scene.lines[0].id, scene.lines[1].id);
+});
+
+test("Auto field projection retains picking/fallback geometry and diagnoses missing transport", () => {
+ const definition = {
+ id: "qualified",
+ positions: [0, 0, 0],
+ normals: [0, 0, 1],
+ indices: [0],
+ cir: {
+ qualification: "cir-qualified",
+ structuralIdentity: "semantic",
+ minimumMm: [0, 0, 0],
+ maximumMm: [1, 1, 1],
+ },
+ };
+ const material = {
+ baseColor: [0.1, 0.2, 0.3],
+ roughness: 0.4,
+ metallic: 0.7,
+ opacity: 0.8,
+ };
+ const packet = {
+ definitions: [definition],
+ occurrences: [
+ {
+ id: "instance",
+ definitionId: "qualified",
+ semanticEntityId: "body",
+ transform: new Matrix4().elements,
+ material,
+ },
+ ],
+ };
+ const missing = fromDisplayMesh(packet);
+ assert.equal(missing.meshes.length, 1);
+ assert.equal(
+ missing.projectionDiagnostics?.[0].status,
+ "shader-artifact-transport-missing",
+ );
+ const artifact = {
+ shaderId: "compiled",
+ sourceIdentity: "semantic",
+ wgsl: "compiler-test-output",
+ vertexEntryPoint: "vertex",
+ fragmentEntryPoint: "fragment",
+ bindings: [],
+ capabilities: [],
+ };
+ const bound = fromDisplayMesh({
+ ...packet,
+ definitions: [
+ { ...definition, shader: { status: "shader-artifact-bound", artifact } },
+ ],
+ });
+ assert.equal(bound.meshes.length, 0);
+ assert.equal(bound.fields.length, 1);
+ assert.equal(bound.fields[0].proxy, bound.fields[0].fallback?.definition);
+ assert.equal(bound.fields[0].material, material);
+ assert.equal(bound.fields[0].identity.definitionId, "qualified");
+ const stale = fromDisplayMesh({
+ ...packet,
+ definitions: [
+ {
+ ...definition,
+ shader: {
+ status: "shader-artifact-bound",
+ artifact: { ...artifact, sourceIdentity: "stale" },
+ },
+ },
+ ],
+ });
+ assert.equal(stale.fields.length, 0);
+ assert.equal(stale.meshes.length, 1);
+ assert.equal(
+ stale.projectionDiagnostics?.[0].status,
+ "shader-artifact-transport-missing",
+ );
});
diff --git a/Directory.Build.props b/Directory.Build.props
index f84e1e3e..ae5b6dc3 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -1,5 +1,6 @@
<Project>
<PropertyGroup>
+ <RestoreAdditionalProjectSources>$(RestoreAdditionalProjectSources);$(MSBuildThisFileDirectory)artifacts/local/cir-artifact-binding/packages</RestoreAdditionalProjectSources>
<Version>2.0.0-preview.3</Version>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
<FileVersion>2.0.0.0</FileVersion>
diff --git a/aetheris.client/index.html b/aetheris.client/index.html
index c82d8359..a70befce 100644
--- a/aetheris.client/index.html
+++ b/aetheris.client/index.html
@@ -2,9 +2,9 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
- <link rel="icon" type="image/svg+xml" href="/vite.svg" />
+ <link rel="icon" href="data:," />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>aetheris.client</title>
+ <title>Aetheris Cadmata</title>
</head>
<body>
<div id="root"></div>
diff --git a/aetheris.client/src/App.css b/aetheris.client/src/App.css
index 7e2cdbf5..44ff73ad 100644
--- a/aetheris.client/src/App.css
+++ b/aetheris.client/src/App.css
@@ -126,7 +126,7 @@
}
.top-bar__wordmark::before {
- content: "P2 / SYSTEM 02";
+ content: "ENGINEERING WORKSPACE";
margin-bottom: 4px;
color: var(--shell-text-secondary);
font-size: 0.58rem;
@@ -548,7 +548,7 @@ strong {
box-shadow: 0 2px 8px rgb(0 0 0 / 35%);
font-family: Inter, ui-sans-serif, system-ui, sans-serif;
font-size: 13px;
- line-height: 1.1;
+ line-height: 1.25;
white-space: nowrap;
cursor: pointer;
text-align: left;
@@ -695,3 +695,34 @@ strong {
.product-gallery__form {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
+.telos-empty {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 12px;
+ color: #cbc7ba;
+ text-align: center;
+ padding: 24px;
+ pointer-events: none;
+ font: 14px/1.5 system-ui, sans-serif;
+}
+.telos-empty strong { font-size: 20px; font-weight: 500; }
+.telos-empty small { opacity: .7; margin-top: 8px; }
+.telos-status {
+ position: absolute;
+ left: 16px;
+ bottom: 16px;
+ max-width: calc(100% - 32px);
+ padding: 10px 14px;
+ border: 1px solid #76766f;
+ border-radius: 6px;
+ color: #fff9e8;
+ background: #1b1d1bf0;
+ font: 13px/1.5 system-ui, sans-serif;
+ z-index: 100;
+}
+.telos-error { border-color: #b56c56; }
+.telos-status button { display: block; margin-top: 8px; padding: 5px 10px; cursor: pointer; }
diff --git a/aetheris.client/src/App.tsx b/aetheris.client/src/App.tsx
index a89a1504..22ebf164 100644
--- a/aetheris.client/src/App.tsx
+++ b/aetheris.client/src/App.tsx
@@ -142,6 +142,9 @@ function createDisplayStatusSummary(
diagnosticOnlyFaceCount,
};
}
+ if (!import.meta.env.DEV) {
+ return { summary: "Import complete.", wireOnlyFaceCount, diagnosticOnlyFaceCount };
+ }
if (preparation.lane === "mixed-fallback") {
return {
@@ -187,6 +190,7 @@ function App() {
const [displayPreparation, setDisplayPreparation] =
useState<DisplayPreparationResponseDto | null>(null);
const [assemblyPacket, setAssemblyPacket] = useState<AssemblyDisplayPacketDto | null>(null);
+ const [assemblySourcePath, setAssemblySourcePath] = useState<string | null>(null);
const [selectedAssemblyOccurrenceId, setSelectedAssemblyOccurrenceId] = useState<string | null>(
null,
);
@@ -241,6 +245,8 @@ function App() {
const lifecyclePhase = documentPhase(documentLifecycleState);
const resetSessionState = useCallback(() => {
+ setAssemblySourcePath(null);
+ setAssemblyPacket(null);
dispatchDocumentEvent({ type: "Close" });
setBodyIds([]);
setActiveBodyId(null);
@@ -457,17 +463,24 @@ function App() {
}, [activeBodyId, documentId, refreshSummaryAndActiveTessellation, runAction, tx, ty, tz]);
const handleRefreshDisplay = useCallback(async () => {
- if (!documentId || !activeBodyId) {
+ if (!assemblySourcePath && (!documentId || !activeBodyId)) {
return;
}
setIsRefreshing(true);
await runAction("Refresh display data", async () => {
+ if (assemblySourcePath) {
+ const packet = await prepareAssemblyDisplay(assemblySourcePath);
+ setAssemblyPacket(packet);
+ setSelectedAssemblyOccurrenceId(selected => packet.occurrences.some(o=>o.stableId===selected) ? selected : null);
+ return;
+ }
+ if (!documentId || !activeBodyId) return;
const preparedDisplay = await prepareBodyDisplay(documentId, activeBodyId);
setDisplayPreparation(preparedDisplay);
});
setIsRefreshing(false);
- }, [activeBodyId, documentId, runAction]);
+ }, [activeBodyId, documentId, assemblySourcePath, runAction]);
const activeOccurrence = useMemo(
() => occurrences.find((item) => item.occurrenceId === activeBodyId) ?? null,
@@ -554,7 +567,7 @@ function App() {
const imported = await importStep(documentId, stepText, fileName);
if (imported.assemblyPresentation) {
setAssemblyPacket(imported.assemblyPresentation);
- setSelectedAssemblyOccurrenceId(imported.assemblyPresentation.rootOccurrenceStableId);
+ setSelectedAssemblyOccurrenceId(null);
setDisplayPreparation(null);
setBodyIds([]);
setOccurrences([]);
@@ -704,13 +717,15 @@ function App() {
if (startupStep.kind === "assembly") {
const packet = await prepareAssemblyDisplay(startupStep.path);
setAssemblyPacket(packet);
- setSelectedAssemblyOccurrenceId(packet.rootOccurrenceStableId);
+ setAssemblySourcePath(startupStep.path);
+ setSelectedAssemblyOccurrenceId(null);
setDisplayPreparation(null);
setStatus("success");
setStatusMessage(`Assembly loaded: ${packet.name}`);
setImportStatus("success");
setImportStatusMessage(
- `Assembly ready: ${packet.occurrences.length - 1} occurrences, ${packet.definitions.length} definitions.`,
+ packet.display ? `Display ready: ${packet.display.occurrences.length} occurrences, ${packet.display.definitions.length} definitions.`
+ : `Assembly ready: ${packet.occurrences.length - 1} occurrences, ${packet.definitions.length} definitions.`,
);
} else await importStepText(startupStep.stepText, startupStep.fileName, "startup-file");
}
@@ -730,7 +745,7 @@ function App() {
setStepImportFile(selected);
}, []);
- const handleStepFileValidationError = useCallback(() => {
+ const clearStepFileSelection = useCallback(() => {
setStepImportFile(null);
}, []);
@@ -929,7 +944,10 @@ function App() {
},
{ property: "Shell count", value: activeBodyId ? 1 : 0 },
{ property: "Viewport theme", value: viewportTheme.label },
- ],
+ ].filter(
+ (row) => import.meta.env.DEV ||
+ ["Definition ID", "Occurrence ID", "Display status", "Viewport theme"].includes(row.property),
+ ),
[
activeBodyId,
activeOccurrence?.definitionId,
@@ -971,7 +989,7 @@ function App() {
onClick={() => void handleRefreshDisplay()}
disabled={
documentStatus !== "ready" ||
- !activeBodyId ||
+ (!activeBodyId && !assemblySourcePath) ||
status === "loading" ||
isRefreshing
}
@@ -1147,6 +1165,8 @@ function App() {
</label>
</div>
<AetherisViewport
+ busyMessage={status === "loading" ? statusMessage : null}
+ errorMessage={status === "error" ? statusMessage : null}
displayScene={displayScene.displayScene}
highlightedFaceId={
cadmataSelection?.faceIds.values().next().value ?? highlightedFaceId
@@ -1347,9 +1367,10 @@ function App() {
<section className="tool-section tool-section--import">
<h2 className="section-title">Step Import</h2>
<StepImportDropzone
+ onSelectionStarting={clearStepFileSelection}
resetToken={stepDropzoneResetToken}
onFileAccepted={handleStepFileAccepted}
- onValidationError={handleStepFileValidationError}
+ onValidationError={clearStepFileSelection}
/>
<Button
type="button"
diff --git a/aetheris.client/src/__tests__/App.test.tsx b/aetheris.client/src/__tests__/App.test.tsx
index bb483516..85a4dfc4 100644
--- a/aetheris.client/src/__tests__/App.test.tsx
+++ b/aetheris.client/src/__tests__/App.test.tsx
@@ -286,6 +286,47 @@ describe("App STEP file upload flow", () => {
expect(screen.getByText("Compatibility: Supported")).toBeTruthy();
});
+ it("disables the previous import while reading a new file and ignores stale header completion", async () => {
+ render(<App />);
+ await screen.findByText("Document: Ready");
+ const input = screen.getByTestId("step-import-file-input");
+ const first = new File(["ISO-10303-21;"], "first.step");
+ fireEvent.change(input, { target: { files: [first] } });
+ await screen.findByText("first.step");
+ const importButton = screen.getByRole("button", {
+ name: "Import STEP 242",
+ }) as HTMLButtonElement;
+ expect(importButton.disabled).toBe(false);
+
+ let finishHeader!: (value: string) => void;
+ const pendingHeader = new Promise<string>((resolve) => {
+ finishHeader = resolve;
+ });
+ const second = new File(["ISO-10303-21;"], "second.step");
+ vi.spyOn(second, "slice").mockReturnValue({
+ text: () => pendingHeader,
+ } as Blob);
+ fireEvent.change(input, { target: { files: [second] } });
+ expect(importButton.disabled).toBe(true);
+ fireEvent.click(importButton);
+ expect(apiMocks.importStep).not.toHaveBeenCalled();
+
+ const latest = new File(["ISO-10303-21;"], "latest.step");
+ fireEvent.change(input, { target: { files: [latest] } });
+ await screen.findByText("latest.step");
+ finishHeader("ISO-10303-21;");
+ await pendingHeader;
+ await waitFor(() => expect(screen.queryByText("second.step")).toBeNull());
+ fireEvent.click(importButton);
+ await waitFor(() =>
+ expect(apiMocks.importStep).toHaveBeenCalledWith(
+ "doc-1",
+ "ISO-10303-21;",
+ "latest.step",
+ ),
+ );
+ });
+
it("shows inline validation when non-STEP file is selected", async () => {
render(<App />);
await screen.findByText("Document: Ready");
diff --git a/aetheris.client/src/api/aetherisApi.ts b/aetheris.client/src/api/aetherisApi.ts
index c9509706..685332b1 100644
--- a/aetheris.client/src/api/aetherisApi.ts
+++ b/aetheris.client/src/api/aetherisApi.ts
@@ -198,6 +198,7 @@ export interface AssemblyDisplayToleranceDto {
expandedContributors?: string[];
}
export interface AssemblyDisplayPacketDto {
+ display?: import('@aetheris/three-telos').DisplayPacket & { cameras?: readonly { name: string; transform: readonly number[]; lookAtMm?: readonly number[]; fovDegrees: number }[] };
schema: string;
name: string;
rootOccurrenceStableId: string;
diff --git a/aetheris.client/src/components/StepImportDropzone.tsx b/aetheris.client/src/components/StepImportDropzone.tsx
index f00f327e..648bcb58 100644
--- a/aetheris.client/src/components/StepImportDropzone.tsx
+++ b/aetheris.client/src/components/StepImportDropzone.tsx
@@ -17,6 +17,7 @@ type StepFileMetadata = {
};
type StepImportDropzoneProps = {
+ onSelectionStarting?: () => void;
resetToken: number;
onFileAccepted: (file: File) => void;
onValidationError: (message: string) => void;
@@ -147,6 +148,7 @@ async function readStepHeader(file: File): Promise<string> {
}
export function StepImportDropzone({
+ onSelectionStarting,
resetToken,
onFileAccepted,
onValidationError,
@@ -155,8 +157,10 @@ export function StepImportDropzone({
const [selectionMetadata, setSelectionMetadata] = useState<StepFileMetadata | null>(null);
const [selectionError, setSelectionError] = useState<string | null>(null);
const inputRef = useRef<HTMLInputElement | null>(null);
+ const selectionRevision = useRef(0);
useEffect(() => {
+ selectionRevision.current++;
// The parent token deliberately resets this component's local selection.
// eslint-disable-next-line react-hooks/set-state-in-effect
setSelectionMetadata(null);
@@ -165,6 +169,10 @@ export function StepImportDropzone({
const handleFiles = useCallback(
async (files: File[]) => {
+ const revision = ++selectionRevision.current;
+ setSelectionMetadata(null);
+ setSelectionError(null);
+ onSelectionStarting?.();
const parsed = stepFileSelectionSchema.safeParse(files);
if (!parsed.success) {
const message = parsed.error.issues[0]?.message ?? "Invalid STEP file selection.";
@@ -184,6 +192,8 @@ export function StepImportDropzone({
schemaFamily = "Unknown";
}
+ if (revision !== selectionRevision.current) return;
+
const metadataResult = stepFileMetadataSchema.safeParse({
fileName: file.name,
size: file.size,
@@ -204,7 +214,7 @@ export function StepImportDropzone({
setSelectionMetadata(metadataResult.data);
onFileAccepted(file);
},
- [onFileAccepted, onValidationError],
+ [onFileAccepted, onValidationError, onSelectionStarting],
);
const handleBrowseClick = useCallback(() => {
diff --git a/aetheris.client/src/viewer/AetherisViewport.tsx b/aetheris.client/src/viewer/AetherisViewport.tsx
index 48fb8a60..0fcaa53a 100644
--- a/aetheris.client/src/viewer/AetherisViewport.tsx
+++ b/aetheris.client/src/viewer/AetherisViewport.tsx
@@ -14,7 +14,8 @@ export type { AetherisViewportProps } from "./viewportProps";
/** One graphics authority; legacy rendering is loaded only for unsupported browsers. */
export function AetherisViewport(props: AetherisViewportProps) {
- const supported = typeof navigator !== "undefined" && "gpu" in navigator;
+ const [generation, setGeneration] = useState(0);
+ const supported = typeof navigator !== "undefined" && !!navigator.gpu;
const legacyReason = !supported ? "WebGPU unavailable" : null;
if (legacyReason)
return (
@@ -38,10 +39,16 @@ export function AetherisViewport(props: AetherisViewportProps) {
</small>
</div>
);
- return <TelosViewport {...props} />;
+ return (
+ <TelosViewport
+ key={generation}
+ {...props}
+ onRetry={() => setGeneration((value) => value + 1)}
+ />
+ );
}
-function TelosViewport(props: AetherisViewportProps) {
+function TelosViewport(props: AetherisViewportProps & { onRetry(): void }) {
const canvas = useRef<HTMLCanvasElement>(null),
container = useRef<HTMLDivElement>(null),
host = useRef<TelosHost | null>(null);
@@ -67,6 +74,7 @@ function TelosViewport(props: AetherisViewportProps) {
};
useEffect(() => {
let disposed = false;
+ const initialization = new AbortController();
const element = canvas.current;
if (!element) return;
const click = (event: MouseEvent) => {
@@ -92,7 +100,32 @@ function TelosViewport(props: AetherisViewportProps) {
value.onAssemblyOccurrenceSelect?.(hit.occurrenceId);
};
element.addEventListener("click", click);
- void TelosHost.create(element, setDiagnostic)
+ const hover = (event: PointerEvent) => {
+ const current = host.current;
+ if (!current || event.buttons) return;
+ const rect = element.getBoundingClientRect();
+ const hit =
+ event.type === "pointerleave"
+ ? null
+ : current.picker.pick([
+ event.clientX - rect.left,
+ event.clientY - rect.top,
+ ]);
+ let changed = false;
+ for (const mesh of current.scene.meshes) {
+ const hovered =
+ !!hit &&
+ !mesh.overlay &&
+ mesh.identity.occurrenceId === hit.occurrenceId &&
+ (hit.faceId === undefined || mesh.identity.faceId === hit.faceId);
+ changed ||= mesh.hovered !== hovered;
+ mesh.hovered = hovered;
+ }
+ if (changed) current.invalidate();
+ };
+ element.addEventListener("pointermove", hover);
+ element.addEventListener("pointerleave", hover);
+ void TelosHost.create(element, setDiagnostic, initialization.signal)
.then((current) => {
if (disposed) {
current.dispose();
@@ -101,6 +134,8 @@ function TelosViewport(props: AetherisViewportProps) {
host.current = current;
setLabelHost(current);
current.camera.mode = "orthographic";
+ current.camera.up.set(0, 0, 1);
+ current.gridPlane = "xy";
current.attach(container.current!);
apply();
latest.current.onHostReady?.(current);
@@ -110,7 +145,10 @@ function TelosViewport(props: AetherisViewportProps) {
});
return () => {
disposed = true;
+ initialization.abort();
element.removeEventListener("click", click);
+ element.removeEventListener("pointermove", hover);
+ element.removeEventListener("pointerleave", hover);
host.current?.dispose();
host.current = null;
};
@@ -124,13 +162,76 @@ function TelosViewport(props: AetherisViewportProps) {
ref={container}
style={{ width: "100%", height: "100%", position: "relative" }}
data-display-host="three-telos"
+ aria-busy={!labelHost || !!props.busyMessage}
+ className="telos-viewport"
>
<canvas
ref={canvas}
aria-label="Engineering WebGPU viewport"
style={{ display: "block", width: "100%", height: "100%" }}
/>
- {diagnostic && <div role="alert">{diagnostic}</div>}
+ {!!props.assemblyPacket?.display?.cameras?.length && (
+ <select
+ aria-label="Scene camera"
+ style={{ position: "absolute", left: 12, top: 12, zIndex: 2 }}
+ defaultValue=""
+ onChange={(event) => {
+ const camera = props.assemblyPacket?.display?.cameras?.find(
+ (c) => c.name === event.target.value,
+ );
+ if (camera && host.current) {
+ host.current.camera.applyDisplayCamera(camera);
+ host.current.invalidate();
+ } else if (!event.target.value && host.current) {
+ host.current.fit();
+ host.current.invalidate();
+ }
+ }}
+ >
+ <option value="">Fit view</option>
+ {props.assemblyPacket.display.cameras.map((c) => (
+ <option key={c.name}>{c.name}</option>
+ ))}
+ </select>
+ )}
+ {!diagnostic && (!labelHost || props.busyMessage) && (
+ <div className="telos-status" role="status">
+ {props.busyMessage ?? "Preparing viewport…"}
+ </div>
+ )}
+ {labelHost &&
+ !props.busyMessage &&
+ !props.displayScene?.renderables.length &&
+ !props.assemblyPacket && (
+ <div
+ className="telos-empty"
+ style={{
+ color: (props.theme ?? ATELIER_VIEWPORT_THEME).annotation.text,
+ }}
+ >
+ <strong>Open a model to begin</strong>
+ <span>
+ Import a STEP file or choose a model from the Product Gallery.
+ </span>
+ <small>Drag to orbit · Shift-drag to pan · Scroll to zoom</small>
+ </div>
+ )}
+ {(diagnostic || props.errorMessage) && (
+ <div className="telos-status telos-error" role="alert">
+ {diagnostic
+ ? "The viewport could not render. Your model is retained."
+ : props.errorMessage}
+ {diagnostic && (
+ <>
+ <details>
+ <summary>Details</summary>
+ {diagnostic}
+ </details>
+ <button onClick={props.onRetry}>Restart viewport</button>
+ </>
+ )}
+ </div>
+ )}
<PmiAnnotationLayer
host={labelHost}
artifact={props.cadmataArtifact ?? null}
diff --git a/aetheris.client/src/viewer/cadmataTelos.ts b/aetheris.client/src/viewer/cadmataTelos.ts
index cba2b7d8..02d6e1eb 100644
--- a/aetheris.client/src/viewer/cadmataTelos.ts
+++ b/aetheris.client/src/viewer/cadmataTelos.ts
@@ -1,5 +1,6 @@
import {
materialFromAppearance,
+ fromDisplayMesh,
identityTransform,
type TelosScene,
type TelosMesh,
@@ -23,6 +24,27 @@ const assemblyGeometry = new WeakMap<
/** Product packet interpretation only. Camera, drawing and engineering picking live in Telos. */
export function cadmataTelosScene(props: AetherisViewportProps): TelosScene {
+ if (props.assemblyPacket?.display) {
+ const scene = fromDisplayMesh(props.assemblyPacket.display);
+ const selected = new Set(
+ props.assemblyPacket.occurrences.find(
+ (o) => o.stableId === props.selectedAssemblyOccurrenceId,
+ )?.selectionMembers ?? [props.selectedAssemblyOccurrenceId],
+ );
+ const overlays = cadmataOverlays(props);
+ return {
+ ...scene,
+ fields: scene.fields.map(f => ({ ...f, selected: selected.has(f.identity.occurrenceId) })),
+ meshes: [
+ ...scene.meshes.map((m) => ({
+ ...m,
+ selected: selected.has(m.identity.occurrenceId),
+ })),
+ ...overlays.meshes,
+ ],
+ lines: [...scene.lines, ...overlays.lines],
+ };
+ }
const theme = props.theme ?? ATELIER_VIEWPORT_THEME;
const meshes: TelosMesh[] = [],
lines: TelosLine[] = [];
@@ -135,5 +157,9 @@ export function cadmataTelosScene(props: AetherisViewportProps): TelosScene {
});
}
const overlays = cadmataOverlays(props);
- return { meshes: [...meshes, ...overlays.meshes], lines: [...lines, ...overlays.lines], fields: [] };
+ return {
+ meshes: [...meshes, ...overlays.meshes],
+ lines: [...lines, ...overlays.lines],
+ fields: [],
+ };
}
diff --git a/aetheris.client/src/viewer/viewportProps.ts b/aetheris.client/src/viewer/viewportProps.ts
index 6caa2139..87e6ec84 100644
--- a/aetheris.client/src/viewer/viewportProps.ts
+++ b/aetheris.client/src/viewer/viewportProps.ts
@@ -5,6 +5,8 @@ import type { CadmataLayerVisibility } from "./cadmataLayers";
import type { PmiVisibility } from "./pmiPresentation";
import type { ViewportTheme } from "./viewportTheme";
export interface AetherisViewportProps {
+ busyMessage?: string | null;
+ errorMessage?: string | null;
/** Bounded shared Telos developer comparison controls; spatial AA remains the default. */
aaMode?: import("@aetheris/three-telos").TelosAAMode;
aaDebug?: import("@aetheris/three-telos").TelosAADebug;
diff --git a/aetheris.client/vite.config.ts b/aetheris.client/vite.config.ts
index cc889ff3..5cdd6974 100644
--- a/aetheris.client/vite.config.ts
+++ b/aetheris.client/vite.config.ts
@@ -61,8 +61,6 @@ export default defineConfig(({ command }) => ({
output: {
manualChunks: {
three: ["three"],
- "react-three-fiber": ["@react-three/fiber"],
- "react-three-drei": ["@react-three/drei"],
},
},
},
@@ -70,9 +68,17 @@ export default defineConfig(({ command }) => ({
server:
command === "serve"
? {
- fs: env.AETHERIS_TELOS_WITNESS === "1" ? {
- allow: [fileURLToPath(new URL(".", import.meta.url)), fileURLToPath(new URL("../fixtures/three-telos", import.meta.url)), fileURLToPath(new URL("../docs/development/milestones/modules/sheetmetal/artifacts/ctc03-manufacturing-release", import.meta.url)), fileURLToPath(new URL("../artifacts/local/three-telos/cir", import.meta.url))],
- } : undefined,
+ fs: {
+ allow: [
+ fileURLToPath(new URL(".", import.meta.url)),
+ fileURLToPath(new URL("../Aetheris.Web.Runtime/telos", import.meta.url)),
+ ...(env.AETHERIS_TELOS_WITNESS === "1" ? [
+ "../fixtures/three-telos",
+ "../docs/development/milestones/modules/sheetmetal/artifacts/ctc03-manufacturing-release",
+ "../artifacts/local/three-telos/cir",
+ ].map(value => fileURLToPath(new URL(value, import.meta.url))) : []),
+ ],
+ },
proxy: {
"^/api": {
target,
diff --git a/docs/public/three-telos.md b/docs/public/three-telos.md
index 37b72426..38c9c9f8 100644
--- a/docs/public/three-telos.md
+++ b/docs/public/three-telos.md
@@ -6,6 +6,12 @@ The shared mesh and line shaders live in standalone `.wgsl` files, loaded throug
When WebGPU is unavailable, both products label their WebGL fallback. Cadmata loads that renderer only at the unsupported-browser boundary. Semantic authoring or PMI never selects it in a supported browser.
+Spatial rendering uses four-sample MSAA by default, with local coverage for topology lines. Experimental temporal AA remains disabled. Fit uses the viewport aspect ratio and product world-up; both products use Z-up engineering views. GPU initialization has visible feedback. A viewport failure offers Restart viewport while retaining the product model. Failed model builds retain the last valid geometry.
+
PMI panels remain React DOM buttons, projected through TelosCamera in CSS pixels. They preserve semantic targets, camera-facing text, category filters, deterministic collision layout, selection and presentation-only dragging. Their leaders use retained Telos GPU buffers. Selecting a face highlights its published related PMI without broadening the face selection.
-Three Telos supports direct WGSL field artifacts, with real CIR mixed-depth and CIR-plus-PMI browser witnesses. Automatic CIR product packet construction and default field rendering are future CIR-DISPLAY-X1B work. The [X0 substrate report](../release/THREE-TELOS-X0.md) and [X1 overlay migration report](../release/THREE-TELOS-X1.md) record qualification and reproduction commands.
+Three Telos supports direct WGSL field artifacts. Normal product Auto now projects qualified primitive definitions into fields using compiler-generated artifacts, alongside mesh geometry and authoritative topology. The [binding report](../release/P4-01A3-CIR-SHADER-BINDING-CLOSEOUT.md) records product qualification and the remaining CSG source-route boundary. The [X0 substrate report](../release/THREE-TELOS-X0.md) and [X1 overlay migration report](../release/THREE-TELOS-X1.md) retain their historical witness evidence.
+
+Part, Assembly and Scene source now reach shared compiler-owned display projection in Cadmata and Helios. The SDK accepts explicit project documents for Scene dependencies. Resolved authored colours, roughness, metallic, opacity and emissive values travel per occurrence; products offer the Scene's named cameras. Simple translucent panes use mesh blending and object-level ordering. The [transport report](../release/P4-01A2-DISPLAY-TRANSPORT-X0.md) records actual house, factory and guitar views and the bounded transparency limits.
+
+Compiled definitions retain qualified CIR admission, structural identity and bounds alongside BRep. The managed provider generates each semantic artifact once at display projection, with bounded caching. Fields carry the same resolved material state as meshes and retain invisible engineering picking proxies. Module or pipeline rejection keeps the mesh visible; developer inspection distinguishes generation, transport and GPU failures. The [Preview 4 rerun](../release/P4-01A-DISPLAY-PROJECTION-CLOSEOUT.md) records the current verdict and development WASM limits.
diff --git a/docs/release/CIR-DISPLAY-X1.md b/docs/release/CIR-DISPLAY-X1.md
index 5ae79c6c..8d1e4f34 100644
--- a/docs/release/CIR-DISPLAY-X1.md
+++ b/docs/release/CIR-DISPLAY-X1.md
@@ -208,3 +208,22 @@ The native artifact-provider requirement above describes the earlier X0 path;
it is no longer necessary for a browser host that adopts this direct backend.
The existing Aetheris SDK has not yet adopted it. Shared render-host/depth ownership
and compatible Cadmata overlays remain the X1 product integration boundary.
+
+## Subsequent Preview 4 audit
+
+The shared Three Telos host and Cadmata overlay migration subsequently landed.
+The host/material incompatibilities recorded above are historical, not the
+current reason automatic authored CIR is blocked. The initial P4-01A audit found
+that V2 discarded admitted field geometry and Scene/appearance metadata stopped
+before product transport. [P4-01A1](P4-01A1-CIR-AUTHORITY-RETENTION.md) now retains
+the existing CIR beside BRep; [P4-01A2](P4-01A2-DISPLAY-TRANSPORT-X0.md) carries
+owned Scene and resolved materials into both products. The
+[P4-01A rerun](P4-01A-DISPLAY-PROJECTION-CLOSEOUT.md) isolates the next boundary:
+qualified field metadata has no production-bound WGSL artifact. Direct managed
+WGSL is available; adopting that backend and binding/caching its artifacts
+remains necessary. No native-subprocess requirement or second renderer is proposed.
+
+That A2 snapshot is superseded by [P4-01A3](P4-01A3-CIR-SHADER-BINDING-CLOSEOUT.md):
+one compiler-owned managed provider now binds artifacts into normal product Auto.
+The remaining simple CSG qualification boundary is its historical V1 source route,
+not the shader-artifact connector.
diff --git a/docs/release/P4-01A-DISPLAY-PROJECTION-CLOSEOUT.md b/docs/release/P4-01A-DISPLAY-PROJECTION-CLOSEOUT.md
new file mode 100644
index 00000000..924cec2c
--- /dev/null
+++ b/docs/release/P4-01A-DISPLAY-PROJECTION-CLOSEOUT.md
@@ -0,0 +1,343 @@
+# P4-01A — Display projection closeout audit
+
+## Current rerun after P4-01A3
+
+**Verdict: Accepted for Preview 4 scope, with experimental CSG qualification deferred.**
+
+Normal authored Parts, mixed Assemblies and Scenes now automatically reach
+FieldPass for qualified primitives in both Cadmata and Helios, alongside owned
+mesh fallback. One compiler-owned managed WGSL provider supplies versioned
+artifacts; no witness injection is required. Actual Edge draws distinguish fields
+from visual meshes and invisible engineering proxies. Repeated occurrences share
+programs; material/placement edits reuse them; radius edits change artifact identity.
+Both products preserve selection and mesh visibility on bounded GPU rejection.
+Authoritative Assembly BRep edges now travel with shared definitions, and ordinary
+occurrence/face picking agrees with mixed-depth surface pixels in both directions.
+The current house, guitar, factory and robot regressions remain functional.
+
+The deferred experimental qualification boundary is the previously qualified simple
+CSG specimen's source route: its compatibility-owned retained root lowers and
+binds, but normal in-memory compilation rejects the V1 document at
+`FirmamentV2.CompatibilityFirewall` with `firmament-v2-source-required`. Canonical
+V2 CSG retention/product qualification remains optional future experimentation
+outside Preview 4 acceptance; accepting V1 browser input would bypass existing
+ownership policy. Runtime-only shared faces
+remain runtime-only rather than receiving invented source selectors. Existing
+emission/PBR and advanced transparency limitations remain explicit.
+
+See [P4-01A3](P4-01A3-CIR-SHADER-BINDING-CLOSEOUT.md) for the full trace, current
+gates, failure cases, cache/material/edit evidence and performance observations.
+Experimental CSG no longer blocks P4-01B or distribution work. Those steps and
+final visual release qualification have not been completed by this rerun.
+
+## Historical rerun after P4-01A1 and P4-01A2
+
+**A2 verdict: Meaningful progression.** The following records that earlier state;
+the shader-artifact and Assembly-edge blockers described here are superseded above.
+
+[P4-01A1](P4-01A1-CIR-AUTHORITY-RETENTION.md) succeeds: normal V2 primitive
+compilation retains the existing evaluable CIR beside native BRep, with stable
+definition identity and transport-safe admission metadata. Assembly and Scene
+definitions carry the retained metadata without duplicating it per occurrence.
+Engineering topology remains BRep-owned.
+
+[P4-01A2](P4-01A2-DISPLAY-TRANSPORT-X0.md) succeeds: the shared projector carries
+owned Scene environment, resolved materials, cameras, boundaries and bounds
+through native/product and SDK/Worker transports. Cadmata and Helios now render
+the house from normal source input, rather than refusing it or retaining the
+previous cylinder. Cadmata also renders authored guitar and factory materials.
+
+The next exact blocker is **`shader-artifact-not-bound`**. The normal cylinder
+packet contains `cir-qualified` metadata, typed field source and structural
+identity, but production adapters still draw it through `telos-mesh/1`. Aetheris
+has not adopted the existing managed WGSL backend as a production dependency or
+bound its artifacts to the existing Telos field ABI. This is no longer a lost
+compiler-representation or Scene/material transport problem.
+
+The smallest next repair is a bounded engine-owned artifact provider/cache over
+retained CIR, with ordinary versioned backend dependency adoption and stable
+definition/structural identity. Automatic field dispatch must then qualify its
+BRep picking proxy, mixed-depth, material and selection behavior in the products.
+Complete Assembly BRep-edge transport and CIR face(+Z) selection remain open.
+Emissive values are transported but not applied by the current mesh shader.
+P4-01B threaded faces were not changed.
+
+The rerun preserves the original source witnesses and product workflows. The
+robot is an additional regression witness; it has no authored appearance bindings.
+Raw packets/UI evidence and visually inspected screenshots are in ignored
+`artifacts/local/display-projection-closeout/products-a2/`:
+
+| Witness | Current normal product result |
+|---|---|
+| Cadmata cylinder | HTTP 200, 1 definition / 1 occurrence; one retained qualified field, explicit mesh fallback |
+| Cadmata guitar | HTTP 200, 56 / 171; 99 resolved material bindings render |
+| Cadmata house | HTTP 200, 94 / 254; 161 materials, 3 translucent bindings, 3 cameras; Hero interior renders |
+| Cadmata factory | HTTP 200, 124 / 2,562; 1,492 materials, 2 translucent bindings, 5 cameras; Hero view renders |
+| Cadmata robot | HTTP 200, 24 / 64; existing Assembly rendering preserved |
+| Helios cylinder | Worker compile succeeds, 1 / 1, zero diagnostics, mesh pipeline |
+| Helios house | Explicit multi-file Worker compile succeeds, 94 / 254, zero diagnostics; authored palette and Hero interior render |
+
+The final development/non-AOT Helios house build took 52.6 seconds (48.8 seconds
+reported compile, with 9.4 seconds of display preparation included in that phase).
+Release performance is not qualified. Simple pane opacity uses bounded mesh
+blending, not OIT/refraction research. Native tests prove Room-finish, placement
+and camera edits retain engineering definition revisions; product GPU reuse for
+those edits is not measured here. Shared WebGPU controls still qualify mixed
+field/mesh depth, AA transitions, resources and disposal; they do not substitute
+for automatic product CIR evidence.
+
+Consolidating display exposed imported OCCT regression cases. The shared exporter
+now honors existing external-STEP provenance and bounded mesh behavior, including
+explicit diagnostics for unmeshed imported faces. Authored patch validation stays
+strict; no filled replacement geometry or source-shape inference was added.
+
+### Rerun reproduction
+
+```powershell
+pwsh -File scripts/audit-display-projection-closeout.ps1 -OutputDirectory artifacts/local/display-projection-closeout/compiler-a2
+# In HeliosCAD: npm run sdk:install; npm run dev -- --host 127.0.0.1
+node scripts/audit-display-projection-products.mts <playwright-module-path> artifacts/local/display-projection-closeout/products-a2
+dotnet build Aetheris.slnx -c Release -m:1
+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
+npm --prefix Aetheris.Web.Runtime/telos test
+npm --prefix Aetheris.Web.Runtime/telos run build:witness
+node scripts/qualify-three-telos-browser.mts <playwright-module-path>
+npm --prefix aetheris.client test
+# In HeliosCAD: npm test; npm run build:fast
+```
+
+### Rerun validation
+
+- Release solution build: passed, zero errors; existing nullable and WASM SQLite warnings remain.
+- Fast kernel lane: 1,005 passed, zero failed/skipped.
+- Full serial solution lane: **4,320 passed across 20 projects**, zero failed/skipped.
+- Eight added compiler/transport regression cases pass; existing imported OCCT
+ server cases now also check canonical transport and explicit unmeshed-face diagnostics.
+- Telos build/typecheck and tests: 11 passed. Shared Edge/WebGPU qualification:
+ `PASS`, zero GPU/page errors; mixed depth, AA transitions, resource reuse and disposal checked.
+- Cadmata: production build passed, 86 tests across 18 files passed.
+- Helios: refreshed local SDK and development build passed, 29 tests across 7 files passed.
+ Queued source revisions are checked with their matching project resource snapshots.
+- Native contract audit and repository CLI house/factory `scene inspect --repeat 2 --json`: passed.
+- Final real-product audit completed with the results above; captures were inspected.
+- Repository layout guard and diff whitespace checks passed. Test-generated STEP
+ line-ending metadata was restored only after confirming no substantive diff.
+- Temporary product hosts were stopped and the Helios audit port is closed.
+
+Logs use the `a1a2-` prefix under ignored
+`artifacts/local/display-projection-closeout/`; compiler contracts are under
+`compiler-a2/`, product captures under `products-a2/`, and shared GPU qualification
+is `artifacts/local/three-telos/browser-report.json`. The Telos test log is
+`a2-telos-tests.log`. Earlier viewport polish edits were preserved. No commits,
+background services or startup hooks were created.
+
+The original audit follows as historical evidence; its absent contracts and
+failed product views describe the state before A1/A2, not current behavior.
+
+## Initial audit (before A1/A2)
+
+**Verdict: Honest stop. Preview 4 display projection is not accepted.**
+
+Normal Cadmata and Helios workflows do not yet automatically project Parts,
+Assemblies and Scenes into one canonical Telos scene with qualified CIR and
+authored materials. The audit isolates missing retained compiler data and
+duplicated projection ownership below the product adapters. Adding a frontend
+primitive detector or an empty canonical packet would conceal those boundaries.
+The polished mesh path remains intact. This change adds reproducible diagnostics
+and corrects documentation; it does not claim a production projection repair.
+
+## Current ownership and normal paths
+
+| Input | Existing authority / normal path | Where projection stops |
+|---|---|---|
+| Authored V2 Part | `FirmamentBuildAndExport.CompileSource` → `FirmamentStepExportResult` → Web runtime BRep/STEP reimport → `WebMeshBuilder` → SDK mesh → Helios Telos adapter | Result has no retained CIR root/program/admission contract. Cadmata startup classifies `.firmament` as Assembly, including ordinary Parts. |
+| BRep-backed Part | Compiler `RuntimeBody` and `RuntimeCorrespondence`, when supplied | Box retains both; cylinder supplies neither and uses STEP reimport. Engineering correspondence must survive independently of display dispatch. |
+| Analytic CIR | Legacy `FirmamentCompilationArtifact.PrimitiveLoweringPlan` → `FirmamentCirLowerer`; existing `SdfNode` → `CirVisualTsLowerer` → direct WGSL backend → Telos field | Legacy compiler rejects the current V2 Box and Cylinder sources. Standalone SDF roots are diagnostic controls, not normal authored compilation. |
+| Assembly | `AssemblyM1Pipeline` / `FirmamentAssemblyDocumentCompiler` retain engineering definitions, occurrences, transforms and resolved appearances | `AssemblyExecutedGeometry` exposes artifact and BRep dictionaries, without retained authored CIR or V2 correspondence. Shared mesh exporter and Cadmata face-patch service produce different packets. Neither carries complete material/field/topology data. |
+| Scene | `FirmamentSceneSession` → `CompiledScene` | Neither product invokes this owner for Scene source. SDK has Part/Assembly dispatch and no Scene/project-resource input. |
+| Room / walls / floor / ceiling | Scene owner produces environment definitions and boundary identities | Geometry exists upstream; product display cannot carry it. Do not reproduce panels in React. |
+| Door / Window | Scene compiler cuts openings and produces frame/pane finish geometry | Product Scene dispatch absent; pane opacity/frame and glazing appearance absent from transport. |
+| Scene display geometry | `CompiledScene.Display`, `Nodes`, `Boundaries`, world bounds | USD/GLB exporter projection consumes it, including cutaway filtering; no shared Telos projection exposes these semantics. |
+| Appearance / occurrence override | Compiler-resolved `Appearance` and `Preview` values; Scene `Appearances` | Guitar has 99 authored bindings, including `with-appearance-override`; Cadmata display packet omits them. Theme material is used instead. |
+| Imported STEP | Existing BRep import, tessellation, topology and semantic/PMI service | Mesh remains the safe path. No imported analytic-surface guess constitutes CIR admission. |
+| Recovered/spline geometry | Existing bounded surfacing/mesh pipelines | Remains mesh fallback; generic implicit recovery is outside this milestone. |
+| PMI / topology / selection | BRep edge provenance, semantic correspondence and existing pick services | Web Part mesh retains engineering ranges/edges where available; assembly face-patch transport lacks equivalent edge projection. CIR proxies/PMI anchors cannot be manufactured from display triangles. |
+
+The Web runtime's `FirmamentFieldProjector` projects editable Box/Hole **source
+properties** and parser spans. It is not an implicit field/CIR provider.
+
+Relevant implementation seams are `Aetheris.Web.Runtime/Program.cs`,
+`Aetheris.Web.Runtime/sdk/src/index.d.ts`,
+`Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs`,
+`Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs`,
+`Aetheris.Kernel.Firmament/Assembly/AssemblyDisplayMeshExporter.cs`,
+`Aetheris.Kernel.Firmament/Scene/SceneCompilation.cs`,
+`Aetheris.Kernel.Firmament/Scene/SceneExport.cs`,
+`Aetheris.Server/Api/AssemblyDisplayService.cs`, and
+`aetheris.client/src/viewer/cadmataTelos.ts`.
+
+## Exact missing contract
+
+The normal V2 export result contains STEP and feature inspection data, with
+optional BRep and correspondence. It does not retain a compiler-admitted field
+definition bound to the exported engineering definition. The assembly
+materializer retains BRep/semantics/export artifact but does not retain that
+field representation or V2 topology correspondence in `AssemblyExecutedGeometry`.
+Consequently, adding fields to SDK JSON alone cannot supply their authority.
+
+The native audit proves this on `fixtures/Canonical/Basics/cylinder.firmament`:
+normal compilation succeeds, but `RuntimeBody` and `RuntimeCorrespondence` are
+absent. Both current Box and Cylinder sources fail in the legacy CIR-capable
+compiler with:
+
+```text
+[FIRM-PARSE-0001] Firmament source must be valid canonical TOON-style text or JSON with an object root.
+```
+
+The existing cylinder SDF control lowers successfully and produces structural
+identity `da4151e90e22f2e4f112260e722a0ac155dc15a4abd51c1c352857c80a5c07cd`.
+That establishes a usable lowering seam, not a safe link from this authored
+document to that field. Re-parsing source in a product, inferring primitives
+from tessellation, or routing V2 through a legacy compatibility reader would
+create a competing geometry interpretation.
+
+Direct managed WGSL emission already exists; a native compiler subprocess is
+not the fundamental blocker. `scripts/qualify-three-telos-cir.cs` demonstrates
+the existing SDF/v.ts/direct-WGSL chain. The sphere, cylinder, cone, torus and
+bounded CSG witnesses remain standalone qualification evidence. Production
+adapters still return `fields: []`; no automatic CIR, mixed product Assembly,
+shader artifact reuse or CIR face-selection acceptance is claimed here.
+
+## Scene and material evidence
+
+The native Scene compiler already retains the required spatial semantics.
+These measurements are from a fresh session followed by an unchanged compile
+in the same session; they are CPU compilation measurements, not GPU frame times.
+
+| Native compiled witness | Definitions / occurrences | Environment or window-finish occurrences | Resolved looks / translucent looks | Cameras | Retained engineering definitions |
+|---|---:|---:|---:|---:|---:|
+| WarmModernHouse | 94 / 254 | 57 | 161 / 3 | 3 | 49 reused, 0 rebuilt |
+| FactoryX0 | 124 / 2,562 | 38 | 1,492 / 2 | 5 | 92 reused, 0 rebuilt |
+| Industrial Atlas Assembly | 24 / 64 | — | 0 / 0 | — | Not measured here |
+| GuitarX0 Assembly | 56 / 171 | — | 99 authored bindings | — | Not measured here |
+
+House first compile: 603 ms; display preparation 143 ms initially / 137 ms
+retained. Factory first compile: 2,089 ms; display preparation 293 ms initially /
+234 ms retained. Existing engineering definition reuse works; display preparation
+still runs. This does not prove bounded GPU invalidation after appearance,
+placement or geometry edits.
+
+House bounds are `[-100,-100,-100]` to `[11700,7100,3200]` mm;
+factory bounds are `[-180,-180,-180]` to `[42180,28180,7180]` mm.
+Authored camera positions, targets and FOV are retained in the audit JSON.
+`SceneExport` applies validated hidden-boundary projection and resolved looks
+for USD/GLB. Those exporters are not evidence that either product displays them.
+
+The house references six sibling Assembly files. The normal SDK compile input
+has no project-resource snapshot; native `FirmamentSceneSession` resolves files
+through its existing filesystem path. Browser integration needs an explicit
+resource input bound to the existing project authority, rather than hardcoded
+house component loading. Existing `FirmamentProjectSnapshot` is a reuse seam;
+Scene does not currently accept it.
+
+Industrial Atlas has no authored appearance bindings in this fixture. Its
+uniform product material is therefore not proof that a robot palette was lost.
+The guitar's physical defaults and Sunburst occurrence override provide the
+actual material-loss witness. Mesh/CIR appearance parity and normal glass
+presentation remain unqualified.
+
+## Real product checks
+
+The diagnostic opened repository sources through actual Cadmata startup/API
+and Helios file input in Edge with WebGPU, at 1600×1000 CSS pixels and DPR 2.
+It injected pipeline-label instrumentation only, never model/render packets.
+
+| Product / source | Observed result |
+|---|---|
+| Cadmata cylinder | HTTP 400: `assembly-parse-missing-root: Expected 'Assembly Name { ... }'.` No model surface pipeline. |
+| Cadmata guitar | HTTP 200, 56 definitions / 171 occurrences. Packet definition has `stableId`, `definitionIdentity`, `facePatches`; no appearance or field artifact. Actual view is uniformly themed mesh. |
+| Cadmata house / factory | Same Assembly-parser refusal as cylinder. No Scene surface display. |
+| Helios cylinder | Normal worker compile succeeds, 1 definition / 1 occurrence, zero diagnostics; `telos-mesh/1` pipeline, no field pipeline. |
+| Helios house | Build fails with two diagnostics and `MODEL OUT OF DATE`; previous cylinder remains visible at display revision 1 while source advances to 2. This is failure-retention evidence, not a house view. |
+
+Screenshots and packet/UI evidence are under ignored
+`artifacts/local/display-projection-closeout/products/`:
+`cadmata-cylinder.png`, `cadmata-guitar.png`, `cadmata-house.png`,
+`cadmata-factory.png`, `helios-cylinder.png`, `helios-house.png`, and `audit.json`.
+No accepted house, factory, automatic CIR mechanical, robot material or mixed
+Assembly screenshot set exists. Prior robot/mechanical evidence in
+`VIEWPORT-FINISH-X0.md` remains historical and does not close these criteria.
+
+## Friction log and smallest permanent repair
+
+| Old path / gap | Correct owner and smallest repair | Safe fallback / deferred boundary |
+|---|---|---|
+| V2 export discards admitted field structure | Retain optional CIR eligibility/root plus definition identity at V2 definition construction; carry it through assembly materialization. Reuse existing CIR lowering and direct managed WGSL emission. | Keep existing BRep mesh. Do not infer fields from imports. |
+| Several mesh/export/witness packet builders | One engine-owned, product-neutral projection over retained compiled definitions/occurrences, with adapters only at transport/backend boundaries. | Preserve existing working packets until the shared replacement qualifies. |
+| Part/Scene treated as Assembly or Part-only SDK input | Dispatch on existing compiled document kind and provide project resources to the existing compiler owner. | Actionable refusal and last valid display; no Scene reconstruction. |
+| Resolved appearances omitted | Carry compiler-resolved defaults/occurrence overrides through the shared projector; use the existing material conversion and one fallback policy. | Current theme/default mesh material; parity remains open. |
+| Scene cameras, boundaries, opacity omitted | Project `CompiledScene` data, including validated cutaway visibility, environment identity, bounds and camera metadata. Telos retains camera/render authority. | No product Scene acceptance until normal source loading works. |
+| Engineering selection not bound to field admission | Retain BRep/correspondence alongside CIR; automatically project invisible picking proxy and semantic edge overlays under the same identities. | Existing mesh picking/PMI; no display-triangle authority. |
+| Retained compilation does not imply retained projection | Key projection/shader artifacts by existing definition/revision and structural identities; occurrence changes update occurrence state. | No new giant cache; appearance/transform edit qualification deferred. |
+
+The proposed definition contract should retain engineering identity, optional
+admitted CIR representation, BRep/topology correspondence, mesh fallback, bounds
+and resolved default appearance. Occurrences retain identity, parent/world
+transform and resolved override. A shared projector then emits deterministic
+field/mesh admission diagnostics, shader identities and artifacts, topology and
+selection proxies, Scene environment and cameras without duplicating payloads.
+These are proposed repairs, not new APIs shipped by this audit.
+
+No new renderer, IR, language, implicit recovery, TAA, transparency research,
+distribution work or P4-01B threaded-face repair was introduced. No witness-only
+provider was promoted into production. The cleanup pass identifies duplicate
+owners and corrects stale documentation; deleting working paths before their
+replacement qualifies would regress the products.
+
+## Reproduction and validation
+
+```powershell
+pwsh -File scripts/audit-display-projection-closeout.ps1
+# Start the actual Helios development app on 127.0.0.1:4173 first.
+node scripts/audit-display-projection-products.mts <playwright-module-path>
+dotnet build Aetheris.slnx -c Release -m:1 --nologo -v:q
+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
+npm --prefix Aetheris.Web.Runtime/telos test
+npm --prefix aetheris.client test
+# In the explicitly scoped HeliosCAD checkout:
+npm test
+```
+
+The repository CLI independently passes `scene inspect --repeat 2 --json` for
+both house and factory; results are `house-cli.json` and `factory-cli.json`.
+The compiler diagnostic emits `compiled-contracts.json` into ignored
+`artifacts/local/display-projection-closeout/`. Both scripts are standalone
+diagnostics without production callers. Product audit records observed failures;
+a successful diagnostic exit does not mean milestone acceptance.
+
+Validation completed:
+
+- Release solution build passed: zero errors, two existing WASM SQLite warnings.
+- Fast kernel lane: 1,005 passed, zero failed/skipped.
+- Full serial solution lane: **4,312 passed across 20 projects**, zero failed/skipped.
+- Telos build/typecheck and tests: 10 passed.
+- Cadmata frontend tests: 86 passed across 18 files.
+- Helios frontend tests: 29 passed across 7 files; existing CSS parser advisories remain.
+- Native compiler audit and both repository CLI Scene inspections passed.
+- Actual product audit completed; the recorded refusals and mesh-only behavior
+ are expected diagnostic findings, not acceptance passes.
+- Repository layout guard and diff whitespace checks passed. Test-generated
+ STEP line-ending metadata was restored after confirming no substantive diff.
+- Temporary product hosts were stopped; the Helios audit port is closed.
+
+Logs remain under `artifacts/local/display-projection-closeout/`. There are no
+new production code edits for P4-01A; earlier VIEWPORT-FINISH-X0 changes in both
+checkouts were preserved. No commits, background services or startup hooks were
+created.
+
+**Executive answer: No.** The retained compiler/transport prerequisites above
+remain blockers. The next repair must retain authored field and engineering
+correspondence at their compiler owner and feed one shared projector, before
+Preview 4 can move on to P4-01B and final visual requalification.
diff --git a/docs/release/P4-01A1-CIR-AUTHORITY-RETENTION.md b/docs/release/P4-01A1-CIR-AUTHORITY-RETENTION.md
new file mode 100644
index 00000000..ee83bbf2
--- /dev/null
+++ b/docs/release/P4-01A1-CIR-AUTHORITY-RETENTION.md
@@ -0,0 +1,61 @@
+# P4-01A1 — CIR authority retention
+
+**Verdict: Success for retention. Production CIR rendering remains a separate gate.**
+
+The admitted V2 primitive executor already builds an evaluable CIR mirror.
+It previously discarded that root while returning the mirror's audit summary.
+The executor now retains that same root in `NativeGeometryCirMirrorState`;
+`FirmamentBuildAndExport` carries it beside the canonical BRep through
+`FirmamentStepExportResult.Cir`. The existing legacy bounded-CSG mirror also
+retains its already-built root. No second source parser or geometry inference
+is involved.
+
+`FirmamentCirRetention` separates runtime authority from transport:
+
+- `RuntimeRoot` is the existing evaluable `SdfNode`, excluded from JSON.
+- `Schema` is `aetheris/cir-retention/1`.
+- `DefinitionId` uses the existing deterministic STEP-content identity for
+ Parts; Assembly and Scene projection bind it to their existing definition ID.
+- `Qualification`, `FallbackReason`, `StructuralIdentity`, `FieldSource` and
+ millimetre bounds come from the existing `CirVisualTsLowerer` admission.
+- `FieldSource` is typed Visual TypeScript, not WGSL or a new CIR AST format.
+
+Assembly materialization carries CIR once per definition in
+`AssemblyExecutedGeometry.DefinitionCir`. Retained compilation copies mutable
+metadata arrays before returning cached results. Canonical BRep, STEP and
+construction correspondence continue to own engineering geometry and selection.
+Cylinder, Sphere, Cone and Torus now also retain their existing native BRep
+instead of requiring display to reimport their export.
+
+The regression cases compile normal V2 Box, Cylinder, Sphere, Cone and Torus,
+verify stable definition identity, evaluate the retained root, and verify JSON
+contains neither runtime root nor BRep. An existing legacy CSG fixture proves
+root retention without extending V2 CSG syntax. Unsupported mirror/lowering
+paths retain explicit mesh eligibility and reasons.
+
+## Next boundary
+
+Qualification does not bind a GPU program. The canonical display definition
+remains `displayPath: mesh`, with `shader-artifact-not-bound` for a qualified
+field. The normal Cadmata cylinder packet now carries one qualified field
+definition, but its observed GPU pipeline is still `telos-mesh/1`.
+
+The next owner-layer repair is an artifact provider/cache over this retained
+representation, adopting the existing managed WGSL backend through an ordinary
+versioned dependency and binding the existing Telos field ABI. This milestone
+does not promote a witness-only provider or reference a sibling checkout from
+production.
+
+## Validation and reproduction
+
+Eight `DisplayProjectionTests` cases cover retention, existing CSG,
+Scene/project transport and missing-resource refusal. Full gate and real-product
+results are recorded in the [P4-01A rerun](P4-01A-DISPLAY-PROJECTION-CLOSEOUT.md).
+
+```powershell
+dotnet test Aetheris.Kernel.Firmament.Tests -c Release --no-build --filter FullyQualifiedName~DisplayProjectionTests
+pwsh -File scripts/audit-display-projection-closeout.ps1 -OutputDirectory artifacts/local/display-projection-closeout/compiler-a2
+```
+
+Raw evidence remains ignored under
+`artifacts/local/display-projection-closeout/compiler-a2/compiled-contracts.json`.
diff --git a/docs/release/P4-01A2-DISPLAY-TRANSPORT-X0.md b/docs/release/P4-01A2-DISPLAY-TRANSPORT-X0.md
new file mode 100644
index 00000000..b4839654
--- /dev/null
+++ b/docs/release/P4-01A2-DISPLAY-TRANSPORT-X0.md
@@ -0,0 +1,91 @@
+# P4-01A2 — Display transport X0
+
+**Verdict: Success for Scene and resolved-material transport in both products.**
+
+The remaining artifact/edge qualifications described in this A2 snapshot are
+superseded by [P4-01A3](P4-01A3-CIR-SHADER-BINDING-CLOSEOUT.md), which binds normal
+product Auto fields and carries Assembly BRep edges. The original transport
+evidence and timings below remain historical.
+
+Normal Cadmata and Helios loading now reaches the existing Scene compiler and
+renders its owned environment, placements, materials and authored cameras.
+Before this change, both products refused the house Scene; the guitar's 99
+authored appearance bindings were lost before Cadmata rendering.
+
+## Owners and transport
+
+`DisplayProjection` projects already compiled Scene and already resolved
+Appearance values. It reuses `SceneExport.Project` for environment geometry and
+validated hidden-boundary filtering. Output carries existing definition and
+occurrence identities, world transforms, millimetre bounds, boundary metadata,
+named camera poses/look-at/FOV, and resolved colour, roughness, metallic, opacity
+and emissive values. Assembly display uses the same material conversion. Neither
+UI interprets Appearance source or reconstructs Rooms, openings or glazing.
+
+Definitions retain optional CIR admission and immutable geometry revisions;
+occurrences retain placement and resolved material override. Telos consumes
+material through its existing adapter and retains geometry buffers when
+definition ID and geometry revision agree across new transport arrays. The
+native retained-Scene test proves that Room-finish, placement and camera edits
+rebuild zero engineering definitions and preserve geometry revisions. This is
+not a measured product GPU reuse claim for those edits.
+
+The SDK adds `projectDocuments` for Scene dependencies to compile/session source updates and accepts
+the existing Scene display schema. The Web runtime invokes
+`FirmamentSceneSession.CompileProject`; explicit immutable project resources
+are the only dependency source for that path. Missing resources produce
+`scene-assembly-file-missing`, even if a matching native file exists. Scene tree
+source references use compiler-owned spans in supplied documents. Scene has no
+synthetic STEP export; the runtime reports `step-export-unavailable`.
+
+Cadmata's existing display endpoint dispatches Part, Assembly and Scene source.
+Its canonical `display` payload comes from shared compiler/exporter output.
+Legacy face-patch transport remains for compatibility, derived from that same
+geometry rather than a second tessellation. External STEP definition provenance
+selects the existing bounded mesh route. Existing unmeshed imported faces retain
+zero-triangle ranges and explicit per-definition diagnostics; they are never
+filled with invented geometry. Authored geometry still fails on invalid patches.
+Imported STEP topology, semantic and PMI services remain their existing owners.
+
+Helios carries each queued revision's matching resource snapshot and offers a
+multi-file loader plus root-document selection. The loader currently uses unique
+sibling filenames; the SDK supports project-relative paths. This is not a full
+dependency editor or directory-import workflow. Both products offer authored
+Scene cameras and an explicit Fit view option.
+
+## Actual product evidence
+
+Edge/WebGPU at DPR 2 loaded normal sources through product APIs and file input.
+No constructed display packet was injected. Screenshots were visually inspected.
+
+| Product / witness | Definitions / occurrences | Resolved materials | Cameras | Observed result |
+|---|---:|---:|---:|---|
+| Cadmata cylinder | 1 / 1 | 0 | 0 | Part loading works; qualified CIR metadata, explicit mesh fallback |
+| Cadmata guitar | 56 / 171 | 99 | 0 | Authored assembly colours reach the viewport |
+| Cadmata house | 94 / 254 | 161, including 3 translucent | 3 | Room/environment, furniture and glazing render; Hero camera works |
+| Cadmata factory | 124 / 2,562 | 1,492, including 2 translucent | 5 | Factory environment and authored equipment palette render |
+| Cadmata robot | 24 / 64 | 0 | 0 | Existing Assembly renders; source has no authored appearance bindings |
+| Helios cylinder | 1 / 1 | Default | 0 | Worker build, zero diagnostics, mesh rendering |
+| Helios house | 94 / 254 | Authored palette visible | 3 | Multi-file Worker compile, zero diagnostics, Hero interior view |
+
+The final Helios development/non-AOT house build took 52.6 seconds.
+This is not release-performance acceptance. Native retained composition and
+browser Worker execution are separate measurements.
+
+Opacity uses bounded mesh blending: opaque meshes draw first, translucent meshes
+draw after fields with depth writes disabled and object-level back-to-front
+ordering. This covers the current simple panes; it does not qualify OIT,
+intersecting transparency, refraction or advanced physical glass.
+
+## Limits and reproduction
+
+Qualified CIR metadata has no production-bound WGSL artifact yet. Automatic
+field dispatch, product CIR picking proxies and complete Assembly BRep-edge
+transport remain unqualified. Emissive values are transported, but the existing
+mesh shader does not apply them; emission appearance is not qualified. The shared
+host remains the renderer; this
+milestone does not expand rendering research or repair P4-01B threaded faces.
+
+See the [P4-01A rerun](P4-01A-DISPLAY-PROJECTION-CLOSEOUT.md) for gates, commands,
+captures and the exact next artifact-binding boundary. Raw output stays under
+ignored `artifacts/local/display-projection-closeout/`.
diff --git a/docs/release/P4-01A3-CIR-SHADER-BINDING-CLOSEOUT.md b/docs/release/P4-01A3-CIR-SHADER-BINDING-CLOSEOUT.md
new file mode 100644
index 00000000..6c8cd4be
--- /dev/null
+++ b/docs/release/P4-01A3-CIR-SHADER-BINDING-CLOSEOUT.md
@@ -0,0 +1,225 @@
+# P4-01A3 — CIR shader artifact binding closeout
+
+**Verdict: Accepted for Preview 4 scope, with experimental CSG qualification deferred.**
+The `shader-artifact-not-bound` connector is
+repaired in both real products. Normal authored primitives, a locating pin,
+mixed Assembly and Scene now submit compiler-generated WGSL through FieldPass.
+The remaining previously qualified simple CSG specimen uses historical V1 input;
+canonical in-memory compilation refuses it with `firmament-v2-source-required`.
+Its retained root lowers and binds successfully in compiler tests. No V1 browser
+firewall was weakened and no new CIR coverage was invented.
+
+**P4-01A rerun: Accepted for Preview 4 scope, with experimental CSG qualification deferred.**
+Automatic primitive display is no longer blocked by shader binding. Experimental
+CSG product qualification remains open outside Preview 4 acceptance and no longer
+blocks P4-01B or distribution work. Those steps have not been completed here.
+
+## Exact seam and ownership
+
+The initial trace reached `FirmamentStepExportResult.Cir`, native Assembly
+`DefinitionCir`, browser definition `cir`, and Cadmata's canonical `display`
+packet. All contained qualification, structural identity, typed field source and
+bounds. None supplied an executable artifact to `fromDisplayMesh`; products made
+visual meshes and never submitted a field. This was the precise missing connector.
+
+| Stage | Current owner/data |
+|---|---|
+| Authored source | Normal `Basics/cylinder.firmament`, `BareCylinder.Base`, radius 12 mm, height 30 mm |
+| Existing CIR creation | Primitive executor/native geometry mirror retains its evaluable root beside BRep |
+| A1 retention | `FirmamentCirRetention`: stable definition and structural identity, compiler-lowered typed field, conservative bounds; runtime AST omitted from JSON |
+| Compiled definition | Native Part `Cir`, Assembly `DefinitionCir`, Scene's shared definitions |
+| Display projection | `AssemblyDisplayMeshExporter`, `DisplayProjection`, Web Part mesh builder and native Part service resolve the same provider |
+| Artifact generation | `CirShaderArtifactProvider` invokes existing managed `WgslGraphicsBackend.Compile`: Copeland frontend → VD-MIR → direct WGSL |
+| Transport | Normal native JSON and development WASM SDK/Worker definition `shader` contains artifact, entrypoints, bindings, source/compiler identity and state |
+| Product definition | Cadmata canonical `display`; Helios `ModelSession.mesh`; no product registry |
+| Field construction | Shared `fromDisplayMesh` checks qualified CIR, matching artifact source identity and retained bounds; carries resolved material/transform/engineering identity |
+| GPU ownership | Telos validates modules/pipelines, owns bind groups, attachments, resource cache and lifetime |
+| Actual FieldPass | Compiler pipeline `draw(6)` and field submission counts; no visual mesh surface for accepted field definitions; invisible BRep picking proxy retained |
+
+The production typed field source is
+`Aetheris.Kernel.Firmament/Display/telos-field.v.ts`. The earlier standalone
+fixture was moved to this owner and its qualification script consumes that file.
+There is no handwritten primitive WGSL, copied shader compiler, frontend CIR
+interpreter, witness import, debug registration or per-product artifact provider.
+
+## Generation, contract and caching
+
+Generation is **lazy at display projection**, not STEP compilation or rendering.
+The existing retained compiler payload is sufficient; artifacts cross transport
+as deterministic WGSL plus ordinary metadata. Native and browser use the same
+managed backend. Browser execution has no DXC, Naga, subprocess or native shader
+compiler requirement.
+
+The artifact schema is `aetheris/display-shader/1`. Identity combines the retained
+structural identity, managed backend/compiler version, shared typed template
+contract and compiled semantic program hash. It does not depend on occurrence,
+filename, pointer identity or emitted WGSL formatting alone. A synchronized FIFO
+cache holds at most 256 generation results, including failures. Scene projection
+reuses an existing binding instead of resolving it twice. Equivalent definitions
+and occurrences reuse one artifact; appearance/placement changes do not specialize
+the program.
+
+The managed dependency uses exact package version
+`0.1.0-preview.1-a3.7329cf8ff04d504a`, with reviewed producer source hash
+`7329cf8ff04d504a062e8b5f62adcb9e12a1bbd13159c9c0af42b94576ba38d9`.
+`scripts/prepare-managed-wgsl.ps1 -CopelandRoot <explicit checkout>` verifies that
+source graph and packs the existing projects into an ignored local feed. This is
+a build prerequisite for a fresh checkout, not a production sibling-project
+reference, vendored source tree or new package service. Copeland source was not
+edited. Production AOT/distribution remains a separate lane.
+
+GPU cache keys retain semantic artifact identity, attachment formats, sample
+count, entrypoints and drawing/transparency state. Module identity collisions are
+rejected. Geometry changes release old draw buffers and drop obsolete field
+module/pipeline references; those GPU objects have no explicit destroy API.
+Material and transform changes retain program state.
+
+## Auto, material and failure behavior
+
+Qualified CIR plus matching artifact produces a field automatically. Unsupported
+geometry, generation failure or missing/mismatched transport produces the owned
+mesh. Product fields keep that visual mesh while asynchronous GPU validation is
+pending. Module/pipeline rejection emits `shader-artifact-gpu-failed` and preserves
+mesh visibility and engineering picking; it does not install a fatal viewport
+overlay. Non-rigid product occurrences retain mesh fallback.
+
+The field receives the same resolved base colour, roughness, metallic and opacity
+as the mesh. `telos-field-rays/2` adds metallic at vertex location 6 (76-byte
+vertices), retaining the canonical 32-byte tint/opacity/roughness uniform. The
+prior rays/1 ABI is still supported. The typed shader now uses roughness and
+metallic in bounded lighting. Its diffuse/specular and square-root display encoding
+are approximations; pixel-identical mesh lighting, PBR, emission realization and
+advanced/intersecting transparency are not claimed. Current house panes remain
+on the already-supported mesh blending path. TAA was not revised.
+
+Developer inspection exposes definition/binding state, shader identity, actual
+field and visual mesh counts, separate picking proxies, submitted field draws
+and GPU cache counts through `inspectDisplay()` and canvas data attributes. It
+distinguishes compiler qualification/binding, generation failure, missing
+transport, pending GPU state and GPU rejection without dumping WGSL.
+
+Two adjacent issues were isolated and corrected during real product qualification:
+
+- Cadmata's existing Refresh Display Data action was disabled for normal source
+ startup. It now recompiles the owned source path and preserves valid occurrence
+ selection, while keeping the existing body refresh path.
+- Shared Assembly/Scene face ranges used a definition ID as a semantic entity ID.
+ They now retain BRep face IDs with a null feature entity where no such binding
+ exists. The SDK's existing occurrence resolution selects the actual engineering
+ occurrence. Runtime-only faces do not acquire fabricated source selectors.
+
+The larger managed dependency also exposed an Edge private-context asset fetch
+failure: `Microsoft.CodeAnalysis.CSharp` (6,687,001 bytes) returned
+`net::ERR_CACHE_WRITE_FAILURE`, followed by a .NET boot fetch rejection. The shared
+development Vite middleware now sends `no-store` and explicit content lengths.
+Actual product reruns have no page errors. Production fingerprint caching remains
+unchanged; no WASM loader redesign was performed.
+
+## Real Edge product evidence
+
+Every model came from normal Cadmata source startup/API or Helios file input and
+Build. Browser instrumentation observed actual draws using the compiler pipeline;
+it never supplied field packets or registered shaders. Negative cases deliberately
+rejected a real compiler-produced GPU module, leaving compiler/transport data intact.
+
+| Case, both products | Actual fields / visual meshes | Evidence |
+|---|---:|---|
+| Normal Cylinder | 1 / 0 | One compiler shader module, actual field draws, one invisible proxy; orbit/zoom/pick remain functional |
+| Sphere, Cone, Torus | 1 / 0 each | Normal Auto dispatch and real compiler pipeline draws |
+| Locating pin, Ø6 × 20 mm | 1 / 0 | Clean nominal mechanical specimen; no threaded-showcase dependency or manufacturing-release claim |
+| Mixed Assembly | 2 / 1 | Repeated cylinder definition shares one artifact/module/pipeline; annular plate uses mesh; BRep edges and face identity retained |
+| Mixed Scene | 2 / 1 | Same shared binding, authored cameras, stable engineering face/occurrence picking |
+| Rejected GPU module | 0 / 1 | Named GPU failure, visible mesh, selection functional, viewport alive in Cadmata and Helios |
+| House Scene | 0 / 161 | 94 definitions / 254 total hierarchy occurrences, authored environment/furniture/materials, three cameras and translucent panes preserved |
+
+Mixed-depth qualification uses two ordinary authored Scene cameras. In both
+products the front centre pixel is blue mesh `[40,99,171]`, with the Mesh occurrence
+picked; the back pixel is copper CIR `[174,102,63]`, with CylinderA picked. Selection
+overlays are cleared through a normal background click before sampling. This
+proves both occlusion directions as well as agreement with engineering proxies.
+
+Cadmata's normal refresh remains CIR and does not recreate its shader module.
+Helios edits the Cylinder radius **12 → 14 mm** in Monaco and clicks Build:
+the artifact identity changes, the field remains active, the occurrence identity
+survives and obsolete program references leave the cache. Helios also edits the
+Copper colour `.55 → .15` and the repeated occurrence translation **50 → 70 mm**.
+Both reuse the original artifact/module; the resolved colour updates and pipeline
+counts remain unchanged for placement-only rebuilding. Native Scene tests verify
+the same reuse across appearance/placement updates.
+
+## Performance observations
+
+A fresh native diagnostic process measured the first Box artifact at 129.31 ms,
+then Cylinder 8.82 ms, Sphere 6.29 ms, Cone 6.44 ms, Torus 5.87 ms and locating pin
+5.59 ms. Every immediate repeat was a cache hit with zero regeneration time.
+These are backend generation timings, not total product load times.
+
+The final Helios product audit measured Cylinder/Sphere/Cone/locating-pin loads
+at 0.86–0.87 s, Torus 1.88 s, mixed Assembly 2.46 s and mixed Scene 1.89 s. The
+development/non-AOT house load was **53.485 s**, compared with the previous A2
+52.6 s observation. These are single observations under qualification load,
+not a performance claim. No retained-compilation or whole-house optimization was
+attempted. The bounded reuse win is avoiding duplicate semantic generation and
+unnecessary program creation on material/placement edits.
+
+## Validation and cleanup
+
+- Release solution build: zero errors; existing build advisories retained.
+- Fast .NET lane: 1,005 passed.
+- Full serial .NET lane: **4,323 passed across 20 projects**, zero failed/skipped.
+- Focused display projection: 11 passed, including primitives, serialization,
+ identity/corruption, repeated occurrences, Scene edits and the CSG route boundary.
+- Telos: 12 tests passed; Cadmata: 86 across 18 files; Helios: 29 across 7 files.
+- Both frontend builds and development SDK build/install passed.
+- Real Edge substrate/direct-WGSL qualification: PASS, zero page/console errors.
+- Real product qualification: 16 main witnesses plus the separate Helios negative
+ case passed. Normal house/guitar/factory/robot regression captures were refreshed.
+- Repository CLI independently inspects Cylinder, locating pin and mixed Scene;
+ native compiler audit records shader identity, generation/reuse and exact CSG refusal.
+- Ownership/cache/import/lifetime cleanup completed. Source formatting, repository
+ layout and whitespace checks passed. Prior viewport/A1/A2 work was preserved.
+
+Raw reports/captures/logs are ignored under `artifacts/local/cir-artifact-binding/`:
+`products/`, `products-negative/`, `regressions/`, `native/`, and the named gate logs.
+The release document records compact conclusions rather than promoting run dumps.
+
+## Reproduction
+
+```powershell
+./scripts/prepare-managed-wgsl.ps1 -CopelandRoot <explicit matching Copeland checkout>
+dotnet build Aetheris.slnx -c Release -m:1
+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
+npm --prefix Aetheris.Web.Runtime/telos test
+npm --prefix aetheris.client test
+npm --prefix aetheris.client run build
+dotnet build Aetheris.Server -c Release -m:1
+# In the explicitly scoped HeliosCAD checkout: npm run sdk:install; npm test;
+# npm run build:fast; npm run dev -- --host 127.0.0.1
+node scripts/audit-cir-artifact-products.mts <Playwright module path>
+node scripts/audit-display-projection-products.mts <Playwright module path> artifacts/local/cir-artifact-binding/regressions
+./scripts/audit-display-projection-closeout.ps1 -OutputDirectory artifacts/local/cir-artifact-binding/native
+```
+
+The default current strict product audit also includes the Helios GPU-negative
+case; `--failure-only` can isolate it with a separate output directory. Substrate
+regeneration uses `prepare-three-telos-cir.ps1`, `build:witness` and
+`qualify-three-telos-browser.mts`; it is independent corroboration, not product
+acceptance authority.
+
+## Deferred experimental CSG qualification
+
+`fixtures/Compatibility/LegacyV1/Examples/w2_cylinder_root_blind_bore_semantic.firmament`
+compiles through its compatibility owner, retains a qualified evaluable CSG root,
+and binds through this provider in tests. The same document passed to normal
+`CompileSource` fails at `FirmamentV2.CompatibilityFirewall`, including
+`firmament-v2-source-required`. Future experimental qualification would need to
+exercise that existing CSG through a canonical V2 authored/retained execution route, preserving
+BRep authority; allowing historical V1 input in the browser would bypass the
+existing language boundary. This is isolated source/retention qualification work,
+not another shader registry or renderer patch.
+
+P4-01A is **Accepted for Preview 4 scope, with experimental CSG qualification deferred.**
+Threaded wire-only faces,
+final visual release qualification, distribution and production AOT were left
+outside this milestone.
diff --git a/docs/release/THREE-TELOS-X0.md b/docs/release/THREE-TELOS-X0.md
index c59fa228..8507525e 100644
--- a/docs/release/THREE-TELOS-X0.md
+++ b/docs/release/THREE-TELOS-X0.md
@@ -52,7 +52,7 @@ The retained compiler qualification path is:
```text
existing CIR SdfCylinderNode(0.8, 2)
-> CirVisualTsLowerer (existing CIR tape)
- -> Field + typed fixtures/three-telos/field-pass.v.ts
+ -> Field + typed Aetheris.Kernel.Firmament/Display/telos-field.v.ts
-> Copeland parser/binder -> VD-MIR -> WgslGraphicsBackend
-> artifact -> Telos Field pass -> real Edge WebGPU
```
diff --git a/docs/release/VIEWPORT-FINISH-X0.md b/docs/release/VIEWPORT-FINISH-X0.md
new file mode 100644
index 00000000..3e9d42a0
--- /dev/null
+++ b/docs/release/VIEWPORT-FINISH-X0.md
@@ -0,0 +1,146 @@
+# VIEWPORT-FINISH-X0 — Preview 4 product audit
+
+Date: 2026-10-05. Verdict: **Honest stop**.
+
+Cadmata and Helios have a more reliable shared viewport, but this milestone is **not accepted for Preview 4**. Actual product use exposed missing display contracts, not optional aesthetic refinements: neither product supplies authored CIR fields; Scene sources cannot reach their display path; authored assembly finishes are omitted; the threaded showcase has 37 wire-only faces. A complete, presentation-worthy five-model screenshot set cannot be produced from these products yet.
+
+The current stable mesh viewport is preserved. No geometry language, IR, GPU compiler, second renderer, or new AA framework was introduced. Completing these gates requires the existing engineering/display owners to supply their missing projection, followed by product qualification. Cosmetic shaders cannot reconstruct that authority.
+
+## Real product audit and provenance
+
+The audit used Microsoft Edge with the real NVIDIA Ampere WebGPU adapter, actual application navigation, STEP file input, product startup-file claims, the Cadmata API, and Helios's WASM worker. It did not inject synthetic display packets into the products.
+
+- Cadmata: built Release server, production Vite bundle copied into its `wwwroot`, real browser at localhost. Earlier baseline/dev-server captures also exposed shader asset admission and React StrictMode initialization failures.
+- Helios: actual `/local` application, installed WASM SDK and worker, Monaco/source/file/build/pick controls, and a successful development bundle build. Its production build refuses the currently installed non-AOT SDK: `Production requires the AOT SDK package. Run npm run sdk:install:production.` Production Helios packaging is not qualified by this audit.
+- Canonical captures use a 1600 × 1000 CSS viewport at DPR 2. Lifecycle checks also use 1150 × 850 and DPR 3. Fallback captures deliberately remove `navigator.gpu`; this tests the explicit boundary, not a second physical hardware platform.
+- Source and generated evidence are separated. Raw screenshots, JSON, meshes, CLI outputs, and logs remain ignored under `artifacts/local/viewport-finish-x0/`.
+
+Reproduction entry point: `scripts/qualify-viewport-finish.mts <playwright-module-path> final <cadmata-url> 2`. Helios is expected at `http://127.0.0.1:4173/local`. The script opens fresh Cadmata processes for the guitar and robot because startup-file claims are one-shot. Use the real repository CLI DLL to generate the threaded STEP before the run:
+
+```powershell
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll build fixtures/Thread/hexbolt-threaded.firmament artifacts/local/viewport-finish-x0/threaded.step --json
+node scripts/qualify-viewport-finish.mts <playwright-module-path> final http://127.0.0.1:5142 2
+node scripts/qualify-viewport-finish.mts <playwright-module-path> themes http://127.0.0.1:5142 2
+```
+
+The CLI successfully compiles the threaded source and inspects both house and factory Scenes. That proves their source owners work; it does not prove these products display them.
+
+## Changes and friction log
+
+| Issue and user impact | Root owner | Repair or release boundary |
+|---|---|---|
+| Shader asset requests were refused; supported-browser viewport stayed blank | Product Vite asset admission | Admit the shared Telos package directory in both dev servers. Helios scripts explicitly select `vite.config.ts`, avoiding a stale emitted JS config. |
+| Packaged temporal WGSL returned 404 even when its asset existed | Cadmata static file hosting | Explicit `.wgsl` → `text/plain` content type, verified by real HTTP 200 and product startup. Unknown file types remain restricted. |
+| React StrictMode could dispose an older initialization after a new context was configured | Telos device and product initialization | Abort pending startup; destroy canceled devices before configuring the canvas; only the current context owner may unconfigure it. |
+| `SpatialOnly` did not give mesh silhouettes multisample coverage | Telos frame/pipeline owner | Four-sample color and the single authoritative depth attachment, shared by drawing passes, with one final color resolve. |
+| Wide-model framing clipped in narrow panes; initial fit ran before pane sizing | Shared camera/host | Size synchronously before fit; account for viewport aspect in both projection modes; respect product world-up. |
+| Engineering views had inconsistent orientation and unnecessary depth range | Camera projection | Both products use Z-up, XY grid, restrained isometric first fit, and bounds-relative near/far planes. |
+| Grid terminals and excess line density looked accidental | Telos grid/line shader | Bounded 1/2/5 decade spacing, at most 32 lines either side per axis, derivative coverage, and finite end fading. |
+| Opening an assembly highlighted the whole model | Cadmata selection projection | Start with no assembly selection. Explicit user selection still uses the published occurrence tree. |
+| Opaque bright face emphasis hid material/form | Shared material projection | Amber blended into original material; selected and hover strengths differ; preserve opacity. Both mesh and field selection use the same helper. |
+| Hover was absent or kept redrawing while dragging | Product pointer projection | Local picking for hover; clear on leave, skip navigation drags, invalidate only when hover changes. Engineering click authority stays in its existing owner. |
+| FIT SEL fitted the whole scene | Shared bounds fit / Helios control | Fit selected occurrence bounds; retain shared camera authority. |
+| Empty/GPU initialization/error states could be silent or clipped | Product viewport UI | Useful empty guidance, quiet busy status, bounded diagnostic panel, and Restart viewport retaining the product model. |
+| DPR changed without CSS resize or media-query notification | Shared host lifecycle | ResizeObserver, resize/media-query notifications, plus a 500 ms attached scalar DPR check. Unchanged DPR schedules no frame; disposal removes its timer/listeners. |
+| Repeated edge definitions collided across occurrences | Telos adapter | Include occurrence identity in line identity; retain definition geometry reuse and kernel edge provenance. |
+| File header reading left the previous STEP import enabled | Cadmata file selection | Clear admitted selection immediately; ignore stale async header completions. A UI regression test checks disabled import and out-of-order completion. |
+| Renderer implementation rows and the template browser title leaked into normal UI | Cadmata product projection | Production inspector omits renderer counters/lanes; full import status avoids implementation labels; preserve partial-display warnings. Product title and neutral workspace caption replace template/milestone labels. |
+| Both products made a missing default favicon request | Product HTML | Explicit empty favicon avoids console/network noise without shipping template branding. The asset audit attributes the earlier remaining 404s to `favicon.ico`, not a GPU shader failure. |
+| Helios development fallback emitted `ResizeObserver loop completed with undelivered notifications` | Legacy fallback/layout boundary; exact observer not isolated | One legacy renderer mounts and the capture completes. The warning remains recorded; unsupported-browser resize behavior is not fully qualified and no hidden second graphics owner was introduced to mask it. |
+| Authored analytic geometry still displays preview triangles | Product CIR artifact/provider seam | **Blocked:** missing qualified CIR artifact/admission projection; see below. |
+| Guitar loses authored finishes; guitar/robot lack assembly topology lines | Assembly display projection | **Blocked:** DTO has face patches and transforms but omits authored appearance and engineering edge polylines. P4-01A confirms the robot fixture has no authored looks. Do not infer materials from names or edges from triangle diagonals. |
+| House/factory cannot open as Scenes | Cadmata service / Web runtime build dispatch | **Blocked:** route to the existing Scene compilation owner and publish its occurrences/materials/cameras. |
+| Threaded close-up has visibly missing shaded thread faces | Kernel display preparation | **Blocked:** real import and preparation succeed with `Partial`, 37 wire-only faces. Preserve the admission warning; fix the existing preparation/tessellation owner. |
+| Guitar first display is slow; complete stutter comparison unavailable | Compile/serialize/upload product path | Recorded rather than claimed resolved. No speculative prewarm or performance rewrite. |
+| Large generated mate identities clutter guitar inspector | Cadmata semantic inspector | Retained for diagnosis; presentation simplification remains unqualified. Do not alter semantic mate identity to beautify a screenshot. |
+| Helios production bundle cannot use the installed SDK | SDK packaging | Separate AOT package prerequisite; development evidence is labeled accordingly. |
+
+## CIR default and Auto policy
+
+Production policy remains: **qualified engineering-supplied CIR artifact → CIR; otherwise → published mesh fallback**. Qualification must include field shader/ABI, bounds, transforms, material, engineering selection proxy and topology overlays. It cannot be inferred solely from a surface kind or an `analytic` display-lane label.
+
+The current products cannot fulfill the first branch:
+
+1. `aetheris.client/src/viewer/cadmataTelos.ts` draws analytic `previewMesh` data and returns `fields: []`.
+2. `Aetheris.Server/Contracts/ApiContracts.cs` assembly display DTOs carry face patches, occurrence transforms and semantic selection members. They do not carry CIR artifacts/admission, authored appearance, topology lines, or cameras.
+3. `Aetheris.Web.Runtime/sdk/src/index.d.ts` publishes mesh definitions/ranges/optional edges and occurrences. It has no CIR artifact/provider contract, appearance projection, or Scene camera projection.
+4. `Aetheris.Server/Api/AssemblyDisplayService.cs` routes `.firmament` input to `AssemblyM1Pipeline`. House and factory requests both return HTTP 400, `assembly-parse-missing-root: Expected 'Assembly Name { ... }'.`
+5. `Aetheris.Web.Runtime/Program.cs` dispatches only Assembly versus Part compilation. Opening the house in actual Helios fails while retaining the previous bracket and marking `MODEL OUT OF DATE`.
+
+Existing sphere/cylinder/cone/torus/CSG qualification in `CIR-DISPLAY-X0` remains substrate evidence. This run rechecks a real GPU CIR-cylinder/mesh mixed-depth witness, transforms, perspective/orthographic projection, picking, and resource reuse. It does **not** relabel that witness as a sphere/cone/torus/CSG product sweep. Product assembly/Scene CIR occurrence and selection qualification remains blocked. No automatic CIR coverage percentage or completed Auto mode is claimed.
+
+Smallest repair: extend the existing engineering-owned display contract/provider with qualified CIR artifacts and proxies; project them through the existing Telos adapters. Reuse the existing Scene session/compiler for Scene dispatch and preserve compiled occurrences, finishes, units, and cameras. Carry authored assembly appearance and kernel edge polylines through the existing DTO. Then re-run the requested primitive and showcase qualification. A renderer-only reconstruction would create a parallel authority and would not close these gates.
+
+## AA, camera, grid, lighting and selection policies
+
+Spatial AA is the production default. Meshes and thick lines use four-sample MSAA and one shared depth owner. Topology lines retain local derivative coverage; the GPU witness reads exactly four device pixels at DPR 1 and eight at DPR 2, at camera spans 3 and 10. Perspective/orthographic mixed depth and picking remain qualified in the shared witness.
+
+`None`, `TAA`, and `TAAUtility` use one sample. Mode transitions rebuild the required attachments/pipeline bindings and pass real GPU readback without validation errors. Temporal modes remain opt-in developer experiments; no temporal mode is exposed in ordinary product controls or enabled by default. The existing center-ray CIR shader ABI does not gain analytic silhouette coverage simply by rendering to a multisampled attachment. Field-aware AA and coherent full CIR material response are not newly qualified here.
+
+Fit uses authoritative display bounds, pane aspect, useful margin and product world-up. Camera tests contain every bounding-box corner in narrow and wide panes, both projection modes, at scales `1e-5`, `1`, and `1e6`. Actual orbit, wheel navigation, resize, named view, and face selection were exercised. Full pan/maximize/minimize/dock permutations and room/factory-scale navigation remain unqualified.
+
+The shared neutral studio-like mesh shader remains restrained; selection blends amber rather than replacing all shading. Existing roughness/metallic mesh inputs remain intact. The default fallback material makes geometry legible, but uniform guitar appearance cannot substitute for its authored finishes. P4-01A confirms the robot fixture has no authored appearance bindings. Opacity and roughness/metallic parity across product CIR/mesh, house glass and mixed Scene materials are not qualified.
+
+PMI remains CSS-pixel DOM text projected through the shared camera, with GPU leaders and published semantic targets. Slightly more line spacing improves readability. CTC03 datum selection passes without broadening engineering selection authority. Existing authoring overlays remain supported; this run does not qualify every construction-plane/preview case. The Helios face pick records its runtime face identity and explicitly does not assert a new compiler-owned source selector.
+
+## Witnesses and visual review
+
+| Real witness | Review and remaining limitation | Capture |
+|---|---|---|
+| Threaded hex bolt | Framed close view, curved thread silhouette and mesh edges visible. **Incomplete shading:** distal thread region becomes wire-only. Not presentation-worthy or CIR proof. | `final/mechanical-closeup.png` |
+| CTC03 manufacturing AP242 | Thin sheet, openings and rounded bends readable; datum/GD&T panels have clear contrast and leaders. Selected Datum A remains selectable. Dense full PMI can still require category filters. | `final/cadmata-pmi.png`, `final/cadmata-selected.png` |
+| GuitarX0 | Useful full-model framing; strings and composition visible; no initial all-model highlight. Authored woods/metal finishes and assembly edges absent; generated mate labels remain noisy. | `final/guitar.png` |
+| Industrial Atlas | Useful Z-up robot pose; repeated occurrence hierarchy retained, recesses visible. Assembly topology lines absent. Subsequent P4-01A audit confirms this fixture has no authored appearance bindings; uniform material alone does not prove material loss. | `final/robot.png` |
+| WarmModernHouse | Source compiles through CLI; Cadmata refuses Scene as Assembly; Helios retains last valid bracket with clear failed-build state. No actual house viewport exists to review glass/camera/materials. | `final/helios-house-refusal.png` is refusal evidence, **not a house showcase** |
+| FactoryX0 | Source compiles through CLI; product display endpoint refuses Scene as Assembly. Factory presentation is unqualified. | `FactoryX0-packet.json` |
+| Helios editable bracket | Hole form, topology outline, isometric fit, face selection and split view are legible. Failed rebuild retains display revision 0 while source revisions advance. | `final/helios-part.png`, `final/helios-selected.png`, `final/helios-last-valid.png` |
+
+The supplementary `themes/` run checks Cadmata Atelier and light Monument rendering/PMI. Themes remain product presentation choices. The shared grid/lighting are intentionally simple; every legacy animated/theme lighting parameter is not projected by Telos.
+
+The `before/` captures are genuine failed startup/asset-admission states. `final/` shows the repair, not a manufactured aesthetic comparison. There is no measured before/after silhouette-quality or performance comparison against a functioning pre-change product. The requested README/Release/VC screenshot set is **partial and not accepted**: the mechanical image is defect evidence, the guitar lacks authored finishes, and there is no house image. No screenshot was substituted from Blender, GLB, or a synthetic renderer. An earlier mistimed mechanical capture was discarded; the final script verifies the actual request name, successful display response and completed product loading before capture.
+
+## Performance and resource evidence
+
+`final/audit.json` contains measured browser instrumentation. These are end-to-end navigation/queue-completion timings, not GPU timestamp durations or a sustained FPS benchmark. Screenshot capture, browser scheduling and compilation can affect them.
+
+| Measurement | Cadmata CTC03 | Helios bracket |
+|---|---|---|
+| Active render pipeline samples | 4 | 4 |
+| Idle 500 ms | No new GPU submission | No new GPU submission |
+| Resource inventory before/recovered | 543 buffers / 2 textures | 43 buffers / 2 textures |
+| Live DPR change | 1506×1344 at DPR 2 → 2259×2016 at DPR 3 | 1036×1032 at DPR 2 → 1554×1548 at DPR 3 |
+
+Twenty wheel-navigation steps measure Cadmata at 12.15 ms mean / 17.90 ms maximum and Helios at 6.73 ms mean / 8.60 ms maximum. The JSON also records CPU encode and queue completion distributions. Fresh guitar startup takes 17.59 seconds to first captured display and robot startup 6.31 seconds. These include browser/application load and capture overhead, and were measured while serial regression validation was active; they are intentionally not release performance budgets. The threaded import/export/display path also needs further performance qualification. A zero-idle-submit check and equal post-recovery inventory establish bounded lifecycle behavior, not a claim of leak-free arbitrary model switching.
+
+The separate shared mixed-depth GPU witness passes with no GPU or console errors, retains one geometry definition across transformed occurrences, and releases buffers/textures on disposal/recreation. Full showcase camera-motion/stutter and Scene-switching qualification remain open.
+
+## Validation and cleanup
+
+- Release `.NET` solution build: passed, zero errors; two existing WASM SQLite warnings.
+- Fast kernel lane: 1,005 passed.
+- Full serial solution lane: **4,312 passed across 20 test projects; zero failed/skipped**.
+- Telos build/typecheck and tests: **10 passed**, including aspect/scale framing and repeated-occurrence edge identity.
+- Cadmata production build/typecheck and frontend suite: **86 passed across 18 files**, including the async STEP-selection regression.
+- Helios development bundle/typecheck and frontend suite: **29 passed across 7 files**. Existing large Monaco bundle/CSS parser advisories remain; production AOT prerequisite is recorded separately.
+- Shared real GPU qualification: passed, including four AA mode transitions, depth/readback, line DPR widths, picking, reuse and disposal.
+- Actual product audit: orbit redraw, PMI/face selection, pane resize, live DPR change, zero idle submissions, forced device loss/restart, failed-build retention, explicit fallback and showcase startup all exercised.
+- Final asset/theme smoke: both actual products start without console/page errors or missing assets; Cadmata's packaged WGSL responds HTTP 200 as `text/plain` (5,284 bytes). Repository layout guard and both repository diff whitespace checks pass.
+
+Commands used include the required full gate:
+
+```powershell
+dotnet build Aetheris.slnx -c Release -m:1 --nologo -v:q
+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
+npm --prefix Aetheris.Web.Runtime/telos test
+npm --prefix aetheris.client test
+npm --prefix aetheris.client run build
+npm --prefix ../HeliosCAD test
+npm --prefix ../HeliosCAD run build:fast
+npm --prefix Aetheris.Web.Runtime/telos run build:witness
+node scripts/qualify-three-telos-browser.mts <playwright-module-path>
+```
+
+Cleanup retains one supported-browser Telos graphics/camera/depth authority, sample-specific pipeline caching, shader-module reuse and local resource ownership. The unsupported-browser renderer is lazy; forced R3F/Drei preload chunks were removed. Device recovery remounts the viewport rather than introducing a parallel loop. No background service, startup hook, renderer research, or new JudgmentEngine selector was added: these repairs are deterministic transformations/lifecycle fixes, and no competing qualified product CIR candidates exist to score.
+
+**Executive answer:** the repaired shared mesh viewport is materially better, but automatic qualified CIR, complete canonical geometry, authored finishes and actual Scene presentation prevent saying that both products now have the requested finished Preview 4 viewport. Repair the display-provider prerequisites before aesthetic acceptance.
diff --git a/fixtures/Canonical/DisplayProjection/cone.firmament b/fixtures/Canonical/DisplayProjection/cone.firmament
new file mode 100644
index 00000000..811fbef7
--- /dev/null
+++ b/fixtures/Canonical/DisplayProjection/cone.firmament
@@ -0,0 +1,4 @@
+Model RetainedCone {
+ Units: mm
+ Cone Base { BottomRadius: 12mm; TopRadius: 0mm; Height: 30mm }
+}
diff --git a/fixtures/Canonical/DisplayProjection/locating-pin.firmament b/fixtures/Canonical/DisplayProjection/locating-pin.firmament
new file mode 100644
index 00000000..d884f852
--- /dev/null
+++ b/fixtures/Canonical/DisplayProjection/locating-pin.firmament
@@ -0,0 +1,6 @@
+// Nominal straight cylindrical locating pin: diameter 6 mm, length 20 mm.
+// This bounded display specimen makes no edge-finish or manufacturing-release claim.
+Model LocatingPin {
+ Units: mm
+ Cylinder PinBody { Radius: 3mm; Height: 20mm; }
+}
diff --git a/fixtures/Canonical/DisplayProjection/mixed.firmament b/fixtures/Canonical/DisplayProjection/mixed.firmament
new file mode 100644
index 00000000..21284335
--- /dev/null
+++ b/fixtures/Canonical/DisplayProjection/mixed.firmament
@@ -0,0 +1,27 @@
+Template < R: Length > Model AnalyticCylinder {
+ Units: mm; Cylinder Body { Radius: R; Height: 30mm; }
+}
+Template < W: Length > Struct MeshPlate {
+ Circle2 Outer { Center: [0mm,0mm]; Radius: W; }
+ Circle2 Inner { Center: [0mm,0mm]; Radius: 4mm; }
+ Profile Ring { Loop Outer { Outer |> TraceLoop } Loop Bore { Inner As InnerBoundary |> TraceLoop } }
+ Extrude Body { Profile: Ring; From: 0mm; To: 5mm; }
+}
+Appearance CopperLook { Color: [.55,.18,.06]; Roughness: .3; Metallic: .7; }
+Material Copper { Identity: "copper"; Appearance: CopperLook; }
+Appearance BlueSteelLook { Color: [.02,.15,.5]; Roughness: .5; Metallic: .6; }
+Material BlueSteel { Identity: "steel"; Appearance: BlueSteelLook; }
+Assembly MixedDisplay {
+ <Assembly MixedDisplay>
+ <Part CylinderA = AnalyticCylinder<R:12mm>> Material: Copper;
+ Placement LegacyExplicit = [1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];
+ </Part>
+ <Part CylinderB = AnalyticCylinder<R:12mm>>
+ Placement LegacyExplicit = [1,0,0,0,0,1,0,0,0,0,1,0,50,0,0,1];
+ </Part>
+ <Part Mesh = MeshPlate<W:20mm>> Material: BlueSteel;
+ Placement LegacyExplicit = [1,0,0,0,0,1,0,0,0,0,1,0,0,-60,10,1];
+ </Part>
+ </Assembly>
+ Anchor: MixedDisplay;
+}
diff --git a/fixtures/Canonical/DisplayProjection/scene.firmament b/fixtures/Canonical/DisplayProjection/scene.firmament
new file mode 100644
index 00000000..cb74a371
--- /dev/null
+++ b/fixtures/Canonical/DisplayProjection/scene.firmament
@@ -0,0 +1,9 @@
+Scene FieldWorkshop {
+ units: mm;
+ <Assembly carriage = AssemblyFile<"mixed.firmament">>
+ Placement { from: Origin; to: World; translateLocal: [0mm,0mm,0mm]; }
+ </Assembly>
+ Camera Hero { position: [100mm,-160mm,120mm]; lookAt: [20mm,-20mm,15mm]; fov: 55deg; }
+ Camera Front { position: [0mm,-200mm,12.5mm]; lookAt: [0mm,0mm,12.5mm]; fov: 55deg; }
+ Camera Back { position: [0mm,200mm,12.5mm]; lookAt: [0mm,0mm,12.5mm]; fov: 55deg; }
+}
diff --git a/fixtures/Canonical/DisplayProjection/sphere.firmament b/fixtures/Canonical/DisplayProjection/sphere.firmament
new file mode 100644
index 00000000..b2288c10
--- /dev/null
+++ b/fixtures/Canonical/DisplayProjection/sphere.firmament
@@ -0,0 +1,4 @@
+Model RetainedSphere {
+ Units: mm
+ Sphere Base { Radius: 12mm }
+}
diff --git a/fixtures/Canonical/DisplayProjection/torus.firmament b/fixtures/Canonical/DisplayProjection/torus.firmament
new file mode 100644
index 00000000..4a3b09f2
--- /dev/null
+++ b/fixtures/Canonical/DisplayProjection/torus.firmament
@@ -0,0 +1,4 @@
+Model RetainedTorus {
+ Units: mm
+ Torus Base { MajorRadius: 20mm; MinorRadius: 5mm }
+}
diff --git a/scripts/audit-cir-artifact-products.mts b/scripts/audit-cir-artifact-products.mts
new file mode 100644
index 00000000..8e0dc04c
--- /dev/null
+++ b/scripts/audit-cir-artifact-products.mts
@@ -0,0 +1,522 @@
+import assert from "node:assert/strict";
+import { resolve, dirname } from "node:path";
+import { pathToFileURL } from "node:url";
+import { mkdir, readFile, writeFile, readdir } from "node:fs/promises";
+import { spawn } from "node:child_process";
+import { inflateSync } from "node:zlib";
+
+// Normal startup/file input/editor actions only. GPU instrumentation observes
+// submission; the single negative case rejects a real compiler-produced module.
+const { chromium } = await import(pathToFileURL(resolve(process.argv[2])).href);
+const output = resolve(
+ process.argv[3] ?? "artifacts/local/cir-artifact-binding/products",
+);
+await mkdir(output, { recursive: true });
+const browser = await chromium.launch({
+ executablePath:
+ "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe",
+ headless: true,
+});
+const records: any[] = [];
+const failureOnly = process.argv.includes("--failure-only");
+async function pageFor(url: string, fail = false) {
+ const page = await browser.newPage({
+ viewport: { width: 1600, height: 1000 },
+ deviceScaleFactor: 1,
+ });
+ const errors: string[] = [];
+ page.on("pageerror", (e) => errors.push(e.stack ?? String(e)));
+ page.on("requestfailed", (r) =>
+ console.error("REQUEST FAILED", r.url(), r.failure()),
+ );
+ await page.addInitScript((fail: boolean) => {
+ const scope = window as any;
+ scope.cirAudit = { modules: [], pipelines: [], draws: 0, fail };
+ const module = GPUDevice.prototype.createShaderModule;
+ GPUDevice.prototype.createShaderModule = function (d) {
+ scope.cirAudit.modules.push(d.label);
+ if (scope.cirAudit.fail && /^[a-f0-9]{64}$/.test(String(d.label))) {
+ scope.cirAudit.fail = false;
+ return module.call(this, {
+ ...d,
+ code: "bounded qualification: invalid WGSL",
+ });
+ }
+ return module.call(this, d);
+ };
+ const pipeline = GPUDevice.prototype.createRenderPipeline;
+ GPUDevice.prototype.createRenderPipeline = function (d) {
+ scope.cirAudit.pipelines.push(d.label);
+ return pipeline.call(this, d);
+ };
+ const begin = GPUCommandEncoder.prototype.beginRenderPass;
+ GPUCommandEncoder.prototype.beginRenderPass = function (d) {
+ const pass = begin.call(this, d),
+ set = pass.setPipeline.bind(pass),
+ draw = pass.draw.bind(pass);
+ let field = false;
+ pass.setPipeline = (p) => {
+ field = /^\["[a-f0-9]{64}"/.test(p.label);
+ return set(p);
+ };
+ pass.draw = (...args) => {
+ if (field) scope.cirAudit.draws++;
+ return draw(...args);
+ };
+ return pass;
+ };
+ }, fail);
+ await page.goto(url);
+ return { page, errors };
+}
+async function inspect(page: any) {
+ return page
+ .locator("[data-display-host=three-telos] canvas")
+ .evaluate((canvas: HTMLCanvasElement) => ({
+ ...JSON.parse(canvas.dataset.telosDisplay ?? "{}"),
+ submittedFields: Number(canvas.dataset.telosFieldDraws),
+ gpu: (window as any).cirAudit,
+ }));
+}
+async function ready(page: any, fields: number, mesh: number, fail = false) {
+ await page
+ .waitForFunction(
+ ({ fields, mesh, fail }) => {
+ const canvas = document.querySelector(
+ "[data-display-host=three-telos] canvas",
+ ) as HTMLCanvasElement;
+ if (!canvas?.dataset.telosDisplay) return false;
+ const display = JSON.parse(canvas.dataset.telosDisplay);
+ return (
+ display.fields === fields &&
+ display.meshSurfaces === mesh &&
+ (fail
+ ? display.shaders.some((s: string[]) =>
+ s[1].startsWith("shader-artifact-gpu-failed"),
+ )
+ : fields === 0 || Number(canvas.dataset.telosFieldDraws) === fields)
+ );
+ },
+ { fields, mesh, fail },
+ { timeout: 120000 },
+ )
+ .catch(async (error) => {
+ console.error(
+ await inspect(page),
+ await page.locator("body").innerText(),
+ );
+ await page.screenshot({ path: `${output}/failed-readiness.png` });
+ throw error;
+ });
+ const state = await inspect(page);
+ if (fields)
+ assert(state.gpu.draws > 0, "Actual compiler pipeline draw required");
+ return state;
+}
+async function interact(page: any) {
+ const canvas = page.locator("[data-display-host=three-telos] canvas"),
+ box = await canvas.boundingBox();
+ const x = box.x + box.width * 0.5,
+ y = box.y + box.height * 0.5;
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x + 55, y + 25, { steps: 6 });
+ await page.mouse.up();
+ await page.mouse.wheel(0, -180);
+ await page.waitForTimeout(200);
+ await page.mouse.click(x, y);
+ await page.waitForTimeout(150);
+}
+async function replaceDigit(
+ page: any,
+ source: string,
+ token: string,
+ digit: string,
+ digitOffset = 0,
+) {
+ const lines = source.split(/\r?\n/);
+ const line = lines.findIndex((l) => l.includes(token));
+ assert(line >= 0);
+ const column = lines[line].indexOf(token) + digitOffset;
+ await page.getByRole("button", { name: "Edit Source", exact: true }).click();
+ await page.waitForTimeout(100);
+ await page.keyboard.press("Control+Home");
+ for (let i = 0; i < line; i++) await page.keyboard.press("ArrowDown");
+ await page.keyboard.press("Home");
+ for (let i = 0; i <= column; i++) await page.keyboard.press("ArrowRight");
+ await page.keyboard.press("Backspace");
+ await page.keyboard.type(digit, { delay: 30 });
+ await page.waitForFunction(() =>
+ document
+ .querySelector(".statusbar")
+ ?.textContent?.includes("MODEL OUT OF DATE"),
+ );
+ await page.getByRole("button", { name: /^Build$/i }).click();
+ await page
+ .locator(".statusbar .status-ready")
+ .filter({ hasText: "READY" })
+ .waitFor({ timeout: 120000 });
+ assert(
+ !(await page.locator(".statusbar").innerText()).includes(
+ "MODEL OUT OF DATE",
+ ),
+ );
+}
+async function mixedDepth(page: any, product: string) {
+ const results: any[] = [];
+ for (const camera of ["Front", "Back"]) {
+ await page
+ .getByRole("combobox", { name: "Scene camera" })
+ .selectOption(camera);
+ await page.waitForTimeout(250);
+ const box = await page
+ .locator("[data-display-host=three-telos] canvas")
+ .boundingBox();
+ // Clear the prior pick's gold face overlay before testing surface colour/depth.
+ await page.mouse.click(box.x + box.width - 15, box.y + box.height - 15);
+ await page.waitForTimeout(150);
+ const x = Math.floor(box.x + box.width / 2),
+ y = Math.floor(box.y + box.height / 2);
+ const png = await page.screenshot({ clip: { x, y, width: 1, height: 1 } });
+ const chunks: Buffer[] = [];
+ for (let i = 8; i < png.length; ) {
+ const size = png.readUInt32BE(i);
+ if (png.toString("ascii", i + 4, i + 8) === "IDAT")
+ chunks.push(png.subarray(i + 8, i + 8 + size));
+ i += size + 12;
+ }
+ const rgb = [...inflateSync(Buffer.concat(chunks)).subarray(1, 4)];
+ await page.mouse.click(x, y);
+ await page.waitForTimeout(150);
+ const selected =
+ product === "cadmata"
+ ? await page.locator(".semantic-tree__item.active-row").innerText()
+ : await page.locator(".status-selection").innerText();
+ if (camera === "Front") {
+ assert(selected.includes("Mesh"), selected);
+ assert(rgb[2] > rgb[0], String(rgb));
+ } else {
+ assert(selected.includes("CylinderA"), selected);
+ assert(rgb[0] > rgb[2], String(rgb));
+ }
+ results.push({ camera, rgb, selected });
+ await page.screenshot({
+ path: `${output}/${product}-mixed-depth-${camera}.png`,
+ });
+ }
+ return results;
+}
+const primitiveSources = [
+ ["cylinder", "fixtures/Canonical/Basics/cylinder.firmament"],
+ ...["sphere", "cone", "torus"].map((name) => [
+ name,
+ `fixtures/Canonical/DisplayProjection/${name}.firmament`,
+ ]),
+ ["mixed", "fixtures/Canonical/DisplayProjection/mixed.firmament"],
+ ["scene", "fixtures/Canonical/DisplayProjection/scene.firmament"],
+ [
+ "locating-pin",
+ "fixtures/Canonical/DisplayProjection/locating-pin.firmament",
+ ],
+] as const;
+try {
+ for (const [name, source] of failureOnly
+ ? []
+ : [
+ ...primitiveSources,
+ ["failure", "fixtures/Canonical/Basics/cylinder.firmament"],
+ ]) {
+ const host = spawn(
+ "dotnet",
+ [
+ resolve("Aetheris.Server/bin/Release/net10.0/Cadmata.dll"),
+ resolve(source),
+ "--urls",
+ "http://127.0.0.1:0",
+ "--no-browser",
+ ],
+ {
+ windowsHide: true,
+ env: { ...process.env, ASPNETCORE_ENVIRONMENT: "Development" },
+ },
+ );
+ try {
+ const url = await new Promise<string>((done, reject) => {
+ let text = "";
+ const timer = setTimeout(() => reject(Error("Cadmata timeout")), 20000);
+ host.on("error", reject);
+ host.stdout.on("data", (c) => {
+ text += c;
+ const m = text.match(/Cadmata ready: (http:\/\/[^\s]+)/);
+ if (m) {
+ clearTimeout(timer);
+ done(m[1]);
+ }
+ });
+ });
+ const { page, errors } = await pageFor(url, name === "failure");
+ const packet = await (
+ await page.request.post(url + "/api/v1/assemblies/display", {
+ data: { path: resolve(source) },
+ })
+ ).json();
+ assert(packet.success ?? packet.data, "Normal compilation must succeed");
+ const mixed = name === "mixed" || name === "scene",
+ fail = name === "failure";
+ const state = await ready(
+ page,
+ fail ? 0 : mixed ? 2 : 1,
+ fail || mixed ? 1 : 0,
+ fail,
+ );
+ await interact(page);
+ const afterInteraction = await ready(
+ page,
+ fail ? 0 : mixed ? 2 : 1,
+ fail || mixed ? 1 : 0,
+ fail,
+ );
+ const text = await page.locator("body").innerText();
+ assert(!text.includes("Viewport unavailable"));
+ if (name === "cylinder" || fail)
+ assert(
+ !text.includes("Occurrence ID:\nNone"),
+ "Cylinder proxy selection should survive",
+ );
+ const shaders = packet.data.display.definitions
+ .filter((d) => d.shader?.artifact)
+ .map((d) => ({
+ id: d.id,
+ cir: d.cir.structuralIdentity,
+ shader: d.shader.artifact.shaderId,
+ cacheHit: d.shader.cacheHit,
+ generationMilliseconds: d.shader.generationMilliseconds,
+ }));
+ if (name === "cylinder") {
+ await page
+ .getByRole("button", { name: "Refresh Display Data", exact: true })
+ .click();
+ await page.waitForFunction(
+ () =>
+ document.body.innerText.includes("Action: success") &&
+ !document.body.innerText.includes("Refresh display data…"),
+ );
+ await ready(page, 1, 0);
+ assert.deepEqual(
+ (await inspect(page)).gpu.modules,
+ state.gpu.modules,
+ "Rebuild must reuse GPU shader module",
+ );
+ }
+ const depth =
+ name === "scene" ? await mixedDepth(page, "cadmata") : undefined;
+ assert.equal(errors.length, 0, errors.join("\n"));
+ records.push({
+ product: "cadmata",
+ depth,
+ name,
+ state,
+ afterInteraction,
+ shaders,
+ text,
+ });
+ console.log("PASS Cadmata", name, state.fields, state.meshSurfaces);
+ await page.screenshot({ path: `${output}/cadmata-${name}.png` });
+ await page.close();
+ } finally {
+ host.kill();
+ }
+ await writeFile(`${output}/audit.json`, JSON.stringify(records, null, 2));
+ }
+ const { page, errors } = await pageFor("http://127.0.0.1:4173/local");
+ await page.locator("input[type=file]").waitFor({ state: "attached" });
+ await page.waitForFunction(
+ () => {
+ const canvas = document.querySelector(
+ "[data-display-host=three-telos] canvas",
+ ) as HTMLCanvasElement;
+ return JSON.parse(canvas?.dataset.telosDisplay ?? "{}").meshSurfaces > 0;
+ },
+ null,
+ { timeout: 120000 },
+ );
+ for (const [name, source] of failureOnly
+ ? []
+ : [
+ ...primitiveSources,
+ ["house", "fixtures/Canonical/Scene/WarmModernHouse/house.firmament"],
+ ]) {
+ const extra =
+ name === "scene"
+ ? [resolve(dirname(source), "mixed.firmament")]
+ : name === "house"
+ ? (await readdir(dirname(source)))
+ .filter(
+ (f) => f.endsWith(".firmament") && f !== "house.firmament",
+ )
+ .map((f) => resolve(dirname(source), f))
+ : [];
+ const started = Date.now();
+ await page
+ .locator("input[type=file]")
+ .setInputFiles([resolve(source), ...extra]);
+ await page.waitForFunction(
+ (name) => document.body.innerText.includes(name + ".firmament"),
+ name,
+ );
+ await page
+ .locator(".statusbar .status-ready")
+ .filter({ hasText: "READY" })
+ .waitFor({ timeout: 120000 });
+ const mixed = name === "mixed" || name === "scene";
+ let state;
+ if (name === "house") {
+ await page.waitForFunction(
+ () => document.body.innerText.includes("94 DEFS · 254 OCC"),
+ null,
+ { timeout: 120000 },
+ );
+ await page
+ .getByRole("combobox", { name: "Scene camera" })
+ .selectOption("Hero");
+ await page.waitForTimeout(600);
+ state = await inspect(page);
+ assert.equal(state.fields, 0);
+ assert.equal(state.meshSurfaces, 161);
+ } else state = await ready(page, mixed ? 2 : 1, mixed ? 1 : 0);
+ const loadMilliseconds = Date.now() - started;
+ await interact(page);
+ if (name === "cylinder") {
+ const id = state.definitions[0].shaderId;
+ await page
+ .getByRole("button", { name: "Edit Source", exact: true })
+ .click();
+ await page.waitForTimeout(100);
+ // Edit only the radius digit through the normal editor. Whole-document
+ // key replay also invokes Monaco suggestions/autoindent and is not a paste.
+ await page.keyboard.press("Control+Home");
+ for (let line = 0; line < 4; line++)
+ await page.keyboard.press("ArrowDown");
+ await page.keyboard.press("End");
+ await page.keyboard.press("ArrowLeft");
+ await page.keyboard.press("ArrowLeft");
+ await page.keyboard.press("Backspace");
+ await page.keyboard.type("4", { delay: 30 });
+ await page.waitForFunction(() =>
+ document
+ .querySelector(".statusbar")
+ ?.textContent?.includes("MODEL OUT OF DATE"),
+ );
+ await page.getByRole("button", { name: /^Build$/i }).click();
+ await page
+ .waitForFunction(
+ (id) => {
+ const c = document.querySelector(
+ "[data-display-host=three-telos] canvas",
+ ) as HTMLCanvasElement;
+ const d = JSON.parse(c?.dataset.telosDisplay ?? "{}");
+ return d.fields === 1 && d.definitions?.[0]?.shaderId !== id;
+ },
+ id,
+ { timeout: 30000 },
+ )
+ .catch(async (e) => {
+ console.error(
+ await inspect(page),
+ await page.locator("body").innerText(),
+ );
+ await page.screenshot({ path: `${output}/geometry-edit-failed.png` });
+ throw e;
+ });
+ state = { ...state, geometryEdit: await ready(page, 1, 0) };
+ assert.notEqual(state.geometryEdit.definitions[0].shaderId, id);
+ assert.equal(
+ state.geometryEdit.occurrences[0].identity.occurrenceId,
+ state.occurrences[0].identity.occurrenceId,
+ );
+ assert.equal(
+ state.geometryEdit.modules,
+ state.modules,
+ "Obsolete program references should be released",
+ );
+ }
+ if (name === "mixed") {
+ const sourceText = await readFile(source, "utf8"),
+ id = state.definitions.find((d) => d.shaderId).shaderId;
+ await replaceDigit(page, sourceText, ".55", "1", 1);
+ const appearanceEdit = await ready(page, 2, 1);
+ assert.equal(
+ appearanceEdit.definitions.find((d) => d.shaderId).shaderId,
+ id,
+ );
+ assert.equal(
+ appearanceEdit.occurrences.find((o) => o.material.metallic === 0.7)
+ .material.baseColor[0],
+ 0.15,
+ );
+ await replaceDigit(
+ page,
+ sourceText.replace(".55", ".15"),
+ "50,0,0,1",
+ "7",
+ );
+ const transformEdit = await ready(page, 2, 1);
+ assert.equal(
+ transformEdit.definitions.find((d) => d.shaderId).shaderId,
+ id,
+ );
+ assert.equal(transformEdit.modules, state.modules);
+ assert.equal(transformEdit.pipelines, appearanceEdit.pipelines);
+ state = { ...state, appearanceEdit, transformEdit };
+ }
+ const depth =
+ name === "scene" ? await mixedDepth(page, "helios") : undefined;
+ assert.equal(errors.length, 0, errors.join("\n"));
+ records.push({
+ product: "helios",
+ depth,
+ name,
+ loadMilliseconds,
+ state,
+ text: (await page.locator("body").innerText()).slice(-10000),
+ });
+ console.log(
+ "PASS Helios",
+ name,
+ state.fields,
+ state.meshSurfaces,
+ loadMilliseconds,
+ );
+ await page.screenshot({ path: `${output}/helios-${name}.png` });
+ await writeFile(`${output}/audit.json`, JSON.stringify(records, null, 2));
+ }
+ await page.close();
+ const negative = await pageFor("http://127.0.0.1:4173/local", true);
+ await negative.page
+ .locator(".statusbar .status-ready")
+ .filter({ hasText: "READY" })
+ .waitFor({ timeout: 120000 });
+ await negative.page
+ .locator("input[type=file]")
+ .setInputFiles(resolve("fixtures/Canonical/Basics/cylinder.firmament"));
+ const failureState = await ready(negative.page, 0, 1, true);
+ await interact(negative.page);
+ assert(
+ !(await negative.page.locator(".status-selection").innerText()).includes(
+ "NO SELECTION",
+ ),
+ );
+ assert.equal(negative.errors.length, 0, negative.errors.join("\n"));
+ records.push({
+ product: "helios",
+ name: "failure",
+ state: failureState,
+ text: await negative.page.locator("body").innerText(),
+ });
+ await negative.page.screenshot({ path: `${output}/helios-failure.png` });
+ await negative.page.close();
+} finally {
+ await writeFile(`${output}/audit.json`, JSON.stringify(records, null, 2));
+ await browser.close();
+}
+console.log(`PASS: ${records.length} normal product witnesses`);
diff --git a/scripts/audit-display-projection-closeout.cs b/scripts/audit-display-projection-closeout.cs
new file mode 100644
index 00000000..44b00cd4
--- /dev/null
+++ b/scripts/audit-display-projection-closeout.cs
@@ -0,0 +1,107 @@
+using System.Diagnostics;
+using System.Text.Json;
+using Aetheris.Continuum.Backends.Sdf;
+using Aetheris.Kernel.Firmament;
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Kernel.Firmament.Scene;
+
+// Diagnostic only: compile through existing owners, inventory what they retain.
+// This never constructs or injects a product display packet.
+var root = Path.GetFullPath(args[0]);
+var output = Path.GetFullPath(args[1]);
+Directory.CreateDirectory(output);
+string[] Properties(Type type) => type.GetProperties().Select(p => p.Name).Order(StringComparer.Ordinal).ToArray();
+var results = new List<object>();
+foreach (var relative in new[] { "fixtures/Canonical/Basics/box.firmament", "fixtures/Canonical/Basics/cylinder.firmament",
+ "fixtures/Canonical/DisplayProjection/sphere.firmament", "fixtures/Canonical/DisplayProjection/cone.firmament",
+ "fixtures/Canonical/DisplayProjection/torus.firmament", "fixtures/Canonical/DisplayProjection/locating-pin.firmament" })
+{
+ var path = Path.Combine(root, relative);
+ var source = File.ReadAllText(path);
+ var clock = Stopwatch.StartNew();
+ var compiled = FirmamentBuildAndExport.CompileSource(source, Path.GetDirectoryName(path));
+ clock.Stop();
+ var shader = compiled.IsSuccess ? CirShaderArtifactProvider.Resolve(compiled.Value.Cir) : null;
+ var repeatedShader = compiled.IsSuccess ? CirShaderArtifactProvider.Resolve(compiled.Value.Cir) : null;
+ var legacy = new FirmamentCompiler().Compile(new(new(source, relative)));
+ results.Add(new {
+ kind = "normal-authored-part", source = relative, compiled.IsSuccess,
+ compileMilliseconds = clock.Elapsed.TotalMilliseconds,
+ shader = shader is null ? null : new { shader.Status, shader.Reason, shader.GenerationMilliseconds, shader.CacheHit,
+ shader.Artifact?.ShaderId, shader.Artifact?.SourceIdentity, shader.Artifact?.CompilerVersion,
+ repeatedCacheHit = repeatedShader!.CacheHit, repeatedMilliseconds = repeatedShader.GenerationMilliseconds },
+ compiled.Diagnostics,
+ retainedBody = compiled.IsSuccess && compiled.Value.RuntimeBody is not null,
+ retainedCorrespondence = compiled.IsSuccess && compiled.Value.RuntimeCorrespondence is not null,
+ retainedCir = compiled.IsSuccess ? compiled.Value.Cir is { } cir ? new { cir.DefinitionId, cir.Qualification,
+ cir.FallbackReason, cir.StructuralIdentity, cir.Schema, runtimeRootRetained = cir.RuntimeRoot is not null,
+ cir.MinimumMm, cir.MaximumMm } : null : null,
+ exportedCategory = compiled.IsSuccess ? compiled.Value.ExportedBodyCategory : null,
+ resultContract = Properties(typeof(FirmamentStepExportResult)),
+ legacyCompatibilityCompilerSuccess = legacy.Compilation.IsSuccess,
+ legacyCompatibilityDiagnostics = legacy.Compilation.Diagnostics,
+ legacyPlanRetained = legacy.Compilation.IsSuccess && legacy.Compilation.Value.PrimitiveLoweringPlan is not null,
+ });
+}
+// Control for the existing field lowering, explicitly not authored product data.
+var field = CirVisualTsLowerer.Lower(new SdfCylinderNode(10, 30));
+results.Add(new { kind = "standalone-cir-control", field.Success, field.FallbackReason,
+ structuralIdentity = field.Program?.StructuralHash, bounds = field.Program?.Bounds });
+var csgSource = File.ReadAllText(Path.Combine(root,"fixtures/Compatibility/LegacyV1/Examples/w2_cylinder_root_blind_bore_semantic.firmament"));
+var csgCompatibility = new FirmamentCompiler().Compile(new(new(csgSource,"compatibility-csg.firmament")));
+var csgRoot = csgCompatibility.Compilation.Value.PrimitiveExecutionResult!.NativeGeometryState.CirMirror.RuntimeRoot;
+var csgLowering = CirVisualTsLowerer.Lower(csgRoot!);
+var csgNormal = FirmamentBuildAndExport.CompileSource(csgSource);
+results.Add(new { kind="preexisting-csg-route-boundary", compatibilitySuccess=csgCompatibility.Compilation.IsSuccess,
+ retainedRoot=csgRoot is not null, loweringQualified=csgLowering.Success, csgLowering.FallbackReason,
+ normalSourceAccepted=csgNormal.IsSuccess, csgNormal.Diagnostics });
+var robotPath = Path.Combine(root, "fixtures/Canonical/AssemblyInterfaces/IndustrialAtlas/atlas-industrial.firmament");
+var robotClock = Stopwatch.StartNew();
+var robot = new AssemblyM1Pipeline().CompileFile(robotPath);
+results.Add(new { kind = "normal-assembly", robot.IsSuccess, robot.Diagnostics,
+ compileMilliseconds = robotClock.Elapsed.TotalMilliseconds,
+ geometryContract = Properties(typeof(AssemblyExecutedGeometry)),
+ definitions = robot.Geometry?.DefinitionBodies.Count,
+ retainedCirDefinitions = robot.Geometry?.DefinitionCir.Count,
+ occurrences = robot.Ir?.Instances.Count,
+ authoredAppearanceBindings = robot.Ir?.Instances.Count(i => i.Appearance is not null),
+ resolvedAppearance = robot.Ir?.Instances.Where(i => i.Appearance is not null).Select(i => new { i.StableId, i.Appearance }).Take(3).ToArray(),
+ displayDefinitionContract = Properties(typeof(AssemblyDisplayMeshDefinition)),
+ displayOccurrenceContract = Properties(typeof(AssemblyDisplayMeshOccurrence)),
+});
+var guitar = new FirmamentAssemblyDocumentCompiler().CompileFile(Path.Combine(root,
+ "fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm")).Compilation;
+results.Add(new { kind = "material-authored-assembly", guitar.IsSuccess, guitar.Diagnostics,
+ definitions = guitar.Geometry?.DefinitionBodies.Count,
+ occurrences = guitar.Ir?.Instances.Count,
+ authoredAppearanceBindings = guitar.Ir?.Instances.Count(i => i.Appearance is not null),
+ resolvedAppearance = guitar.Ir?.Instances.Where(i => i.Appearance is not null).Select(i => new { i.StableId, i.Appearance }).Take(3).ToArray(),
+});
+foreach (var relative in new[] {
+ "fixtures/Canonical/Scene/WarmModernHouse/house.firmament",
+ "fixtures/Canonical/Scene/FactoryX0/factory.firmament" })
+{
+ using var session = new FirmamentSceneSession();
+ var clock = Stopwatch.StartNew();
+ var compiled = session.CompileFile(Path.Combine(root, relative));
+ var elapsed = clock.Elapsed.TotalMilliseconds;
+ var retained = compiled.IsSuccess ? session.CompileFile(Path.Combine(root, relative)) : null;
+ var scene = compiled.Scene;
+ var projected = scene is null ? null : DisplayProjection.Project(scene);
+ results.Add(new { kind = "compiled-scene", source = relative, compiled.IsSuccess, compiled.Diagnostics,
+ compileMilliseconds = elapsed, displaySchema = scene?.Display.Schema,
+ definitions = scene?.Display.Definitions.Count, occurrences = scene?.Display.Occurrences.Count,
+ environmentOccurrences = scene?.Nodes.Count(n => n.Kind is "EnvironmentPanel" or "WindowFinish"),
+ appearances = scene?.Appearances.Count,
+ transportedMaterials = projected?.Occurrences.Count(o => o.Material is not null),
+ transportedBoundaries = projected?.Boundaries.Count,
+ translucentAppearances = scene?.Appearances.Values.Count(a => a.Preview.Opacity < 1),
+ cameras = scene?.Source.Cameras.Select(c => new { c.Name, c.PositionMm, c.LookAtMm, c.FovDegrees }).ToArray(),
+ bounds = scene is null ? null : new { scene.MinimumMm, scene.MaximumMm },
+ scene?.Performance, retainedPerformance = retained?.Scene?.Performance,
+ compiledSceneContract = Properties(typeof(CompiledScene)),
+ });
+}
+var json = JsonSerializer.Serialize(results, new JsonSerializerOptions { WriteIndented = true });
+File.WriteAllText(Path.Combine(output, "compiled-contracts.json"), json);
+Console.WriteLine(json);
diff --git a/scripts/audit-display-projection-closeout.ps1 b/scripts/audit-display-projection-closeout.ps1
new file mode 100644
index 00000000..ea7d181b
--- /dev/null
+++ b/scripts/audit-display-projection-closeout.ps1
@@ -0,0 +1,18 @@
+[CmdletBinding()]
+param([string]$OutputDirectory)
+$ErrorActionPreference = 'Stop'
+$repo = Split-Path $PSScriptRoot -Parent
+if (-not $OutputDirectory) { $OutputDirectory = Join-Path $repo 'artifacts/local/display-projection-closeout' }
+$output = [IO.Path]::GetFullPath($OutputDirectory)
+$projectDirectory = Join-Path $output 'compiler-audit'
+New-Item -ItemType Directory -Force -Path $projectDirectory | Out-Null
+$kernelProject = [Security.SecurityElement]::Escape((Join-Path $repo 'Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj'))
+@"
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
+ <ItemGroup><ProjectReference Include="$kernelProject" /></ItemGroup>
+</Project>
+"@ | Set-Content -LiteralPath (Join-Path $projectDirectory 'Audit.csproj') -Encoding utf8
+Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'audit-display-projection-closeout.cs') -Destination (Join-Path $projectDirectory 'Program.cs')
+dotnet run --project (Join-Path $projectDirectory 'Audit.csproj') -c Release -- $repo $output
+if ($LASTEXITCODE -ne 0) { throw "Display projection compiler audit failed (exit $LASTEXITCODE)." }
diff --git a/scripts/audit-display-projection-products.mts b/scripts/audit-display-projection-products.mts
new file mode 100644
index 00000000..9a287340
--- /dev/null
+++ b/scripts/audit-display-projection-products.mts
@@ -0,0 +1,193 @@
+import { resolve, dirname } from "node:path";
+import { pathToFileURL } from "node:url";
+import { mkdir, writeFile, readdir } from "node:fs/promises";
+import { spawn } from "node:child_process";
+
+// Real product audit. File input/startup and existing APIs supply every model.
+const { chromium } = await import(pathToFileURL(resolve(process.argv[2])).href);
+const output = resolve(
+ process.argv[3] ?? "artifacts/local/display-projection-closeout/products-a2",
+);
+await mkdir(output, { recursive: true });
+const browser = await chromium.launch({
+ executablePath:
+ "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe",
+ headless: true,
+});
+const records: unknown[] = [];
+async function pageFor(url: string) {
+ const page = await browser.newPage({
+ viewport: { width: 1600, height: 1000 },
+ deviceScaleFactor: 2,
+ });
+ await page.addInitScript(() => {
+ (window as any).projectionAuditPipelines = [];
+ const original = GPUDevice.prototype.createRenderPipeline;
+ GPUDevice.prototype.createRenderPipeline = function (descriptor) {
+ (window as any).projectionAuditPipelines.push(descriptor.label);
+ return original.call(this, descriptor);
+ };
+ });
+ await page.goto(url);
+ await page.locator("[data-display-host=three-telos] canvas").waitFor();
+ return page;
+}
+try {
+ for (const [name, source] of [
+ ["cylinder", "fixtures/Canonical/Basics/cylinder.firmament"],
+ ["guitar", "fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm"],
+ ["house", "fixtures/Canonical/Scene/WarmModernHouse/house.firmament"],
+ ["factory", "fixtures/Canonical/Scene/FactoryX0/factory.firmament"],
+ [
+ "robot",
+ "fixtures/Canonical/AssemblyInterfaces/IndustrialAtlas/atlas-industrial.firmament",
+ ],
+ ]) {
+ const host = spawn(
+ "dotnet",
+ [
+ resolve("Aetheris.Server/bin/Release/net10.0/Cadmata.dll"),
+ resolve(source),
+ "--urls",
+ "http://127.0.0.1:0",
+ "--no-browser",
+ ],
+ {
+ windowsHide: true,
+ env: { ...process.env, ASPNETCORE_ENVIRONMENT: "Development" },
+ },
+ );
+ try {
+ const url = await new Promise<string>((done, reject) => {
+ const timer = setTimeout(
+ () => reject(new Error("Cadmata startup timeout")),
+ 20000,
+ );
+ let text = "";
+ host.once("error", reject);
+ host.stdout.on("data", (chunk) => {
+ text += String(chunk);
+ const match = text.match(/Cadmata ready: (http:\/\/[^\s]+)/);
+ if (match) {
+ clearTimeout(timer);
+ done(match[1]);
+ }
+ });
+ });
+ // API and UI exercise the same current product owner, without a fixture loader.
+ const page = await pageFor(url);
+ const response = await page.request.post(
+ url + "/api/v1/assemblies/display",
+ { data: { path: resolve(source) } },
+ );
+ const envelope = await response.json();
+ await page.waitForFunction(
+ () =>
+ document.body.textContent?.includes("Action: error") ||
+ document.body.textContent?.includes("Product tree"),
+ null,
+ { timeout: 120000 },
+ );
+ await page.waitForTimeout(300);
+ const data = envelope.data;
+ const display = data?.display;
+ const cameras = page.getByRole("combobox", { name: "Scene camera" });
+ if (await cameras.count()) {
+ await cameras.selectOption("Hero");
+ await page.waitForTimeout(300);
+ }
+ records.push({
+ product: "cadmata",
+ name,
+ responseStatus: response.status(),
+ diagnostics: envelope.diagnostics,
+ definitions: display?.definitions?.length ?? data?.definitions?.length,
+ occurrences: display?.occurrences?.length ?? data?.occurrences?.length,
+ qualifiedFields: display?.definitions?.filter(
+ (d) => d.cir?.qualification === "cir-qualified",
+ ).length,
+ materials: display?.occurrences?.filter((o) => o.material).length,
+ translucentMaterials: display?.occurrences?.filter(
+ (o) => o.material?.opacity < 1,
+ ).length,
+ cameras: display?.cameras?.length,
+ fallbacks: [
+ ...new Set(display?.definitions?.map((d) => d.fallbackReason) ?? []),
+ ],
+ packetKeys: data ? Object.keys(data) : [],
+ definitionKeys: data?.definitions?.[0]
+ ? Object.keys(data.definitions[0])
+ : [],
+ pipelines: await page.evaluate(
+ () => (window as any).projectionAuditPipelines,
+ ),
+ displayState: await page
+ .locator("[data-display-host=three-telos] canvas")
+ .evaluate((canvas: HTMLCanvasElement) =>
+ JSON.parse(canvas.dataset.telosDisplay ?? "{}"),
+ ),
+ text: (await page.locator("body").innerText()).slice(0, 10000),
+ });
+ await page.screenshot({ path: `${output}/cadmata-${name}.png` });
+ await page.close();
+ } finally {
+ host.kill();
+ }
+ }
+ const page = await pageFor("http://127.0.0.1:4173/local");
+ await page.waitForTimeout(2500);
+ for (const [name, source] of [
+ ["cylinder", "fixtures/Canonical/Basics/cylinder.firmament"],
+ ["house", "fixtures/Canonical/Scene/WarmModernHouse/house.firmament"],
+ ]) {
+ const files =
+ name === "house"
+ ? [
+ resolve(source),
+ ...(await readdir(dirname(resolve(source))))
+ .filter(
+ (file) =>
+ file.endsWith(".firmament") && file !== "house.firmament",
+ )
+ .map((file) => resolve(dirname(source), file)),
+ ]
+ : [resolve(source)];
+ await page.locator("input[type=file]").setInputFiles(files);
+ await page.waitForFunction(
+ (name) =>
+ document.body.innerText.includes(name + ".firmament") &&
+ (document.body.innerText.includes(
+ "Build failed. The last valid model",
+ ) ||
+ document.body.innerText.includes(
+ name === "house" ? "94 DEFS · 254 OCC" : "✓ 0 DIAGNOSTICS",
+ )),
+ name,
+ { timeout: 120000 },
+ );
+ await page.waitForTimeout(name === "house" ? 5000 : 3000);
+ const cameras = page.getByRole("combobox", { name: "Scene camera" });
+ if (await cameras.count()) {
+ await cameras.selectOption("Hero");
+ await page.waitForTimeout(300);
+ }
+ records.push({
+ product: "helios",
+ name,
+ pipelines: await page.evaluate(
+ () => (window as any).projectionAuditPipelines,
+ ),
+ displayState: await page
+ .locator("[data-display-host=three-telos] canvas")
+ .evaluate((canvas: HTMLCanvasElement) =>
+ JSON.parse(canvas.dataset.telosDisplay ?? "{}"),
+ ),
+ text: (await page.locator("body").innerText()).slice(-10000),
+ });
+ await page.screenshot({ path: `${output}/helios-${name}.png` });
+ }
+ await page.close();
+} finally {
+ await writeFile(`${output}/audit.json`, JSON.stringify(records, null, 2));
+ await browser.close();
+}
diff --git a/scripts/managed-wgsl-source-pin.txt b/scripts/managed-wgsl-source-pin.txt
new file mode 100644
index 00000000..053c124c
--- /dev/null
+++ b/scripts/managed-wgsl-source-pin.txt
@@ -0,0 +1 @@
+7329cf8ff04d504a062e8b5f62adcb9e12a1bbd13159c9c0af42b94576ba38d9
diff --git a/scripts/prepare-managed-wgsl.ps1 b/scripts/prepare-managed-wgsl.ps1
new file mode 100644
index 00000000..3cf7fb51
--- /dev/null
+++ b/scripts/prepare-managed-wgsl.ps1
@@ -0,0 +1,33 @@
+param([Parameter(Mandatory=$true)][string]$CopelandRoot)
+$ErrorActionPreference = 'Stop'
+$repo = Split-Path $PSScriptRoot -Parent
+$backend = Join-Path $CopelandRoot 'src/Copeland/Copeland.TS.Backend.Wgsl/Copeland.TS.Backend.Wgsl.csproj'
+$projects = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
+function Visit([string]$path) {
+ $path = [IO.Path]::GetFullPath($path)
+ if (-not $projects.Add($path)) { return }
+ [xml]$project = Get-Content -LiteralPath $path -Raw
+ foreach ($reference in $project.Project.ItemGroup.ProjectReference) {
+ if ($reference.Include) { Visit (Join-Path (Split-Path $path -Parent) $reference.Include) }
+ }
+}
+Visit $backend
+$files = @($projects | ForEach-Object {
+ Get-ChildItem -LiteralPath (Split-Path $_ -Parent) -Recurse -File |
+ Where-Object { $_.Extension -in '.cs','.csproj' -and $_.FullName -notmatch '[\\/](bin|obj)[\\/]' }
+}) + @(Get-ChildItem -LiteralPath $CopelandRoot -Filter 'Directory.*.props')
+$manifest = ($files | Sort-Object FullName -Unique | ForEach-Object {
+ [IO.Path]::GetRelativePath($CopelandRoot,$_.FullName).Replace('\','/') + ':' + (Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash
+}) -join "`n"
+$hash = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($manifest))).ToLowerInvariant()
+$version = '0.1.0-preview.1-a3.' + $hash.Substring(0,16)
+$pin = Join-Path $repo 'scripts/managed-wgsl-source-pin.txt'
+if ((Test-Path $pin) -and (Get-Content $pin -Raw).Trim() -ne $hash) { throw 'Managed WGSL producer source differs from the reviewed source pin.' }
+$output = Join-Path $repo 'artifacts/local/cir-artifact-binding/packages'
+New-Item -ItemType Directory -Force $output | Out-Null
+foreach ($project in $projects | Sort-Object) {
+ dotnet pack $project -c Release -o $output "-p:PackageVersion=$version" "-p:Version=$version" --nologo
+ if ($LASTEXITCODE -ne 0) { throw "Managed WGSL dependency pack failed: $project" }
+}
+Write-Output "Source pin: $hash"
+Write-Output "Package version: $version"
diff --git a/scripts/prepare-three-telos-cir.ps1 b/scripts/prepare-three-telos-cir.ps1
index 86085b18..a2bc6ddc 100644
--- a/scripts/prepare-three-telos-cir.ps1
+++ b/scripts/prepare-three-telos-cir.ps1
@@ -13,5 +13,5 @@ if (-not (Test-Path -LiteralPath $backend)) { throw 'CopelandRoot must contain t
</Project>
"@ | Set-Content -LiteralPath (Join-Path $output 'Qualification.csproj') -Encoding utf8
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'qualify-three-telos-cir.cs') -Destination (Join-Path $output 'Program.cs')
-dotnet run --project (Join-Path $output 'Qualification.csproj') -c Release -- $output (Join-Path $repo 'fixtures/three-telos/field-pass.v.ts')
+dotnet run --project (Join-Path $output 'Qualification.csproj') -c Release -- $output (Join-Path $repo 'Aetheris.Kernel.Firmament/Display/telos-field.v.ts')
if ($LASTEXITCODE -ne 0) { throw 'Direct CIR WGSL compilation failed.' }
diff --git a/scripts/qualify-three-telos-cir.cs b/scripts/qualify-three-telos-cir.cs
index 8a90e406..d1f2d514 100644
--- a/scripts/qualify-three-telos-cir.cs
+++ b/scripts/qualify-three-telos-cir.cs
@@ -18,7 +18,7 @@ File.WriteAllText(Path.Combine(args[0], "cylinder.json"), JsonSerializer.Seriali
shaderId = program.SemanticHash, wgsl = program.Code,
vertexEntryPoint = program.VertexEntryPoint, fragmentEntryPoint = program.FragmentEntryPoint,
bindings = new[] { new { group = 0, binding = 0, kind = "uniform", byteSize = program.Semantics.Material!.Size } },
- capabilities = new[] { "fragment-depth", "telos-field-rays/1", "rigid-occurrence" },
+ capabilities = new[] { "fragment-depth", "telos-field-rays/2", "rigid-occurrence" },
sourceIdentity = lowering.Program.StructuralHash,
compiler = WgslGraphicsBackend.CompatibilityVersion, program.SourceMappings,
}, new JsonSerializerOptions { WriteIndented = true }));
diff --git a/scripts/qualify-viewport-finish.mts b/scripts/qualify-viewport-finish.mts
new file mode 100644
index 00000000..2d450ed4
--- /dev/null
+++ b/scripts/qualify-viewport-finish.mts
@@ -0,0 +1,516 @@
+import { resolve } from "node:path";
+import { pathToFileURL } from "node:url";
+import { mkdir, writeFile } from "node:fs/promises";
+import { spawn } from "node:child_process";
+
+const { chromium } = await import(pathToFileURL(resolve(process.argv[2])).href);
+const phase = process.argv[3] ?? "before";
+const output = resolve("artifacts/local/viewport-finish-x0", phase);
+await mkdir(output, { recursive: true });
+const browser = await chromium.launch({
+ executablePath:
+ "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe",
+ headless: true,
+});
+const records: unknown[] = [];
+try {
+ for (const [product, url] of [
+ ["cadmata", process.argv[4] ?? "http://127.0.0.1:5173"],
+ ["helios", "http://127.0.0.1:4173/local"],
+ ]) {
+ const page = await browser.newPage({
+ viewport: { width: 1600, height: 1000 },
+ deviceScaleFactor: Number(process.argv[5] ?? 1),
+ });
+ const errors: string[] = [];
+ const missingAssets: string[] = [];
+ page.context().on("response", (response) => {
+ if (response.status() === 404) missingAssets.push(response.url());
+ });
+ page.on("pageerror", (error) => errors.push(String(error)));
+ page.on("console", (message) => {
+ if (message.type() === "error") errors.push(`${message.text()} (${message.location().url})`);
+ });
+ await page.addInitScript(() => {
+ const scope = window as any;
+ scope.viewportProbe = {
+ pipelines: [],
+ submits: 0,
+ encodeMs: [],
+ completionMs: [],
+ textures: new Set(),
+ buffers: new Set(),
+ };
+ const configure = GPUCanvasContext.prototype.configure;
+ GPUCanvasContext.prototype.configure = function (descriptor) {
+ scope.viewportProbe.device = descriptor.device;
+ const device = descriptor.device as any;
+ for (const [method, collection] of [
+ ["createTexture", "textures"],
+ ["createBuffer", "buffers"],
+ ]) {
+ const original = device[method].bind(device);
+ device[method] = (options: any) => {
+ const resource = original(options);
+ scope.viewportProbe[collection].add(resource);
+ const destroy = resource.destroy.bind(resource);
+ resource.destroy = () => {
+ scope.viewportProbe[collection].delete(resource);
+ destroy();
+ };
+ return resource;
+ };
+ }
+ const pipeline = device.createRenderPipeline.bind(device);
+ device.createRenderPipeline = (options: any) => {
+ const started = performance.now();
+ const result = pipeline(options);
+ scope.viewportProbe.pipelines.push({
+ samples: options.multisample?.count ?? 1,
+ label: options.label,
+ milliseconds: performance.now() - started,
+ });
+ return result;
+ };
+ const encoder = device.createCommandEncoder.bind(device);
+ device.createCommandEncoder = (options: any) => {
+ scope.viewportProbe.encoderStarted = performance.now();
+ return encoder(options);
+ };
+ const submit = device.queue.submit.bind(device.queue);
+ device.queue.submit = (commands: any) => {
+ const started = performance.now();
+ scope.viewportProbe.encodeMs.push(
+ started - scope.viewportProbe.encoderStarted,
+ );
+ scope.viewportProbe.submits++;
+ const result = submit(commands);
+ void device.queue
+ .onSubmittedWorkDone()
+ .then(() =>
+ scope.viewportProbe.completionMs.push(
+ performance.now() - started,
+ ),
+ )
+ .catch(() => {});
+ return result;
+ };
+ return configure.call(this, descriptor);
+ };
+ });
+ await page.goto(url);
+ await page
+ .locator("[data-display-host=three-telos] canvas")
+ .waitFor({ timeout: 120000 });
+ await page.waitForTimeout(3000);
+ await page.screenshot({ path: `${output}/${product}-initial.png` });
+ records.push({
+ product,
+ state: "initial",
+ alerts: await page.getByRole("alert").allTextContents(),
+ text: (await page.locator("body").innerText()).slice(0, 15000),
+ errors: [...errors],
+ missingAssets: [...missingAssets],
+ });
+ if (product === "cadmata") {
+ await page
+ .getByRole("tab", { name: "STEP 242 Viewer", exact: true })
+ .click();
+ await page
+ .locator("input[type=file]")
+ .setInputFiles(
+ resolve(
+ "docs/development/milestones/modules/sheetmetal/artifacts/ctc03-manufacturing-release/ctc03-manufacturing-ap242.step",
+ ),
+ );
+ await page
+ .getByRole("button", { name: "Import STEP 242", exact: true })
+ .click();
+ await page.waitForTimeout(5000);
+ await page.waitForTimeout(300);
+ await page.screenshot({ path: `${output}/cadmata-pmi.png` });
+ await page
+ .getByRole("combobox", { name: "Viewport theme", exact: true })
+ .selectOption("monument");
+ await page.waitForTimeout(200);
+ await page.screenshot({ path: `${output}/cadmata-light.png` });
+ await page
+ .getByRole("combobox", { name: "Viewport theme", exact: true })
+ .selectOption("atelier");
+ } else {
+ await page.waitForFunction(
+ () =>
+ document
+ .querySelector(".status-ready")
+ ?.textContent?.includes("READY"),
+ null,
+ { timeout: 120000 },
+ );
+ await page.screenshot({ path: `${output}/helios-part.png` });
+ }
+ records.push({
+ product,
+ state: "model",
+ alerts: await page.getByRole("alert").allTextContents(),
+ text: (await page.locator("body").innerText()).slice(0, 15000),
+ errors: [...errors],
+ missingAssets: [...missingAssets],
+ });
+ if (phase === "final") {
+ const canvas = page.locator("[data-display-host=three-telos] canvas");
+ if (product === "cadmata") {
+ await page
+ .getByRole("button", { name: "Inspect Datum A", exact: true })
+ .click();
+ if (
+ !(
+ await page
+ .getByRole("button", { name: "Inspect Datum A", exact: true })
+ .getAttribute("class")
+ )?.includes("is-selected")
+ )
+ throw new Error("PMI selection lost");
+ } else {
+ await page.getByRole("button", { name: "TOP", exact: true }).click();
+ await page.waitForTimeout(150);
+ const bounds = (await canvas.boundingBox())!;
+ await canvas.click({
+ position: { x: bounds.width * 0.65, y: bounds.height * 0.45 },
+ });
+ await page.waitForTimeout(150);
+ const selection = await page.locator(".status-selection").innerText();
+ if (!selection.includes("face:"))
+ throw new Error("engineering face selection missing: " + selection);
+ records.push({ product, state: "selection", selector: selection });
+ }
+ await page.screenshot({ path: `${output}/${product}-selected.png` });
+ const before = await canvas.screenshot();
+ const rect = (await canvas.boundingBox())!;
+ await page.mouse.move(
+ rect.x + rect.width * 0.7,
+ rect.y + rect.height * 0.45,
+ );
+ await page.mouse.down();
+ await page.mouse.move(
+ rect.x + rect.width * 0.7 + 75,
+ rect.y + rect.height * 0.45 + 25,
+ { steps: 12 },
+ );
+ await page.mouse.up();
+ await page.waitForTimeout(200);
+ if (before.equals(await canvas.screenshot()))
+ throw new Error(`${product} orbit did not redraw`);
+ await page.mouse.move(0, 0);
+ await page.setViewportSize({ width: 1150, height: 850 });
+ await page.waitForTimeout(200);
+ const sizes = await canvas.evaluate((element: HTMLCanvasElement) => ({
+ width: element.width,
+ height: element.height,
+ cssWidth: element.clientWidth,
+ cssHeight: element.clientHeight,
+ dpr: devicePixelRatio,
+ }));
+ if (
+ Math.abs(sizes.width - sizes.cssWidth * sizes.dpr) > 2 ||
+ Math.abs(sizes.height - sizes.cssHeight * sizes.dpr) > 2
+ )
+ throw new Error("stale resize target");
+ await page.screenshot({ path: `${output}/${product}-resize.png` });
+ const session = await page.context().newCDPSession(page);
+ await session.send("Emulation.setDeviceMetricsOverride", {
+ width: 1150,
+ height: 850,
+ deviceScaleFactor: 3,
+ mobile: false,
+ });
+ await page.waitForTimeout(750);
+ const liveDpr = await canvas.evaluate((element: HTMLCanvasElement) => ({
+ width: element.width,
+ height: element.height,
+ cssWidth: element.clientWidth,
+ cssHeight: element.clientHeight,
+ dpr: devicePixelRatio,
+ }));
+ if (
+ liveDpr.dpr !== 3 ||
+ Math.abs(liveDpr.width - liveDpr.cssWidth * 3) > 2
+ )
+ throw new Error(
+ "DPR change did not resize render target: " + JSON.stringify(liveDpr),
+ );
+ const resources = () =>
+ page.evaluate(() => {
+ const probe = (window as any).viewportProbe;
+ const summarize = (values: number[]) => ({
+ count: values.length,
+ mean: values.reduce((sum, value) => sum + value, 0) / values.length,
+ maximum: Math.max(...values),
+ });
+ return {
+ buffers: probe.buffers.size,
+ textures: probe.textures.size,
+ submits: probe.submits,
+ encodeMs: summarize(probe.encodeMs),
+ completionMs: summarize(probe.completionMs),
+ samples: [
+ ...new Set(probe.pipelines.map((item: any) => item.samples)),
+ ],
+ };
+ });
+ const steadyBefore = await resources();
+ await page.waitForTimeout(500);
+ const steadyAfter = await resources();
+ if (steadyAfter.submits !== steadyBefore.submits)
+ throw new Error(`${product} continues rendering while idle`);
+ const cameraSteps = await page.evaluate(async () => {
+ const element = document.querySelector(
+ "[data-display-host=three-telos] canvas",
+ )!;
+ const device = (window as any).viewportProbe.device;
+ const times: number[] = [];
+ for (let index = 0; index < 20; index++) {
+ const started = performance.now();
+ element.dispatchEvent(
+ new WheelEvent("wheel", {
+ deltaY: index % 2 ? -5 : 5,
+ cancelable: true,
+ }),
+ );
+ await new Promise(requestAnimationFrame);
+ await device.queue.onSubmittedWorkDone();
+ times.push(performance.now() - started);
+ }
+ return {
+ count: times.length,
+ mean: times.reduce((sum, value) => sum + value, 0) / times.length,
+ maximum: Math.max(...times),
+ };
+ });
+ await page.evaluate(() => (window as any).viewportProbe.device.destroy());
+ await page
+ .getByRole("button", { name: "Restart viewport", exact: true })
+ .waitFor();
+ await page.screenshot({ path: `${output}/${product}-device-loss.png` });
+ await page
+ .getByRole("button", { name: "Restart viewport", exact: true })
+ .click();
+ await page.waitForTimeout(1000);
+ if (
+ await page
+ .getByRole("button", { name: "Restart viewport", exact: true })
+ .count()
+ )
+ throw new Error("viewport recovery failed");
+ await page.screenshot({ path: `${output}/${product}-recovered.png` });
+ records.push({
+ product,
+ state: "lifecycle",
+ sizes,
+ liveDpr,
+ steadyBefore,
+ steadyAfter,
+ cameraSteps,
+ recovered: await resources(),
+ });
+ if (product === "helios") {
+ await page.locator("input[type=file]").setInputFiles({
+ name: "invalid.firmament",
+ mimeType: "text/plain",
+ buffer: Buffer.from(
+ "Model Broken { Units: mm Box Body { Size: [invalid] } }",
+ ),
+ });
+ await page.waitForTimeout(2500);
+ const text = await page.locator("body").innerText();
+ if (
+ !text.includes("DISPLAY REV 0") ||
+ !text.includes("MODEL OUT OF DATE")
+ )
+ throw new Error("last valid model was lost");
+ await page.screenshot({ path: `${output}/helios-last-valid.png` });
+ records.push({
+ product,
+ state: "failed-build",
+ text: text.slice(-5000),
+ });
+ await page
+ .locator("input[type=file]")
+ .setInputFiles(
+ resolve("fixtures/Canonical/Scene/WarmModernHouse/house.firmament"),
+ );
+ await page.waitForTimeout(2500);
+ records.push({
+ product,
+ state: "house-refusal",
+ text: (await page.locator("body").innerText()).slice(-7000),
+ });
+ await page.screenshot({ path: `${output}/helios-house-refusal.png` });
+ } else {
+ await page.setViewportSize({ width: 1600, height: 1000 });
+ await session.send("Emulation.setDeviceMetricsOverride", {
+ width: 1600,
+ height: 1000,
+ deviceScaleFactor: 2,
+ mobile: false,
+ });
+ await page.waitForTimeout(750);
+ await page
+ .locator("input[type=file]")
+ .setInputFiles(
+ resolve("artifacts/local/viewport-finish-x0/threaded.step"),
+ );
+ const imported = page.waitForResponse(
+ (response) => response.url().endsWith("/import/step"),
+ { timeout: 120000 },
+ );
+ const prepared = page
+ .waitForResponse(
+ (response) => response.url().endsWith("/display/prepare"),
+ { timeout: 120000 },
+ )
+ .catch(() => null);
+ await page
+ .getByRole("button", { name: "Import STEP 242", exact: true })
+ .click();
+ const importResponse = await imported;
+ const importedFileName = importResponse.request().postDataJSON().name;
+ if (importedFileName !== "threaded.step")
+ throw new Error("Stale STEP selection imported");
+ const importStatus = importResponse.status();
+ const display = importStatus === 200 ? await prepared : null;
+ const displaySuccess = display?.status() === 200;
+ if (displaySuccess) {
+ await page.waitForFunction(
+ () =>
+ document
+ .querySelector(".telos-viewport")
+ ?.getAttribute("aria-busy") === "false",
+ null,
+ { timeout: 120000 },
+ );
+ const bounds = await page
+ .locator(".telos-viewport canvas")
+ .boundingBox();
+ if (bounds) {
+ await page.mouse.move(
+ bounds.x + bounds.width / 2,
+ bounds.y + bounds.height / 2,
+ );
+ await page.mouse.wheel(0, -180);
+ }
+ }
+ await page.waitForTimeout(500);
+ await page.screenshot({
+ path: `${output}/${displaySuccess ? "mechanical-closeup" : "thread-refusal"}.png`,
+ });
+ records.push({
+ product,
+ state: "threaded",
+ alerts: await page.getByRole("alert").allTextContents(),
+ resources: await resources(),
+ importStatus,
+ importedFileName,
+ displaySuccess,
+ text: (await page.locator("body").innerText()).slice(-7000),
+ });
+ }
+ }
+ await page.close();
+ }
+ if (phase === "final") {
+ for (const [product, url] of [
+ ["cadmata", process.argv[4] ?? "http://127.0.0.1:5173"],
+ ["helios", "http://127.0.0.1:4173/local"],
+ ]) {
+ const page = await browser.newPage({
+ viewport: { width: 1600, height: 1000 },
+ });
+ await page.addInitScript(() => {
+ Object.defineProperty(navigator, "gpu", { value: undefined });
+ });
+ await page.goto(url);
+ await page
+ .locator("[data-display-host=transitional-webgl] canvas")
+ .waitFor({ timeout: 30000 });
+ if (await page.locator("[data-display-host=three-telos]").count())
+ throw new Error("dual renderer fallback");
+ await page.screenshot({ path: `${output}/${product}-fallback.png` });
+ records.push({
+ product,
+ state: "fallback",
+ fallbackCanvasCount: await page
+ .locator("[data-display-host=transitional-webgl] canvas")
+ .count(),
+ });
+ await page.close();
+ }
+ for (const [name, source] of [
+ [
+ "guitar",
+ "fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm",
+ ],
+ [
+ "robot",
+ "fixtures/Canonical/AssemblyInterfaces/IndustrialAtlas/atlas-industrial.firmament",
+ ],
+ ]) {
+ // Startup claims are intentionally one-shot. Each capture owns a fresh real product process.
+ const host = spawn(
+ "dotnet",
+ [
+ resolve("Aetheris.Server/bin/Release/net10.0/Cadmata.dll"),
+ resolve(source),
+ "--urls",
+ "http://127.0.0.1:0",
+ "--no-browser",
+ ],
+ {
+ windowsHide: true,
+ env: { ...process.env, ASPNETCORE_ENVIRONMENT: "Development" },
+ },
+ );
+ try {
+ const url = await new Promise<string>((done, reject) => {
+ const timeout = setTimeout(
+ () => reject(new Error("Cadmata startup timeout")),
+ 20000,
+ );
+ host.on("error", reject);
+ let output = "";
+ host.stdout.on("data", (chunk) => {
+ output += String(chunk);
+ const match = output.match(/Cadmata ready: (http:\/\/[^\s]+)/);
+ if (match) {
+ clearTimeout(timeout);
+ done(match[1]);
+ }
+ });
+ });
+ const page = await browser.newPage({
+ viewport: { width: 1600, height: 1000 },
+ deviceScaleFactor: 2,
+ });
+ const started = performance.now();
+ await page.goto(url);
+ await page
+ .getByText("Product tree", { exact: true })
+ .waitFor({ timeout: 120000 });
+ await page.waitForTimeout(500);
+ await page.screenshot({ path: `${output}/${name}.png` });
+ const alerts = await page.getByRole("alert").allTextContents();
+ records.push({
+ product: "cadmata",
+ state: name,
+ firstDisplayMs: performance.now() - started,
+ alerts,
+ });
+ await page.close();
+ } finally {
+ host.kill();
+ }
+ }
+ }
+} finally {
+ await browser.close();
+ await writeFile(`${output}/audit.json`, JSON.stringify(records, null, 2));
+}