Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Improve static factory scene authoring and presentation

Yuechen Li502a2c811d4e
diff --git a/Aetheris.Web.Runtime/telos/README.md b/Aetheris.Web.Runtime/telos/README.md
index 15211843..450c2437 100644
--- a/Aetheris.Web.Runtime/telos/README.md
+++ b/Aetheris.Web.Runtime/telos/README.md
@@ -4,4 +4,10 @@ Three Telos is an engineering display layer that uses Three.js where Three.js is
Reuse upstream data structures. Own downstream GPU behavior.
-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` in the repository for qualification and migration limits.
+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.
+
+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.
+
+`overlayId` carries product-owned pick identity. DOM buttons receive their own DOM events; GPU picking prioritizes always-on-top authoring meshes, dynamic overlay leaders, construction lines/surfaces and then model geometry. Hidden or depth-occluded overlays do not steal geometry picks. This supplies graphics interaction identity, not CAD selector authority.
diff --git a/Aetheris.Web.Runtime/telos/src/contracts.ts b/Aetheris.Web.Runtime/telos/src/contracts.ts
index 99ed5c03..941cfb69 100644
--- a/Aetheris.Web.Runtime/telos/src/contracts.ts
+++ b/Aetheris.Web.Runtime/telos/src/contracts.ts
@@ -1,12 +1,15 @@
export type Vec3 = readonly [number, number, number];
export type Pixel = readonly [number, number];
export type NumericArray = ArrayLike<number>;
+/** Coordinates are world space; line thickness and projected DOM placements use CSS pixels. */
+export type TelosDepthMode = "depth-tested" | "depth-biased" | "always-on-top";
export interface TelosIdentity {
occurrenceId: string;
bodyId?: string;
definitionId?: string;
faceId?: string | number;
edgeId?: string | number;
+ overlayId?: string;
}
export interface TelosMaterial {
baseColor: readonly number[];
@@ -35,6 +38,8 @@ export interface TelosMesh {
hovered?: boolean;
overlay?: boolean;
visible?: boolean;
+ depthMode?: TelosDepthMode;
+ unlit?: boolean;
}
export interface TelosLine {
id: string;
@@ -46,6 +51,7 @@ export interface TelosLine {
selected?: boolean;
overlay?: boolean;
visible?: boolean;
+ depthMode?: TelosDepthMode;
}
export interface TelosShaderArtifact {
shaderId: string;
diff --git a/Aetheris.Web.Runtime/telos/src/host.ts b/Aetheris.Web.Runtime/telos/src/host.ts
index 578df046..b2c965fb 100644
--- a/Aetheris.Web.Runtime/telos/src/host.ts
+++ b/Aetheris.Web.Runtime/telos/src/host.ts
@@ -29,6 +29,12 @@ type Draw<T> = {
geometry?: GeometryBuffers;
count: number;
};
+const meshKey = (item: TelosMesh) =>
+ JSON.stringify([
+ item.identity.occurrenceId,
+ item.identity.overlayId,
+ item.definition.id,
+ ]);
const emptyScene = (): TelosScene => ({ meshes: [], lines: [], fields: [] });
const matrix = (values?: NumericArray) =>
values ? new Matrix4().fromArray(values) : new Matrix4();
@@ -45,6 +51,65 @@ export class TelosHost {
private meshes: Draw<TelosMesh>[] = [];
private lines: Draw<TelosLine>[] = [];
private fields: Draw<TelosField>[] = [];
+ private dynamicLines = new Map<string, Draw<TelosLine>>();
+ private frameListeners = new Set<() => void>();
+ /** Called with current camera matrices before drawing. No separate projection loop. */
+ beforeFrame(listener: () => void) {
+ this.frameListeners.add(listener);
+ this.invalidate();
+ return () => {
+ this.frameListeners.delete(listener);
+ };
+ }
+ /** Retained world-space lines, intended for projected leaders and interactive previews.
+ * A stable ID and segment count retain both vertex and uniform buffers. */
+ setDynamicLines(items: readonly TelosLine[]) {
+ const started = performance.now();
+ const used = new Set<string>();
+ for (const item of items) {
+ if (used.has(item.id))
+ throw new Error("telos-dynamic-line-identity-collision: " + item.id);
+ used.add(item.id);
+ const count = Math.max(0, item.points.length / 3 - 1);
+ if (!Number.isInteger(count))
+ throw new Error("telos-line-points-invalid");
+ const pipeline = telosPipeline(
+ this.owner,
+ "overlay-line",
+ undefined,
+ item.depthMode,
+ );
+ let draw = this.dynamicLines.get(item.id);
+ if (draw && (draw.count !== count || draw.pipeline !== pipeline)) {
+ this.owner.resources.release(draw.uniform);
+ this.owner.resources.release(draw.vertices!);
+ this.dynamicLines.delete(item.id);
+ draw = undefined;
+ }
+ if (!count) continue;
+ if (!draw) {
+ draw = this.draw(item, pipeline, 160, count);
+ draw.vertices = this.owner.resources.buffer(
+ new Float32Array(count * 6),
+ GPUBufferUsage.VERTEX,
+ );
+ this.dynamicLines.set(item.id, draw);
+ }
+ draw.item = item;
+ const points = new Float32Array(count * 6);
+ for (let i = 0; i < count; i++)
+ for (let j = 0; j < 6; j++) points[i * 6 + j] = item.points[i * 3 + j];
+ this.owner.device.queue.writeBuffer(draw.vertices!, 0, points);
+ }
+ for (const [id, draw] of this.dynamicLines)
+ if (!used.has(id)) {
+ this.owner.resources.release(draw.uniform);
+ this.owner.resources.release(draw.vertices!);
+ this.dynamicLines.delete(id);
+ }
+ this.picker.dynamicLines = items;
+ this.metrics.dynamicLineUpdateMs = performance.now() - started;
+ }
private gridDraw?: Draw<TelosLine>;
private gridKey = "";
private raf = 0;
@@ -58,6 +123,8 @@ export class TelosHost {
frameMs: 0,
frames: 0,
draws: 0,
+ overlayUpdateMs: 0,
+ dynamicLineUpdateMs: 0,
};
static async create(
canvas: HTMLCanvasElement,
@@ -124,7 +191,23 @@ export class TelosHost {
return { item, pipeline, uniform, binding, count };
}
setScene(scene: TelosScene) {
- this.releaseDraws();
+ const previous = [...this.meshes, ...this.lines, ...this.fields];
+ const retained = new Set<
+ Draw<TelosMesh> | Draw<TelosLine> | Draw<TelosField>
+ >();
+ const oldMeshes = new Map(
+ this.meshes.map((draw) => [meshKey(draw.item), draw]),
+ );
+ const oldLines = new Map(this.lines.map((draw) => [draw.item.id, draw]));
+ const oldFields = new Map(
+ this.fields.map((draw) => [
+ draw.item.identity.occurrenceId + ":" + draw.item.artifact.shaderId,
+ draw,
+ ]),
+ );
+ this.meshes = [];
+ this.lines = [];
+ this.fields = [];
this.scene = scene;
const resources = this.owner.resources,
used = new Set<string>();
@@ -140,7 +223,10 @@ export class TelosHost {
geometry.definition.indices !== definition.indices ||
geometry.definition.normals !== definition.normals)
) {
- if (repeated) throw new Error('telos-definition-identity-collision: ' + definition.id);
+ if (repeated)
+ throw new Error(
+ "telos-definition-identity-collision: " + definition.id,
+ );
this.releaseGeometry(geometry);
this.geometry.delete(definition.id);
geometry = undefined;
@@ -164,12 +250,21 @@ export class TelosHost {
};
this.geometry.set(definition.id, geometry);
}
- const draw = this.draw(
- item,
- telosPipeline(this.owner, item.overlay ? "overlay-mesh" : "mesh"),
- 224,
- geometry.count,
+ const pipeline = telosPipeline(
+ this.owner,
+ item.overlay ? "overlay-mesh" : "mesh",
+ undefined,
+ item.depthMode,
);
+ const old = oldMeshes.get(meshKey(item));
+ const draw =
+ old?.pipeline === pipeline
+ ? old
+ : this.draw(item, pipeline, 224, geometry.count);
+ oldMeshes.delete(meshKey(item));
+ draw.item = item;
+ draw.count = geometry.count;
+ retained.add(draw);
draw.geometry = geometry;
this.meshes.push(draw);
}
@@ -185,16 +280,32 @@ export class TelosHost {
const segments: number[] = [];
for (let i = 3; i < item.points.length; i += 3)
for (let j = i - 3; j < i + 3; j++) segments.push(item.points[j]);
- const draw = this.draw(
- item,
- telosPipeline(this.owner, item.overlay ? "overlay-line" : "line"),
- 160,
- segments.length / 6,
- );
- draw.vertices = resources.buffer(
- new Float32Array(segments),
- GPUBufferUsage.VERTEX,
+ const pipeline = telosPipeline(
+ this.owner,
+ item.overlay ? "overlay-line" : "line",
+ undefined,
+ item.depthMode,
);
+ const old = oldLines.get(item.id);
+ oldLines.delete(item.id);
+ const reusable =
+ old?.pipeline === pipeline && old.count === segments.length / 6;
+ const draw = reusable
+ ? old
+ : this.draw(item, pipeline, 160, segments.length / 6);
+ if (!reusable)
+ draw.vertices = resources.buffer(
+ new Float32Array(segments),
+ GPUBufferUsage.VERTEX,
+ );
+ else if (old.item.points !== item.points)
+ this.owner.device.queue.writeBuffer(
+ draw.vertices!,
+ 0,
+ new Float32Array(segments),
+ );
+ draw.item = item;
+ retained.add(draw);
this.lines.push(draw);
}
this.metrics.lineUploadMs = performance.now() - lineStart;
@@ -222,25 +333,34 @@ export class TelosHost {
Math.abs(axes[1].dot(axes[2])) > 1e-6
)
throw new Error("telos-field-transform-not-rigid");
- const draw = this.draw(
- item,
- telosPipeline(this.owner, "mesh", item.artifact),
- 32,
- 6,
- );
- draw.vertices = resources.buffer(
- new Float32Array(108),
- GPUBufferUsage.VERTEX,
+ const pipeline = telosPipeline(this.owner, "mesh", item.artifact);
+ const old = oldFields.get(
+ item.identity.occurrenceId + ":" + item.artifact.shaderId,
);
+ const draw =
+ old?.pipeline === pipeline ? old : this.draw(item, pipeline, 32, 6);
+ if (draw !== old)
+ draw.vertices = resources.buffer(
+ new Float32Array(108),
+ GPUBufferUsage.VERTEX,
+ );
+ draw.item = item;
+ retained.add(draw);
this.fields.push(draw);
}
this.metrics.fieldPipelineMs = performance.now() - fieldStart;
+ for (const draw of previous)
+ if (!retained.has(draw)) {
+ resources.release(draw.uniform);
+ if (draw.vertices) resources.release(draw.vertices);
+ }
this.picker.setScene(scene);
this.invalidate();
}
fit() {
const bounds = new Box3();
- for (const item of this.scene.meshes) {
+ const modelMeshes = this.scene.meshes.filter((item) => !item.overlay);
+ for (const item of modelMeshes.length ? modelMeshes : this.scene.meshes) {
const transform = matrix(item.transform),
p = item.definition.positions;
for (let i = 0; i < p.length; i += 3)
@@ -274,7 +394,10 @@ export class TelosHost {
: [...material.baseColor.slice(0, 3), material.opacity],
48,
);
- data.set([material.roughness, material.metallic, 0, 0], 52);
+ data.set(
+ [material.roughness, material.metallic, draw.item.unlit ? 1 : 0, 0],
+ 52,
+ );
this.owner.device.queue.writeBuffer(draw.uniform, 0, data);
}
private updateLine(draw: Draw<TelosLine>) {
@@ -294,7 +417,7 @@ export class TelosHost {
draw.item.selected
? Math.max(3, draw.item.widthPixels ?? 1)
: (draw.item.widthPixels ?? 1),
- 0,
+ draw.item.depthMode === "depth-tested" ? 0 : 0.000002,
],
36,
);
@@ -440,6 +563,9 @@ export class TelosHost {
this.raf = 0;
const started = performance.now();
this.camera.update();
+ const overlayStart = performance.now();
+ for (const listener of this.frameListeners) listener();
+ this.metrics.overlayUpdateMs = performance.now() - overlayStart;
this.updateGrid();
this.frame.begin(this.background);
this.metrics.draws = 0;
@@ -491,12 +617,17 @@ export class TelosHost {
pass = this.frame.pass("Overlay");
for (const draw of this.meshes.filter((draw) => draw.item.overlay))
drawMesh(pass, draw);
- for (const draw of this.lines.filter((draw) => draw.item.overlay)) {
+ for (const draw of [
+ ...this.lines.filter((draw) => draw.item.overlay),
+ ...this.dynamicLines.values(),
+ ]) {
+ if (draw.item.visible === false) continue;
this.updateLine(draw);
pass.setPipeline(draw.pipeline);
pass.setBindGroup(0, draw.binding);
pass.setVertexBuffer(0, draw.vertices!);
pass.draw(6, draw.count);
+ this.metrics.draws++;
}
pass.end();
this.frame.end();
@@ -554,6 +685,8 @@ export class TelosHost {
this.observer?.disconnect();
this.detach?.();
this.picker.dispose();
+ this.setDynamicLines([]);
+ this.frameListeners.clear();
this.releaseDraws();
this.geometry.clear();
this.frame.dispose();
diff --git a/Aetheris.Web.Runtime/telos/src/pick.ts b/Aetheris.Web.Runtime/telos/src/pick.ts
index 388e778a..f9f2b86d 100644
--- a/Aetheris.Web.Runtime/telos/src/pick.ts
+++ b/Aetheris.Web.Runtime/telos/src/pick.ts
@@ -25,6 +25,7 @@ export class TelosPick {
camera: TelosCamera;
proxies: Mesh[];
lines: readonly TelosLine[];
+ dynamicLines: readonly TelosLine[] = [];
raycaster: Raycaster;
constructor(camera: TelosCamera) {
this.camera = camera;
@@ -33,45 +34,97 @@ export class TelosPick {
this.raycaster = new Raycaster();
}
setScene(scene: TelosScene) {
- this.dispose();
+ const previous = new Map(
+ this.proxies.map((mesh) => [
+ JSON.stringify([
+ mesh.userData.item.identity.occurrenceId,
+ mesh.userData.item.identity.overlayId,
+ mesh.userData.definition.id,
+ ]),
+ mesh,
+ ]),
+ );
+ this.proxies = [];
this.lines = scene.lines ?? [];
for (const item of [
...(scene.meshes ?? []),
...(scene.fields ?? []).filter((field) => field.proxy),
]) {
const definition = "definition" in item ? item.definition : item.proxy!;
- const geometry = new BufferGeometry();
- geometry.setAttribute(
- "position",
- new BufferAttribute(Float32Array.from(definition.positions), 3),
- );
- geometry.setIndex(
- new BufferAttribute(Uint32Array.from(definition.indices), 1),
- );
- const mesh = new Mesh(
- geometry,
- new MeshBasicMaterial({ side: DoubleSide }),
- );
+ const key = JSON.stringify([
+ item.identity.occurrenceId,
+ item.identity.overlayId,
+ definition.id,
+ ]);
+ let mesh = previous.get(key);
+ if (
+ mesh &&
+ (mesh.userData.definition.positions !== definition.positions ||
+ mesh.userData.definition.indices !== definition.indices)
+ )
+ mesh = undefined;
+ if (!mesh) {
+ const geometry = new BufferGeometry();
+ geometry.setAttribute(
+ "position",
+ new BufferAttribute(Float32Array.from(definition.positions), 3),
+ );
+ geometry.setIndex(
+ new BufferAttribute(Uint32Array.from(definition.indices), 1),
+ );
+ mesh = new Mesh(geometry, new MeshBasicMaterial({ side: DoubleSide }));
+ } else previous.delete(key);
mesh.matrixAutoUpdate = false;
mesh.matrix.fromArray(item.transform ?? new Matrix4().elements);
mesh.updateMatrixWorld(true);
mesh.userData = { item, definition };
this.proxies.push(mesh);
}
+ for (const mesh of previous.values()) {
+ mesh.geometry.dispose();
+ if (!Array.isArray(mesh.material)) mesh.material.dispose();
+ }
}
pick(pixel: Pixel, mode = "face"): TelosHit | null {
const ray = this.camera.worldRay(pixel);
this.raycaster.ray.set(ray.origin, ray.direction);
- const closest = this.raycaster.intersectObjects(this.proxies, false)[0];
+ const intersections = this.raycaster.intersectObjects(
+ this.proxies.filter((mesh) => mesh.userData.item.visible !== false),
+ false,
+ );
+ // Explicit authoring surfaces take priority over model faces. Equal priority uses distance.
+ const nearestModel = intersections.find(
+ (hit) => !hit.object.userData.item.identity.overlayId,
+ );
+ const overlay = intersections.find(
+ (hit) =>
+ hit.object.userData.item.identity.overlayId &&
+ (hit.object.userData.item.depthMode === "always-on-top" ||
+ !nearestModel ||
+ hit.distance <= nearestModel.distance),
+ );
+ const closest = overlay ?? intersections[0];
const faceHit = closest ? this.hit(closest) : null;
- if (mode !== "edge") return faceHit;
+ if (overlay?.object.userData.item.depthMode === "always-on-top")
+ return faceHit;
let hit: TelosHit | null = null,
- distance = Infinity;
- for (const line of this.lines) {
+ distance = Infinity,
+ priority = -1;
+ for (const line of [...this.dynamicLines, ...this.lines]) {
+ if (
+ line.visible === false ||
+ (mode !== "edge" && !line.identity.overlayId)
+ )
+ continue;
const transform = new Matrix4().fromArray(
line.transform ?? new Matrix4().elements,
);
const points = line.points;
+ const linePriority = this.dynamicLines.includes(line)
+ ? 2
+ : line.identity.overlayId
+ ? 1
+ : 0;
for (let i = 3; i < points.length; i += 3) {
const a = new Vector3(
points[i - 3],
@@ -110,10 +163,14 @@ export class TelosPick {
Math.max(this.camera.span / this.camera.height, d * 0.001) * 3;
if (
pixels <= Math.max(4, (line.widthPixels ?? 1) / 2 + 2) &&
- d < distance &&
- (!closest || d <= closest.distance + tolerance)
+ (linePriority > priority ||
+ (linePriority === priority && d < distance)) &&
+ (line.depthMode === "always-on-top" ||
+ !closest ||
+ d <= closest.distance + tolerance)
) {
distance = d;
+ priority = linePriority;
hit = {
...line.identity,
worldPosition: onSegment.toArray(),
@@ -123,7 +180,7 @@ export class TelosPick {
}
}
}
- return hit;
+ return hit ?? (mode === "edge" ? null : faceHit);
}
hit(hit: Intersection): TelosHit {
const { item, definition } = hit.object.userData as {
diff --git a/Aetheris.Web.Runtime/telos/src/pipelines.ts b/Aetheris.Web.Runtime/telos/src/pipelines.ts
index cca8d634..474dc893 100644
--- a/Aetheris.Web.Runtime/telos/src/pipelines.ts
+++ b/Aetheris.Web.Runtime/telos/src/pipelines.ts
@@ -1,5 +1,5 @@
import type { TelosDevice } from "./device.js";
-import type { TelosField } from "./contracts.js";
+import type { TelosField, TelosDepthMode } from "./contracts.js";
import { meshShader, lineShader } from "./shaders.js";
const vertexLayout: GPUVertexBufferLayout = {
arrayStride: 12,
@@ -11,11 +11,30 @@ export function telosPipeline(
owner: TelosDevice,
kind: "mesh" | "line" | "overlay-mesh" | "overlay-line",
artifact?: TelosField["artifact"],
+ depthMode?: TelosDepthMode,
) {
const format = owner.format,
resources = owner.resources;
- const id = artifact?.shaderId ?? "telos-" + kind + "/1";
- const key = JSON.stringify([id, kind, format, "depth32float", 1, artifact?.vertexEntryPoint ?? 'vertex', artifact?.fragmentEntryPoint ?? 'fragment']);
+ const resolvedDepth =
+ depthMode ??
+ (kind.startsWith("overlay")
+ ? "always-on-top"
+ : kind.includes("line")
+ ? "depth-biased"
+ : "depth-tested");
+ const id =
+ artifact?.shaderId ??
+ "telos-" + (kind.includes("mesh") ? "mesh" : "line") + "/1";
+ const key = JSON.stringify([
+ id,
+ kind,
+ resolvedDepth,
+ format,
+ "depth32float",
+ 1,
+ artifact?.vertexEntryPoint ?? "vertex",
+ artifact?.fragmentEntryPoint ?? "fragment",
+ ]);
const shader = resources.module(
id,
artifact?.wgsl ?? (kind.includes("mesh") ? meshShader : lineShader),
@@ -90,11 +109,14 @@ export function telosPipeline(
format: "depth32float",
depthWriteEnabled:
!kind.includes("line") && !kind.startsWith("overlay"),
- depthCompare: kind.startsWith("overlay")
- ? "always"
- : kind.includes("line")
- ? "less-equal"
- : "less",
+ depthBias:
+ resolvedDepth === "depth-biased" && kind.includes("mesh") ? -1 : 0,
+ depthCompare:
+ resolvedDepth === "always-on-top"
+ ? "always"
+ : kind.includes("line")
+ ? "less-equal"
+ : "less",
},
}),
);
diff --git a/Aetheris.Web.Runtime/telos/src/shaders.ts b/Aetheris.Web.Runtime/telos/src/shaders.ts
index cdda0e69..2856d2f5 100644
--- a/Aetheris.Web.Runtime/telos/src/shaders.ts
+++ b/Aetheris.Web.Runtime/telos/src/shaders.ts
@@ -11,7 +11,7 @@ struct Output { @builtin(position) position: vec4<f32>, @location(0) normal: vec
let diffuse = 0.28 + 0.72 * abs(dot(n, light));
let roughness = clamp(state.parameters.x, 0.04, 1.0); let metallic = clamp(state.parameters.y, 0.0, 1.0);
let specular = pow(abs(dot(n, normalize(light + vec3<f32>(0,0,1)))), mix(64.0, 2.0, roughness)) * (0.05 + metallic * 0.2);
- let linear = state.color.rgb * diffuse + vec3<f32>(specular);
+ let linear = select(state.color.rgb * diffuse + vec3<f32>(specular), state.color.rgb, state.parameters.z > 0.5);
return vec4(pow(max(linear, vec3<f32>(0)), vec3<f32>(1.0 / 2.2)), state.color.a);
}`;
@@ -30,7 +30,7 @@ struct State { vp: mat4x4<f32>, model: mat4x4<f32>, color: vec4<f32>, viewport:
let perpendicular = vec2(-direction.y, direction.x);
let corners = array<vec2<f32>,6>(vec2(0,-1),vec2(1,-1),vec2(0,1),vec2(0,1),vec2(1,-1),vec2(1,1));
let corner = corners[vertex]; var p = mix(a,b,corner.x);
- p = vec4(p.xy + perpendicular * corner.y * state.viewport.z / state.viewport.xy * p.w, p.z - 0.000002 * p.w, p.w);
+ p = vec4(p.xy + perpendicular * corner.y * state.viewport.z / state.viewport.xy * p.w, p.z - state.viewport.w * p.w, p.w);
return p;
}
@fragment fn fragment() -> @location(0) vec4<f32> { return state.color; }
diff --git a/Aetheris.Web.Runtime/telos/tests/overlay.test.ts b/Aetheris.Web.Runtime/telos/tests/overlay.test.ts
new file mode 100644
index 00000000..123849b2
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/tests/overlay.test.ts
@@ -0,0 +1,95 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readFileSync, readdirSync } from "node:fs";
+import {
+ TelosCamera,
+ TelosPick,
+ materialFromAppearance,
+} from "../dist/index.js";
+import type { TelosMesh, TelosLine } from "../dist/index.js";
+const camera = () => {
+ const camera = new TelosCamera();
+ camera.resize(800, 600);
+ camera.mode = "orthographic";
+ camera.position.set(0, 0, 5);
+ camera.target.set(0, 0, 0);
+ camera.span = 4;
+ camera.update();
+ return camera;
+};
+const definition = {
+ id: "plane",
+ positions: [-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0],
+ normals: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1],
+ indices: [0, 1, 2, 2, 1, 3],
+};
+const mesh: TelosMesh = {
+ definition,
+ identity: { occurrenceId: "part", faceId: "face(+Z)" },
+ material: materialFromAppearance({ color: "#aaa" }),
+};
+test("normal Cadmata graphics imports are independent of the unsupported-browser renderer", () => {
+ const directory = new URL(
+ "../../../aetheris.client/src/viewer/",
+ import.meta.url,
+ );
+ for (const name of readdirSync(directory).filter((name) =>
+ /\.tsx?$/.test(name),
+ )) {
+ const source = readFileSync(new URL(name, directory), "utf8");
+ if (name.startsWith("Legacy") || name === "ThemeBackground.tsx") continue;
+ assert.doesNotMatch(
+ source,
+ /from ["']@react-three\/|WebGLRenderer|useThree\(|useFrame\(/,
+ name,
+ );
+ }
+ const wrapper = readFileSync(
+ new URL("AetherisViewport.tsx", directory),
+ "utf8",
+ );
+ assert.match(wrapper, /lazy\(/);
+ assert.doesNotMatch(wrapper, /props\.cadmataArtifact\s*\?(?!\?)/);
+});
+test("overlay priority, visibility, and engineering geometry identity", () => {
+ const pick = new TelosPick(camera());
+ const leader: TelosLine = {
+ id: "leader",
+ points: [-1, 0, -1, 1, 0, -1],
+ identity: { occurrenceId: "overlay", overlayId: "datum:A" },
+ depthMode: "always-on-top",
+ };
+ pick.setScene({ meshes: [mesh], lines: [], fields: [] });
+ assert.equal(pick.pick([400, 300])?.faceId, "face(+Z)");
+ pick.dynamicLines = [leader];
+ assert.equal(pick.pick([400, 300])?.overlayId, "datum:A");
+ pick.dynamicLines = [{ ...leader, visible: false }];
+ assert.equal(pick.pick([400, 300])?.faceId, "face(+Z)");
+ pick.dynamicLines = [{ ...leader, depthMode: "depth-tested" }];
+ assert.equal(pick.pick([400, 300])?.faceId, "face(+Z)");
+ pick.dispose();
+});
+test("selection/filter updates retain CPU geometry; a rebuild replaces it and preserves stable face identity", () => {
+ const pick = new TelosPick(camera());
+ pick.setScene({ meshes: [mesh], lines: [], fields: [] });
+ const proxy = pick.proxies[0];
+ pick.setScene({
+ meshes: [{ ...mesh, selected: true }],
+ lines: [],
+ fields: [],
+ });
+ assert.equal(pick.proxies[0], proxy);
+ pick.setScene({
+ meshes: [
+ {
+ ...mesh,
+ definition: { ...definition, positions: [...definition.positions] },
+ },
+ ],
+ lines: [],
+ fields: [],
+ });
+ assert.notEqual(pick.proxies[0], proxy);
+ assert.equal(pick.pick([400, 300])?.faceId, "face(+Z)");
+ pick.dispose();
+});
diff --git a/README.md b/README.md
index 30945b8b..51d0f089 100644
--- a/README.md
+++ b/README.md
@@ -27,7 +27,7 @@ Automated design-for-manufacturing (DFM) checks, finite element analysis (FEA),
## Architecture
-[Three Telos](Aetheris.Web.Runtime/telos/README.md) is the shared engineering display layer. It uses Three.js where Three.js is useful and replaces it where engineering visualization requires stronger guarantees. Reuse upstream data structures; own downstream GPU behavior. See the [X0 qualification and migration limits](docs/release/THREE-TELOS-X0.md).
+[Three Telos](Aetheris.Web.Runtime/telos/README.md) is the shared engineering display layer. It uses Three.js where Three.js is useful and replaces it where engineering visualization requires stronger guarantees. Reuse upstream data structures; own downstream GPU behavior. See the [X0 substrate qualification](docs/release/THREE-TELOS-X0.md) and [X1 Cadmata authoring/PMI migration](docs/release/THREE-TELOS-X1.md).
Aetheris' native representation format is **Firmament**, a domain specific programming language designed specifically for 3D modeling applications. Unlike other CAD software, Aetheris is AI-native and so designed to be **code-first**, enabling full headless usage from the CLI.
diff --git a/aetheris.client/src/App.tsx b/aetheris.client/src/App.tsx
index 5e349b9a..a89a1504 100644
--- a/aetheris.client/src/App.tsx
+++ b/aetheris.client/src/App.tsx
@@ -44,7 +44,7 @@ import {
STEP_UPLOAD_LIMIT_MB,
formatMegabytes,
} from "./config/stepUpload";
-import { DEFAULT_CADMATA_LAYERS, type CadmataLayerVisibility } from "./viewer/CadmataOverlay";
+import { DEFAULT_CADMATA_LAYERS, type CadmataLayerVisibility } from "./viewer/cadmataLayers";
import {
parseCadmataVisualizationArtifact,
resolveCadmataSelection,
@@ -58,7 +58,7 @@ import {
loadViewportThemePreference,
saveViewportThemePreference,
} from "./viewer/viewportThemePreference";
-import { DEFAULT_PMI_VISIBILITY, type PmiCategory, type PmiVisibility } from "./viewer/PmiAnnotationLayer";
+import { DEFAULT_PMI_VISIBILITY, type PmiCategory, type PmiVisibility } from "./viewer/pmiPresentation";
type RequestStatus = "idle" | "loading" | "success" | "error";
type BooleanOperationUi = "Union" | "Subtract" | "Intersect";
diff --git a/aetheris.client/src/__tests__/AetherisViewport.test.tsx b/aetheris.client/src/__tests__/AetherisViewport.test.tsx
index 3b97ef03..224d2b1d 100644
--- a/aetheris.client/src/__tests__/AetherisViewport.test.tsx
+++ b/aetheris.client/src/__tests__/AetherisViewport.test.tsx
@@ -79,7 +79,7 @@ describe("AetherisViewport", () => {
).not.toThrow();
});
- it("RendersWirePatchWithoutMeshArrays", () => {
+ it("RendersWirePatchWithoutMeshArrays", async () => {
const scene: DisplayScene = {
...baseScene,
renderables: [
@@ -95,10 +95,10 @@ describe("AetherisViewport", () => {
},
],
};
- const { getAllByTestId } = render(
+ const { findAllByTestId } = render(
<AetherisViewport displayScene={scene} showGrid={false} showAxisGuide={false} />,
);
- expect(getAllByTestId("line").length).toBeGreaterThan(0);
+ expect((await findAllByTestId("line")).length).toBeGreaterThan(0);
});
it("AcceptsDiagnosticOnlyFace", () => {
diff --git a/aetheris.client/src/__tests__/pmiPresentation.test.ts b/aetheris.client/src/__tests__/pmiPresentation.test.ts
index a594c892..107417d6 100644
--- a/aetheris.client/src/__tests__/pmiPresentation.test.ts
+++ b/aetheris.client/src/__tests__/pmiPresentation.test.ts
@@ -3,7 +3,7 @@ import {
DEFAULT_PMI_VISIBILITY,
layoutPmiCallouts,
semanticPmiItems,
-} from "../viewer/PmiAnnotationLayer";
+} from "../viewer/pmiPresentation";
import type { CadmataVisualizationArtifact } from "../viewer/conceptVisualization";
const artifact: CadmataVisualizationArtifact = {
diff --git a/aetheris.client/src/__tests__/telos-x1-witness.tsx b/aetheris.client/src/__tests__/telos-x1-witness.tsx
new file mode 100644
index 00000000..8a153179
--- /dev/null
+++ b/aetheris.client/src/__tests__/telos-x1-witness.tsx
@@ -0,0 +1,162 @@
+/* eslint-disable react-refresh/only-export-components -- real API/wrapper browser qualification entry. */
+import { useEffect, useState } from "react";
+import { createRoot } from "react-dom/client";
+import type { TelosHost } from "@aetheris/three-telos";
+import {
+ createDocument,
+ importStep,
+ prepareBodyDisplay,
+ loadCadmataFixture,
+ pickBody,
+} from "../api/aetherisApi";
+import { AetherisViewport } from "../viewer/AetherisViewport";
+import { DEFAULT_CADMATA_LAYERS } from "../viewer/cadmataLayers";
+import { DEFAULT_PMI_VISIBILITY } from "../viewer/pmiPresentation";
+import {
+ resolveCadmataSelection,
+ parseCadmataVisualizationArtifact,
+ type CadmataVisualizationArtifact,
+} from "../viewer/conceptVisualization";
+import { resolvePublishedBrepEntity } from "../viewer/semanticInspection";
+import { buildDisplaySceneData } from "../viewer/displaySceneBuilder";
+import type { DisplayScene } from "../viewer/displayRenderables";
+import "../App.css";
+import ctc03Source from "../../../docs/development/milestones/modules/sheetmetal/artifacts/ctc03-manufacturing-release/ctc03-manufacturing-ap242.step?raw";
+declare global {
+ interface Window {
+ cadmataX1?: {
+ host?: TelosHost;
+ artifact?: CadmataVisualizationArtifact;
+ selected?: string | null;
+ revision: number;
+ };
+ }
+}
+function Witness() {
+ const [model, setModel] = useState<{
+ scene: DisplayScene | null;
+ artifact: CadmataVisualizationArtifact;
+ documentId: string;
+ bodyId: string;
+ } | null>(null);
+ const [selected, setSelected] = useState<string | null>(null);
+ const [mode, setMode] = useState("ctc03");
+ const [revision, setRevision] = useState(0);
+ const [visibility, setVisibility] = useState(DEFAULT_PMI_VISIBILITY);
+ const [error, setError] = useState("");
+ const load = async (kind: string) => {
+ const document = await createDocument("Telos X1 qualification");
+ let artifact: CadmataVisualizationArtifact, bodyId: string;
+ if (kind === "ctc03") {
+ const source = ctc03Source;
+ const imported = await importStep(
+ document.documentId,
+ source,
+ "ctc03-manufacturing-ap242.step",
+ );
+ artifact = parseCadmataVisualizationArtifact(
+ imported.semanticPresentation,
+ );
+ bodyId = imported.occurrenceId;
+ } else {
+ const fixture = await loadCadmataFixture(
+ document.documentId,
+ kind === "authored-pmi"
+ ? "pmi-projected-hole-diameter"
+ : "construction-plane-positive-x",
+ );
+ artifact = parseCadmataVisualizationArtifact(fixture.visualization);
+ bodyId = fixture.bodyId;
+ }
+ const scene = buildDisplaySceneData(
+ await prepareBodyDisplay(document.documentId, bodyId),
+ ).displayScene;
+ setModel({ scene, artifact, documentId: document.documentId, bodyId });
+ setRevision((value) => value + 1);
+ };
+ useEffect(() => {
+ void Promise.resolve()
+ .then(() => load(mode))
+ .catch((reason) => setError(String(reason)));
+ }, [mode]);
+ useEffect(() => {
+ window.cadmataX1 = {
+ ...window.cadmataX1,
+ artifact: model?.artifact,
+ selected,
+ revision,
+ };
+ }, [model, selected, revision]);
+ const selection = model
+ ? resolveCadmataSelection(model.artifact, selected)
+ : null;
+ return (
+ <>
+ <button
+ onClick={() => setMode(mode === "ctc03" ? "construction" : "ctc03")}
+ >
+ Switch model
+ </button>
+ <button onClick={() => setMode("authored-pmi")}>Authored PMI</button>
+ <button
+ onClick={() =>
+ void load(mode).catch((reason) => setError(String(reason)))
+ }
+ >
+ Rebuild
+ </button>
+ <button
+ onClick={() =>
+ setVisibility({
+ datums: true,
+ dimensions: true,
+ geometricTolerances: true,
+ engineeringAnnotations: true,
+ })
+ }
+ >
+ All PMI
+ </button>
+ <button onClick={() => setVisibility(DEFAULT_PMI_VISIBILITY)}>
+ Default PMI
+ </button>
+ <div style={{ width: 1100, height: 800 }}>
+ <AetherisViewport
+ displayScene={model?.scene}
+ cadmataArtifact={model?.artifact}
+ cadmataLayers={DEFAULT_CADMATA_LAYERS}
+ selectedCadmataIds={selection?.entityIds}
+ highlightedFaceIds={selection?.faceIds}
+ highlightedEdgeIds={selection?.edgeIds}
+ pmiVisibility={visibility}
+ onCadmataSelect={setSelected}
+ onHostReady={(host) => {
+ window.cadmataX1 = { ...window.cadmataX1, revision, host };
+ }}
+ onPickRay={(origin, direction) => {
+ if (model)
+ void pickBody(model.documentId, model.bodyId, {
+ origin,
+ direction,
+ tessellationOptions: null,
+ pickOptions: { nearestOnly: true },
+ }).then((result) => {
+ const hit = result.hits[0];
+ if (hit)
+ setSelected(
+ resolvePublishedBrepEntity(
+ model.artifact,
+ hit.entityKind,
+ hit.faceId ?? hit.edgeId ?? -1,
+ )?.stableId ?? null,
+ );
+ });
+ }}
+ />
+ </div>
+ <output>{selected ?? "No selection"}</output>
+ {error && <div role="alert">{error}</div>}
+ </>
+ );
+}
+createRoot(document.querySelector("#root")!).render(<Witness />);
diff --git a/aetheris.client/src/__tests__/telosOverlays.test.tsx b/aetheris.client/src/__tests__/telosOverlays.test.tsx
new file mode 100644
index 00000000..488777cd
--- /dev/null
+++ b/aetheris.client/src/__tests__/telosOverlays.test.tsx
@@ -0,0 +1,116 @@
+import { describe, expect, it } from "vitest";
+import { cadmataOverlays } from "../viewer/cadmataOverlays";
+import { DEFAULT_CADMATA_LAYERS } from "../viewer/cadmataLayers";
+import {
+ pmiPresentationSelection,
+ semanticPmiItems,
+ DEFAULT_PMI_VISIBILITY,
+} from "../viewer/pmiPresentation";
+import {
+ resolveCadmataSelection,
+ type CadmataVisualizationArtifact,
+} from "../viewer/conceptVisualization";
+const artifact: CadmataVisualizationArtifact = {
+ schemaVersion: "cadmata-concept-viz-x1",
+ fixtureId: "overlays",
+ sourcePath: "authoritative.firmament",
+ selections: [],
+ entities: [
+ {
+ stableId: "plane",
+ kind: "ConstructionPlane",
+ label: "YZ",
+ layer: "constructionPlanes",
+ geometry: {
+ type: "plane",
+ origin: { x: 3, y: 0, z: 0 },
+ u: { x: 0, y: 2, z: 0 },
+ v: { x: 0, y: 0, z: 4 },
+ },
+ },
+ {
+ stableId: "point",
+ kind: "Point",
+ label: "Origin",
+ layer: "conceptPoints",
+ geometry: { type: "point", point: { x: 3, y: 0, z: 0 } },
+ },
+ {
+ stableId: "face:+Z",
+ kind: "BRepFace",
+ label: "Top",
+ layer: "material",
+ parentIds: ["target"],
+ topology: { faceIds: [17] },
+ },
+ {
+ stableId: "target",
+ kind: "EngineeringTarget",
+ label: "Top",
+ layer: "selections",
+ topology: { faceIds: [17] },
+ },
+ {
+ stableId: "datum:A",
+ kind: "Datum",
+ label: "Datum A",
+ layer: "selections",
+ childIds: ["target"],
+ metadata: { targetSemanticId: "target" },
+ geometry: { type: "point", point: { x: 0, y: 0, z: 2 } },
+ },
+ ],
+};
+describe("Telos authoring adapter and PMI correspondence", () => {
+ it("uses published plane basis and explicit depth; reuses geometry across selection and filters", () => {
+ const props = {
+ cadmataArtifact: artifact,
+ cadmataLayers: DEFAULT_CADMATA_LAYERS,
+ };
+ const first = cadmataOverlays(props),
+ selected = cadmataOverlays({
+ ...props,
+ selectedCadmataIds: new Set(["plane"]),
+ });
+ expect(first.meshes[0].definition.positions).toEqual([
+ 3, -2, -4, 3, -2, 4, 3, 2, -4, 3, 2, 4,
+ ]);
+ expect(first.meshes[0].depthMode).toBe("depth-tested");
+ expect(first.meshes[1].depthMode).toBe("always-on-top");
+ expect(selected.meshes[0].definition).toBe(first.meshes[0].definition);
+ expect(
+ cadmataOverlays({
+ ...props,
+ cadmataLayers: { ...DEFAULT_CADMATA_LAYERS, constructionPlanes: false },
+ }).meshes,
+ ).toHaveLength(1);
+ expect(
+ first.meshes.some((mesh) => mesh.identity.overlayId === "datum:A"),
+ ).toBe(false);
+ });
+ it("preserves semantic anchors through source rebuild and selection in both directions", () => {
+ const selection = resolveCadmataSelection(artifact, "datum:A");
+ expect(selection.faceIds.has(17)).toBe(true);
+ expect(
+ pmiPresentationSelection(artifact, new Set(["face:+Z"])).has("datum:A"),
+ ).toBe(true);
+ const item = semanticPmiItems(artifact, DEFAULT_PMI_VISIBILITY)[0];
+ expect(item.anchor).toEqual([0, 0, 2]);
+ const rebuilt = {
+ ...artifact,
+ entities: artifact.entities.map((entity) =>
+ entity.stableId === "datum:A"
+ ? {
+ ...entity,
+ geometry: { type: "point" as const, point: { x: 0, y: 0, z: 3 } },
+ }
+ : entity,
+ ),
+ };
+ expect(semanticPmiItems(rebuilt, DEFAULT_PMI_VISIBILITY)[0]).toMatchObject({
+ entity: { stableId: "datum:A" },
+ anchor: [0, 0, 3],
+ });
+ expect(item.anchor).toEqual([0, 0, 2]);
+ });
+});
diff --git a/aetheris.client/src/viewer/AetherisViewport.tsx b/aetheris.client/src/viewer/AetherisViewport.tsx
index 4e9acf58..262ac172 100644
--- a/aetheris.client/src/viewer/AetherisViewport.tsx
+++ b/aetheris.client/src/viewer/AetherisViewport.tsx
@@ -1,21 +1,21 @@
-import { useEffect, useRef, useState } from "react";
+import { lazy, Suspense, useEffect, useRef, useState } from "react";
import { TelosHost, clearColor } from "@aetheris/three-telos";
-import {
- LegacyAetherisViewport,
- type AetherisViewportProps,
-} from "./LegacyAetherisViewport";
+import type { AetherisViewportProps } from "./viewportProps";
+import { PmiAnnotationLayer } from "./PmiAnnotationLayer";
+import { DEFAULT_PMI_VISIBILITY } from "./pmiPresentation";
+const LegacyAetherisViewport = lazy(() =>
+ import("./LegacyAetherisViewport").then((module) => ({
+ default: module.LegacyAetherisViewport,
+ })),
+);
import { cadmataTelosScene } from "./cadmataTelos";
import { ATELIER_VIEWPORT_THEME } from "./viewportTheme";
-export type { AetherisViewportProps } from "./LegacyAetherisViewport";
+export type { AetherisViewportProps } from "./viewportProps";
-/** Transitional WebGL remains for unsupported GPUs and unmigrated semantic authoring/PMI overlays. */
+/** 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 legacyReason = !supported
- ? "WebGPU unavailable"
- : props.cadmataArtifact
- ? "authoring overlays / PMI migration pending"
- : null;
+ const legacyReason = !supported ? "WebGPU unavailable" : null;
if (legacyReason)
return (
<div
@@ -23,7 +23,9 @@ export function AetherisViewport(props: AetherisViewportProps) {
data-display-host="transitional-webgl"
data-display-reason={legacyReason}
>
- <LegacyAetherisViewport {...props} />
+ <Suspense fallback={<small>Loading browser fallback…</small>}>
+ <LegacyAetherisViewport {...props} />
+ </Suspense>
<small
style={{
position: "absolute",
@@ -45,6 +47,7 @@ function TelosViewport(props: AetherisViewportProps) {
host = useRef<TelosHost | null>(null);
const latest = useRef(props);
const [diagnostic, setDiagnostic] = useState<string | null>(null);
+ const [labelHost, setLabelHost] = useState<TelosHost | null>(null);
const lastModel = useRef<unknown>(undefined);
const apply = () => {
const current = host.current;
@@ -73,13 +76,17 @@ function TelosViewport(props: AetherisViewportProps) {
event.clientX - rect.left,
event.clientY - rect.top,
];
+ const hit = current.picker.pick(pixel);
+ if (hit?.overlayId) {
+ latest.current.onCadmataSelect?.(hit.overlayId);
+ return;
+ }
const ray = current.camera.worldRay(pixel),
value = latest.current;
value.onPickRay?.(
{ x: ray.origin.x, y: ray.origin.y, z: ray.origin.z },
{ x: ray.direction.x, y: ray.direction.y, z: ray.direction.z },
);
- const hit = current.picker.pick(pixel);
if (value.assemblyPacket && hit)
value.onAssemblyOccurrenceSelect?.(hit.occurrenceId);
};
@@ -91,9 +98,11 @@ function TelosViewport(props: AetherisViewportProps) {
return;
}
host.current = current;
+ setLabelHost(current);
current.camera.mode = "orthographic";
current.attach(container.current!);
apply();
+ latest.current.onHostReady?.(current);
})
.catch((error) => {
if (!disposed) setDiagnostic(String(error));
@@ -121,6 +130,18 @@ function TelosViewport(props: AetherisViewportProps) {
style={{ display: "block", width: "100%", height: "100%" }}
/>
{diagnostic && <div role="alert">{diagnostic}</div>}
+ <PmiAnnotationLayer
+ host={labelHost}
+ artifact={props.cadmataArtifact ?? null}
+ visible={props.showPmi !== false}
+ visibility={props.pmiVisibility ?? DEFAULT_PMI_VISIBILITY}
+ selectedIds={props.selectedCadmataIds ?? EMPTY_SELECTION}
+ onSelect={props.onCadmataSelect ?? NO_SELECT}
+ theme={props.theme ?? ATELIER_VIEWPORT_THEME}
+ showAxisGuide={props.showAxisGuide !== false}
+ />
</div>
);
}
+const EMPTY_SELECTION = new Set<string>();
+const NO_SELECT = () => {};
diff --git a/aetheris.client/src/viewer/LegacyAetherisViewport.tsx b/aetheris.client/src/viewer/LegacyAetherisViewport.tsx
index 4e811ce4..0753df21 100644
--- a/aetheris.client/src/viewer/LegacyAetherisViewport.tsx
+++ b/aetheris.client/src/viewer/LegacyAetherisViewport.tsx
@@ -27,10 +27,11 @@ import {
import type { AssemblyDisplayPacketDto } from "../api/aetherisApi";
import { mapFacePatchToRenderFacePatch } from "./tessellationMapper";
import { buildAdaptiveGridPlan, type GridBounds } from "./logarithmicGrid";
-import { CadmataOverlay, type CadmataLayerVisibility } from "./CadmataOverlay";
-import type { CadmataVisualizationArtifact } from "./conceptVisualization";
+import { CadmataOverlay } from "./LegacyCadmataOverlay";
+
import { ATELIER_VIEWPORT_THEME, type ViewportTheme } from "./viewportTheme";
-import { DEFAULT_PMI_VISIBILITY, PmiAnnotationLayer, type PmiVisibility } from "./PmiAnnotationLayer";
+import { PmiAnnotationLayer } from "./LegacyPmiAnnotationLayer";
+import { DEFAULT_PMI_VISIBILITY } from "./pmiPresentation";
import { ThemeBackground } from "./ThemeBackground";
function intersectGround(origin: Vector3, direction: Vector3, y: number): Vector3 | null {
@@ -264,29 +265,8 @@ function ViewportPerformanceProbe({ resetKey }: { resetKey: unknown }) {
return null;
}
-export interface AetherisViewportProps {
- displayScene?: DisplayScene | null;
- highlightedFaceId?: number | null;
- highlightedEdgeId?: number | null;
- highlightedFaceIds?: Set<number>;
- highlightedEdgeIds?: Set<number>;
- showGrid?: boolean;
- showAxisGuide?: boolean;
- theme?: ViewportTheme;
- onPickRay?: (
- origin: { x: number; y: number; z: number },
- direction: { x: number; y: number; z: number },
- ) => void;
- cadmataArtifact?: CadmataVisualizationArtifact | null;
- cadmataLayers?: CadmataLayerVisibility;
- selectedCadmataIds?: Set<string>;
- onCadmataSelect?: (stableId: string) => void;
- showPmi?: boolean;
- pmiVisibility?: PmiVisibility;
- assemblyPacket?: AssemblyDisplayPacketDto | null;
- selectedAssemblyOccurrenceId?: string | null;
- onAssemblyOccurrenceSelect?: (stableId: string) => void;
-}
+export type { AetherisViewportProps } from "./viewportProps";
+import type { AetherisViewportProps } from "./viewportProps";
function FaceMesh({
positions,
diff --git a/aetheris.client/src/viewer/CadmataOverlay.tsx b/aetheris.client/src/viewer/LegacyCadmataOverlay.tsx
similarity index 87%
rename from aetheris.client/src/viewer/CadmataOverlay.tsx
rename to aetheris.client/src/viewer/LegacyCadmataOverlay.tsx
index 6722daf9..215d5e03 100644
--- a/aetheris.client/src/viewer/CadmataOverlay.tsx
+++ b/aetheris.client/src/viewer/LegacyCadmataOverlay.tsx
@@ -1,31 +1,14 @@
-/* eslint-disable react-refresh/only-export-components -- layer contracts and the overlay intentionally share one small module. */
import { Line } from "@react-three/drei";
import { useMemo } from "react";
import { DoubleSide, Vector3 } from "three";
import type {
CadmataEntity,
- CadmataLayer,
CadmataVisualizationArtifact,
} from "./conceptVisualization";
import type { ViewportTheme } from "./viewportTheme";
import { SEMANTIC_PMI_KINDS } from "./semanticInspection";
-export type CadmataLayerVisibility = Record<CadmataLayer, boolean>;
-export const DEFAULT_CADMATA_LAYERS: CadmataLayerVisibility = {
- material: true,
- brepEdges: true,
- conceptPoints: true,
- conceptAxes: true,
- conceptRegions: true,
- conceptPlanes: true,
- constructionPlanes: true,
- profileGuides: true,
- profileLoops: true,
- composeRegions: true,
- selections: true,
- diagnostics: true,
-};
-
+import type { CadmataLayerVisibility } from "./cadmataLayers";
function colorFor(entity: CadmataEntity, selected: boolean, theme: ViewportTheme) {
if (selected) return theme.overlay.selection;
if (entity.layer === "profileGuides" || entity.layer === "profileLoops")
diff --git a/aetheris.client/src/viewer/LegacyPmiAnnotationLayer.tsx b/aetheris.client/src/viewer/LegacyPmiAnnotationLayer.tsx
new file mode 100644
index 00000000..ee9283d9
--- /dev/null
+++ b/aetheris.client/src/viewer/LegacyPmiAnnotationLayer.tsx
@@ -0,0 +1,94 @@
+import { Html, Line } from "@react-three/drei";
+import { useFrame, useThree } from "@react-three/fiber";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { Vector3 } from "three";
+import type { CadmataEntity, CadmataVisualizationArtifact } from "./conceptVisualization";
+import type { ViewportTheme } from "./viewportTheme";
+import { semanticPmiItems, layoutPmiCallouts, pmiCategory, CalloutContent, type PmiVisibility } from "./pmiPresentation";
+type Point = [number, number, number];
+type Placement = { entity: CadmataEntity; anchor: Point; label: Point; hidden: boolean };
+export function PmiAnnotationLayer({
+ artifact,
+ visible,
+ visibility,
+ selectedIds,
+ onSelect,
+ theme,
+}: {
+ artifact: CadmataVisualizationArtifact | null;
+ visible: boolean;
+ visibility: PmiVisibility;
+ selectedIds: Set<string>;
+ onSelect: (id: string) => void;
+ theme: ViewportTheme;
+}) {
+ const { camera, size } = useThree();
+ const items = useMemo(() => artifact ? semanticPmiItems(artifact, visibility) : [], [artifact, visibility]);
+ const [placements, setPlacements] = useState<Placement[]>([]);
+ const [manualOffsets, setManualOffsets] = useState<Map<string, { x: number; y: number }>>(new Map());
+ const drag = useRef<{ id: string; originX: number; originY: number; initial: { x: number; y: number } } | null>(null);
+ const lastSignature = useRef("");
+
+ useEffect(() => {
+ const move = (event: PointerEvent) => {
+ if (!drag.current) return;
+ const current = drag.current;
+ setManualOffsets((previous) => new Map(previous).set(current.id, {
+ x: current.initial.x + event.clientX - current.originX,
+ y: current.initial.y + event.clientY - current.originY,
+ }));
+ };
+ const up = () => { drag.current = null; };
+ window.addEventListener("pointermove", move);
+ window.addEventListener("pointerup", up);
+ return () => { window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", up); };
+ }, []);
+
+ useFrame(() => {
+ if (!visible || items.length === 0) return;
+ camera.updateMatrixWorld(false);
+ const signature = `${size.width}:${size.height}:${camera.matrixWorld.elements.map((value) => value.toFixed(4)).join(",")}:${camera.projectionMatrix.elements.map((value) => value.toFixed(4)).join(",")}:${items.map((item) => item.entity.stableId).join("|")}:${JSON.stringify([...manualOffsets])}`;
+ if (signature === lastSignature.current) return;
+ lastSignature.current = signature;
+ const projected = items.map((item) => {
+ const screen = new Vector3(...item.anchor).project(camera);
+ return { ...item, screenAnchor: { x: (screen.x + 1) * size.width / 2, y: (1 - screen.y) * size.height / 2, z: screen.z } };
+ });
+ const layout = layoutPmiCallouts(projected, size.width, size.height, manualOffsets);
+ setPlacements(projected.map((item, index) => {
+ const screen = layout[index];
+ const world = new Vector3(screen.x / size.width * 2 - 1, 1 - screen.y / size.height * 2, item.screenAnchor.z).unproject(camera);
+ return { entity: item.entity, anchor: item.anchor, label: [world.x, world.y, world.z], hidden: screen.hidden };
+ }));
+ });
+
+ if (!visible || !artifact) return null;
+ return <group name="semantic-pmi-annotations">
+ {placements.filter((placement) => !placement.hidden).map(({ entity, anchor: target, label }) => {
+ const category = pmiCategory(entity)!;
+ const selected = selectedIds.has(entity.stableId);
+ const color = selected ? theme.annotation.selected : category === "datums" ? theme.annotation.datum : category === "dimensions" ? theme.annotation.dimension : theme.annotation.text;
+ const wholePart = !(entity.topology?.faceIds?.length);
+ return <group key={entity.stableId}>
+ <Line points={[target, label]} color={theme.annotation.leader} lineWidth={selected ? 2.5 : 1.2} depthTest={false} />
+ <Html position={label} center style={{ pointerEvents: "auto" }} zIndexRange={selected ? [90, 80] : [60, 10]}>
+ <button
+ className={`pmi-callout pmi-callout--${category}${wholePart ? " pmi-callout--global" : ""}${selected ? " is-selected" : ""}`}
+ type="button"
+ onPointerDown={(event) => {
+ event.stopPropagation();
+ const initial = manualOffsets.get(entity.stableId) ?? { x: 0, y: 0 };
+ drag.current = { id: entity.stableId, originX: event.clientX, originY: event.clientY, initial };
+ }}
+ onClick={(event) => { event.stopPropagation(); onSelect(entity.stableId); }}
+ style={{ color, background: theme.annotation.background, borderColor: color }}
+ aria-label={`Inspect ${entity.label}`}
+ title="Select; drag to adjust presentation only"
+ >
+ <CalloutContent entity={entity} />
+ </button>
+ </Html>
+ </group>;
+ })}
+ </group>;
+}
diff --git a/aetheris.client/src/viewer/PmiAnnotationLayer.tsx b/aetheris.client/src/viewer/PmiAnnotationLayer.tsx
index b2ccb8ec..79d5f95b 100644
--- a/aetheris.client/src/viewer/PmiAnnotationLayer.tsx
+++ b/aetheris.client/src/viewer/PmiAnnotationLayer.tsx
@@ -1,204 +1,236 @@
-/* eslint-disable react-refresh/only-export-components -- the presentation contract and its pure deterministic layout helpers are tested together with the rendering adapter. */
-import { Html, Line } from "@react-three/drei";
-import { useFrame, useThree } from "@react-three/fiber";
-import { useEffect, useMemo, useRef, useState } from "react";
-import { Vector3 } from "three";
-import type { CadmataEntity, CadmataVisualizationArtifact } from "./conceptVisualization";
-import { formatPmiLabel, SEMANTIC_PMI_KINDS } from "./semanticInspection";
+import { useEffect, useMemo, useRef } from "react";
+import {
+ materialFromAppearance,
+ type TelosHost,
+ type TelosLine,
+} from "@aetheris/three-telos";
+import type { CadmataVisualizationArtifact } from "./conceptVisualization";
import type { ViewportTheme } from "./viewportTheme";
+import {
+ semanticPmiItems,
+ layoutPmiCallouts,
+ pmiCategory,
+ CalloutContent,
+ pmiPresentationSelection,
+ type PmiVisibility,
+} from "./pmiPresentation";
-export type PmiCategory = "datums" | "dimensions" | "geometricTolerances" | "engineeringAnnotations";
-export type PmiVisibility = Record<PmiCategory, boolean>;
-export const DEFAULT_PMI_VISIBILITY: PmiVisibility = {
- datums: true,
- dimensions: false,
- geometricTolerances: true,
- engineeringAnnotations: false,
-};
-
-type Point = [number, number, number];
-type ScreenPoint = { x: number; y: number; z: number };
-type LayoutItem = { entity: CadmataEntity; anchor: Point; width: number; height: number };
-type Placement = { entity: CadmataEntity; anchor: Point; label: Point; hidden: boolean };
-
-function anchor(entity: CadmataEntity): Point | null {
- const geometry = entity.geometry;
- if (geometry?.type === "circle") return [geometry.center.x, geometry.center.y, geometry.center.z];
- if (geometry?.type === "point") return [geometry.point.x, geometry.point.y, geometry.point.z];
- if (geometry?.type === "polyline" && geometry.points.length) {
- const point = geometry.points[geometry.points.length - 1];
- return [point.x, point.y, point.z];
- }
- return null;
-}
-
-export function pmiCategory(entity: CadmataEntity): PmiCategory | null {
- if (entity.kind === "Datum") return "datums";
- if (entity.kind === "Dimension" || entity.kind === "Diameter" || entity.kind === "HoleDiameter") return "dimensions";
- if (entity.kind === "Position") return "geometricTolerances";
- if (entity.kind === "Annotation") return "engineeringAnnotations";
- return null;
-}
-
-function priority(entity: CadmataEntity) {
- const category = pmiCategory(entity);
- return category === "datums" ? 0 : category === "geometricTolerances" ? 1 : category === "dimensions" ? 2 : 3;
-}
-
-function estimatedSize(entity: CadmataEntity) {
- const category = pmiCategory(entity);
- if (category === "datums") return { width: 86, height: 38 };
- if (category === "geometricTolerances") return { width: 190, height: 54 };
- if (category === "engineeringAnnotations") return { width: 230, height: 82 };
- return { width: 166, height: 48 };
-}
-
-export function semanticPmiItems(artifact: CadmataVisualizationArtifact, visibility: PmiVisibility): LayoutItem[] {
- return artifact.entities
- .filter((entity) => SEMANTIC_PMI_KINDS.has(entity.kind))
- .filter((entity) => {
- const category = pmiCategory(entity);
- return category !== null && visibility[category];
- })
- .map((entity) => {
- const resolvedAnchor = anchor(entity);
- return resolvedAnchor ? { entity, anchor: resolvedAnchor, ...estimatedSize(entity) } : null;
- })
- .filter((item): item is LayoutItem => item !== null)
- .sort((left, right) => priority(left.entity) - priority(right.entity) || left.entity.stableId.localeCompare(right.entity.stableId));
-}
-
-function overlaps(a: { x: number; y: number; width: number; height: number }, b: { x: number; y: number; width: number; height: number }) {
- return Math.abs(a.x - b.x) < (a.width + b.width) / 2 + 8 && Math.abs(a.y - b.y) < (a.height + b.height) / 2 + 6;
-}
-
-/** Deterministic bounded greedy screen-space placement. */
-export function layoutPmiCallouts(
- items: readonly (LayoutItem & { screenAnchor: ScreenPoint })[],
- width: number,
- height: number,
- manualOffsets: ReadonlyMap<string, { x: number; y: number }>,
-) {
- const placed: { x: number; y: number; width: number; height: number }[] = [];
- return items.map((item, index) => {
- const manual = manualOffsets.get(item.entity.stableId);
- const radialCandidates = Array.from({ length: 32 }, (_, attempt) => {
- const ring = Math.floor(attempt / 8);
- const angle = ((attempt + index * 3) % 8) * (Math.PI / 4);
- const radius = 68 + ring * 58;
- return { x: item.screenAnchor.x + Math.cos(angle) * radius, y: item.screenAnchor.y + Math.sin(angle) * radius };
- });
- const gridCandidates = Array.from({ length: 10 }, (_, slot) => ({
- x: slot % 2 === 0 ? item.width / 2 + 18 : width - item.width / 2 - 18,
- y: 106 + Math.floor(slot / 2) * Math.max(item.height + 14, 92),
- }));
- const candidates = manual
- ? [{ x: item.screenAnchor.x + manual.x, y: item.screenAnchor.y + manual.y }]
- : [...radialCandidates, ...gridCandidates];
- let candidate = candidates.find((point) => {
- const box = { ...point, width: item.width, height: item.height };
- return point.x - item.width / 2 >= 8 && point.x + item.width / 2 <= width - 8 && point.y - item.height / 2 >= 56 && point.y + item.height / 2 <= height - 8 && !placed.some((other) => overlaps(box, other));
- });
- const hidden = !candidate && priority(item.entity) >= 3 && items.length > 10;
- candidate ??= candidates[candidates.length - 1];
- candidate = {
- x: Math.max(item.width / 2 + 8, Math.min(width - item.width / 2 - 8, candidate.x)),
- y: Math.max(item.height / 2 + 56, Math.min(height - item.height / 2 - 8, candidate.y)),
- };
- if (!hidden) placed.push({ ...candidate, width: item.width, height: item.height });
- return { ...candidate, hidden };
- });
-}
-
-function CalloutContent({ entity }: { entity: CadmataEntity }) {
- if (entity.kind === "Datum") return <><strong className="pmi-callout__datum">{entity.label.replace(/^Datum\s+/i, "")}</strong><span>DATUM</span></>;
- if (entity.kind === "Position") return <><strong>POSITION · ⌀{String(entity.metadata?.nominal ?? "?")} {String(entity.metadata?.unit ?? "mm")}</strong><small>{String(entity.metadata?.datumRefs ?? "No datum frame")} · {String(entity.metadata?.target ?? "")}</small></>;
- if (entity.kind === "Annotation") return <><strong>{entity.label}</strong><small>{String(entity.metadata?.text ?? "")}</small></>;
- return <><strong>{formatPmiLabel(entity)} {String(entity.metadata?.unit ?? "")}</strong><small>{String(entity.metadata?.target ?? "")}</small></>;
-}
-
+/** DOM text is world-anchored, screen-sized and always-on-top. Telos owns camera and leader resources. */
export function PmiAnnotationLayer({
- artifact,
- visible,
- visibility,
- selectedIds,
- onSelect,
- theme,
+ host,
+ artifact,
+ visible,
+ visibility,
+ selectedIds,
+ onSelect,
+ theme,
+ showAxisGuide = true,
}: {
- artifact: CadmataVisualizationArtifact | null;
- visible: boolean;
- visibility: PmiVisibility;
- selectedIds: Set<string>;
- onSelect: (id: string) => void;
- theme: ViewportTheme;
+ host: TelosHost | null;
+ artifact: CadmataVisualizationArtifact | null;
+ visible: boolean;
+ visibility: PmiVisibility;
+ selectedIds: Set<string>;
+ onSelect: (id: string) => void;
+ theme: ViewportTheme;
+ showAxisGuide?: boolean;
}) {
- const { camera, size } = useThree();
- const items = useMemo(() => artifact ? semanticPmiItems(artifact, visibility) : [], [artifact, visibility]);
- const [placements, setPlacements] = useState<Placement[]>([]);
- const [manualOffsets, setManualOffsets] = useState<Map<string, { x: number; y: number }>>(new Map());
- const drag = useRef<{ id: string; originX: number; originY: number; initial: { x: number; y: number } } | null>(null);
- const lastSignature = useRef("");
-
- useEffect(() => {
- const move = (event: PointerEvent) => {
- if (!drag.current) return;
- const current = drag.current;
- setManualOffsets((previous) => new Map(previous).set(current.id, {
- x: current.initial.x + event.clientX - current.originX,
- y: current.initial.y + event.clientY - current.originY,
- }));
- };
- const up = () => { drag.current = null; };
- window.addEventListener("pointermove", move);
- window.addEventListener("pointerup", up);
- return () => { window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", up); };
- }, []);
-
- useFrame(() => {
- if (!visible || items.length === 0) return;
- camera.updateMatrixWorld(false);
- const signature = `${size.width}:${size.height}:${camera.matrixWorld.elements.map((value) => value.toFixed(4)).join(",")}:${camera.projectionMatrix.elements.map((value) => value.toFixed(4)).join(",")}:${items.map((item) => item.entity.stableId).join("|")}:${JSON.stringify([...manualOffsets])}`;
- if (signature === lastSignature.current) return;
- lastSignature.current = signature;
- const projected = items.map((item) => {
- const screen = new Vector3(...item.anchor).project(camera);
- return { ...item, screenAnchor: { x: (screen.x + 1) * size.width / 2, y: (1 - screen.y) * size.height / 2, z: screen.z } };
- });
- const layout = layoutPmiCallouts(projected, size.width, size.height, manualOffsets);
- setPlacements(projected.map((item, index) => {
- const screen = layout[index];
- const world = new Vector3(screen.x / size.width * 2 - 1, 1 - screen.y / size.height * 2, item.screenAnchor.z).unproject(camera);
- return { entity: item.entity, anchor: item.anchor, label: [world.x, world.y, world.z], hidden: screen.hidden };
- }));
- });
-
- if (!visible || !artifact) return null;
- return <group name="semantic-pmi-annotations">
- {placements.filter((placement) => !placement.hidden).map(({ entity, anchor: target, label }) => {
- const category = pmiCategory(entity)!;
- const selected = selectedIds.has(entity.stableId);
- const color = selected ? theme.annotation.selected : category === "datums" ? theme.annotation.datum : category === "dimensions" ? theme.annotation.dimension : theme.annotation.text;
- const wholePart = !(entity.topology?.faceIds?.length);
- return <group key={entity.stableId}>
- <Line points={[target, label]} color={theme.annotation.leader} lineWidth={selected ? 2.5 : 1.2} depthTest={false} />
- <Html position={label} center style={{ pointerEvents: "auto" }} zIndexRange={selected ? [90, 80] : [60, 10]}>
- <button
- className={`pmi-callout pmi-callout--${category}${wholePart ? " pmi-callout--global" : ""}${selected ? " is-selected" : ""}`}
- type="button"
- onPointerDown={(event) => {
- event.stopPropagation();
- const initial = manualOffsets.get(entity.stableId) ?? { x: 0, y: 0 };
- drag.current = { id: entity.stableId, originX: event.clientX, originY: event.clientY, initial };
- }}
- onClick={(event) => { event.stopPropagation(); onSelect(entity.stableId); }}
- style={{ color, background: theme.annotation.background, borderColor: color }}
- aria-label={`Inspect ${entity.label}`}
- title="Select; drag to adjust presentation only"
- >
- <CalloutContent entity={entity} />
- </button>
- </Html>
- </group>;
- })}
- </group>;
+ const items = useMemo(
+ () => (visible && artifact ? semanticPmiItems(artifact, visibility) : []),
+ [artifact, visible, visibility],
+ );
+ const highlighted = useMemo(
+ () => pmiPresentationSelection(artifact, selectedIds),
+ [artifact, selectedIds],
+ );
+ const buttons = useRef(new Map<string, HTMLButtonElement>());
+ const axes = useRef(new Map<number, HTMLSpanElement>());
+ const manual = useRef(new Map<string, { x: number; y: number }>());
+ const offsets = useRef(new Map<string, { x: number; y: number }>());
+ const drag = useRef<{
+ id: string;
+ x: number;
+ y: number;
+ initial: { x: number; y: number };
+ } | null>(null);
+ useEffect(() => {
+ if (!host) return;
+ let signature = "";
+ const update = () => {
+ const camera = host.camera;
+ const key = JSON.stringify([
+ camera.viewProjection.elements,
+ camera.width,
+ camera.height,
+ [...manual.current],
+ ]);
+ if (key === signature) return;
+ signature = key;
+ const projected = items.map((item) => {
+ const [x, y, z] = camera.project(item.anchor);
+ return { ...item, screenAnchor: { x, y, z } };
+ });
+ const layout = layoutPmiCallouts(
+ projected,
+ camera.width,
+ camera.height,
+ manual.current,
+ );
+ const lines: TelosLine[] = [];
+ projected.forEach((item, i) => {
+ const placement = layout[i],
+ element = buttons.current.get(item.entity.stableId);
+ const shown =
+ !placement.hidden &&
+ item.screenAnchor.z >= 0 &&
+ item.screenAnchor.z <= 1 &&
+ Number.isFinite(item.screenAnchor.x);
+ if (element) {
+ element.style.display = shown ? "" : "none";
+ element.style.left = placement.x + "px";
+ element.style.top = placement.y + "px";
+ }
+ offsets.current.set(item.entity.stableId, {
+ x: placement.x - item.screenAnchor.x,
+ y: placement.y - item.screenAnchor.y,
+ });
+ if (!shown) return;
+ const label = camera.unproject(
+ [placement.x, placement.y],
+ item.screenAnchor.z,
+ );
+ lines.push({
+ id: "pmi:" + item.entity.stableId,
+ identity: { occurrenceId: "pmi", overlayId: item.entity.stableId },
+ points: [...item.anchor, ...label.toArray()],
+ overlay: true,
+ depthMode: "always-on-top",
+ color: materialFromAppearance({
+ color: theme.annotation.leader,
+ }).baseColor.concat(1),
+ widthPixels: highlighted.has(item.entity.stableId) ? 2.5 : 1.2,
+ });
+ });
+ host.setDynamicLines(lines);
+ for (const [axis, element] of axes.current) {
+ const point = [0, 0, 0];
+ point[axis] = 2;
+ const [x, y, z] = camera.project(point);
+ element.style.display = z >= 0 && z <= 1 ? "" : "none";
+ element.style.left = x + "px";
+ element.style.top = y + "px";
+ }
+ };
+ const detach = host.beforeFrame(update);
+ const move = (event: PointerEvent) => {
+ const current = drag.current;
+ if (!current) return;
+ manual.current.set(current.id, {
+ x: current.initial.x + event.clientX - current.x,
+ y: current.initial.y + event.clientY - current.y,
+ });
+ host.invalidate();
+ };
+ const up = () => {
+ drag.current = null;
+ };
+ window.addEventListener("pointermove", move);
+ window.addEventListener("pointerup", up);
+ window.addEventListener("pointercancel", up);
+ return () => {
+ detach();
+ host.invalidate();
+ window.removeEventListener("pointermove", move);
+ window.removeEventListener("pointerup", up);
+ window.removeEventListener("pointercancel", up);
+ };
+ }, [host, items, highlighted, theme, showAxisGuide]);
+ useEffect(
+ () => () => {
+ host?.setDynamicLines([]);
+ host?.invalidate();
+ },
+ [host],
+ );
+ return (
+ <div
+ data-telos-labels="world-anchored-screen-sized"
+ style={{
+ position: "absolute",
+ inset: 0,
+ overflow: "hidden",
+ pointerEvents: "none",
+ }}
+ >
+ {items.map(({ entity }) => {
+ const category = pmiCategory(entity)!;
+ const selected = highlighted.has(entity.stableId);
+ const color = selected
+ ? theme.annotation.selected
+ : category === "datums"
+ ? theme.annotation.datum
+ : category === "dimensions"
+ ? theme.annotation.dimension
+ : theme.annotation.text;
+ return (
+ <button
+ key={entity.stableId}
+ ref={(element) => {
+ if (element) buttons.current.set(entity.stableId, element);
+ else buttons.current.delete(entity.stableId);
+ }}
+ className={`pmi-callout pmi-callout--${category}${!entity.topology?.faceIds?.length ? " pmi-callout--global" : ""}${selected ? " is-selected" : ""}`}
+ data-pmi-id={entity.stableId}
+ type="button"
+ aria-label={`Inspect ${entity.label}`}
+ title="Select; drag to adjust presentation only"
+ style={{
+ position: "absolute",
+ display: "none",
+ transform: "translate(-50%, -50%)",
+ pointerEvents: "auto",
+ zIndex: selected ? 90 : 60,
+ color,
+ background: theme.annotation.background,
+ borderColor: color,
+ }}
+ onPointerDown={(event) => {
+ event.stopPropagation();
+ event.currentTarget.setPointerCapture(event.pointerId);
+ drag.current = {
+ id: entity.stableId,
+ x: event.clientX,
+ y: event.clientY,
+ initial: offsets.current.get(entity.stableId) ?? { x: 0, y: 0 },
+ };
+ }}
+ onClick={(event) => {
+ event.stopPropagation();
+ onSelect(entity.stableId);
+ }}
+ >
+ <CalloutContent entity={entity} />
+ </button>
+ );
+ })}
+ {showAxisGuide &&
+ [theme.axis.x, theme.axis.y, theme.axis.z].map((color, axis) => (
+ <span
+ key={axis}
+ ref={(element) => {
+ if (element) axes.current.set(axis, element);
+ else axes.current.delete(axis);
+ }}
+ style={{
+ position: "absolute",
+ color,
+ fontSize: 12,
+ display: "none",
+ }}
+ >
+ {"XYZ"[axis]}
+ </span>
+ ))}
+ </div>
+ );
}
diff --git a/aetheris.client/src/viewer/cadmataLayers.ts b/aetheris.client/src/viewer/cadmataLayers.ts
new file mode 100644
index 00000000..f5d2ba6c
--- /dev/null
+++ b/aetheris.client/src/viewer/cadmataLayers.ts
@@ -0,0 +1,16 @@
+import type { CadmataLayer } from "./conceptVisualization";
+export type CadmataLayerVisibility = Record<CadmataLayer, boolean>;
+export const DEFAULT_CADMATA_LAYERS: CadmataLayerVisibility = {
+ material: true,
+ brepEdges: true,
+ conceptPoints: true,
+ conceptAxes: true,
+ conceptRegions: true,
+ conceptPlanes: true,
+ constructionPlanes: true,
+ profileGuides: true,
+ profileLoops: true,
+ composeRegions: true,
+ selections: true,
+ diagnostics: true,
+};
diff --git a/aetheris.client/src/viewer/cadmataOverlays.ts b/aetheris.client/src/viewer/cadmataOverlays.ts
new file mode 100644
index 00000000..e7a43e0a
--- /dev/null
+++ b/aetheris.client/src/viewer/cadmataOverlays.ts
@@ -0,0 +1,135 @@
+import { SphereGeometry, Matrix4, Vector3 } from "three";
+import {
+ materialFromAppearance,
+ type TelosGeometry,
+ type TelosScene,
+ type TelosMesh,
+ type TelosLine,
+} from "@aetheris/three-telos";
+import type { CadmataEntity } from "./conceptVisualization";
+import type { AetherisViewportProps } from "./viewportProps";
+import { SEMANTIC_PMI_KINDS } from "./semanticInspection";
+import { ATELIER_VIEWPORT_THEME } from "./viewportTheme";
+
+const sphere = new SphereGeometry(1.8, 12, 8);
+const pointDefinition: TelosGeometry = {
+ id: "authoring-point/1",
+ positions: sphere.attributes.position.array,
+ normals: sphere.attributes.normal.array,
+ indices: sphere.index!.array,
+};
+sphere.dispose();
+const shapes = new WeakMap<
+ CadmataEntity,
+ { definition?: TelosGeometry; points?: number[]; transform?: number[] }
+>();
+const xyz = (point: { x: number; y: number; z: number }) => [
+ point.x,
+ point.y,
+ point.z,
+];
+function shape(entity: CadmataEntity) {
+ const existing = shapes.get(entity);
+ if (existing) return existing;
+ const geometry = entity.geometry;
+ const result: {
+ definition?: TelosGeometry;
+ points?: number[];
+ transform?: number[];
+ } = {};
+ if (geometry?.type === "point") {
+ result.definition = pointDefinition;
+ result.transform = new Matrix4().makeTranslation(
+ ...(xyz(geometry.point) as [number, number, number]),
+ ).elements;
+ } else if (geometry?.type === "plane") {
+ const origin = new Vector3(...xyz(geometry.origin)),
+ u = new Vector3(...xyz(geometry.u)),
+ v = new Vector3(...xyz(geometry.v));
+ const normal = u.clone().cross(v).normalize().toArray();
+ result.definition = {
+ id: "overlay:" + entity.stableId,
+ positions: [-1, 1].flatMap((a) =>
+ [-1, 1].flatMap((b) =>
+ origin.clone().addScaledVector(u, a).addScaledVector(v, b).toArray(),
+ ),
+ ),
+ normals: Array.from({ length: 4 }, () => normal).flat(),
+ indices: [0, 2, 1, 1, 2, 3],
+ };
+ } else if (geometry?.type === "circle") {
+ // Preserve the current XY circle authoring convention.
+ result.points = Array.from({ length: 49 }, (_, i) => [
+ geometry.center.x + Math.cos((i / 48) * Math.PI * 2) * geometry.radius,
+ geometry.center.y + Math.sin((i / 48) * Math.PI * 2) * geometry.radius,
+ geometry.center.z,
+ ]).flat();
+ } else if (geometry?.type === "polyline" && geometry.points.length) {
+ result.points = (
+ geometry.closed
+ ? [...geometry.points, geometry.points[0]]
+ : geometry.points
+ ).flatMap(xyz);
+ }
+ shapes.set(entity, result);
+ return result;
+}
+
+/** Compiler-owned world geometry; selection and layer policy remain in Cadmata. */
+export function cadmataOverlays(props: AetherisViewportProps): TelosScene {
+ const meshes: TelosMesh[] = [],
+ lines: TelosLine[] = [];
+ const theme = props.theme ?? ATELIER_VIEWPORT_THEME;
+ if (!props.cadmataLayers) return { meshes, lines, fields: [] };
+ for (const entity of props.cadmataArtifact?.entities ?? []) {
+ if (
+ !props.cadmataLayers[entity.layer] ||
+ SEMANTIC_PMI_KINDS.has(entity.kind) ||
+ entity.kind === "EngineeringTarget"
+ )
+ continue;
+ const selected = props.selectedCadmataIds?.has(entity.stableId);
+ const color = selected
+ ? theme.overlay.selection
+ : entity.layer === "profileGuides" || entity.layer === "profileLoops"
+ ? theme.overlay.profile
+ : entity.layer === "composeRegions"
+ ? theme.overlay.compose
+ : entity.layer === "diagnostics"
+ ? theme.overlay.diagnostic
+ : theme.overlay.concept;
+ const identity = { occurrenceId: "authoring", overlayId: entity.stableId };
+ const data = shape(entity);
+ if (data.definition)
+ meshes.push({
+ definition: data.definition,
+ transform: data.transform,
+ identity,
+ material: {
+ ...materialFromAppearance({ color }),
+ opacity: entity.geometry?.type === "plane" ? 0.12 : 1,
+ },
+ overlay: true,
+ unlit: true,
+ depthMode:
+ entity.geometry?.type === "point" ? "always-on-top" : "depth-tested",
+ });
+ if (data.points)
+ lines.push({
+ id: "overlay:" + entity.stableId,
+ points: data.points,
+ identity,
+ overlay: true,
+ depthMode: "depth-biased",
+ color: materialFromAppearance({ color }).baseColor.concat(1),
+ widthPixels: selected
+ ? 4
+ : entity.geometry?.type === "circle"
+ ? 1.5
+ : entity.layer === "profileLoops"
+ ? 2.5
+ : 1.25,
+ });
+ }
+ return { meshes, lines, fields: [] };
+}
diff --git a/aetheris.client/src/viewer/cadmataTelos.ts b/aetheris.client/src/viewer/cadmataTelos.ts
index 6ee1114f..cba2b7d8 100644
--- a/aetheris.client/src/viewer/cadmataTelos.ts
+++ b/aetheris.client/src/viewer/cadmataTelos.ts
@@ -6,7 +6,8 @@ import {
type TelosLine,
type NumericArray,
} from "@aetheris/three-telos";
-import type { AetherisViewportProps } from "./LegacyAetherisViewport";
+import type { AetherisViewportProps } from "./viewportProps";
+import { cadmataOverlays } from "./cadmataOverlays";
import { ATELIER_VIEWPORT_THEME } from "./viewportTheme";
import {
mapFacePatchToRenderFacePatch,
@@ -133,5 +134,6 @@ export function cadmataTelosScene(props: AetherisViewportProps): TelosScene {
overlay: true,
});
}
- return { meshes, lines, fields: [] };
+ const overlays = cadmataOverlays(props);
+ return { meshes: [...meshes, ...overlays.meshes], lines: [...lines, ...overlays.lines], fields: [] };
}
diff --git a/aetheris.client/src/viewer/pmiPresentation.tsx b/aetheris.client/src/viewer/pmiPresentation.tsx
new file mode 100644
index 00000000..cfc203d1
--- /dev/null
+++ b/aetheris.client/src/viewer/pmiPresentation.tsx
@@ -0,0 +1,244 @@
+/* eslint-disable react-refresh/only-export-components -- pure presentation helpers and content share the semantic contract. */
+import type {
+ CadmataEntity,
+ CadmataVisualizationArtifact,
+} from "./conceptVisualization";
+import {
+ formatPmiLabel,
+ SEMANTIC_PMI_KINDS,
+ indexSemanticInspection,
+} from "./semanticInspection";
+/** Geometry selection highlights published related PMI without broadening the topology pick. */
+export function pmiPresentationSelection(
+ artifact: CadmataVisualizationArtifact | null,
+ selected: Set<string>,
+) {
+ if (
+ !artifact ||
+ artifact.entities.some(
+ (entity) =>
+ selected.has(entity.stableId) && SEMANTIC_PMI_KINDS.has(entity.kind),
+ )
+ )
+ return selected;
+ const result = new Set(selected),
+ index = indexSemanticInspection(artifact);
+ for (const id of selected) {
+ const entity = index.byId.get(id);
+ if (!entity?.kind.startsWith("BRep")) continue;
+ const owners = [
+ ...(entity.topology?.faceIds ?? []).flatMap(
+ (face) => index.faceOwners.get(face) ?? [],
+ ),
+ ...(entity.topology?.edgeIds ?? []).flatMap(
+ (edge) => index.edgeOwners.get(edge) ?? [],
+ ),
+ ];
+ for (const owner of owners) {
+ if (SEMANTIC_PMI_KINDS.has(owner.kind)) result.add(owner.stableId);
+ for (const pmi of index.pmiByTarget.get(owner.stableId) ?? [])
+ result.add(pmi.stableId);
+ }
+ }
+ return result;
+}
+export type PmiCategory =
+ | "datums"
+ | "dimensions"
+ | "geometricTolerances"
+ | "engineeringAnnotations";
+export type PmiVisibility = Record<PmiCategory, boolean>;
+export const DEFAULT_PMI_VISIBILITY: PmiVisibility = {
+ datums: true,
+ dimensions: false,
+ geometricTolerances: true,
+ engineeringAnnotations: false,
+};
+
+export type Point = [number, number, number];
+type ScreenPoint = { x: number; y: number; z: number };
+export type LayoutItem = {
+ entity: CadmataEntity;
+ anchor: Point;
+ width: number;
+ height: number;
+};
+
+function anchor(entity: CadmataEntity): Point | null {
+ const geometry = entity.geometry;
+ if (geometry?.type === "circle")
+ return [geometry.center.x, geometry.center.y, geometry.center.z];
+ if (geometry?.type === "point")
+ return [geometry.point.x, geometry.point.y, geometry.point.z];
+ if (geometry?.type === "polyline" && geometry.points.length) {
+ const point = geometry.points[geometry.points.length - 1];
+ return [point.x, point.y, point.z];
+ }
+ return null;
+}
+
+export function pmiCategory(entity: CadmataEntity): PmiCategory | null {
+ if (entity.kind === "Datum") return "datums";
+ if (
+ entity.kind === "Dimension" ||
+ entity.kind === "Diameter" ||
+ entity.kind === "HoleDiameter"
+ )
+ return "dimensions";
+ if (entity.kind === "Position") return "geometricTolerances";
+ if (entity.kind === "Annotation") return "engineeringAnnotations";
+ return null;
+}
+
+function priority(entity: CadmataEntity) {
+ const category = pmiCategory(entity);
+ return category === "datums"
+ ? 0
+ : category === "geometricTolerances"
+ ? 1
+ : category === "dimensions"
+ ? 2
+ : 3;
+}
+
+function estimatedSize(entity: CadmataEntity) {
+ const category = pmiCategory(entity);
+ if (category === "datums") return { width: 86, height: 38 };
+ if (category === "geometricTolerances") return { width: 190, height: 54 };
+ if (category === "engineeringAnnotations") return { width: 230, height: 82 };
+ return { width: 166, height: 48 };
+}
+
+export function semanticPmiItems(
+ artifact: CadmataVisualizationArtifact,
+ visibility: PmiVisibility,
+): LayoutItem[] {
+ return artifact.entities
+ .filter((entity) => SEMANTIC_PMI_KINDS.has(entity.kind))
+ .filter((entity) => {
+ const category = pmiCategory(entity);
+ return category !== null && visibility[category];
+ })
+ .map((entity) => {
+ const resolvedAnchor = anchor(entity);
+ return resolvedAnchor
+ ? { entity, anchor: resolvedAnchor, ...estimatedSize(entity) }
+ : null;
+ })
+ .filter((item): item is LayoutItem => item !== null)
+ .sort(
+ (left, right) =>
+ priority(left.entity) - priority(right.entity) ||
+ left.entity.stableId.localeCompare(right.entity.stableId),
+ );
+}
+
+function overlaps(
+ a: { x: number; y: number; width: number; height: number },
+ b: { x: number; y: number; width: number; height: number },
+) {
+ return (
+ Math.abs(a.x - b.x) < (a.width + b.width) / 2 + 8 &&
+ Math.abs(a.y - b.y) < (a.height + b.height) / 2 + 6
+ );
+}
+
+/** Deterministic bounded greedy screen-space placement. */
+export function layoutPmiCallouts(
+ items: readonly (LayoutItem & { screenAnchor: ScreenPoint })[],
+ width: number,
+ height: number,
+ manualOffsets: ReadonlyMap<string, { x: number; y: number }>,
+) {
+ const placed: { x: number; y: number; width: number; height: number }[] = [];
+ return items.map((item, index) => {
+ const manual = manualOffsets.get(item.entity.stableId);
+ const radialCandidates = Array.from({ length: 32 }, (_, attempt) => {
+ const ring = Math.floor(attempt / 8);
+ const angle = ((attempt + index * 3) % 8) * (Math.PI / 4);
+ const radius = 68 + ring * 58;
+ return {
+ x: item.screenAnchor.x + Math.cos(angle) * radius,
+ y: item.screenAnchor.y + Math.sin(angle) * radius,
+ };
+ });
+ const gridCandidates = Array.from({ length: 10 }, (_, slot) => ({
+ x: slot % 2 === 0 ? item.width / 2 + 18 : width - item.width / 2 - 18,
+ y: 106 + Math.floor(slot / 2) * Math.max(item.height + 14, 92),
+ }));
+ const candidates = manual
+ ? [
+ {
+ x: item.screenAnchor.x + manual.x,
+ y: item.screenAnchor.y + manual.y,
+ },
+ ]
+ : [...radialCandidates, ...gridCandidates];
+ let candidate = candidates.find((point) => {
+ const box = { ...point, width: item.width, height: item.height };
+ return (
+ point.x - item.width / 2 >= 8 &&
+ point.x + item.width / 2 <= width - 8 &&
+ point.y - item.height / 2 >= 56 &&
+ point.y + item.height / 2 <= height - 8 &&
+ !placed.some((other) => overlaps(box, other))
+ );
+ });
+ const hidden =
+ !candidate && priority(item.entity) >= 3 && items.length > 10;
+ candidate ??= candidates[candidates.length - 1];
+ candidate = {
+ x: Math.max(
+ item.width / 2 + 8,
+ Math.min(width - item.width / 2 - 8, candidate.x),
+ ),
+ y: Math.max(
+ item.height / 2 + 56,
+ Math.min(height - item.height / 2 - 8, candidate.y),
+ ),
+ };
+ if (!hidden)
+ placed.push({ ...candidate, width: item.width, height: item.height });
+ return { ...candidate, hidden };
+ });
+}
+
+export function CalloutContent({ entity }: { entity: CadmataEntity }) {
+ if (entity.kind === "Datum")
+ return (
+ <>
+ <strong className="pmi-callout__datum">
+ {entity.label.replace(/^Datum\s+/i, "")}
+ </strong>
+ <span>DATUM</span>
+ </>
+ );
+ if (entity.kind === "Position")
+ return (
+ <>
+ <strong>
+ POSITION · ⌀{String(entity.metadata?.nominal ?? "?")}{" "}
+ {String(entity.metadata?.unit ?? "mm")}
+ </strong>
+ <small>
+ {String(entity.metadata?.datumRefs ?? "No datum frame")} ·{" "}
+ {String(entity.metadata?.target ?? "")}
+ </small>
+ </>
+ );
+ if (entity.kind === "Annotation")
+ return (
+ <>
+ <strong>{entity.label}</strong>
+ <small>{String(entity.metadata?.text ?? "")}</small>
+ </>
+ );
+ return (
+ <>
+ <strong>
+ {formatPmiLabel(entity)} {String(entity.metadata?.unit ?? "")}
+ </strong>
+ <small>{String(entity.metadata?.target ?? "")}</small>
+ </>
+ );
+}
diff --git a/aetheris.client/src/viewer/viewportProps.ts b/aetheris.client/src/viewer/viewportProps.ts
new file mode 100644
index 00000000..80f3a20a
--- /dev/null
+++ b/aetheris.client/src/viewer/viewportProps.ts
@@ -0,0 +1,31 @@
+import type { DisplayScene } from "./displayRenderables";
+import type { AssemblyDisplayPacketDto } from "../api/aetherisApi";
+import type { CadmataVisualizationArtifact } from "./conceptVisualization";
+import type { CadmataLayerVisibility } from "./cadmataLayers";
+import type { PmiVisibility } from "./pmiPresentation";
+import type { ViewportTheme } from "./viewportTheme";
+export interface AetherisViewportProps {
+ /** Optional host inspection seam for integration/qualification; does not transfer camera ownership. */
+ onHostReady?: (host: import("@aetheris/three-telos").TelosHost) => void;
+ displayScene?: DisplayScene | null;
+ highlightedFaceId?: number | null;
+ highlightedEdgeId?: number | null;
+ highlightedFaceIds?: Set<number>;
+ highlightedEdgeIds?: Set<number>;
+ showGrid?: boolean;
+ showAxisGuide?: boolean;
+ theme?: ViewportTheme;
+ onPickRay?: (
+ origin: { x: number; y: number; z: number },
+ direction: { x: number; y: number; z: number },
+ ) => void;
+ cadmataArtifact?: CadmataVisualizationArtifact | null;
+ cadmataLayers?: CadmataLayerVisibility;
+ selectedCadmataIds?: Set<string>;
+ onCadmataSelect?: (stableId: string) => void;
+ showPmi?: boolean;
+ pmiVisibility?: PmiVisibility;
+ assemblyPacket?: AssemblyDisplayPacketDto | null;
+ selectedAssemblyOccurrenceId?: string | null;
+ onAssemblyOccurrenceSelect?: (stableId: string) => void;
+}
diff --git a/aetheris.client/vite.config.ts b/aetheris.client/vite.config.ts
index 9119358d..cc889ff3 100644
--- a/aetheris.client/vite.config.ts
+++ b/aetheris.client/vite.config.ts
@@ -71,7 +71,7 @@ export default defineConfig(({ command }) => ({
command === "serve"
? {
fs: env.AETHERIS_TELOS_WITNESS === "1" ? {
- allow: [fileURLToPath(new URL(".", import.meta.url)), fileURLToPath(new URL("../fixtures/three-telos", import.meta.url))],
+ 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,
proxy: {
"^/api": {
diff --git a/docs/public/cadmata/pmi.md b/docs/public/cadmata/pmi.md
index 0af84a21..a64bd34a 100644
--- a/docs/public/cadmata/pmi.md
+++ b/docs/public/cadmata/pmi.md
@@ -3,3 +3,5 @@
Cadmata reads semantic AP242 associations rather than inferring requirements from label positions. Users can filter and select datums, dimensions, geometric tolerances, and engineer-authored notes; the selected presentation remains associated with its semantic feature or face.
The authoritative state is the semantic requirement and its target. Label orientation, camera placement, occlusion handling, and screen layout are presentation choices. Preview 3's public native Firmament export subset is documented in the [PMI guide](../firmament/pmi.md); Cadmata can present broader semantic AP242 content where the importer recognizes it, but that does not expand Firmament authoring support.
+
+In WebGPU browsers, Three Telos draws the model and PMI leaders. Readable DOM callouts use the same Telos camera and remain on top of the model. Drag a callout to adjust its presentation offset; its engineering anchor and target stay unchanged. Selecting a callout highlights its associated geometry, and selecting geometry highlights related visible PMI. Datums and GD&T appear by default; DIM and NOTES enable the other categories. Dense views retain the existing bounded collision layout and may hide low-priority notes.
diff --git a/docs/public/three-telos.md b/docs/public/three-telos.md
index f868f7ae..87b740da 100644
--- a/docs/public/three-telos.md
+++ b/docs/public/three-telos.md
@@ -1,7 +1,9 @@
# Three Telos display
-Cadmata's normal model/assembly view and Helios share the Three Telos WebGPU host. It owns the camera, grid, mesh drawing, semantic topology lines, selection projection and GPU resources. A supported browser/GPU is required for that path.
+Cadmata's model, assembly, authoring overlays and PMI presentation share the Three Telos WebGPU host with Helios. It owns the camera, grid, mesh drawing, semantic topology lines, GPU leaders, selection projection and GPU resources. A supported browser/GPU is required for that path.
-When WebGPU is unavailable, both products label their temporary WebGL fallback. Cadmata's semantic authoring and PMI views also retain a labelled WebGL path while their annotation/selection adapter is migrated. Full X0 product acceptance is pending that migration.
+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.
-Three Telos supports direct WGSL field artifacts, with a real CIR cylinder/mixed-depth browser smoke witness. Automatic CIR product packet construction and default field rendering are future CIR-DISPLAY-X1B work. The [release report](../release/THREE-TELOS-X0.md) records exact qualification and reproduction commands.
+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.
diff --git a/docs/release/THREE-TELOS-X1.md b/docs/release/THREE-TELOS-X1.md
new file mode 100644
index 00000000..c1e0ec72
--- /dev/null
+++ b/docs/release/THREE-TELOS-X1.md
@@ -0,0 +1,190 @@
+# THREE-TELOS-X1 — Cadmata authoring overlays and PMI
+
+## Result: Success
+
+Cadmata's supported-browser model, assembly, construction overlays and semantic PMI now use one Three Telos graphics authority. The presence of an authoring artifact no longer selects WebGL. React retains application state, semantic correspondence, widgets and callout layout. Telos retains camera matrices, GPU passes, depth, picking and resource lifetime. All new implementation and qualification code is TypeScript. Zero Three patches or forks were added.
+
+The motivating case is the original CADMATA-PMI-X1 CTC-03 manufacturing AP242 STEP, loaded through the actual application import UI and server bridge. Its 173 published entities include 29 semantic callouts: 3 datums, 13 dimensions/diameters, 5 position controls and 8 notes. Default presentation shows 8 datum/position panels. The all-category witness preserves all 29 objects; the unchanged dense-layout policy displays 26 and hides 3 low-priority notes in the measured viewport.
+
+## Remaining WebGL surface audit
+
+The audit found no existing transform gizmo, snap tool, dashed GPU leader or arrowhead to migrate. Whole-part notes use dashed **CSS borders**, not stippled GPU lines. New arrow/dash/font frameworks would therefore invent product behavior.
+
+| Original component / exact owner | Current user-facing purpose | Shared? | Telos equivalent / migration |
+| --- | --- | --- | --- |
+| `aetheris.client/src/viewer/CadmataOverlay.tsx`, `OverlayEntity` | Compiler construction/reference points, circles, planes, guide/profile/region polylines; selectable authoring preview | Cadmata only | Removed. `cadmataOverlays.ts` submits cached sphere/plane mesh data and existing Telos thick lines. Layer contract lives in `cadmataLayers.ts`. Rendering-only fallback copy is `LegacyCadmataOverlay.tsx`. |
+| `aetheris.client/src/viewer/PmiAnnotationLayer.tsx` | Semantic datum, dimension, position and annotation panels, leaders, layout, dragging | Cadmata only; layout reused by fallback | Replaced with DOM buttons projected by TelosCamera and retained Telos leaders. Semantic helpers/content live once in `pmiPresentation.tsx`. Fallback rendering is `LegacyPmiAnnotationLayer.tsx`. |
+| `aetheris.client/src/viewer/LegacyAetherisViewport.tsx`, `AxisGuide` | Reference axes and X/Y/Z text | Cadmata only | Existing Telos axis lines plus projected DOM labels; no Drei text authority in normal mode. |
+| `LegacyAetherisViewport.tsx`, `PickRayCapture`, `CameraFit`, `OrbitControls` | Input rays, fitting, navigation | Cadmata only | Canonical TelosCamera/worldRay and existing Telos navigation; overlay IDs are explicitly dispatched before the server BRep query. |
+| `LegacyAetherisViewport.tsx`, `FaceMesh`, `EdgeLine`, `AssemblyMeshes`, `AdaptiveLogGrid` | Model, topology, occurrence selection, grid | Cadmata only | Already migrated by X0. X1 extends retained draw/proxy updates and preserves these paths. |
+| `aetheris.client/src/viewer/ThemeBackground.tsx` | Shader-driven aesthetic backgrounds in WebGL | Cadmata fallback only | Normal Telos uses X0's theme clear/reference grid. Animated shader background parity remains an inherited X0 aesthetic limit; no authoring/PMI coupling. |
+| Legacy viewport performance globals | Debug-only old-renderer counters | Cadmata fallback only | Telos host metrics and browser qualification JSON; no hidden debug renderer. |
+| `Aetheris.Web.Runtime/telos/src/{host,pick,camera,pipelines}.ts` | Graphics authority | Cadmata and both Helios consumers | Only generic graphics contracts were extended; no CAD models or React state entered Telos. |
+
+## Small shared changes
+
+Existing `TelosMesh` and `TelosLine` cover the graphics inventory. No new primitive family was necessary. Their contracts now expose `depthMode`; meshes may be unlit, and `TelosIdentity.overlayId` carries an opaque product-owned interaction ID.
+
+`TelosHost.beforeFrame` provides one projection cadence after camera matrices update and before GPU drawing. `setDynamicLines` retains a vertex/uniform pair for each stable leader ID and segment count. Updates write those buffers; they do not create geometry or pipelines. Removing an ID releases it. Model scene updates also retain unchanged mesh uniforms, line buffers and CPU picking proxies. Semantic artifacts/geometry arrays remain immutable; genuinely rebuilt geometry replaces its buffers.
+
+All line drawing uses the existing segment-quad shader. Pipeline cache keys normalize equivalent default/explicit depth states, and overlay/model variants share the same shader module. In the CTC-03 all-category measurement, 129 geometry definitions and 26 visible leaders use 574 tracked buffers, **3 pipelines and 2 shader modules**. There is no pipeline per label.
+
+## Coordinates, depth and pass order
+
+| Surface | Coordinates / size | Depth |
+| --- | --- | --- |
+| Construction point | World sphere, existing radius 1.8 | Always on top; unlit |
+| Plane region | Published world origin and u/v basis | Depth tested, unlit alpha 0.12, no depth write |
+| Construction circle/polyline | World coordinates; CSS-pixel line width | Depth biased, no depth write |
+| PMI leader | Published world anchor to a camera-unprojected screen-layout endpoint | Always on top, no depth write |
+| PMI DOM panel | World-anchored, screen-sized, CSS-pixel layout | Always on top; culled outside WebGPU clip depth [0,1] |
+| Axis label | Projected world endpoint, screen-sized DOM text | Always on top; same clip policy |
+
+Pass order is Background → ReferenceGrid → MeshOpaque → Field/CIR → Topology → Overlay → presentation. Overlay mesh drawing precedes authoring lines and dynamic PMI leaders. DOM panels composite above the canvas. There is one canvas renderer, device, camera and authoritative depth target. Simple alpha blending is sufficient; no order-independent transparency was introduced.
+
+The plane adapter now honors the published u/v vectors. The old WebGL plane helper used their lengths while leaving every rectangle in XY. This is a local graphics adapter correction, with a focused non-XY basis test. Circle presentation keeps the current XY authoring convention.
+
+## Text and semantics
+
+The existing callouts were HTML buttons through Drei `Html`. They remain HTML buttons with the same content, categories, classes, theme colors, accessible inspect labels and selected state. This preserves the browser typography and pointer interaction without needing a GPU font renderer. Copeland's existing MSDF/font work is the reuse owner if GPU text becomes necessary; X1 neither reimplements nor unnecessarily imports it.
+
+`semanticPmiItems` and `layoutPmiCallouts` were extracted without replacing their anchor or bounded greedy collision algorithms. Both normal mode and browser fallback consume those single product-owned implementations. Projection/unprojection uses TelosCamera directly; no `THREE.Camera`, R3F context or second RAF loop participates.
+
+Dragging changes a per-session CSS-pixel offset only. It starts from the actual current displaced placement, avoiding the former first-drag jump from zero. Leaders update from the same semantic anchor. The real browser asserts identical GPU buffer and geometry objects across the drag. Offsets remain volatile presentation hints, as before.
+
+Selecting PMI still uses `resolveCadmataSelection` to highlight its published target faces. Geometry-to-PMI visual emphasis uses `indexSemanticInspection`'s published owner/target relationships; it does **not** broaden the selected topology set. The original semantic inspector discovery path remains intact. Hidden category panels/leaders are absent from submission/picking.
+
+CTC-03 anchors come from `CadmataStepSemanticBridge`, not display triangles. The authored projected-hole fixture's `pmi:datum:A`, target `face(+Z)`, published anchor `(20,20,6)` and Face 2 association survive a real fixture compiler rebuild. The migration consumes that existing anchor exactly; refining its geometric intent belongs to the semantic bridge, not the renderer.
+
+## Picking and navigation
+
+DOM labels receive DOM events and stop propagation; pointer capture keeps dragging out of navigation. GPU picks use explicit `overlayId` dispatch, without invisible R3F event geometry.
+
+Priority is deterministic: DOM panels by DOM z-index; then always-on-top authoring meshes, dynamic PMI leaders, construction lines/surfaces, and model geometry. Within equal line priority the nearest ray distance wins; ties keep submission order. Hidden surfaces are excluded; depth-tested lines behind an opaque model face do not steal its pick. Existing thick-line CSS-pixel tolerances are reused. Model clicks retain the canonical world ray and server-owned BRep query, while assembly occurrence selection uses Telos identity.
+
+Existing Telos orbit/pan/wheel navigation still drives the same TelosCamera. Tests cover perspective/orthographic projection, DPR 1/2, camera movement, resizing and a near plane crossing the target region.
+
+## Fallback and dependencies
+
+`AetherisViewport.tsx` has one unsupported-browser fallback boundary. Its legacy viewport is dynamically imported only when `navigator.gpu` is absent. Authoring artifacts and PMI never trigger that branch. Real normal-mode application resource traces contain zero R3F/Drei/legacy viewport requests. GPU initialization/loss errors remain explicit diagnostics rather than silently switching renderers.
+
+R3F/Drei stay installed exclusively for the supported unsupported-browser fallback: `LegacyAetherisViewport.tsx`, `LegacyCadmataOverlay.tsx`, `LegacyPmiAnnotationLayer.tsx`, and the legacy-only `ThemeBackground.tsx`. None is a normal-mode renderer or hidden interaction utility. No non-authoritative R3F helper remains on the normal path. A structural test enforces that import fence. The existing nested `stats-gl` Three 0.170 dependency remains unused legacy dependency metadata; primary Three stays pinned at 0.183.2.
+
+## Real-path qualification
+
+| Check | Evidence |
+| --- | --- |
+| Actual Cadmata import UI | Original CTC-03 manufacturing STEP, server import/semantic bridge, actual App and viewport. Default 8 panels; DIM 13; NOTES 8; filter to exactly 8 notes; orbit/wheel; presentation drag moves exactly +74/-37 CSS pixels at both DPRs; refresh remains Telos. |
+| Ordinary authoring UI | Actual Modeling Demo activation, Create Box 40×30×8, Apply Translation +5 X, server occurrence translation shown, Refresh Display Data. This is the existing experimental product workflow, not a new authoring tool. |
+| Construction preview | Real `construction-plane-positive-x` compiler/API fixture: 10 published construction/profile/guide polylines submitted through the normal wrapper. The canonical fixture encodes its plane as wire geometry; no synthetic weaker replacement model was substituted. |
+| Selection both directions | CTC-03 Datum A selects Face 1; real viewport pixel pick of Face 1 highlights the related Datum A panel through the normal server BRep pick path. |
+| Authored rebuild | `pmi-projected-hole-diameter` fixture compiled twice through the real endpoint; `pmi:datum:A`, `face(+Z)`, anchor and selected Face 2 remain stable. |
+| Resources/performance | Real 29-object PMI model, 20 static and 20 moving-camera GPU-submission-completed frames per DPR. Drag retains all buffer/geometry identities. |
+| CIR plus PMI | X0's qualified direct-WGSL cylinder placed at the existing authored datum world anchor; mesh list is empty; actual DOM datum and retained GPU leader remain visible. This proves graphics independence, not automatic product CIR packet construction or field semantic picking. |
+| Shared substrate regression | X0 browser witness rerun: both mixed mesh/field depth directions, perspective/orthographic, pixel-width lines, shared definitions/shaders, hidden topology picking, resize, disposal and recreate. |
+| Actual Helios viewport | Real WASM compile, top `face(+Z)` selection, orbit, zoom, source rebuild 40→45, stable source selector and fresh SDK build revision; no browser errors/alerts. |
+
+Screenshots are generated/ignored under `artifacts/local/three-telos/x1/`:
+
+- [Actual normal authoring](../../artifacts/local/three-telos/x1/normal-authoring-dpr1.png)
+- [Actual canonical PMI](../../artifacts/local/three-telos/x1/default.png)
+- [Selected datum and face](../../artifacts/local/three-telos/x1/selected.png)
+- [Dragged presentation](../../artifacts/local/three-telos/x1/dragged.png)
+- [Filtered notes](../../artifacts/local/three-telos/x1/filtered.png)
+- [DPR 2 orbit/close zoom](../../artifacts/local/three-telos/x1/zoom-dpr2.png)
+- [29-object dense view](../../artifacts/local/three-telos/x1/all-pmi-dpr2.png)
+- [Construction preview](../../artifacts/local/three-telos/x1/construction-dpr1.png)
+- [Authored datum after rebuild](../../artifacts/local/three-telos/x1/authored-rebuild-dpr1.png)
+- [CIR with semantic PMI](../../artifacts/local/three-telos/x1/cir-pmi-dpr1.png)
+
+Reports: `application-dpr{1,2}.json`, `overlays-dpr{1,2}.json`, plus X0 `browser-report.json` and `helios-wrapper.json`. They distinguish actual App workflow from the real-wrapper/API instrumentation witness.
+
+## Bounded performance
+
+Installed Edge, headless WebGPU, reported adapter vendor `nvidia`, architecture `ampere`; 1100×800 CSS-pixel instrumentation viewport. Each number is from 20 frames including `queue.onSubmittedWorkDone`, not an isolated GPU timer.
+
+| Measure | DPR 1 | DPR 2 |
+| --- | ---: | ---: |
+| Static PMI-heavy completed-frame mean | 3.465 ms | 3.420 ms |
+| Static observed p95 (19th sorted sample) | 4.000 ms | 4.100 ms |
+| Moving camera / relayout completed-frame mean | 3.670 ms | 4.450 ms |
+| Moving projection/layout/submission CPU mean | 0.350 ms | 0.420 ms |
+| Retained dynamic line write CPU mean | 0.050 ms | 0.085 ms |
+
+The static layout signature skips recomputation; zero-duration timer samples mean below timer resolution, not free work. Camera movement and label dragging retain buffers. The all-category scene uses 158 draw submissions, 574 buffers, 3 pipelines and 2 modules. Dense labels keep the inherited collision/de-emphasis policy. No comparable timed old-WebGL capture was made, so these are qualification measurements rather than a claimed speedup.
+
+## Validation
+
+- Telos strict TS build and tests: **7 passed**.
+- Cadmata: **85 passed**, lint clean, production TS/Vite build passed.
+- Actual Helios: **29 passed**, development TS/Vite build passed.
+- Aetherion Helios demo: **26 passed**, development TS/Vite build passed.
+- Frontend/shared unit total: **147 passed**.
+- .NET Release solution build passed; initial rebuild had 10 warnings in existing Firmament/test/WASM files outside this change, and the final incremental build had only 2 existing WASM SQLite warnings. Fast kernel lane: **1,005 passed**. Full serial solution lane: **4,312 passed in 20 suites, zero failed/skipped**.
+- Repository CLI `analyze` ran on the canonical CTC-03 STEP; browser import used the same file and semantic bridge.
+- Helios production AOT SDK bundling is not claimed; the real browser uses the existing development WASM SDK and compiles the real fixture.
+- No kernel/compiler/Copeland/Helios source changes were needed. A corpus test changed only generated STEP line endings; verified and restored. All temporary foreground hosts were stopped after qualification.
+
+## Cleanup and friction owners
+
+The dedicated cleanup extracted shared product-only presentation contracts, removed the obsolete overlay component/barrel, sealed fallback rendering behind a lazy import, retained model/picking resources across props changes, normalized equivalent depth cache states, and reused shader modules across overlay/model passes. Camera projection, line rendering and semantic layout each have one normal-mode owner. No React state or product-specific primitive entered Telos.
+
+| Friction / exposed coupling | X1 repair or bounded disposition | Permanent owner |
+| --- | --- | --- |
+| `useThree` / `useFrame` bound callouts to the renderer camera | TelosCamera direct projection plus `beforeFrame`; no extra loop | Telos camera/frame cadence; Cadmata layout |
+| Drei `Html` mixed DOM content and renderer placement | Keep semantic DOM content; replace only projection/placement | Cadmata presentation; browser typography |
+| Potential new GPU text wheel | No GPU text needed; existing Copeland MSDF remains the future reuse seam | Copeland font/MSDF subsystem if requested |
+| Pointer propagation through R3F groups/lines | Opaque `overlayId`, explicit hit priority and product callback dispatch | Telos graphics picking; Cadmata selection intent |
+| `setScene` rebuilt draw uniforms/line buffers/proxies on ordinary props updates | Retain identity-matched draw resources and immutable CPU geometry | Telos resource lifetime |
+| Callout endpoints move on every orbit/drag | Bounded retained leader buffers, updated on placement changes | Telos line buffers; Cadmata offsets/layout |
+| First drag used zero instead of collision-displaced placement | Capture the actual placement-relative offset | Cadmata presentation |
+| Geometry discovery did not visually emphasize related callouts | Use existing published owner/target index; topology selection stays exact | Cadmata semantic correspondence |
+| Plane helper ignored u/v direction | Emit published world corners; non-XY unit check | Cadmata graphics adapter |
+| Canonical construction fixture publishes wire planes | Test its actual polylines; plane-mesh adapter has focused basis coverage | Compiler fixture contract; no synthetic demo replacement |
+| Repeated default/explicit overlay depth pipeline state | Normalize resolved depth and share mesh/line modules | Telos pipeline cache |
+| Dense labels cannot all fit without overlap | Preserve existing bounded hiding of low-priority notes; use category filters | Cadmata layout policy, not GPU backend |
+| Copied authoritative anchors may be coarse (authored datum z=6) | Consume exactly; no triangle-derived correction | Cadmata semantic bridge / compiler provenance |
+| Suspense changed legacy test timing | Await fallback component loading in its existing wire test | Frontend fallback test |
+| Async qualification loader lint heuristic | Defer asynchronous endpoint loading via promise callback; production path unaffected | Test entry point |
+| Existing .NET WASM/nullable/analyzer and Helios jsdom CSS/chunk warnings | Recorded; no unrelated compiler/UI cleanup | Existing .NET and Helios build owners |
+| Theme animation differs from legacy WebGL | Inherited X0 clear/grid policy, explicitly outside overlay migration | Future Telos aesthetics work if requested |
+
+## Reproduction
+
+From repository root, build Telos and the frontend before building the host. Logs and captures stay under ignored `artifacts/local/three-telos/`.
+
+```powershell
+npm --prefix Aetheris.Web.Runtime/telos test
+npm --prefix Aetheris.Web.Runtime/telos run build:witness
+npm --prefix aetheris.client test
+npm --prefix aetheris.client run lint
+npm --prefix aetheris.client run build
+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
+```
+
+Use temporary **foreground** terminals for the server and Vite; stop each with Ctrl+C after testing:
+
+```powershell
+dotnet Aetheris.Server/bin/Release/net10.0/Cadmata.dll --urls https://localhost:7145
+# In a separate foreground terminal, cwd=aetheris.client:
+$env:AETHERIS_VITE_HTTP='1'
+$env:AETHERIS_TELOS_WITNESS='1'
+npm run dev -- --host 127.0.0.1
+# For actual Helios, cwd=../HeliosCAD:
+npm run dev -- --host 127.0.0.1
+```
+
+With the X0 qualified CIR artifact available (regenerate with `scripts/prepare-three-telos-cir.ps1` if needed):
+
+```powershell
+node scripts/qualify-three-telos-x1.mts ../HeliosCAD/node_modules/playwright/index.mjs
+node scripts/qualify-three-telos-x1.mts ../HeliosCAD/node_modules/playwright/index.mjs 2
+node scripts/qualify-three-telos-x1-overlays.mts ../HeliosCAD/node_modules/playwright/index.mjs
+node scripts/qualify-three-telos-x1-overlays.mts ../HeliosCAD/node_modules/playwright/index.mjs 2
+node scripts/qualify-three-telos-browser.mts ../HeliosCAD/node_modules/playwright/index.mjs
+node scripts/qualify-three-telos-products.mts ../HeliosCAD/node_modules/playwright/index.mjs http://127.0.0.1:5173
+```
+
+X1 leaves no Cadmata renderer migration blocker for CIR-DISPLAY-X1B. That milestone still owns automatic authored-geometry CIR packets/dispatch, broader field qualification and semantic selection proxies. This report claims the existing overlay and PMI behavior over the qualified field, not those future capabilities.
diff --git a/fixtures/three-telos/cadmata-x1.html b/fixtures/three-telos/cadmata-x1.html
new file mode 100644
index 00000000..bef1895a
--- /dev/null
+++ b/fixtures/three-telos/cadmata-x1.html
@@ -0,0 +1,8 @@
+<!doctype html><html lang="en"><meta charset="utf-8"><title>Cadmata Telos X1 qualification</title><div id="root"></div>
+<script type="module">
+import RefreshRuntime from '/@react-refresh';
+RefreshRuntime.injectIntoGlobalHook(window);
+window.$RefreshReg$ = () => {};
+window.$RefreshSig$ = () => (type) => type;
+window.__vite_plugin_react_preamble_installed__ = true;
+</script><script type="module" src="/src/__tests__/telos-x1-witness.tsx"></script></html>
diff --git a/scripts/qualify-three-telos-x1-overlays.mts b/scripts/qualify-three-telos-x1-overlays.mts
new file mode 100644
index 00000000..06b5d5fe
--- /dev/null
+++ b/scripts/qualify-three-telos-x1-overlays.mts
@@ -0,0 +1,396 @@
+import { resolve } from "node:path";
+import { pathToFileURL } from "node:url";
+import { readFile, writeFile } from "node:fs/promises";
+import type {
+ TelosHost,
+ TelosShaderArtifact,
+} from "../Aetheris.Web.Runtime/telos/dist/index.js";
+import type { CadmataVisualizationArtifact } from "../aetheris.client/src/viewer/conceptVisualization.ts";
+declare global {
+ interface Window {
+ cadmataX1: {
+ host: TelosHost;
+ artifact: CadmataVisualizationArtifact;
+ selected: string | null;
+ revision: number;
+ };
+ x1Buffers: Set<GPUBuffer>;
+ x1Geometry: unknown[];
+ }
+}
+const { chromium } = await import(pathToFileURL(resolve(process.argv[2])).href);
+const output = "artifacts/local/three-telos/x1",
+ dpr = Number(process.argv[3] ?? 1);
+const browser = await chromium.launch({
+ executablePath:
+ "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe",
+ headless: true,
+});
+const check = (value: unknown, message: string) => {
+ if (!value) throw new Error(message);
+};
+try {
+ const page = await browser.newPage({
+ viewport: { width: 1450, height: 1000 },
+ deviceScaleFactor: dpr,
+ });
+ const errors: string[] = [];
+ page.on("pageerror", (error: Error) => errors.push(String(error)));
+ await page.goto(
+ "http://127.0.0.1:5173/@fs/" +
+ resolve("fixtures/three-telos/cadmata-x1.html").replaceAll("\\", "/"),
+ );
+ await page.waitForFunction(
+ () => window.cadmataX1?.host && window.cadmataX1.revision > 0,
+ null,
+ { timeout: 120000 },
+ );
+ await page
+ .getByRole("button", { name: "Inspect Datum A", exact: true })
+ .waitFor();
+ await page.getByRole("button", { name: "All PMI", exact: true }).click();
+ await page.waitForTimeout(150);
+ check(
+ (await page.locator("[data-pmi-id]").count()) === 29,
+ "canonical PMI inventory",
+ );
+ const steady = await page.evaluate(async () => {
+ const host = window.cadmataX1.host;
+ host.grid = false;
+ host.render();
+ await host.owner.device.queue.onSubmittedWorkDone();
+ const times: number[] = [],
+ resources = host.owner.resources;
+ window.x1Buffers = new Set(resources.buffers);
+ window.x1Geometry = [...host.geometry.values()];
+ for (let i = 0; i < 20; i++) {
+ const started = performance.now();
+ host.render();
+ await host.owner.device.queue.onSubmittedWorkDone();
+ times.push(performance.now() - started);
+ }
+ return {
+ times,
+ buffers: resources.buffers.size,
+ pipelines: resources.pipelines.size,
+ modules: resources.modules.size,
+ geometry: host.geometry.size,
+ metrics: { ...host.metrics },
+ adapter: {
+ vendor: host.owner.adapter.info.vendor,
+ architecture: host.owner.adapter.info.architecture,
+ description: host.owner.adapter.info.description,
+ },
+ visibleLabels: [
+ ...document.querySelectorAll<HTMLButtonElement>("[data-pmi-id]"),
+ ].filter((element) => element.style.display !== "none").length,
+ retained: [...window.x1Buffers].every((buffer) =>
+ resources.buffers.has(buffer),
+ ),
+ };
+ });
+ check(steady.retained, "steady resources changed");
+ const moving = await page.evaluate(async () => {
+ const host = window.cadmataX1.host;
+ const samples: { frame: number; projection: number; upload: number }[] = [];
+ for (let i = 0; i < 20; i++) {
+ host.camera.position.x += 0.2;
+ const started = performance.now();
+ host.render();
+ await host.owner.device.queue.onSubmittedWorkDone();
+ samples.push({
+ frame: performance.now() - started,
+ projection: host.metrics.overlayUpdateMs,
+ upload: host.metrics.dynamicLineUpdateMs,
+ });
+ }
+ return {
+ samples,
+ retained:
+ window.x1Buffers.size === host.owner.resources.buffers.size &&
+ [...window.x1Buffers].every((buffer) =>
+ host.owner.resources.buffers.has(buffer),
+ ),
+ };
+ });
+ check(moving.retained, "camera-facing updates allocated resources");
+
+ await page.screenshot({ path: output + "/all-pmi-dpr" + dpr + ".png" });
+ await page.getByRole("button", { name: "Default PMI", exact: true }).click();
+ const datum = page.getByRole("button", {
+ name: "Inspect Datum A",
+ exact: true,
+ });
+ await datum.click();
+ await page.waitForTimeout(100);
+ const selection = await page.evaluate(() => {
+ const { host, artifact, selected } = window.cadmataX1;
+ const entity = artifact.entities.find(
+ (entity) => entity.stableId === selected,
+ )!;
+ return {
+ selected,
+ faces: entity.topology?.faceIds,
+ highlighted: host.scene.meshes
+ .filter((mesh) => mesh.selected)
+ .map((mesh) => mesh.identity.faceId),
+ };
+ });
+ check(
+ selection.faces?.every((face: number) =>
+ selection.highlighted.includes(face),
+ ),
+ "PMI to geometry highlight lost",
+ );
+ await page.evaluate(() => {
+ const host = window.cadmataX1.host;
+ host.render();
+ window.x1Buffers = new Set(host.owner.resources.buffers);
+ window.x1Geometry = [...host.geometry.values()];
+ });
+ const box = await datum.boundingBox();
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(
+ box.x + box.width / 2 + 60,
+ box.y + box.height / 2 - 30,
+ { steps: 20 },
+ );
+ await page.mouse.up();
+ await page.waitForTimeout(100);
+ const drag = await page.evaluate(() => {
+ const host = window.cadmataX1.host;
+ return {
+ retained:
+ window.x1Buffers.size === host.owner.resources.buffers.size &&
+ [...window.x1Buffers].every((buffer) =>
+ host.owner.resources.buffers.has(buffer),
+ ),
+ geometryRetained: window.x1Geometry.every((geometry) =>
+ [...host.geometry.values()].includes(geometry as never),
+ ),
+ frames: host.metrics.frames,
+ };
+ });
+ check(drag.retained && drag.geometryRetained, "drag rebuilt GPU resources");
+ await page.screenshot({
+ path: output + "/drag-resources-dpr" + dpr + ".png",
+ });
+ const point = await page.evaluate(() => {
+ const host = window.cadmataX1.host;
+ const labels = [...document.querySelectorAll("[data-pmi-id]")].map(
+ (element) => element.getBoundingClientRect(),
+ );
+ const bounds = host.owner.canvas.getBoundingClientRect();
+ for (let y = 80; y < host.camera.height - 20; y += 12)
+ for (let x = 20; x < host.camera.width - 20; x += 12) {
+ if (
+ labels.some(
+ (rect) =>
+ x + bounds.x >= rect.left &&
+ x + bounds.x <= rect.right &&
+ y + bounds.y >= rect.top &&
+ y + bounds.y <= rect.bottom,
+ )
+ )
+ continue;
+ const hit = host.picker.pick([x, y]);
+ if (!hit?.overlayId && hit?.faceId === 1) return { x, y };
+ }
+ return null;
+ });
+ check(point, "no visible Face 1 pick");
+ await page.locator("canvas").click({ position: point });
+ await page.waitForFunction(
+ () =>
+ window.cadmataX1.artifact.entities.find(
+ (entity) => entity.stableId === window.cadmataX1.selected,
+ )?.kind === "BRepFace",
+ );
+ check(
+ await datum.evaluate((element: HTMLElement) =>
+ element.classList.contains("is-selected"),
+ ),
+ "geometry to related PMI highlight lost",
+ );
+ await page.screenshot({ path: output + "/geometry-pmi-dpr" + dpr + ".png" });
+ const cameras = await page.evaluate(async () => {
+ const host = window.cadmataX1.host,
+ results: unknown[] = [];
+ for (const mode of ["perspective", "orthographic"] as const) {
+ host.camera.mode = mode;
+ host.render();
+ await host.owner.device.queue.onSubmittedWorkDone();
+ results.push({
+ mode,
+ frames: host.metrics.frames,
+ labels: [
+ ...document.querySelectorAll<HTMLButtonElement>("[data-pmi-id]"),
+ ].filter((element) => element.style.display !== "none").length,
+ });
+ }
+ const generation = host.frame.generation;
+ host.resize(900, 650, 2);
+ host.render();
+ results.push({
+ resize: host.frame.generation > generation,
+ width: host.frame.width,
+ height: host.frame.height,
+ });
+ host.camera.near = host.camera.position.distanceTo(host.camera.target);
+ host.render();
+ await host.owner.device.queue.onSubmittedWorkDone();
+ results.push({ closeClip: true, stopped: host.owner.stopped });
+ host.camera.near = 0.01;
+ host.camera.fit([-150, 0, 0], [0, 400, 160]);
+ host.render();
+ return results;
+ });
+ check(
+ !JSON.stringify(cameras).includes('"stopped":true'),
+ "close clipping validation failed",
+ );
+ await page.screenshot({ path: output + "/camera-dpr" + dpr + ".png" });
+ await page.getByRole("button", { name: "Switch model", exact: true }).click();
+ await page.waitForFunction(
+ () =>
+ window.cadmataX1.artifact.fixtureId === "construction-plane-positive-x",
+ );
+ await page.waitForTimeout(200);
+ const construction = await page.evaluate(() => ({
+ meshes: window.cadmataX1.host.scene.meshes
+ .filter((mesh) => mesh.overlay)
+ .map((mesh) => ({ id: mesh.identity.overlayId, depth: mesh.depthMode })),
+ lines: window.cadmataX1.host.scene.lines.filter(
+ (line) => line.identity.overlayId,
+ ).length,
+ }));
+ check(construction.lines > 0, "construction preview not submitted");
+ await page.screenshot({ path: output + "/construction-dpr" + dpr + ".png" });
+ await page.getByRole("button", { name: "Authored PMI", exact: true }).click();
+ await page.waitForFunction(
+ () => window.cadmataX1.artifact.fixtureId === "pmi-projected-hole-diameter",
+ );
+ const authoredDatum = page.getByRole("button", {
+ name: "Inspect A",
+ exact: true,
+ });
+ await authoredDatum.click();
+ await page.waitForTimeout(150);
+ const before = await page.evaluate(() => ({
+ selected: window.cadmataX1.selected,
+ entity: window.cadmataX1.artifact.entities.find(
+ (entity) => entity.stableId === window.cadmataX1.selected,
+ ),
+ revision: window.cadmataX1.revision,
+ }));
+ await page.getByRole("button", { name: "Rebuild", exact: true }).click();
+ await page.waitForFunction(
+ (revision: number) => window.cadmataX1.revision > revision,
+ before.revision,
+ );
+ const after = await page.evaluate(() => ({
+ selected: window.cadmataX1.selected,
+ entity: window.cadmataX1.artifact.entities.find(
+ (entity) => entity.stableId === window.cadmataX1.selected,
+ ),
+ selectedFaces: window.cadmataX1.host.scene.meshes
+ .filter((mesh) => mesh.selected)
+ .map((mesh) => mesh.identity.faceId),
+ }));
+ check(
+ before.selected === after.selected &&
+ JSON.stringify(before.entity?.geometry) ===
+ JSON.stringify(after.entity?.geometry) &&
+ after.selectedFaces.length,
+ "authored face(+Z) datum rebuild anchoring failed",
+ );
+ await page.screenshot({
+ path: output + "/authored-rebuild-dpr" + dpr + ".png",
+ });
+ const artifact = JSON.parse(
+ await readFile("artifacts/local/three-telos/cir/cylinder.json", "utf8"),
+ ) as TelosShaderArtifact;
+ await page.evaluate((artifact: TelosShaderArtifact) => {
+ const { host, artifact: semantic, selected } = window.cadmataX1;
+ const entity = semantic.entities.find(
+ (entity) => entity.stableId === selected,
+ )!;
+ const point =
+ entity.geometry!.type === "polyline"
+ ? entity.geometry!.points.at(-1)!
+ : entity.geometry!.type === "point"
+ ? entity.geometry!.point
+ : entity.geometry!.type === "circle"
+ ? entity.geometry!.center
+ : { x: 0, y: 0, z: 0 };
+ const transform = [
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ point.x,
+ point.y,
+ point.z,
+ 1,
+ ];
+ host.setScene({
+ meshes: [],
+ lines: [],
+ fields: [
+ {
+ artifact,
+ transform,
+ identity: { occurrenceId: "qualified-CIR" },
+ bounds: { minimum: [-0.8, -0.8, -1], maximum: [0.8, 0.8, 1] },
+ material: {
+ baseColor: [0.7, 0.15, 0.06],
+ roughness: 0.6,
+ metallic: 0,
+ opacity: 1,
+ },
+ },
+ ],
+ });
+ host.camera.mode = "orthographic";
+ host.camera.position.set(point.x + 3, point.y + 2, point.z + 4);
+ host.camera.target.set(point.x, point.y, point.z);
+ host.camera.span = 6;
+ host.render();
+ }, artifact);
+ await page.waitForTimeout(150);
+ check(await authoredDatum.isVisible(), "semantic PMI over CIR invisible");
+ await page.screenshot({ path: output + "/cir-pmi-dpr" + dpr + ".png" });
+ const alerts = await page.getByRole("alert").allTextContents();
+ check(!alerts.length && !errors.length, JSON.stringify({ alerts, errors }));
+ const report = {
+ status: "PASS",
+ dpr,
+ steady,
+ moving,
+ selection,
+ drag,
+ geometryToPmi: true,
+ cameras,
+ construction,
+ rebuild: { before, after },
+ cirOverlay: true,
+ errors,
+ alerts,
+ };
+ await writeFile(
+ output + "/overlays-dpr" + dpr + ".json",
+ JSON.stringify(report, null, 2),
+ );
+ console.log(JSON.stringify(report, null, 2));
+} finally {
+ await browser.close();
+}
diff --git a/scripts/qualify-three-telos-x1.mts b/scripts/qualify-three-telos-x1.mts
new file mode 100644
index 00000000..5f952413
--- /dev/null
+++ b/scripts/qualify-three-telos-x1.mts
@@ -0,0 +1,178 @@
+import { resolve } from "node:path";
+import { pathToFileURL } from "node:url";
+import { mkdir, writeFile } from "node:fs/promises";
+const { chromium } = await import(pathToFileURL(resolve(process.argv[2])).href);
+const output = "artifacts/local/three-telos/x1";
+await mkdir(output, { recursive: true });
+const browser = await chromium.launch({
+ executablePath:
+ "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe",
+ headless: true,
+});
+try {
+ const page = await browser.newPage({
+ viewport: { width: 1600, height: 1100 },
+ deviceScaleFactor: Number(process.argv[3] ?? 1),
+ });
+ const errors: string[] = [];
+ let captureCanonical = true;
+ page.on("pageerror", (error: Error) => errors.push(String(error)));
+ page.on(
+ "response",
+ async (response: { url(): string; json(): Promise<unknown> }) => {
+ if (response.url().endsWith("/import/step"))
+ await writeFile(
+ output + "/ctc03-import.json",
+ JSON.stringify(await response.json(), null, 2),
+ );
+ if (captureCanonical && response.url().endsWith("/display/prepare"))
+ await writeFile(
+ output + "/ctc03-display.json",
+ JSON.stringify(await response.json(), null, 2),
+ );
+ },
+ );
+ await page.goto("http://127.0.0.1:5173");
+ 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
+ .getByRole("button", { name: "Inspect Datum A", exact: true })
+ .waitFor({ timeout: 120000 });
+ await page.screenshot({ path: output + "/default.png" });
+ const datum = page.getByRole("button", {
+ name: "Inspect Datum A",
+ exact: true,
+ });
+ await datum.click();
+ await page.waitForFunction(() =>
+ document
+ .querySelector('[aria-label="Inspect Datum A"]')
+ ?.classList.contains("is-selected"),
+ );
+ await page.screenshot({ path: output + "/selected.png" });
+ const before = await datum.boundingBox();
+ await page.mouse.move(
+ before.x + before.width / 2,
+ before.y + before.height / 2,
+ );
+ await page.mouse.down();
+ await page.mouse.move(
+ before.x + before.width / 2 + 74,
+ before.y + before.height / 2 - 37,
+ { steps: 12 },
+ );
+ await page.mouse.up();
+ await page.waitForTimeout(200);
+ const after = await datum.boundingBox();
+ if (
+ Math.abs(after.x - before.x - 74) > 2 ||
+ Math.abs(after.y - before.y + 37) > 2
+ )
+ throw new Error("PMI drag displacement failed");
+ await page.screenshot({ path: output + "/dragged.png" });
+ await page.getByRole("button", { name: "DIM", exact: true }).click();
+ if ((await page.locator(".pmi-callout--dimensions").count()) !== 13)
+ throw new Error("13 dimension inventory lost");
+ await page.getByRole("button", { name: "NOTES", exact: true }).click();
+ if (
+ (await page.locator(".pmi-callout--engineeringAnnotations").count()) !== 8
+ )
+ throw new Error("8 note inventory lost");
+ await page.getByRole("button", { name: "DATUM", exact: true }).click();
+ await page.getByRole("button", { name: "GD&T", exact: true }).click();
+ await page.getByRole("button", { name: "DIM", exact: true }).click();
+ if ((await page.locator("[data-pmi-id]").count()) !== 8)
+ throw new Error("category filtering lost");
+ await page.waitForTimeout(200);
+ await page.screenshot({ path: output + "/filtered.png" });
+ const canvas = page.locator("[data-display-host=three-telos] canvas");
+ const rect = await canvas.boundingBox();
+ await page.mouse.move(rect.x + rect.width * 0.7, rect.y + rect.height * 0.3);
+ await page.mouse.down();
+ await page.mouse.move(
+ rect.x + rect.width * 0.7 + 90,
+ rect.y + rect.height * 0.3 + 30,
+ { steps: 8 },
+ );
+ await page.mouse.up();
+ await page.mouse.wheel(0, -250);
+ await page.waitForTimeout(200);
+ await page.screenshot({
+ path: output + "/zoom-dpr" + (process.argv[3] ?? "1") + ".png",
+ });
+ await page
+ .getByRole("button", { name: "Refresh Display Data", exact: true })
+ .click();
+ await page.waitForTimeout(500);
+ if (await page.locator("[data-display-host=transitional-webgl]").count())
+ throw new Error("authoring selected legacy");
+ const webglRequests = await page.evaluate(() =>
+ performance
+ .getEntriesByType("resource")
+ .map((entry) => entry.name)
+ .filter((name) => /react-three|LegacyAetheris/.test(name)),
+ );
+ if (webglRequests.length)
+ throw new Error("normal authoring loaded fallback graphics");
+ captureCanonical = false;
+ await page.getByRole("button", { name: "New Document", exact: true }).click();
+ await page.getByRole("tab", { name: "Modeling Demo (Experimental)" }).click();
+ await page.getByLabel("Width", { exact: true }).fill("40");
+ await page.getByLabel("Height", { exact: true }).fill("30");
+ await page.getByLabel("Depth", { exact: true }).fill("8");
+ await page.getByRole("button", { name: "Create Box", exact: true }).click();
+ await page
+ .getByRole("button", { name: "Apply Translation", exact: true })
+ .waitFor();
+
+ await page.getByLabel("X", { exact: true }).fill("5");
+ await page
+ .getByRole("button", { name: "Apply Translation", exact: true })
+ .click();
+ await page.getByRole("button", { name: /t=\[5.00, 0.00, 0.00\]/ }).waitFor();
+ const picked = page.waitForResponse((response: { url(): string }) => response.url().endsWith('/pick'));
+ await canvas.click({ position: { x: rect.width / 2, y: rect.height / 2 } });
+ const hit = (await (await picked).json()).data.hits[0];
+ if (!hit || hit.entityKind !== 'Face') throw new Error('normal modeling pick failed');
+
+ await page
+ .getByRole("button", { name: "Refresh Display Data", exact: true })
+ .click();
+ await page.waitForTimeout(250);
+ await page.screenshot({
+ path: output + "/normal-authoring-dpr" + (process.argv[3] ?? "1") + ".png",
+ });
+ const report = {
+ status: "PASS",
+ scope:
+ "actual Cadmata application; ordinary canonical CADMATA-PMI-X1 STEP import",
+ dpr: Number(process.argv[3] ?? 1),
+ normalAuthoring:
+ "actual Create Box / Apply Translation / face selection / Refresh Display Data",
+ modelingHit: { entityKind: hit.entityKind, faceId: hit.faceId },
+ defaultPmi: 8,
+ dimensions: 13,
+ notes: 8,
+ drag: { before, after },
+ errors,
+ webglRequests,
+ };
+ if (errors.length || (await page.getByRole("alert").count()))
+ throw new Error(JSON.stringify(errors));
+ await writeFile(
+ output + "/application-dpr" + (process.argv[3] ?? "1") + ".json",
+ JSON.stringify(report, null, 2),
+ );
+ console.log(JSON.stringify(report, null, 2));
+} finally {
+ await browser.close();
+}