Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Consolidate factory scene authoring and validation

Yuechen Lidf1a30e9e64f
diff --git a/Aetheris.Web.Runtime/telos/.gitignore b/Aetheris.Web.Runtime/telos/.gitignore
new file mode 100644
index 00000000..b9470778
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/.gitignore
@@ -0,0 +1,2 @@
+node_modules/
+dist/
diff --git a/Aetheris.Web.Runtime/telos/README.md b/Aetheris.Web.Runtime/telos/README.md
new file mode 100644
index 00000000..15211843
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/README.md
@@ -0,0 +1,7 @@
+# Three Telos
+
+Three Telos is an engineering display layer that 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.
+
+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.
diff --git a/Aetheris.Web.Runtime/telos/package-lock.json b/Aetheris.Web.Runtime/telos/package-lock.json
new file mode 100644
index 00000000..122a8f68
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/package-lock.json
@@ -0,0 +1,116 @@
+{
+ "name": "@aetheris/three-telos",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@aetheris/three-telos",
+ "version": "0.1.0",
+ "license": "AGPL-3.0-only",
+ "dependencies": {
+ "@types/three": "0.183.1",
+ "@webgpu/types": "0.1.69",
+ "three": "0.183.2"
+ },
+ "devDependencies": {
+ "@types/node": "24.10.1",
+ "typescript": "~5.9.3"
+ }
+ },
+ "node_modules/@dimforge/rapier3d-compat": {
+ "version": "0.12.0",
+ "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz",
+ "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/@tweenjs/tween.js": {
+ "version": "23.1.3",
+ "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",
+ "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "24.10.1",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.1.tgz",
+ "integrity": "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~7.16.0"
+ }
+ },
+ "node_modules/@types/stats.js": {
+ "version": "0.17.4",
+ "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz",
+ "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==",
+ "license": "MIT"
+ },
+ "node_modules/@types/three": {
+ "version": "0.183.1",
+ "resolved": "https://registry.npmjs.org/@types/three/-/three-0.183.1.tgz",
+ "integrity": "sha512-f2Pu5Hrepfgavttdye3PsH5RWyY/AvdZQwIVhrc4uNtvF7nOWJacQKcoVJn0S4f0yYbmAE6AR+ve7xDcuYtMGw==",
+ "license": "MIT",
+ "dependencies": {
+ "@dimforge/rapier3d-compat": "~0.12.0",
+ "@tweenjs/tween.js": "~23.1.3",
+ "@types/stats.js": "*",
+ "@types/webxr": ">=0.5.17",
+ "@webgpu/types": "*",
+ "fflate": "~0.8.2",
+ "meshoptimizer": "~1.0.1"
+ }
+ },
+ "node_modules/@types/webxr": {
+ "version": "0.5.24",
+ "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz",
+ "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==",
+ "license": "MIT"
+ },
+ "node_modules/@webgpu/types": {
+ "version": "0.1.69",
+ "resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.69.tgz",
+ "integrity": "sha512-RPmm6kgRbI8e98zSD3RVACvnuktIja5+yLgDAkTmxLr90BEwdTXRQWNLF3ETTTyH/8mKhznZuN5AveXYFEsMGQ==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/fflate": {
+ "version": "0.8.3",
+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
+ "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
+ "license": "MIT"
+ },
+ "node_modules/meshoptimizer": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.0.1.tgz",
+ "integrity": "sha512-Vix+QlA1YYT3FwmBBZ+49cE5y/b+pRrcXKqGpS5ouh33d3lSp2PoTpCw19E0cKDFWalembrHnIaZetf27a+W2g==",
+ "license": "MIT"
+ },
+ "node_modules/three": {
+ "version": "0.183.2",
+ "resolved": "https://registry.npmjs.org/three/-/three-0.183.2.tgz",
+ "integrity": "sha512-di3BsL2FEQ1PA7Hcvn4fyJOlxRRgFYBpMTcyOgkwJIaDOdJMebEFPA+t98EvjuljDx4hNulAGwF6KIjtwI5jgQ==",
+ "license": "MIT"
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz",
+ "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==",
+ "dev": true,
+ "license": "MIT"
+ }
+ }
+}
diff --git a/Aetheris.Web.Runtime/telos/package.json b/Aetheris.Web.Runtime/telos/package.json
new file mode 100644
index 00000000..9351b7e9
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/package.json
@@ -0,0 +1,32 @@
+{
+ "name": "@aetheris/three-telos",
+ "version": "0.1.0",
+ "type": "module",
+ "description": "Shared engineering WebGPU display substrate",
+ "license": "AGPL-3.0-only",
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js"
+ }
+ },
+ "files": [
+ "dist",
+ "src",
+ "README.md"
+ ],
+ "dependencies": {
+ "@types/three": "0.183.1",
+ "@webgpu/types": "0.1.69",
+ "three": "0.183.2"
+ },
+ "devDependencies": {
+ "@types/node": "24.10.1",
+ "typescript": "~5.9.3"
+ },
+ "scripts": {
+ "build": "tsc",
+ "test": "npm run build && tsc -p tsconfig.tests.json && node --test tests/*.test.ts",
+ "build:witness": "tsc -p tsconfig.browser.json"
+ }
+}
diff --git a/Aetheris.Web.Runtime/telos/src/adapters.ts b/Aetheris.Web.Runtime/telos/src/adapters.ts
new file mode 100644
index 00000000..1ca80a42
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/src/adapters.ts
@@ -0,0 +1,116 @@
+import { Matrix4, Color } from "three";
+import type { Object3D, Mesh, MeshStandardMaterial } from "three";
+import type {
+ TelosIdentity,
+ TelosScene,
+ TelosMesh,
+ TelosLine,
+ DisplayPacket,
+ TelosMaterial,
+} from "./contracts.js";
+
+export const identityTransform = () => new Matrix4().elements;
+/** Clear colors are display encoded; mesh material colors are linear lighting inputs. */
+export const clearColor = (color: string | number): [number, number, number, number] => {
+ const encoded = new Color(color).convertLinearToSRGB();
+ return [encoded.r, encoded.g, encoded.b, 1];
+};
+export function materialFromAppearance(
+ appearance: {
+ baseColor?: string | number | readonly number[];
+ color?: string | number;
+ roughness?: number;
+ metallic?: number;
+ metalness?: number;
+ opacity?: number;
+ } = {},
+): TelosMaterial {
+ const color = appearance.baseColor ?? appearance.color ?? "#b8beb3";
+ return {
+ baseColor:
+ typeof color === "string" || typeof color === "number"
+ ? new Color(color).toArray()
+ : Array.from(color),
+ roughness: appearance.roughness ?? 0.62,
+ metallic: appearance.metallic ?? appearance.metalness ?? 0.15,
+ opacity: appearance.opacity ?? 1,
+ };
+}
+/** SDK display packets retain definition/occurrence/topology authority. No tessellation-derived edges. */
+export function fromDisplayMesh(
+ packet: DisplayPacket,
+ appearance?: Parameters<typeof materialFromAppearance>[0],
+): TelosScene {
+ const definitions = new Map(
+ packet.definitions.map((definition) => [definition.id, definition]),
+ );
+ const meshes: TelosMesh[] = [],
+ lines: TelosLine[] = [];
+ for (const occurrence of packet.occurrences) {
+ const definition = occurrence.definitionId
+ ? definitions.get(occurrence.definitionId)
+ : undefined;
+ if (!definition) continue;
+ const identity = {
+ occurrenceId: occurrence.id,
+ bodyId: occurrence.semanticEntityId,
+ definitionId: definition.id,
+ };
+ meshes.push({
+ definition,
+ identity,
+ transform: occurrence.transform,
+ material: materialFromAppearance(appearance),
+ });
+ for (const edge of definition.edges ?? []) {
+ const points = edge.points.flatMap((point) => Array.from(point));
+ if (edge.closed && edge.points.length > 2) points.push(...edge.points[0]);
+ lines.push({
+ id: definition.id + ":" + edge.edgeId,
+ points,
+ transform: occurrence.transform,
+ widthPixels: 1.2,
+ color: [0.15, 0.18, 0.16, 1],
+ identity: { ...identity, edgeId: edge.edgeId },
+ });
+ }
+ }
+ return { meshes, lines, fields: [] };
+}
+/** Three hierarchy is an input, never Telos scene storage or renderer state. */
+export function fromThree(
+ root: Object3D,
+ identityFor: (object: Object3D) => TelosIdentity,
+): TelosScene {
+ root.updateMatrixWorld(true);
+ const meshes: TelosMesh[] = [];
+ root.traverse((object) => {
+ if (!(object as Mesh).isMesh) return;
+ const mesh = object as Mesh;
+ if (Array.isArray(mesh.material))
+ throw new Error("telos-three-multiple-materials-unqualified");
+ const material = mesh.material as MeshStandardMaterial;
+ const geometry = mesh.geometry;
+ if (!geometry.getAttribute("normal")) geometry.computeVertexNormals();
+ const positions = geometry.getAttribute("position").array;
+ meshes.push({
+ definition: {
+ id: geometry.uuid,
+ positions,
+ normals: geometry.getAttribute("normal").array,
+ indices:
+ geometry.index?.array ??
+ Uint32Array.from({ length: positions.length / 3 }, (_, i) => i),
+ },
+ transform: object.matrixWorld.toArray(),
+ identity: identityFor(object),
+ material: materialFromAppearance({
+ baseColor: material.color?.toArray(),
+ roughness: material.roughness,
+ metallic: material.metalness,
+ opacity: material.opacity,
+ }),
+ });
+ });
+ return { meshes, lines: [], fields: [] };
+}
diff --git a/Aetheris.Web.Runtime/telos/src/camera.ts b/Aetheris.Web.Runtime/telos/src/camera.ts
new file mode 100644
index 00000000..c11b5921
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/src/camera.ts
@@ -0,0 +1,141 @@
+import {
+ Matrix4,
+ Vector3,
+ Quaternion,
+ WebGPUCoordinateSystem,
+ PerspectiveCamera,
+ OrthographicCamera,
+} from "three";
+import type { NumericArray, Pixel } from "./contracts.js";
+
+/** Column-major matrices; right-handed world; WebGPU clip depth [0,1]. Pixels are CSS pixels. */
+export class TelosCamera {
+ position: Vector3;
+ target: Vector3;
+ up: Vector3;
+ mode: "perspective" | "orthographic";
+ fov: number;
+ span: number;
+ near: number;
+ far: number;
+ width: number;
+ height: number;
+ view: Matrix4;
+ inverseView: Matrix4;
+ projection: Matrix4;
+ inverseProjection: Matrix4;
+ viewProjection: Matrix4;
+ inverseViewProjection: Matrix4;
+ constructor() {
+ this.position = new Vector3(4, 3, 5);
+ this.target = new Vector3();
+ this.up = new Vector3(0, 1, 0);
+ this.mode = "perspective";
+ this.fov = 35;
+ this.span = 5;
+ this.near = 0.01;
+ this.far = 10000;
+ this.width = 1;
+ this.height = 1;
+ this.view = new Matrix4();
+ this.inverseView = new Matrix4();
+ this.projection = new Matrix4();
+ this.inverseProjection = new Matrix4();
+ this.viewProjection = new Matrix4();
+ this.inverseViewProjection = new Matrix4();
+ this.update();
+ }
+ resize(width: number, height: number) {
+ this.width = Math.max(1, width);
+ this.height = Math.max(1, height);
+ this.update();
+ }
+ update() {
+ if (!(this.near > 0 && this.far > this.near && this.span > 0))
+ throw new Error("telos-camera-clipping-invalid");
+ const rotation = new Matrix4().lookAt(this.position, this.target, this.up);
+ this.inverseView.compose(
+ this.position,
+ new Quaternion().setFromRotationMatrix(rotation),
+ new Vector3(1, 1, 1),
+ );
+ this.view.copy(this.inverseView).invert();
+ const aspect = this.width / this.height;
+ if (this.mode === "orthographic") {
+ const h = this.span / 2;
+ this.projection.makeOrthographic(
+ -h * aspect,
+ h * aspect,
+ h,
+ -h,
+ this.near,
+ this.far,
+ WebGPUCoordinateSystem,
+ );
+ } else {
+ const h = this.near * Math.tan((this.fov * Math.PI) / 360);
+ this.projection.makePerspective(
+ -h * aspect,
+ h * aspect,
+ h,
+ -h,
+ this.near,
+ this.far,
+ WebGPUCoordinateSystem,
+ );
+ }
+ this.inverseProjection.copy(this.projection).invert();
+ this.viewProjection.multiplyMatrices(this.projection, this.view);
+ this.inverseViewProjection.copy(this.viewProjection).invert();
+ }
+ project(point: NumericArray) {
+ const p = new Vector3(point[0], point[1], point[2]).applyMatrix4(
+ this.viewProjection,
+ );
+ return [((p.x + 1) * this.width) / 2, ((1 - p.y) * this.height) / 2, p.z];
+ }
+ unproject(pixel: Pixel, depth: number) {
+ return new Vector3(
+ (pixel[0] / this.width) * 2 - 1,
+ 1 - (pixel[1] / this.height) * 2,
+ depth,
+ ).applyMatrix4(this.inverseViewProjection);
+ }
+ worldRay(pixel: Pixel) {
+ const origin = this.unproject(pixel, 0),
+ end = this.unproject(pixel, 1);
+ return { origin, direction: end.clone().sub(origin).normalize() };
+ }
+ fit(minimum: NumericArray, maximum: NumericArray) {
+ const min = new Vector3(minimum[0], minimum[1], minimum[2]),
+ max = new Vector3(maximum[0], maximum[1], maximum[2]);
+ if (
+ ![...Array.from(minimum), ...Array.from(maximum)].every(Number.isFinite)
+ )
+ return;
+ this.target.copy(min).add(max).multiplyScalar(0.5);
+ const radius = Math.max(max.distanceTo(min) / 2, 1e-5);
+ const distance = (radius / Math.sin((this.fov * Math.PI) / 360)) * 1.2;
+ this.position
+ .copy(this.target)
+ .add(new Vector3(1, 0.8, 1).normalize().multiplyScalar(distance));
+ this.span = radius * 2.5;
+ this.near = Math.max(radius * 1e-4, 1e-8);
+ this.far = distance + radius * 20;
+ this.update();
+ }
+ /** Output-only compatibility state. Changes to the adapter never change Telos. */
+ toThree() {
+ const camera =
+ this.mode === "orthographic"
+ ? new OrthographicCamera()
+ : new PerspectiveCamera();
+ camera.matrixAutoUpdate = false;
+ camera.matrixWorld.copy(this.inverseView);
+ camera.matrixWorldInverse.copy(this.view);
+ camera.projectionMatrix.copy(this.projection);
+ camera.projectionMatrixInverse.copy(this.inverseProjection);
+ camera.position.copy(this.position);
+ return camera;
+ }
+}
diff --git a/Aetheris.Web.Runtime/telos/src/contracts.ts b/Aetheris.Web.Runtime/telos/src/contracts.ts
new file mode 100644
index 00000000..99ed5c03
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/src/contracts.ts
@@ -0,0 +1,99 @@
+export type Vec3 = readonly [number, number, number];
+export type Pixel = readonly [number, number];
+export type NumericArray = ArrayLike<number>;
+export interface TelosIdentity {
+ occurrenceId: string;
+ bodyId?: string;
+ definitionId?: string;
+ faceId?: string | number;
+ edgeId?: string | number;
+}
+export interface TelosMaterial {
+ baseColor: readonly number[];
+ roughness: number;
+ metallic: number;
+ opacity: number;
+}
+export interface MeshRange {
+ startTriangle: number;
+ triangleCount: number;
+ faceId: string | number;
+}
+export interface TelosGeometry {
+ id: string;
+ positions: NumericArray;
+ normals: NumericArray;
+ indices: NumericArray;
+ ranges?: readonly MeshRange[];
+}
+export interface TelosMesh {
+ definition: TelosGeometry;
+ identity: TelosIdentity;
+ transform?: NumericArray;
+ material: TelosMaterial;
+ selected?: boolean;
+ hovered?: boolean;
+ overlay?: boolean;
+ visible?: boolean;
+}
+export interface TelosLine {
+ id: string;
+ points: NumericArray;
+ identity: TelosIdentity;
+ transform?: NumericArray;
+ widthPixels?: number;
+ color?: readonly number[];
+ selected?: boolean;
+ overlay?: boolean;
+ visible?: boolean;
+}
+export interface TelosShaderArtifact {
+ shaderId: string;
+ wgsl: string;
+ vertexEntryPoint: string;
+ fragmentEntryPoint: string;
+ bindings: readonly {
+ group: number;
+ binding: number;
+ kind: "uniform";
+ byteSize: number;
+ }[];
+ capabilities: readonly string[];
+ sourceIdentity: string;
+}
+/** X0 field ABI: clip, local near/delta, depth/w rows, epsilon; canonical 32-byte tint/roughness uniform. Rigid occurrences only. */
+export interface TelosField {
+ artifact: TelosShaderArtifact;
+ identity: TelosIdentity;
+ bounds: { minimum: Vec3; maximum: Vec3 };
+ transform?: NumericArray;
+ material: TelosMaterial;
+ proxy?: TelosGeometry;
+ selected?: boolean;
+}
+export interface TelosScene {
+ meshes: readonly TelosMesh[];
+ lines: readonly TelosLine[];
+ fields: readonly TelosField[];
+}
+export interface TelosHit extends TelosIdentity {
+ triangleIndex?: number;
+ worldPosition: number[];
+ worldNormal: number[] | null;
+ distance: number;
+}
+export interface DisplayPacket {
+ definitions: readonly (TelosGeometry & {
+ edges?: readonly {
+ edgeId: string;
+ points: readonly (readonly number[])[];
+ closed: boolean;
+ }[];
+ })[];
+ occurrences: readonly {
+ id: string;
+ definitionId?: string;
+ semanticEntityId: string;
+ transform: NumericArray;
+ }[];
+}
diff --git a/Aetheris.Web.Runtime/telos/src/device.ts b/Aetheris.Web.Runtime/telos/src/device.ts
new file mode 100644
index 00000000..6858311d
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/src/device.ts
@@ -0,0 +1,206 @@
+export class TelosResources {
+ device: GPUDevice;
+ buffers: Set<GPUBuffer>;
+ textures: Set<GPUTexture>;
+ modules: Map<string, { module: GPUShaderModule; code: string }>;
+ pipelines: Map<string, GPURenderPipeline>;
+ constructor(device: GPUDevice) {
+ this.device = device;
+ this.buffers = new Set();
+ this.textures = new Set();
+ this.modules = new Map();
+ this.pipelines = new Map();
+ }
+ buffer(
+ data: Float32Array<ArrayBuffer> | Uint32Array<ArrayBuffer>,
+ usage: GPUBufferUsageFlags,
+ ) {
+ const buffer = this.device.createBuffer({
+ size: Math.max(4, Math.ceil(data.byteLength / 4) * 4),
+ usage: usage | GPUBufferUsage.COPY_DST,
+ });
+ this.device.queue.writeBuffer(buffer, 0, data);
+ this.buffers.add(buffer);
+ return buffer;
+ }
+ texture(descriptor: GPUTextureDescriptor) {
+ const texture = this.device.createTexture(descriptor);
+ this.textures.add(texture);
+ return texture;
+ }
+ release(resource: GPUBuffer | GPUTexture) {
+ resource.destroy();
+ if ("mapAsync" in resource) this.buffers.delete(resource);
+ else this.textures.delete(resource);
+ }
+ module(id: string, code: string) {
+ const previous = this.modules.get(id);
+ if (previous && previous.code !== code)
+ throw new Error("telos-shader-identity-collision: " + id);
+ if (previous) return previous.module;
+ const module = this.device.createShaderModule({ label: id, code });
+ this.modules.set(id, { module, code });
+ return module;
+ }
+ pipeline(key: string, create: () => GPURenderPipeline): GPURenderPipeline {
+ if (!this.pipelines.has(key)) this.pipelines.set(key, create());
+ return this.pipelines.get(key)!;
+ }
+ dispose() {
+ for (const resource of [...this.buffers, ...this.textures])
+ resource.destroy();
+ this.buffers.clear();
+ this.textures.clear();
+ this.modules.clear();
+ this.pipelines.clear();
+ }
+}
+
+export class TelosDevice {
+ adapter: GPUAdapter;
+ device: GPUDevice;
+ context: GPUCanvasContext;
+ canvas: HTMLCanvasElement;
+ diagnostic: (message: string) => void;
+ format: GPUTextureFormat;
+ resources: TelosResources;
+ capabilities: { features: string[]; limits: GPUSupportedLimits };
+ stopped: boolean;
+ onLost?: () => void;
+ onError: (event: GPUUncapturedErrorEvent) => void;
+ static async create(
+ canvas: HTMLCanvasElement,
+ diagnostic: (message: string) => void = () => {},
+ ) {
+ if (!navigator.gpu)
+ throw new Error(
+ "telos-webgpu-unavailable: use a WebGPU-capable browser.",
+ );
+ const adapter = await navigator.gpu.requestAdapter();
+ if (!adapter) throw new Error("telos-adapter-unavailable");
+ const device = await adapter.requestDevice();
+ const context = canvas.getContext("webgpu");
+ if (!context) {
+ device.destroy();
+ throw new Error("telos-context-unavailable");
+ }
+ return new TelosDevice(adapter, device, context, canvas, diagnostic);
+ }
+ constructor(
+ adapter: GPUAdapter,
+ device: GPUDevice,
+ context: GPUCanvasContext,
+ canvas: HTMLCanvasElement,
+ diagnostic: (message: string) => void,
+ ) {
+ this.adapter = adapter;
+ this.device = device;
+ this.context = context;
+ this.canvas = canvas;
+ this.diagnostic = diagnostic;
+ this.format = navigator.gpu.getPreferredCanvasFormat();
+ this.resources = new TelosResources(device);
+ this.capabilities = {
+ features: [...device.features],
+ limits: device.limits,
+ };
+ this.stopped = false;
+ context.configure({
+ device,
+ format: this.format,
+ alphaMode: "opaque",
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
+ });
+ device.lost.then((info) => {
+ this.stopped = true;
+ if (info.reason !== "destroyed")
+ diagnostic("telos-device-lost: " + info.message);
+ this.onLost?.();
+ });
+ this.onError = (event) => {
+ diagnostic("telos-gpu-validation: " + event.error.message);
+ this.stopped = true;
+ this.onLost?.();
+ };
+ device.addEventListener("uncapturederror", this.onError);
+ }
+ dispose() {
+ this.stopped = true;
+ this.resources.dispose();
+ this.context.unconfigure();
+ this.device.removeEventListener("uncapturederror", this.onError);
+ this.device.destroy();
+ }
+}
+
+/** Single sample, depth32float, clear=1, less; every drawing pass loads/stores this target. */
+export class TelosFrame {
+ owner: TelosDevice;
+ depth: GPUTexture | null;
+ depthView!: GPUTextureView;
+ colorView!: GPUTextureView;
+ target!: GPUTexture;
+ encoder!: GPUCommandEncoder;
+ width: number;
+ height: number;
+ generation: number;
+ dpr = 1;
+ constructor(owner: TelosDevice) {
+ this.owner = owner;
+ this.depth = null;
+ this.width = 0;
+ this.height = 0;
+ this.generation = 0;
+ }
+ resize(width: number, height: number, dpr = 1) {
+ this.dpr = Math.max(0.25, dpr);
+ const limit = this.owner.device.limits.maxTextureDimension2D;
+ const w = Math.min(limit, Math.max(1, Math.round(width * this.dpr))),
+ h = Math.min(limit, Math.max(1, Math.round(height * this.dpr)));
+ if (this.width === w && this.height === h) return;
+ if (this.depth) this.owner.resources.release(this.depth);
+ this.owner.canvas.width = this.width = w;
+ this.owner.canvas.height = this.height = h;
+ this.depth = this.owner.resources.texture({
+ label: "Telos authoritative depth",
+ size: [w, h],
+ format: "depth32float",
+ usage: GPUTextureUsage.RENDER_ATTACHMENT,
+ });
+ this.depthView = this.depth.createView();
+ this.generation++;
+ }
+ begin(background: GPUColor) {
+ this.target = this.owner.context.getCurrentTexture();
+ this.colorView = this.target.createView();
+ this.encoder = this.owner.device.createCommandEncoder();
+ const pass = this.pass("Background", true, background);
+ pass.end();
+ }
+ pass(label: string, clear = false, background: GPUColor = [0, 0, 0, 1]) {
+ return this.encoder.beginRenderPass({
+ label,
+ colorAttachments: [
+ {
+ view: this.colorView,
+ clearValue: background,
+ loadOp: clear ? "clear" : "load",
+ storeOp: "store",
+ },
+ ],
+ depthStencilAttachment: {
+ view: this.depthView,
+ depthClearValue: 1,
+ depthLoadOp: clear ? "clear" : "load",
+ depthStoreOp: "store",
+ },
+ });
+ }
+ end() {
+ this.owner.device.queue.submit([this.encoder.finish()]);
+ }
+ dispose() {
+ if (this.depth) this.owner.resources.release(this.depth);
+ this.depth = null;
+ }
+}
diff --git a/Aetheris.Web.Runtime/telos/src/host.ts b/Aetheris.Web.Runtime/telos/src/host.ts
new file mode 100644
index 00000000..578df046
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/src/host.ts
@@ -0,0 +1,562 @@
+import { Matrix4, Vector3, Box3 } from "three";
+import { TelosCamera } from "./camera.js";
+import { TelosDevice, TelosFrame } from "./device.js";
+import { TelosPick } from "./pick.js";
+import { attachNavigation } from "./navigation.js";
+import { telosPipeline } from "./pipelines.js";
+import type {
+ TelosScene,
+ TelosMesh,
+ TelosLine,
+ TelosField,
+ TelosGeometry,
+ NumericArray,
+} from "./contracts.js";
+
+type GeometryBuffers = {
+ definition: TelosGeometry;
+ positions: GPUBuffer;
+ normals: GPUBuffer;
+ indices: GPUBuffer;
+ count: number;
+};
+type Draw<T> = {
+ item: T;
+ uniform: GPUBuffer;
+ binding: GPUBindGroup;
+ pipeline: GPURenderPipeline;
+ vertices?: GPUBuffer;
+ geometry?: GeometryBuffers;
+ count: number;
+};
+const emptyScene = (): TelosScene => ({ meshes: [], lines: [], fields: [] });
+const matrix = (values?: NumericArray) =>
+ values ? new Matrix4().fromArray(values) : new Matrix4();
+
+export class TelosHost {
+ readonly camera = new TelosCamera();
+ readonly picker = new TelosPick(this.camera);
+ readonly frame: TelosFrame;
+ scene = emptyScene();
+ background: GPUColor = [0.08, 0.1, 0.09, 1];
+ grid = false;
+ gridPlane: "xy" | "xz" = "xz";
+ readonly geometry = new Map<string, GeometryBuffers>();
+ private meshes: Draw<TelosMesh>[] = [];
+ private lines: Draw<TelosLine>[] = [];
+ private fields: Draw<TelosField>[] = [];
+ private gridDraw?: Draw<TelosLine>;
+ private gridKey = "";
+ private raf = 0;
+ private disposed = false;
+ private detach?: () => void;
+ private observer?: ResizeObserver;
+ metrics = {
+ meshUploadMs: 0,
+ lineUploadMs: 0,
+ fieldPipelineMs: 0,
+ frameMs: 0,
+ frames: 0,
+ draws: 0,
+ };
+ static async create(
+ canvas: HTMLCanvasElement,
+ diagnostic?: (message: string) => void,
+ ) {
+ const owner = await TelosDevice.create(canvas, diagnostic);
+ return new TelosHost(owner);
+ }
+ constructor(readonly owner: TelosDevice) {
+ this.frame = new TelosFrame(owner);
+ this.frame.resize(1, 1);
+ owner.onLost = () => {
+ cancelAnimationFrame(this.raf);
+ this.raf = 0;
+ };
+ }
+ /** A product supplies DOM inputs; all GPU sizing and scheduling stay here. */
+ attach(container: HTMLElement) {
+ this.detach?.();
+ this.observer?.disconnect();
+ this.detach = attachNavigation(this.owner.canvas, this.camera, () =>
+ this.invalidate(),
+ );
+ this.observer = new ResizeObserver(() => this.invalidate());
+ this.observer.observe(container);
+ this.invalidate();
+ }
+ resize(width: number, height: number, dpr = 1) {
+ this.camera.resize(width, height);
+ this.frame.resize(width, height, dpr);
+ }
+ invalidate() {
+ if (this.disposed || this.owner.stopped || this.raf) return;
+ this.raf = requestAnimationFrame(() => {
+ this.raf = 0;
+ try {
+ const canvas = this.owner.canvas;
+ this.resize(
+ canvas.clientWidth || this.camera.width,
+ canvas.clientHeight || this.camera.height,
+ globalThis.devicePixelRatio || 1,
+ );
+ this.render();
+ } catch (error) {
+ this.owner.diagnostic(String(error));
+ this.owner.stopped = true;
+ }
+ });
+ }
+ private draw<T>(
+ item: T,
+ pipeline: GPURenderPipeline,
+ bytes: number,
+ count: number,
+ ): Draw<T> {
+ const uniform = this.owner.resources.buffer(
+ new Float32Array(bytes / 4),
+ GPUBufferUsage.UNIFORM,
+ );
+ const binding = this.owner.device.createBindGroup({
+ layout: pipeline.getBindGroupLayout(0),
+ entries: [{ binding: 0, resource: { buffer: uniform } }],
+ });
+ return { item, pipeline, uniform, binding, count };
+ }
+ setScene(scene: TelosScene) {
+ this.releaseDraws();
+ this.scene = scene;
+ const resources = this.owner.resources,
+ used = new Set<string>();
+ const start = performance.now();
+ for (const item of scene.meshes) {
+ const definition = item.definition;
+ const repeated = used.has(definition.id);
+ used.add(definition.id);
+ let geometry = this.geometry.get(definition.id);
+ if (
+ geometry &&
+ (geometry.definition.positions !== definition.positions ||
+ geometry.definition.indices !== definition.indices ||
+ geometry.definition.normals !== definition.normals)
+ ) {
+ if (repeated) throw new Error('telos-definition-identity-collision: ' + definition.id);
+ this.releaseGeometry(geometry);
+ this.geometry.delete(definition.id);
+ geometry = undefined;
+ }
+ if (!geometry) {
+ geometry = {
+ definition,
+ positions: resources.buffer(
+ Float32Array.from(definition.positions),
+ GPUBufferUsage.VERTEX,
+ ),
+ normals: resources.buffer(
+ Float32Array.from(definition.normals),
+ GPUBufferUsage.VERTEX,
+ ),
+ indices: resources.buffer(
+ Uint32Array.from(definition.indices),
+ GPUBufferUsage.INDEX,
+ ),
+ count: definition.indices.length,
+ };
+ this.geometry.set(definition.id, geometry);
+ }
+ const draw = this.draw(
+ item,
+ telosPipeline(this.owner, item.overlay ? "overlay-mesh" : "mesh"),
+ 224,
+ geometry.count,
+ );
+ draw.geometry = geometry;
+ this.meshes.push(draw);
+ }
+ for (const [id, geometry] of this.geometry)
+ if (!used.has(id)) {
+ this.releaseGeometry(geometry);
+ this.geometry.delete(id);
+ }
+ this.metrics.meshUploadMs = performance.now() - start;
+ const lineStart = performance.now();
+ for (const item of scene.lines) {
+ if (item.points.length < 6) continue;
+ 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,
+ );
+ this.lines.push(draw);
+ }
+ this.metrics.lineUploadMs = performance.now() - lineStart;
+ const fieldStart = performance.now();
+ for (const item of scene.fields) {
+ if (
+ item.artifact.bindings.length !== 1 ||
+ item.artifact.bindings[0].group !== 0 ||
+ item.artifact.bindings[0].binding !== 0 ||
+ item.artifact.bindings[0].byteSize !== 32 ||
+ !item.artifact.capabilities.includes("telos-field-rays/1")
+ )
+ throw new Error("telos-field-abi-unsupported");
+ const model = matrix(item.transform),
+ e = model.elements;
+ const axes = [
+ new Vector3(e[0], e[1], e[2]),
+ new Vector3(e[4], e[5], e[6]),
+ new Vector3(e[8], e[9], e[10]),
+ ];
+ if (
+ axes.some((axis) => Math.abs(axis.length() - 1) > 1e-6) ||
+ Math.abs(axes[0].dot(axes[1])) > 1e-6 ||
+ Math.abs(axes[0].dot(axes[2])) > 1e-6 ||
+ Math.abs(axes[1].dot(axes[2])) > 1e-6
+ )
+ 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,
+ );
+ this.fields.push(draw);
+ }
+ this.metrics.fieldPipelineMs = performance.now() - fieldStart;
+ this.picker.setScene(scene);
+ this.invalidate();
+ }
+ fit() {
+ const bounds = new Box3();
+ for (const item of this.scene.meshes) {
+ const transform = matrix(item.transform),
+ p = item.definition.positions;
+ for (let i = 0; i < p.length; i += 3)
+ bounds.expandByPoint(
+ new Vector3(p[i], p[i + 1], p[i + 2]).applyMatrix4(transform),
+ );
+ }
+ for (const field of this.scene.fields)
+ bounds.union(
+ new Box3(
+ new Vector3(...field.bounds.minimum),
+ new Vector3(...field.bounds.maximum),
+ ).applyMatrix4(matrix(field.transform)),
+ );
+ if (!bounds.isEmpty())
+ this.camera.fit(bounds.min.toArray(), bounds.max.toArray());
+ this.invalidate();
+ }
+ private updateMesh(draw: Draw<TelosMesh>) {
+ const model = matrix(draw.item.transform);
+ const data = new Float32Array(56);
+ data.set(this.camera.viewProjection.elements);
+ data.set(model.elements, 16);
+ data.set(model.clone().invert().transpose().elements, 32);
+ const material = draw.item.material;
+ data.set(
+ draw.item.selected
+ ? [0.8, 0.55, 0.12, 1]
+ : draw.item.hovered
+ ? [0.25, 0.65, 0.48, 1]
+ : [...material.baseColor.slice(0, 3), material.opacity],
+ 48,
+ );
+ data.set([material.roughness, material.metallic, 0, 0], 52);
+ this.owner.device.queue.writeBuffer(draw.uniform, 0, data);
+ }
+ private updateLine(draw: Draw<TelosLine>) {
+ const data = new Float32Array(40);
+ data.set(this.camera.viewProjection.elements);
+ data.set(matrix(draw.item.transform).elements, 16);
+ data.set(
+ draw.item.selected
+ ? [1, 0.75, 0.2, 1]
+ : (draw.item.color ?? [0.15, 0.18, 0.16, 1]),
+ 32,
+ );
+ data.set(
+ [
+ this.camera.width,
+ this.camera.height,
+ draw.item.selected
+ ? Math.max(3, draw.item.widthPixels ?? 1)
+ : (draw.item.widthPixels ?? 1),
+ 0,
+ ],
+ 36,
+ );
+ this.owner.device.queue.writeBuffer(draw.uniform, 0, data);
+ }
+ private updateField(draw: Draw<TelosField>) {
+ const inverse = matrix(draw.item.transform).invert(),
+ localVP = this.camera.viewProjection
+ .clone()
+ .multiply(matrix(draw.item.transform));
+ const m = localVP.elements,
+ min = draw.item.bounds.minimum,
+ max = draw.item.bounds.maximum;
+ const epsilon = Math.max(
+ 1e-6,
+ new Vector3(...min).distanceTo(new Vector3(...max)) * 1e-5,
+ );
+ const corners: [number, number][] = [
+ [0, this.camera.height],
+ [this.camera.width, this.camera.height],
+ [0, 0],
+ [0, 0],
+ [this.camera.width, this.camera.height],
+ [this.camera.width, 0],
+ ];
+ const vertices = new Float32Array(
+ corners.flatMap((pixel) => {
+ const origin = this.camera.unproject(pixel, 0).applyMatrix4(inverse),
+ far = this.camera.unproject(pixel, 1).applyMatrix4(inverse);
+ return [
+ (pixel[0] / this.camera.width) * 2 - 1,
+ 1 - (pixel[1] / this.camera.height) * 2,
+ 0,
+ ...origin.toArray(),
+ ...far.sub(origin).toArray(),
+ m[2],
+ m[6],
+ m[10],
+ m[14],
+ m[3],
+ m[7],
+ m[11],
+ m[15],
+ epsilon,
+ ];
+ }),
+ );
+ this.owner.device.queue.writeBuffer(draw.vertices!, 0, vertices);
+ const data = new Float32Array(8);
+ data.set(
+ draw.item.selected
+ ? [0.8, 0.55, 0.12, 1]
+ : [
+ ...draw.item.material.baseColor.slice(0, 3),
+ draw.item.material.opacity,
+ ],
+ 0,
+ );
+ data[4] = draw.item.material.roughness;
+ this.owner.device.queue.writeBuffer(draw.uniform, 0, data);
+ }
+ private updateGrid() {
+ const key = JSON.stringify([
+ this.grid,
+ this.gridPlane,
+ this.camera.viewProjection.elements,
+ this.camera.span,
+ this.camera.width,
+ this.camera.height,
+ ]);
+ if (key === this.gridKey) return;
+ this.gridKey = key;
+ if (this.gridDraw) {
+ this.owner.resources.release(this.gridDraw.uniform);
+ this.owner.resources.release(this.gridDraw.vertices!);
+ this.gridDraw = undefined;
+ }
+ if (!this.grid) return;
+ const axis = this.gridPlane === "xy" ? "z" : "y",
+ points: Vector3[] = [];
+ for (const pixel of [
+ [0, 0],
+ [this.camera.width, 0],
+ [0, this.camera.height],
+ [this.camera.width, this.camera.height],
+ ] as [number, number][]) {
+ const ray = this.camera.worldRay(pixel),
+ t = -ray.origin[axis] / ray.direction[axis];
+ if (Number.isFinite(t) && t > 0 && t < this.camera.far)
+ points.push(ray.origin.clone().addScaledVector(ray.direction, t));
+ }
+ const span = Math.max(
+ this.camera.span,
+ this.camera.position.distanceTo(this.camera.target) * 0.5,
+ 1e-8,
+ );
+ const extent = Math.min(
+ span * 20,
+ Math.max(span, ...points.map((p) => p.distanceTo(this.camera.target))),
+ );
+ const step = Math.pow(10, Math.floor(Math.log10(extent / 12)));
+ const centerX = Math.round(this.camera.target.x / step) * step;
+ const centerY =
+ Math.round(
+ (this.gridPlane === "xy"
+ ? this.camera.target.y
+ : this.camera.target.z) / step,
+ ) * step;
+ const count = Math.min(40, Math.ceil(extent / step));
+ const segments: number[] = [];
+ const point = (x: number, y: number) =>
+ this.gridPlane === "xy" ? [x, y, 0] : [x, 0, y];
+ for (let i = -count; i <= count; i++) {
+ segments.push(
+ ...point(centerX + i * step, centerY - count * step),
+ ...point(centerX + i * step, centerY + count * step),
+ );
+ segments.push(
+ ...point(centerX - count * step, centerY + i * step),
+ ...point(centerX + count * step, centerY + i * step),
+ );
+ }
+ this.gridDraw = this.draw(
+ {
+ id: "reference-grid",
+ points: segments,
+ identity: { occurrenceId: "reference-grid" },
+ widthPixels: 0.7,
+ color: [0.45, 0.48, 0.46, 0.18],
+ },
+ telosPipeline(this.owner, "line"),
+ 160,
+ segments.length / 6,
+ );
+ this.gridDraw.vertices = this.owner.resources.buffer(
+ new Float32Array(segments),
+ GPUBufferUsage.VERTEX,
+ );
+ }
+ render() {
+ if (this.owner.stopped || this.disposed) return;
+ cancelAnimationFrame(this.raf);
+ this.raf = 0;
+ const started = performance.now();
+ this.camera.update();
+ this.updateGrid();
+ this.frame.begin(this.background);
+ this.metrics.draws = 0;
+ if (this.gridDraw) {
+ const grid = this.frame.pass("ReferenceGrid");
+ this.updateLine(this.gridDraw);
+ grid.setPipeline(this.gridDraw.pipeline);
+ grid.setBindGroup(0, this.gridDraw.binding);
+ grid.setVertexBuffer(0, this.gridDraw.vertices!);
+ grid.draw(6, this.gridDraw.count);
+ grid.end();
+ }
+ const drawMesh = (pass: GPURenderPassEncoder, draw: Draw<TelosMesh>) => {
+ if (draw.item.visible === false) return;
+ this.updateMesh(draw);
+ pass.setPipeline(draw.pipeline);
+ pass.setBindGroup(0, draw.binding);
+ pass.setVertexBuffer(0, draw.geometry!.positions);
+ pass.setVertexBuffer(1, draw.geometry!.normals);
+ pass.setIndexBuffer(draw.geometry!.indices, "uint32");
+ pass.drawIndexed(draw.count);
+ this.metrics.draws++;
+ };
+ let pass = this.frame.pass("MeshOpaque");
+ for (const draw of this.meshes.filter((draw) => !draw.item.overlay))
+ drawMesh(pass, draw);
+ pass.end();
+ pass = this.frame.pass("Field");
+ for (const draw of this.fields) {
+ this.updateField(draw);
+ pass.setPipeline(draw.pipeline);
+ pass.setBindGroup(0, draw.binding);
+ pass.setVertexBuffer(0, draw.vertices!);
+ pass.draw(6);
+ this.metrics.draws++;
+ }
+ pass.end();
+ pass = this.frame.pass("Topology");
+ for (const draw of this.lines.filter((draw) => !draw.item.overlay)) {
+ 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();
+ 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)) {
+ this.updateLine(draw);
+ pass.setPipeline(draw.pipeline);
+ pass.setBindGroup(0, draw.binding);
+ pass.setVertexBuffer(0, draw.vertices!);
+ pass.draw(6, draw.count);
+ }
+ pass.end();
+ this.frame.end();
+ this.metrics.frames++;
+ this.metrics.frameMs = performance.now() - started;
+ }
+ /** Qualification readback uses the authoritative presented texture. */
+ async readPixels(): Promise<Uint8Array> {
+ const { width, height, target } = this.frame;
+ const bytesPerRow = Math.ceil((width * 4) / 256) * 256;
+ const buffer = this.owner.device.createBuffer({
+ size: bytesPerRow * height,
+ usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
+ });
+ const encoder = this.owner.device.createCommandEncoder();
+ encoder.copyTextureToBuffer({ texture: target }, { buffer, bytesPerRow }, [
+ width,
+ height,
+ ]);
+ this.owner.device.queue.submit([encoder.finish()]);
+ await buffer.mapAsync(GPUMapMode.READ);
+ const input = new Uint8Array(buffer.getMappedRange()),
+ output = new Uint8Array(width * height * 4);
+ for (let y = 0; y < height; y++)
+ output.set(
+ input.subarray(y * bytesPerRow, y * bytesPerRow + width * 4),
+ y * width * 4,
+ );
+ buffer.unmap();
+ buffer.destroy();
+ return output;
+ }
+ private releaseGeometry(geometry: GeometryBuffers) {
+ for (const buffer of [
+ geometry.positions,
+ geometry.normals,
+ geometry.indices,
+ ])
+ this.owner.resources.release(buffer);
+ }
+ private releaseDraws() {
+ for (const draw of [...this.meshes, ...this.lines, ...this.fields]) {
+ this.owner.resources.release(draw.uniform);
+ if (draw.vertices) this.owner.resources.release(draw.vertices);
+ }
+ this.meshes = [];
+ this.lines = [];
+ this.fields = [];
+ }
+ dispose() {
+ if (this.disposed) return;
+ this.disposed = true;
+ cancelAnimationFrame(this.raf);
+ this.raf = 0;
+ this.observer?.disconnect();
+ this.detach?.();
+ this.picker.dispose();
+ this.releaseDraws();
+ this.geometry.clear();
+ this.frame.dispose();
+ this.owner.dispose();
+ }
+}
diff --git a/Aetheris.Web.Runtime/telos/src/index.ts b/Aetheris.Web.Runtime/telos/src/index.ts
new file mode 100644
index 00000000..8d16a242
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/src/index.ts
@@ -0,0 +1,7 @@
+/// <reference types="@webgpu/types" preserve="true" />
+export * from "./contracts.js";
+export * from "./camera.js";
+export * from "./device.js";
+export * from "./pick.js";
+export * from "./host.js";
+export * from "./adapters.js";
diff --git a/Aetheris.Web.Runtime/telos/src/navigation.ts b/Aetheris.Web.Runtime/telos/src/navigation.ts
new file mode 100644
index 00000000..aea36bd5
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/src/navigation.ts
@@ -0,0 +1,91 @@
+import { Vector3, Quaternion } from "three";
+import type { TelosCamera } from "./camera.js";
+
+/** Inputs change Telos state directly, rather than copying authoritative camera state from controls. */
+export function attachNavigation(
+ canvas: HTMLCanvasElement,
+ camera: TelosCamera,
+ invalidate: () => void,
+) {
+ let drag: { x: number; y: number; button: number } | null = null;
+ const down = (event: PointerEvent) => {
+ drag = { x: event.clientX, y: event.clientY, button: event.button };
+ canvas.setPointerCapture(event.pointerId);
+ };
+ const move = (event: PointerEvent) => {
+ if (!drag) return;
+ const dx = event.clientX - drag.x,
+ dy = event.clientY - drag.y;
+ drag.x = event.clientX;
+ drag.y = event.clientY;
+ const offset = camera.position.clone().sub(camera.target);
+ if (drag.button === 0 && !event.shiftKey) {
+ offset.applyQuaternion(
+ new Quaternion().setFromAxisAngle(
+ camera.up.clone().normalize(),
+ -dx * 0.006,
+ ),
+ );
+ const right = new Vector3().crossVectors(offset, camera.up).normalize();
+ const next = offset
+ .clone()
+ .applyQuaternion(new Quaternion().setFromAxisAngle(right, -dy * 0.006));
+ if (Math.abs(next.clone().normalize().dot(camera.up)) < 0.995)
+ offset.copy(next);
+ camera.position.copy(camera.target).add(offset);
+ } else {
+ const scale =
+ (camera.mode === "orthographic"
+ ? camera.span
+ : offset.length() * Math.tan((camera.fov * Math.PI) / 360) * 2) /
+ camera.height;
+ const right = new Vector3().setFromMatrixColumn(camera.inverseView, 0),
+ up = new Vector3().setFromMatrixColumn(camera.inverseView, 1);
+ const delta = right
+ .multiplyScalar(-dx * scale)
+ .add(up.multiplyScalar(dy * scale));
+ camera.position.add(delta);
+ camera.target.add(delta);
+ }
+ camera.update();
+ invalidate();
+ };
+ const up = () => {
+ drag = null;
+ };
+ const wheel = (event: WheelEvent) => {
+ event.preventDefault();
+ const factor = Math.exp(Math.max(-1, Math.min(1, event.deltaY * 0.001)));
+ if (camera.mode === "orthographic")
+ camera.span = Math.max(1e-8, camera.span * factor);
+ else {
+ const offset = camera.position
+ .clone()
+ .sub(camera.target)
+ .multiplyScalar(factor);
+ if (
+ offset.length() > camera.near * 2 &&
+ offset.length() < camera.far * 0.9
+ )
+ camera.position.copy(camera.target).add(offset);
+ }
+ camera.update();
+ invalidate();
+ };
+ const context = (event: MouseEvent) => event.preventDefault();
+ canvas.style.touchAction = "none";
+ canvas.addEventListener("pointerdown", down);
+ canvas.addEventListener("pointermove", move);
+ canvas.addEventListener("pointerup", up);
+ canvas.addEventListener("pointercancel", up);
+ canvas.addEventListener("wheel", wheel, { passive: false });
+ canvas.addEventListener("contextmenu", context);
+ return () => {
+ canvas.removeEventListener("pointerdown", down);
+ canvas.removeEventListener("pointermove", move);
+ canvas.removeEventListener("pointerup", up);
+ canvas.removeEventListener("pointercancel", up);
+ canvas.removeEventListener("wheel", wheel);
+ canvas.removeEventListener("contextmenu", context);
+ };
+}
diff --git a/Aetheris.Web.Runtime/telos/src/pick.ts b/Aetheris.Web.Runtime/telos/src/pick.ts
new file mode 100644
index 00000000..388e778a
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/src/pick.ts
@@ -0,0 +1,160 @@
+import {
+ BufferGeometry,
+ BufferAttribute,
+ Mesh,
+ MeshBasicMaterial,
+ DoubleSide,
+ Matrix4,
+ Raycaster,
+ Vector3,
+} from "three";
+import type { Intersection } from "three";
+import type { TelosCamera } from "./camera.js";
+import type {
+ TelosScene,
+ TelosLine,
+ Pixel,
+ TelosHit,
+ TelosMesh,
+ TelosField,
+ TelosGeometry,
+} from "./contracts.js";
+
+/** CPU engineering proxy; field objects may supply the same mesh proxy without drawing it. */
+export class TelosPick {
+ camera: TelosCamera;
+ proxies: Mesh[];
+ lines: readonly TelosLine[];
+ raycaster: Raycaster;
+ constructor(camera: TelosCamera) {
+ this.camera = camera;
+ this.proxies = [];
+ this.lines = [];
+ this.raycaster = new Raycaster();
+ }
+ setScene(scene: TelosScene) {
+ this.dispose();
+ 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 }),
+ );
+ mesh.matrixAutoUpdate = false;
+ mesh.matrix.fromArray(item.transform ?? new Matrix4().elements);
+ mesh.updateMatrixWorld(true);
+ mesh.userData = { item, definition };
+ this.proxies.push(mesh);
+ }
+ }
+ 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 faceHit = closest ? this.hit(closest) : null;
+ if (mode !== "edge") return faceHit;
+ let hit: TelosHit | null = null,
+ distance = Infinity;
+ for (const line of this.lines) {
+ const transform = new Matrix4().fromArray(
+ line.transform ?? new Matrix4().elements,
+ );
+ const points = line.points;
+ for (let i = 3; i < points.length; i += 3) {
+ const a = new Vector3(
+ points[i - 3],
+ points[i - 2],
+ points[i - 1],
+ ).applyMatrix4(transform);
+ const b = new Vector3(
+ points[i],
+ points[i + 1],
+ points[i + 2],
+ ).applyMatrix4(transform);
+ const pa = this.camera.project(a.toArray()),
+ pb = this.camera.project(b.toArray());
+ if (pa[2] < 0 || pb[2] < 0 || pa[2] > 1 || pb[2] > 1) continue;
+ const dx = pb[0] - pa[0],
+ dy = pb[1] - pa[1],
+ length = dx * dx + dy * dy;
+ const t = length
+ ? Math.max(
+ 0,
+ Math.min(
+ 1,
+ ((pixel[0] - pa[0]) * dx + (pixel[1] - pa[1]) * dy) / length,
+ ),
+ )
+ : 0;
+ const pixels = Math.hypot(
+ pixel[0] - pa[0] - t * dx,
+ pixel[1] - pa[1] - t * dy,
+ );
+ const onRay = new Vector3(),
+ onSegment = new Vector3();
+ this.raycaster.ray.distanceSqToSegment(a, b, onRay, onSegment);
+ const d = onRay.distanceTo(ray.origin);
+ const tolerance =
+ 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)
+ ) {
+ distance = d;
+ hit = {
+ ...line.identity,
+ worldPosition: onSegment.toArray(),
+ worldNormal: null,
+ distance: d,
+ };
+ }
+ }
+ }
+ return hit;
+ }
+ hit(hit: Intersection): TelosHit {
+ const { item, definition } = hit.object.userData as {
+ item: TelosMesh | TelosField;
+ definition: TelosGeometry;
+ };
+ const triangleIndex = hit.faceIndex ?? 0;
+ const range = definition.ranges?.find(
+ (range) =>
+ triangleIndex >= range.startTriangle &&
+ triangleIndex < range.startTriangle + range.triangleCount,
+ );
+ return {
+ ...item.identity,
+ faceId: range?.faceId ?? item.identity.faceId,
+ triangleIndex,
+ worldPosition: hit.point.toArray(),
+ worldNormal: hit
+ .face!.normal.clone()
+ .transformDirection(
+ new Matrix4().copy(hit.object.matrixWorld).invert().transpose(),
+ )
+ .toArray(),
+ distance: hit.distance,
+ };
+ }
+ dispose() {
+ for (const mesh of this.proxies) {
+ mesh.geometry.dispose();
+ if (!Array.isArray(mesh.material)) mesh.material.dispose();
+ }
+ this.proxies = [];
+ }
+}
diff --git a/Aetheris.Web.Runtime/telos/src/pipelines.ts b/Aetheris.Web.Runtime/telos/src/pipelines.ts
new file mode 100644
index 00000000..cca8d634
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/src/pipelines.ts
@@ -0,0 +1,101 @@
+import type { TelosDevice } from "./device.js";
+import type { TelosField } from "./contracts.js";
+import { meshShader, lineShader } from "./shaders.js";
+const vertexLayout: GPUVertexBufferLayout = {
+ arrayStride: 12,
+ attributes: [{ shaderLocation: 0, offset: 0, format: "float32x3" }],
+};
+
+/** Cache identity includes shader semantics, drawing state and authoritative attachment formats. */
+export function telosPipeline(
+ owner: TelosDevice,
+ kind: "mesh" | "line" | "overlay-mesh" | "overlay-line",
+ artifact?: TelosField["artifact"],
+) {
+ 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 shader = resources.module(
+ id,
+ artifact?.wgsl ?? (kind.includes("mesh") ? meshShader : lineShader),
+ );
+ return resources.pipeline(key, () =>
+ owner.device.createRenderPipeline({
+ label: key,
+ layout: "auto",
+ vertex: {
+ module: shader,
+ entryPoint: artifact?.vertexEntryPoint ?? "vertex",
+ buffers: artifact
+ ? [
+ {
+ arrayStride: 72,
+ attributes: [
+ ...[0, 1, 2].map((i) => ({
+ shaderLocation: i,
+ offset: i * 12,
+ format: "float32x3" as const,
+ })),
+ { shaderLocation: 3, offset: 36, format: "float32x4" },
+ { shaderLocation: 4, offset: 52, format: "float32x4" },
+ { shaderLocation: 5, offset: 68, format: "float32" },
+ ],
+ },
+ ]
+ : kind.includes("mesh")
+ ? [
+ vertexLayout,
+ {
+ arrayStride: 12,
+ attributes: [
+ { shaderLocation: 1, offset: 0, format: "float32x3" },
+ ],
+ },
+ ]
+ : [
+ {
+ arrayStride: 24,
+ stepMode: "instance",
+ attributes: [
+ { shaderLocation: 0, offset: 0, format: "float32x3" },
+ { shaderLocation: 1, offset: 12, format: "float32x3" },
+ ],
+ },
+ ],
+ },
+ fragment: {
+ module: shader,
+ entryPoint: artifact?.fragmentEntryPoint ?? "fragment",
+ targets: [
+ {
+ format,
+ blend: {
+ color: {
+ srcFactor: "src-alpha",
+ dstFactor: "one-minus-src-alpha",
+ operation: "add",
+ },
+ alpha: {
+ srcFactor: "one",
+ dstFactor: "one-minus-src-alpha",
+ operation: "add",
+ },
+ },
+ },
+ ],
+ },
+ primitive: { topology: "triangle-list", cullMode: "none" },
+ depthStencil: {
+ format: "depth32float",
+ depthWriteEnabled:
+ !kind.includes("line") && !kind.startsWith("overlay"),
+ depthCompare: kind.startsWith("overlay")
+ ? "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
new file mode 100644
index 00000000..cdda0e69
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/src/shaders.ts
@@ -0,0 +1,37 @@
+export const meshShader = `
+struct State { vp: mat4x4<f32>, model: mat4x4<f32>, normal: mat4x4<f32>, color: vec4<f32>, parameters: vec4<f32> }
+@group(0) @binding(0) var<uniform> state: State;
+struct Output { @builtin(position) position: vec4<f32>, @location(0) normal: vec3<f32> }
+@vertex fn vertex(@location(0) position: vec3<f32>, @location(1) normal: vec3<f32>) -> Output {
+ var out: Output; out.position = state.vp * state.model * vec4(position, 1);
+ out.normal = (state.normal * vec4(normal, 0)).xyz; return out;
+}
+@fragment fn fragment(input: Output) -> @location(0) vec4<f32> {
+ let n = normalize(input.normal); let light = normalize(vec3<f32>(0.3, 0.8, 0.6));
+ 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);
+ return vec4(pow(max(linear, vec3<f32>(0)), vec3<f32>(1.0 / 2.2)), state.color.a);
+}`;
+
+// Expanded segment quads. Width is CSS pixels; bias is 2e-6 in normalized depth.
+export const lineShader = `
+struct State { vp: mat4x4<f32>, model: mat4x4<f32>, color: vec4<f32>, viewport: vec4<f32> }
+@group(0) @binding(0) var<uniform> state: State;
+@vertex fn vertex(@builtin(vertex_index) vertex: u32, @location(0) start: vec3<f32>, @location(1) end: vec3<f32>) -> @builtin(position) vec4<f32> {
+ var a = state.vp * state.model * vec4(start,1); var b = state.vp * state.model * vec4(end,1);
+ // Clip before dividing by w: segments crossing the near plane remain finite.
+ if (a.z < 0 && b.z >= 0) { a = mix(a,b, -a.z / (b.z-a.z)); }
+ if (b.z < 0 && a.z >= 0) { b = mix(b,a, -b.z / (a.z-b.z)); }
+ if (a.z < 0 && b.z < 0) { return vec4<f32>(2,2,2,1); }
+ let delta = (b.xy/b.w-a.xy/a.w) * state.viewport.xy;
+ let direction = delta / max(length(delta), 0.00001);
+ let perpendicular = vec2(-direction.y, direction.x);
+ 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);
+ return p;
+}
+@fragment fn fragment() -> @location(0) vec4<f32> { return state.color; }
+`;
diff --git a/Aetheris.Web.Runtime/telos/tests/browser-witness.ts b/Aetheris.Web.Runtime/telos/tests/browser-witness.ts
new file mode 100644
index 00000000..7721cfab
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/tests/browser-witness.ts
@@ -0,0 +1,259 @@
+import { Matrix4 } from "three";
+import { TelosHost, materialFromAppearance } from "../src/index.js";
+import type {
+ TelosMesh,
+ TelosField,
+ TelosScene,
+ TelosShaderArtifact,
+ TelosLine,
+} from "../src/index.js";
+
+declare global {
+ interface Window {
+ telosQualification: unknown;
+ telosWitness: TelosHost;
+ }
+}
+const check = (value: unknown, message: string) => {
+ if (!value) throw new Error(message);
+};
+const canvas = document.querySelector("canvas")!;
+const status = document.querySelector("pre")!;
+const errors: string[] = [];
+try {
+ const started = performance.now();
+ const host = await TelosHost.create(canvas, (message) =>
+ errors.push(message),
+ );
+ window.telosWitness = host;
+ const initMs = performance.now() - started;
+ host.resize(256, 256, 1);
+ host.camera.position.set(0, 0, 5);
+ host.camera.target.set(0, 0, 0);
+ host.camera.near = 0.1;
+ host.camera.far = 100;
+ host.camera.span = 4;
+ host.camera.update();
+ const artifact = (await (
+ await fetch("/artifacts/local/three-telos/cir/cylinder.json")
+ ).json()) as TelosShaderArtifact;
+ check(
+ artifact.wgsl.startsWith("// Generated by vd-wgsl/1"),
+ "not direct WGSL",
+ );
+ const plane = {
+ id: "shared-plane",
+ positions: [-1.3, -1.3, 0, 1.3, -1.3, 0, -1.3, 1.3, 0, 1.3, 1.3, 0],
+ normals: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1],
+ indices: [0, 1, 2, 2, 1, 3],
+ };
+ const mesh = (z: number, id = "mesh"): TelosMesh => ({
+ definition: plane,
+ transform: new Matrix4().makeTranslation(0, 0, z).elements,
+ identity: { occurrenceId: id, bodyId: "mesh-body" },
+ material: materialFromAppearance({ baseColor: [0.05, 0.8, 0.12] }),
+ });
+ const field: TelosField = {
+ artifact,
+ identity: { occurrenceId: "CIR-cylinder", bodyId: "authored-cylinder" },
+ bounds: { minimum: [-0.8, -0.8, -1], maximum: [0.8, 0.8, 1] },
+ material: materialFromAppearance({ baseColor: [0.85, 0.12, 0.06] }),
+ };
+ const results: Record<string, unknown> = {
+ initMs,
+ shaderId: artifact.shaderId,
+ directCompiler: true,
+ };
+ const initialStart = performance.now();
+ host.setScene({ meshes: [mesh(-2)], lines: [], fields: [field] });
+ host.render();
+ await host.owner.device.queue.onSubmittedWorkDone();
+ results.firstFrame = {
+ ...host.metrics,
+ submissionCompletedMs: performance.now() - initialStart,
+ };
+ const render = async (scene: TelosScene) => {
+ host.setScene(scene);
+ host.render();
+ const pixels = await host.readPixels();
+ await host.owner.device.queue.onSubmittedWorkDone();
+ check(!errors.length, errors.join("\n"));
+ return pixels;
+ };
+ const center = (pixels: Uint8Array) =>
+ Array.from(
+ pixels.subarray((128 * 256 + 128) * 4, (128 * 256 + 128) * 4 + 4),
+ );
+ const same = (a: number[], b: number[]) =>
+ a.every((n, i) => Math.abs(n - b[i]) <= 2);
+ for (const mode of ["perspective", "orthographic"] as const) {
+ host.camera.mode = mode;
+ host.camera.update();
+ const cir = center(
+ await render({ meshes: [], lines: [], fields: [field] }),
+ );
+ const front = center(
+ await render({ meshes: [mesh(2)], lines: [], fields: [] }),
+ );
+ const mixedBack = center(
+ await render({ meshes: [mesh(-2)], lines: [], fields: [field] }),
+ );
+ const mixedFront = center(
+ await render({ meshes: [mesh(2)], lines: [], fields: [field] }),
+ );
+ check(!same(cir, front), "empty or indistinguishable CIR");
+ check(
+ same(cir, mixedBack),
+ mode +
+ ": field must occlude mesh " +
+ JSON.stringify({ cir, mixedBack, front, mixedFront }),
+ );
+ check(same(front, mixedFront), mode + ": mesh must occlude field");
+ const meshOverlap = center(
+ await render({
+ meshes: [mesh(2), { ...mesh(-2), material: field.material }],
+ lines: [],
+ fields: [],
+ }),
+ );
+ check(same(front, meshOverlap), "mesh depth failed");
+ results[mode] = { cir, front, mixedBack, mixedFront, meshOverlap };
+ }
+ const line: TelosLine = {
+ id: "edge",
+ points: [-1, 0, 0, 1, 0, 0],
+ widthPixels: 4,
+ color: [1, 1, 1, 1],
+ identity: { occurrenceId: "line", edgeId: "BRep-edge" },
+ };
+ const lineWidths = [];
+ for (const dpr of [1, 2])
+ for (const span of [3, 10]) {
+ host.camera.span = span;
+ host.resize(256, 256, dpr);
+ const pixels = await render({
+ meshes: [],
+ fields: [],
+ lines: [
+ {
+ ...line,
+ transform: new Matrix4().makeTranslation(0, 0, 0.5).elements,
+ },
+ ],
+ });
+ const x = host.frame.width / 2;
+ let width = 0;
+ for (let y = 0; y < host.frame.height; y++) {
+ const offset = (y * host.frame.width + x) * 4;
+ if (
+ pixels[offset] > 200 &&
+ pixels[offset + 1] > 200 &&
+ pixels[offset + 2] > 200
+ )
+ width++;
+ }
+ check(Math.abs(width / dpr - 4) <= 1, "line CSS width drift");
+ lineWidths.push({ dpr, span, devicePixels: width });
+ }
+ results.lineWidths = lineWidths;
+ host.resize(256, 256, 1);
+ host.camera.span = 4;
+ const surface = center(
+ await render({ meshes: [mesh(2)], fields: [], lines: [] }),
+ );
+ const hidden = center(
+ await render({ meshes: [mesh(2)], fields: [], lines: [line] }),
+ );
+ check(same(surface, hidden), "hidden edge leakage");
+ const selected = center(
+ await render({
+ meshes: [],
+ fields: [],
+ lines: [{ ...line, selected: true }],
+ }),
+ );
+ check(!same(surface, selected), "selected edge style");
+ const sharedScene: TelosScene = {
+ meshes: [
+ { ...mesh(0, "left"), selected: true },
+ {
+ ...mesh(0, "right"),
+ transform: new Matrix4().makeTranslation(2, 0, 0).elements,
+ },
+ ],
+ fields: [
+ field,
+ {
+ ...field,
+ identity: { occurrenceId: "second-cylinder" },
+ selected: true,
+ transform: new Matrix4().makeTranslation(-2, 0, 0).elements,
+ },
+ ],
+ lines: [line],
+ };
+ await render(sharedScene);
+ check(host.geometry.size === 1, "duplicate definition buffers");
+ check(host.owner.resources.modules.size === 3, "duplicate shader modules");
+ results.reuse = {
+ definitions: host.geometry.size,
+ modules: host.owner.resources.modules.size,
+ pipelines: host.owner.resources.pipelines.size,
+ };
+ const depthGeneration = host.frame.generation;
+ host.resize(320, 180, 2);
+ host.render();
+ await host.readPixels();
+ check(host.frame.generation > depthGeneration, "depth resize failed");
+ for (const span of [0.01, 10000]) {
+ host.camera.span = span;
+ host.grid = true;
+ host.render();
+ await host.readPixels();
+ check(!errors.length, "grid/camera stress validation");
+ }
+ host.grid = false;
+ host.resize(256, 256, 1);
+ host.camera.span = 4;
+ host.camera.position.set(4, 3, 6);
+ host.camera.update();
+ host.render();
+ await host.readPixels();
+ const times = [];
+ for (let i = 0; i < 20; i++) {
+ const start = performance.now();
+ host.render();
+ await host.owner.device.queue.onSubmittedWorkDone();
+ times.push(performance.now() - start);
+ }
+ results.timings = {
+ ...host.metrics,
+ steadySubmissionMeanMs: times.reduce((a, b) => a + b) / times.length,
+ };
+ results.gpu = {
+ vendor: host.owner.adapter.info.vendor,
+ architecture: host.owner.adapter.info.architecture,
+ description: host.owner.adapter.info.description,
+ };
+ const resources = host.owner.resources;
+ host.dispose();
+ check(
+ resources.buffers.size === 0 && resources.textures.size === 0,
+ "resources retained after disposal",
+ );
+ const recreated = await TelosHost.create(canvas, (message) =>
+ errors.push(message),
+ );
+ recreated.resize(256, 256);
+ recreated.setScene(sharedScene);
+ recreated.fit();
+ recreated.render();
+ await recreated.readPixels();
+ check(!errors.length, errors.join("\n"));
+ window.telosWitness = recreated;
+ window.telosQualification = { status: "PASS", results, errors };
+ status.textContent = JSON.stringify(window.telosQualification, null, 2);
+} catch (error) {
+ window.telosQualification = { status: "FAIL", error: String(error), errors };
+ status.textContent = JSON.stringify(window.telosQualification, null, 2);
+}
diff --git a/Aetheris.Web.Runtime/telos/tests/browser.html b/Aetheris.Web.Runtime/telos/tests/browser.html
new file mode 100644
index 00000000..c48b4330
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/tests/browser.html
@@ -0,0 +1,5 @@
+<!doctype html><html lang="en"><meta charset="utf-8"><title>Three Telos X0</title>
+<style>body{background:#19231f;color:#e5ece7;font:16px system-ui;margin:24px}canvas{width:512px;height:512px}pre{white-space:pre-wrap}</style>
+<h1>Three Telos: shared mesh, CIR and topology</h1><canvas></canvas><pre>Qualifying real WebGPU…</pre>
+<script type="importmap">{"imports":{"three":"/Aetheris.Web.Runtime/telos/node_modules/three/build/three.module.js"}}</script>
+<script type="module" src="/artifacts/local/three-telos/browser/tests/browser-witness.js"></script></html>
diff --git a/Aetheris.Web.Runtime/telos/tests/camera.test.ts b/Aetheris.Web.Runtime/telos/tests/camera.test.ts
new file mode 100644
index 00000000..a52a75c1
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/tests/camera.test.ts
@@ -0,0 +1,114 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { Vector3, Matrix4 } from "three";
+import {
+ TelosCamera,
+ TelosPick,
+ materialFromAppearance,
+ fromDisplayMesh,
+} from "../dist/index.js";
+import type { TelosScene } from "../dist/index.js";
+
+for (const mode of ["perspective", "orthographic"] as const)
+ test(`${mode}: project, unproject, ray, aspect and scale`, () => {
+ const camera = new TelosCamera();
+ camera.mode = mode;
+ camera.resize(800, 600);
+ for (const scale of [1e-5, 1, 1e6]) {
+ camera.fit([-scale, -scale, -scale], [scale, scale, scale]);
+ const world = new Vector3(scale * 0.2, scale * 0.3, scale * 0.1),
+ pixel = camera.project(world.toArray());
+ const restored = camera.unproject([pixel[0], pixel[1]], pixel[2]);
+ assert.ok(restored.distanceTo(world) < scale * 1e-6);
+ const ray = camera.worldRay([pixel[0], pixel[1]]);
+ assert.ok(ray.direction.length() > 0.999999);
+ assert.ok(
+ ray.direction
+ .clone()
+ .cross(world.clone().sub(ray.origin).normalize())
+ .length() < 1e-8,
+ );
+ const before = camera.projection.elements[0];
+ camera.resize(1600, 600);
+ assert.ok(camera.projection.elements[0] < before);
+ camera.resize(800, 600);
+ }
+ const adapter = camera.toThree();
+ adapter.position.set(100, 200, 300);
+ assert.notEqual(camera.position.x, 100);
+ });
+
+test("stable identity, occurrence transforms and nearest surface picking", () => {
+ const camera = new TelosCamera();
+ camera.position.set(0, 0, 5);
+ camera.target.set(0, 0, 0);
+ camera.resize(200, 200);
+ camera.update();
+ const definition = {
+ id: "shared",
+ positions: [-1, -1, 0, 1, -1, 0, 0, 1, 0],
+ normals: [0, 0, 1, 0, 0, 1, 0, 0, 1],
+ indices: [0, 1, 2],
+ ranges: [
+ { startTriangle: 0, triangleCount: 1, faceId: "construction-face" },
+ ],
+ };
+ const material = materialFromAppearance();
+ const scene: TelosScene = {
+ meshes: [
+ {
+ definition,
+ material,
+ identity: { occurrenceId: "back", bodyId: "body" },
+ },
+ {
+ definition,
+ material,
+ transform: new Matrix4().makeTranslation(0, 0, 1).elements,
+ identity: { occurrenceId: "front", bodyId: "body" },
+ },
+ ],
+ lines: [],
+ fields: [],
+ };
+ const picker = new TelosPick(camera);
+ picker.setScene(scene);
+ const hit = picker.pick([100, 100]);
+ assert.equal(hit?.occurrenceId, "front");
+ assert.equal(hit?.faceId, "construction-face");
+ assert.equal(hit?.triangleIndex, 0);
+ assert.equal(hit?.worldPosition[2], 1);
+ picker.dispose();
+ assert.equal(picker.proxies.length, 0);
+});
+
+test("SDK adapter preserves shared geometry and kernel edge identity", () => {
+ const definition = {
+ id: "definition",
+ positions: [0, 0, 0],
+ normals: [0, 0, 1],
+ indices: [0],
+ edges: [
+ {
+ edgeId: "brep-edge",
+ points: [
+ [0, 0, 0],
+ [1, 0, 0],
+ ],
+ closed: false,
+ },
+ ],
+ };
+ const scene = fromDisplayMesh({
+ definitions: [definition],
+ occurrences: ["left", "right"].map((id) => ({
+ id,
+ definitionId: definition.id,
+ semanticEntityId: "body",
+ transform: new Matrix4().elements,
+ })),
+ });
+ assert.equal(scene.meshes[0].definition, scene.meshes[1].definition);
+ assert.equal(scene.lines[1].identity.edgeId, "brep-edge");
+ assert.equal(scene.lines[1].identity.occurrenceId, "right");
+});
diff --git a/Aetheris.Web.Runtime/telos/tsconfig.browser.json b/Aetheris.Web.Runtime/telos/tsconfig.browser.json
new file mode 100644
index 00000000..4d17fa86
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/tsconfig.browser.json
@@ -0,0 +1,5 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": { "rootDir": ".", "outDir": "../../artifacts/local/three-telos/browser", "declaration": false },
+ "include": ["src/**/*.ts", "tests/browser-witness.ts"]
+}
diff --git a/Aetheris.Web.Runtime/telos/tsconfig.json b/Aetheris.Web.Runtime/telos/tsconfig.json
new file mode 100644
index 00000000..487c3fc8
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/tsconfig.json
@@ -0,0 +1,9 @@
+{
+ "compilerOptions": {
+ "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext",
+ "lib": ["ES2022", "DOM", "DOM.Iterable"], "types": ["@webgpu/types"],
+ "strict": true, "skipLibCheck": true, "declaration": true, "outDir": "dist",
+ "rootDir": "src", "noEmitOnError": true
+ },
+ "include": ["src/**/*.ts"]
+}
diff --git a/Aetheris.Web.Runtime/telos/tsconfig.tests.json b/Aetheris.Web.Runtime/telos/tsconfig.tests.json
new file mode 100644
index 00000000..458d994f
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/tsconfig.tests.json
@@ -0,0 +1,5 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": { "rootDir": ".", "noEmit": true, "types": ["@webgpu/types", "node"] },
+ "include": ["src/**/*.ts", "tests/**/*.ts"]
+}
diff --git a/README.md b/README.md
index 9e3e9fdd..30945b8b 100644
--- a/README.md
+++ b/README.md
@@ -27,6 +27,8 @@ 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).
+
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.
Similar to OpenSCAD, the simplified core architecture description of Aetheris is that it's a compiler for 3D object, you can also think of it as LLVM for CAD. Unlike OpenSCAD, Aetheris emits 3D objects in exact boundary representations instead of SCAD's mesh. The native export format of Aetheris is industry standard STEP AP242, enabling full interop with any other 3D parametric CAD software.
diff --git a/aetheris.client/package.json b/aetheris.client/package.json
index 91a1e897..755e7589 100644
--- a/aetheris.client/package.json
+++ b/aetheris.client/package.json
@@ -11,6 +11,7 @@
"test": "vitest run"
},
"dependencies": {
+ "@aetheris/three-telos": "file:../Aetheris.Web.Runtime/telos",
"@react-three/drei": "^10.7.7",
"@react-three/fiber": "^9.5.0",
"class-variance-authority": "^0.7.1",
@@ -19,7 +20,7 @@
"react": "^19.2.0",
"react-dom": "^19.2.0",
"tailwind-merge": "^3.5.0",
- "three": "^0.183.1",
+ "three": "0.183.2",
"zod": "^3.25.76"
},
"devDependencies": {
diff --git a/aetheris.client/src/__tests__/cadmataTelos.test.ts b/aetheris.client/src/__tests__/cadmataTelos.test.ts
new file mode 100644
index 00000000..256328cc
--- /dev/null
+++ b/aetheris.client/src/__tests__/cadmataTelos.test.ts
@@ -0,0 +1,51 @@
+import { describe, it, expect } from "vitest";
+import { cadmataTelosScene } from "../viewer/cadmataTelos";
+import type { DisplayScene } from "../viewer/displayRenderables";
+
+describe("Cadmata Telos packet adapter", () => {
+ it("preserves mesh face and kernel edge identity with highlight state", () => {
+ const scene: DisplayScene = {
+ status: "Complete",
+ sourceAuthority: "BRep",
+ displayAuthority: "DisplayIR",
+ lanes: [],
+ diagnostics: [],
+ renderables: [
+ {
+ kind: "MeshPatch",
+ faceId: 17,
+ surfaceKind: "Plane",
+ status: "Mesh",
+ patchKind: "MeshPatch",
+ materializationLane: "BoundedMesh",
+ diagnostics: [],
+ mesh: {
+ faceId: 17,
+ positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1]),
+ indices: new Uint32Array([0, 1, 2]),
+ },
+ },
+ {
+ kind: "WirePatch",
+ faceId: 17,
+ surfaceKind: "Plane",
+ status: "Wire",
+ patchKind: "WirePatch",
+ materializationLane: null,
+ diagnostics: [],
+ wires: [{ edgeId: 31, points: new Float32Array([0, 0, 0, 1, 0, 0]) }],
+ },
+ ],
+ };
+ const result = cadmataTelosScene({
+ displayScene: scene,
+ highlightedFaceId: 17,
+ showAxisGuide: false,
+ });
+ expect(result.meshes[0].identity.faceId).toBe(17);
+ expect(result.meshes[0].selected).toBe(true);
+ expect(result.lines[0].identity.edgeId).toBe(31);
+ expect(result.lines[0].selected).toBe(true);
+ });
+});
diff --git a/aetheris.client/src/__tests__/telos-witness.tsx b/aetheris.client/src/__tests__/telos-witness.tsx
new file mode 100644
index 00000000..27ea2c9e
--- /dev/null
+++ b/aetheris.client/src/__tests__/telos-witness.tsx
@@ -0,0 +1,74 @@
+/* eslint-disable react-refresh/only-export-components -- standalone browser qualification entry point. */
+import { useState } from "react";
+import { createRoot } from "react-dom/client";
+import { AetherisViewport } from "../viewer/AetherisViewport";
+import type { DisplayScene } from "../viewer/displayRenderables";
+const scene: DisplayScene = {
+ status: "Complete",
+ sourceAuthority: "BRep",
+ displayAuthority: "DisplayIR",
+ lanes: [],
+ diagnostics: [],
+ renderables: [
+ {
+ kind: "MeshPatch",
+ faceId: 17,
+ surfaceKind: "Plane",
+ status: "Mesh",
+ patchKind: "MeshPatch",
+ materializationLane: "BoundedMesh",
+ diagnostics: [],
+ mesh: {
+ faceId: 17,
+ positions: new Float32Array([-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0]),
+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),
+ indices: new Uint32Array([0, 1, 2, 2, 1, 3]),
+ },
+ },
+ {
+ kind: "WirePatch",
+ faceId: 17,
+ surfaceKind: "Plane",
+ status: "Wire",
+ patchKind: "WirePatch",
+ materializationLane: null,
+ diagnostics: [],
+ wires: [
+ {
+ edgeId: 31,
+ points: new Float32Array([
+ -1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0, -1, -1, 0,
+ ]),
+ },
+ ],
+ },
+ ],
+};
+declare global {
+ interface Window {
+ cadmataTelosRay?: {
+ origin: { x: number; y: number; z: number };
+ direction: { x: number; y: number; z: number };
+ };
+ }
+}
+function Witness() {
+ const [selected, setSelected] = useState(false);
+ return (
+ <>
+ <h1>Real Cadmata wrapper + DisplayScene fixture</h1>
+ <button onClick={() => setSelected(!selected)}>Select</button>
+ <div style={{ width: 800, height: 600 }}>
+ <AetherisViewport
+ displayScene={scene}
+ highlightedFaceId={selected ? 17 : null}
+ highlightedEdgeId={selected ? 31 : null}
+ onPickRay={(origin, direction) => {
+ window.cadmataTelosRay = { origin, direction };
+ }}
+ />
+ </div>
+ </>
+ );
+}
+createRoot(document.querySelector("#root")!).render(<Witness />);
diff --git a/aetheris.client/src/viewer/AetherisViewport.tsx b/aetheris.client/src/viewer/AetherisViewport.tsx
index fce7c083..4e9acf58 100644
--- a/aetheris.client/src/viewer/AetherisViewport.tsx
+++ b/aetheris.client/src/viewer/AetherisViewport.tsx
@@ -1,712 +1,126 @@
-/* eslint-disable react-hooks/immutability -- Three.js cameras/renderers are intentionally configured through their imperative mutable API. */
-import { Line, OrbitControls, Text } from "@react-three/drei";
-import { Canvas, useFrame, useThree } from "@react-three/fiber";
-import { matchKind } from "machinalayout/match";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
+import { TelosHost, clearColor } from "@aetheris/three-telos";
import {
- ACESFilmicToneMapping,
- BufferAttribute,
- BufferGeometry,
- DoubleSide,
- Float32BufferAttribute,
- LineBasicMaterial,
- MeshStandardMaterial,
- Matrix4,
- OrthographicCamera,
- Raycaster,
- SRGBColorSpace,
- Vector2,
- Vector3,
-} from "three";
-import type { DisplayScene } from "./displayRenderables";
-import {
- computeDisplaySceneBounds,
- computeOrthographicCameraFit,
- sceneBoundsFromExtents,
-} from "./displaySceneBounds";
-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 { ATELIER_VIEWPORT_THEME, type ViewportTheme } from "./viewportTheme";
-import { DEFAULT_PMI_VISIBILITY, PmiAnnotationLayer, type PmiVisibility } from "./PmiAnnotationLayer";
-import { ThemeBackground } from "./ThemeBackground";
-
-function intersectGround(origin: Vector3, direction: Vector3, y: number): Vector3 | null {
- if (Math.abs(direction.y) < 1e-6) return null;
- const distance = (y - origin.y) / direction.y;
- return Number.isFinite(distance) ? origin.clone().addScaledVector(direction, distance) : null;
-}
-
-function visibleGroundBounds(
- camera: OrthographicCamera,
- y: number,
- extentScale: number,
-): GridBounds {
- const zoom = Math.max(camera.zoom, 0.0001);
- const halfWidth = Math.abs(camera.right - camera.left) / (2 * zoom);
- const halfHeight = Math.abs(camera.top - camera.bottom) / (2 * zoom);
- const right = new Vector3();
- const up = new Vector3();
- const forward = new Vector3();
- camera.updateMatrixWorld(false);
- camera.matrixWorld.extractBasis(right, up, forward);
- const direction = forward.negate().normalize();
- const hits = [-1, 1]
- .flatMap((x) =>
- [-1, 1].map((z) =>
- intersectGround(
- camera.position
- .clone()
- .addScaledVector(right, x * halfWidth)
- .addScaledVector(up, z * halfHeight),
- direction,
- y,
- ),
- ),
- )
- .filter((hit): hit is Vector3 => hit !== null);
-
- if (hits.length < 2) {
- const extent = Math.max(12 / zoom, 4);
- return {
- minX: camera.position.x - extent,
- maxX: camera.position.x + extent,
- minZ: camera.position.z - extent,
- maxZ: camera.position.z + extent,
- };
- }
- const minX = Math.min(...hits.map((hit) => hit.x));
- const maxX = Math.max(...hits.map((hit) => hit.x));
- const minZ = Math.min(...hits.map((hit) => hit.z));
- const maxZ = Math.max(...hits.map((hit) => hit.z));
- const margin = Math.max(maxX - minX, maxZ - minZ) * Math.max(0, extentScale - 1) * 0.5;
- return { minX: minX - margin, maxX: maxX + margin, minZ: minZ - margin, maxZ: maxZ + margin };
-}
-
-function GridSegments({
- positions,
- color,
- opacity,
-}: {
- positions: Float32Array;
- color: string;
- opacity: number;
-}) {
- const geometry = useMemo(() => {
- const next = new BufferGeometry();
- next.setAttribute("position", new Float32BufferAttribute(positions, 3));
- return next;
- }, [positions]);
- const material = useMemo(
- () => new LineBasicMaterial({ color, transparent: true, opacity, depthWrite: false }),
- [color, opacity],
- );
- useEffect(
- () => () => {
- geometry.dispose();
- material.dispose();
- },
- [geometry, material],
- );
- return <lineSegments geometry={geometry} material={material} frustumCulled={false} />;
-}
-
-function AdaptiveLogGrid({ theme }: { theme: ViewportTheme }) {
- const { camera, gl } = useThree();
- const [revision, setRevision] = useState(0);
- const last = useMemo(() => ({ x: Number.NaN, z: Number.NaN, zoom: Number.NaN }), []);
-
- useFrame(() => {
- const orthographic = camera as OrthographicCamera;
- const zoom = Math.max(orthographic.zoom, 0.0001);
- const visibleSpan = Math.max(Math.abs(orthographic.right - orthographic.left) / zoom, 1);
- const moved =
- !Number.isFinite(last.x) ||
- Math.hypot(camera.position.x - last.x, camera.position.z - last.z) > visibleSpan * 0.04;
- const zoomed =
- !Number.isFinite(last.zoom) ||
- Math.abs(zoom - last.zoom) / Math.max(last.zoom, 0.0001) > 0.04;
- if (moved || zoomed) {
- last.x = camera.position.x;
- last.z = camera.position.z;
- last.zoom = zoom;
- setRevision((value) => value + 1);
- }
- });
-
- const plan = useMemo(() => {
- void revision;
- const style = theme.gridStyle;
- return buildAdaptiveGridPlan({
- bounds: visibleGroundBounds(camera as OrthographicCamera, style.yOffset, style.extentScale),
- targetCellCount: style.targetCellCount,
- maxLinesPerAxis: style.maxLinesPerAxis,
- majorStep: style.majorStep,
- y: style.yOffset,
- });
- }, [camera, revision, theme]);
- useEffect(() => {
- if (typeof window !== "undefined" && new URLSearchParams(window.location.search).has("perf")) {
- publishPerformance(gl.domElement, {
- ...(window.__cadmataPerformance ?? {}),
- gridLineCount: plan.lineCount,
- gridDrawCalls: plan.drawCallCount,
- gridAllocatedBytes: plan.allocatedBytes,
- });
- }
- }, [gl, plan]);
-
- return (
- <group
- name="adaptive-log-grid"
- userData={{
- lineCount: plan.lineCount,
- drawCallCount: plan.drawCallCount,
- allocatedBytes: plan.allocatedBytes,
- }}
- >
- {plan.layers.map((layer, index) => (
- <group key={`${layer.spacing}-${index}`}>
- {layer.minorLineCount > 0 ? (
- <GridSegments
- positions={layer.minorPositions}
- color={theme.gridStyle.minorColor}
- opacity={theme.gridStyle.minorOpacity * layer.weight}
- />
- ) : null}
- {layer.majorLineCount > 0 ? (
- <GridSegments
- positions={layer.majorPositions}
- color={theme.gridStyle.majorColor}
- opacity={theme.gridStyle.majorOpacity * layer.weight}
- />
- ) : null}
- </group>
- ))}
- </group>
- );
-}
-
-function publishPerformance(
- canvas: HTMLCanvasElement,
- patch: NonNullable<Window["__cadmataPerformance"]>,
-) {
- let current: NonNullable<Window["__cadmataPerformance"]> = {};
- try {
- current = JSON.parse(canvas.dataset.cadmataPerformance ?? "{}") as typeof current;
- } catch {
- current = {};
- }
- const next = { ...current, ...patch };
- canvas.dataset.cadmataPerformance = JSON.stringify(next);
- window.__cadmataPerformance = next;
-}
-
-declare global {
- interface Window {
- __cadmataPerformance?: {
- averageFrameMs?: number;
- frameSamples?: number;
- drawCalls?: number;
- triangles?: number;
- geometries?: number;
- textures?: number;
- shaderPrograms?: number;
- themeId?: string;
- gridLineCount?: number;
- gridDrawCalls?: number;
- gridAllocatedBytes?: number;
- };
- }
-}
-
-function ViewportPerformanceProbe({ resetKey }: { resetKey: unknown }) {
- const { gl } = useThree();
- const previousTime = useRef<number | null>(null);
- const totalFrameTime = useRef(0);
- const samples = useRef(0);
- const enabled = useMemo(
- () => typeof window !== "undefined" && new URLSearchParams(window.location.search).has("perf"),
- [],
- );
- useEffect(() => {
- previousTime.current = null;
- totalFrameTime.current = 0;
- samples.current = 0;
- }, [resetKey]);
-
- useFrame(() => {
- if (!enabled) return;
- const now = performance.now();
- if (previousTime.current !== null) {
- const frameTime = now - previousTime.current;
- if (frameTime < 250) {
- totalFrameTime.current += frameTime;
- samples.current += 1;
- }
- }
- previousTime.current = now;
- if (samples.current > 0 && samples.current % 30 === 0) {
- publishPerformance(gl.domElement, {
- averageFrameMs: totalFrameTime.current / samples.current,
- frameSamples: samples.current,
- drawCalls: gl.info.render.calls,
- triangles: gl.info.render.triangles,
- geometries: gl.info.memory.geometries,
- textures: gl.info.memory.textures,
- shaderPrograms: gl.info.programs?.length ?? 0,
- });
- }
- });
-
- 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;
-}
-
-function FaceMesh({
- positions,
- normals,
- indices,
- isHighlighted,
- theme,
-}: {
- positions: Float32Array;
- normals: Float32Array;
- indices: Uint32Array;
- isHighlighted: boolean;
- theme: ViewportTheme;
-}) {
- const geometry = useMemo(() => {
- const next = new BufferGeometry();
- next.setAttribute("position", new BufferAttribute(positions, 3));
- next.setAttribute("normal", new BufferAttribute(normals, 3));
- next.setIndex(new BufferAttribute(indices, 1));
- next.computeBoundingSphere();
- return next;
- }, [indices, normals, positions]);
- const material = useMemo(
- () =>
- new MeshStandardMaterial({
- color: isHighlighted ? theme.selectedMaterial.color : theme.objectMaterial.color,
- emissive: isHighlighted ? theme.selectedMaterial.emissive : "#000000",
- emissiveIntensity: isHighlighted ? theme.selectedMaterial.emissiveIntensity : 0,
- metalness: theme.objectMaterial.metalness,
- roughness: theme.objectMaterial.roughness,
- side: DoubleSide,
- }),
- [isHighlighted, theme],
- );
- useEffect(
- () => () => {
- geometry.dispose();
- material.dispose();
- },
- [geometry, material],
- );
- return (
- <mesh
- geometry={geometry}
- material={material}
- castShadow={theme.shadowStyle.enabled}
- receiveShadow={theme.shadowStyle.enabled}
- />
- );
-}
-
-function AxisGuide({ theme }: { theme: ViewportTheme }) {
- const end = 2;
- return (
- <group>
- <Line
- points={[
- [0, 0, 0],
- [end, 0, 0],
- ]}
- color={theme.axis.x}
- lineWidth={1}
- />
- <Line
- points={[
- [0, 0, 0],
- [0, end, 0],
- ]}
- color={theme.axis.y}
- lineWidth={1}
- />
- <Line
- points={[
- [0, 0, 0],
- [0, 0, end],
- ]}
- color={theme.axis.z}
- lineWidth={1}
- />
- {(["X", "Y", "Z"] as const).map((label, index) => (
- <Text
- key={label}
- position={index === 0 ? [2.14, 0, 0] : index === 1 ? [0, 2.14, 0] : [0, 0, 2.14]}
- fontSize={0.16}
- color={theme.axis.label}
- >
- {label}
- </Text>
- ))}
- </group>
- );
-}
-
-function EdgeLine({
- points,
- isHighlighted,
- theme,
-}: {
- points: Float32Array;
- isHighlighted: boolean;
- theme: ViewportTheme;
-}) {
- const linePoints = useMemo(
- () =>
- Array.from(
- { length: points.length / 3 },
- (_, index) =>
- [points[index * 3], points[index * 3 + 1], points[index * 3 + 2]] as [
- number,
- number,
- number,
- ],
- ),
- [points],
- );
- return (
- <Line
- points={linePoints}
- color={isHighlighted ? theme.edgeStyle.selectedColor : theme.edgeStyle.color}
- lineWidth={isHighlighted ? theme.edgeStyle.selectedWidth : theme.edgeStyle.width}
- />
- );
-}
-
-function PickRayCapture({ onPickRay }: { onPickRay?: AetherisViewportProps["onPickRay"] }) {
- const { camera, gl } = useThree();
- useEffect(() => {
- if (!onPickRay) return;
- const raycaster = new Raycaster();
- const pointer = new Vector2();
- const handleClick = (event: MouseEvent) => {
- if (event.button !== 0) return;
- const rect = gl.domElement.getBoundingClientRect();
- pointer.set(
- ((event.clientX - rect.left) / rect.width) * 2 - 1,
- -((event.clientY - rect.top) / rect.height) * 2 + 1,
- );
- raycaster.setFromCamera(pointer, camera);
- onPickRay({ ...raycaster.ray.origin }, { ...raycaster.ray.direction });
- };
- gl.domElement.addEventListener("click", handleClick);
- return () => gl.domElement.removeEventListener("click", handleClick);
- }, [camera, gl.domElement, onPickRay]);
- return null;
-}
-
-function FitCameraToScene({ displayScene }: { displayScene: DisplayScene | null }) {
- const { camera, controls, size } = useThree();
- const bounds = useMemo(() => computeDisplaySceneBounds(displayScene), [displayScene]);
- useEffect(() => {
- if (!(camera instanceof OrthographicCamera) || !bounds.isValid) return;
- const fit = computeOrthographicCameraFit(
- bounds,
- Math.abs(camera.right - camera.left) || size.width || 1,
- Math.abs(camera.top - camera.bottom) || size.height || 1,
- );
- if (!fit) return;
- camera.position.set(...fit.position);
- camera.zoom = fit.zoom;
- camera.near = fit.near;
- camera.far = fit.far;
- camera.lookAt(...fit.target);
- camera.updateProjectionMatrix();
- camera.updateMatrixWorld(false);
- if (controls && typeof controls === "object" && "target" in controls) {
- const orbit = controls as { target: Vector3; update?: () => void };
- orbit.target.set(...fit.target);
- orbit.update?.();
- }
- }, [bounds, camera, controls, size.height, size.width]);
- return null;
-}
-
-function FitCameraToAssembly({ packet }: { packet: AssemblyDisplayPacketDto | null }) {
- const { camera, controls, size } = useThree();
- const bounds = useMemo(
- () =>
- packet
- ? sceneBoundsFromExtents(packet.bounds.minimum, packet.bounds.maximum)
- : sceneBoundsFromExtents([], []),
- [packet],
- );
- useEffect(() => {
- if (!(camera instanceof OrthographicCamera) || !bounds.isValid) return;
- const fit = computeOrthographicCameraFit(
- bounds,
- Math.abs(camera.right - camera.left) || size.width || 1,
- Math.abs(camera.top - camera.bottom) || size.height || 1,
- );
- if (!fit) return;
- camera.position.set(...fit.position);
- camera.zoom = fit.zoom;
- camera.near = fit.near;
- camera.far = fit.far;
- camera.lookAt(...fit.target);
- camera.updateProjectionMatrix();
- camera.updateMatrixWorld(false);
- if (controls && typeof controls === "object" && "target" in controls) {
- const orbit = controls as { target: Vector3; update?: () => void };
- orbit.target.set(...fit.target);
- orbit.update?.();
- }
- }, [bounds, camera, controls, size.height, size.width]);
- return null;
-}
-
-function AssemblyMeshes({
- packet,
- selectedId,
- onSelect,
- theme,
-}: {
- packet: AssemblyDisplayPacketDto;
- selectedId: string | null;
- onSelect: (stableId: string) => void;
- theme: ViewportTheme;
-}) {
- const definitions = useMemo(
- () =>
- new Map(
- packet.definitions.map((definition) => [
- definition.stableId,
- definition.facePatches.map(mapFacePatchToRenderFacePatch),
- ]),
- ),
- [packet],
- );
- const selectedMembers = useMemo(
- () =>
- new Set(
- packet.occurrences.find((item) => item.stableId === selectedId)?.selectionMembers ??
- (selectedId ? [selectedId] : []),
- ),
- [packet, selectedId],
- );
- return packet.occurrences
- .filter((occurrence) => occurrence.kind === "Part" && occurrence.definitionStableId)
- .map((occurrence) => {
- const matrix = new Matrix4().fromArray(occurrence.worldTransform);
- return (
- <group
- key={occurrence.stableId}
- matrix={matrix}
- matrixAutoUpdate={false}
- onClick={(event) => {
- event.stopPropagation();
- onSelect(occurrence.stableId);
- }}
- >
- {(definitions.get(occurrence.definitionStableId!) ?? []).map((patch) => (
- <FaceMesh
- key={`${occurrence.stableId}-${patch.faceId}`}
- positions={patch.positions}
- normals={patch.normals}
- indices={patch.indices}
- isHighlighted={selectedMembers.has(occurrence.stableId)}
- theme={theme}
- />
- ))}
- </group>
- );
- });
-}
-
-function RendererConfiguration({ theme }: { theme: ViewportTheme }) {
- const { gl } = useThree();
- useEffect(() => {
- gl.outputColorSpace = SRGBColorSpace;
- gl.toneMapping = ACESFilmicToneMapping;
- gl.toneMappingExposure = theme.environment.toneMappingExposure;
- }, [gl, theme]);
- return null;
-}
-
-export function AetherisViewport({
- displayScene = null,
- highlightedFaceId = null,
- highlightedEdgeId = null,
- highlightedFaceIds,
- highlightedEdgeIds,
- showGrid = true,
- showAxisGuide = true,
- theme = ATELIER_VIEWPORT_THEME,
- onPickRay,
- cadmataArtifact = null,
- cadmataLayers,
- selectedCadmataIds = new Set(),
- onCadmataSelect = () => undefined,
- showPmi = true,
- pmiVisibility = DEFAULT_PMI_VISIBILITY,
- assemblyPacket = null,
- selectedAssemblyOccurrenceId = null,
- onAssemblyOccurrenceSelect = () => undefined,
-}: AetherisViewportProps) {
- return (
- <Canvas
- style={{ display: "block", width: "100%", height: "100%", background: theme.sceneBackground }}
- orthographic
- shadows={theme.shadowStyle.enabled}
- camera={{
- position: [...theme.cameraPresentation.position],
- zoom: theme.cameraPresentation.zoom,
- near: -10000,
- far: 10000,
- }}
- gl={{ alpha: false, antialias: true }}
- onCreated={({ gl }) => {
- if (new URLSearchParams(window.location.search).has("perf")) {
- publishPerformance(gl.domElement, {
- drawCalls: gl.info.render.calls,
- triangles: gl.info.render.triangles,
- geometries: gl.info.memory.geometries,
- textures: gl.info.memory.textures,
- });
- }
- }}
- >
- <color attach="background" args={[theme.sceneBackground]} />
- <ThemeBackground theme={theme} />
- {theme.fog.enabled ? (
- <fog attach="fog" args={[theme.fog.color, theme.fog.near, theme.fog.far]} />
- ) : null}
- <RendererConfiguration theme={theme} />
- <ViewportPerformanceProbe resetKey={`${theme.id}:${displayScene?.renderables.length ?? 0}`} />
- <ambientLight intensity={theme.lights.ambient} />
- <hemisphereLight
- args={[
- theme.lights.hemisphereSky,
- theme.lights.hemisphereGround,
- theme.lights.hemisphereIntensity,
- ]}
- />
- <directionalLight
- position={[...theme.lights.keyPosition]}
- color={theme.lights.keyColor}
- intensity={theme.lights.keyIntensity}
- castShadow={theme.shadowStyle.enabled}
- />
- <directionalLight
- position={[...theme.lights.rimPosition]}
- color={theme.lights.rimColor}
- intensity={theme.lights.rimIntensity}
- />
- <directionalLight
- position={[...theme.lights.fillPosition]}
- color={theme.lights.fillColor}
- intensity={theme.lights.fillIntensity}
- />
- <FitCameraToScene displayScene={displayScene} />
- <FitCameraToAssembly packet={assemblyPacket} />
- {showGrid && theme.gridStyle.enabled ? <AdaptiveLogGrid theme={theme} /> : null}
- {showAxisGuide ? <AxisGuide theme={theme} /> : null}
- {displayScene?.renderables.flatMap((renderable) =>
- matchKind(renderable, {
- AnalyticPatch: (patch) => [
- <FaceMesh
- key={`analytic-${patch.faceId}`}
- positions={patch.previewMesh.positions}
- normals={patch.previewMesh.normals}
- indices={patch.previewMesh.indices}
- isHighlighted={
- highlightedFaceIds?.has(patch.faceId) ?? highlightedFaceId === patch.faceId
- }
- theme={theme}
- />,
- ],
- MeshPatch: (patch) => [
- <FaceMesh
- key={`mesh-${patch.faceId}`}
- positions={patch.mesh.positions}
- normals={patch.mesh.normals}
- indices={patch.mesh.indices}
- isHighlighted={
- highlightedFaceIds?.has(patch.faceId) ?? highlightedFaceId === patch.faceId
- }
- theme={theme}
- />,
- ],
- WirePatch: (patch) =>
- patch.wires.map((wire) => (
- <EdgeLine
- key={`wire-${patch.faceId}-${wire.edgeId}`}
- points={wire.points}
- isHighlighted={
- (highlightedFaceIds?.has(patch.faceId) ?? highlightedFaceId === patch.faceId) ||
- (highlightedEdgeIds?.has(wire.edgeId) ?? highlightedEdgeId === wire.edgeId)
- }
- theme={theme}
- />
- )),
- DiagnosticPatch: () => [],
- }),
- )}
- {assemblyPacket ? (
- <AssemblyMeshes
- packet={assemblyPacket}
- selectedId={selectedAssemblyOccurrenceId}
- onSelect={onAssemblyOccurrenceSelect}
- theme={theme}
- />
- ) : null}
- {cadmataLayers ? (
- <CadmataOverlay
- artifact={cadmataArtifact}
- layers={cadmataLayers}
- selectedIds={selectedCadmataIds}
- onSelect={onCadmataSelect}
- theme={theme}
- />
- ) : null}
- <PmiAnnotationLayer
- artifact={cadmataArtifact}
- visible={showPmi}
- visibility={pmiVisibility}
- selectedIds={selectedCadmataIds}
- onSelect={onCadmataSelect}
- theme={theme}
- />
- <PickRayCapture onPickRay={onPickRay} />
- <OrbitControls makeDefault enablePan enableZoom />
- </Canvas>
- );
+ LegacyAetherisViewport,
+ type AetherisViewportProps,
+} from "./LegacyAetherisViewport";
+import { cadmataTelosScene } from "./cadmataTelos";
+import { ATELIER_VIEWPORT_THEME } from "./viewportTheme";
+export type { AetherisViewportProps } from "./LegacyAetherisViewport";
+
+/** Transitional WebGL remains for unsupported GPUs and unmigrated semantic authoring/PMI overlays. */
+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;
+ if (legacyReason)
+ return (
+ <div
+ style={{ width: "100%", height: "100%", position: "relative" }}
+ data-display-host="transitional-webgl"
+ data-display-reason={legacyReason}
+ >
+ <LegacyAetherisViewport {...props} />
+ <small
+ style={{
+ position: "absolute",
+ bottom: 4,
+ left: 8,
+ pointerEvents: "none",
+ }}
+ >
+ Transitional WebGL: {legacyReason}
+ </small>
+ </div>
+ );
+ return <TelosViewport {...props} />;
+}
+
+function TelosViewport(props: AetherisViewportProps) {
+ const canvas = useRef<HTMLCanvasElement>(null),
+ container = useRef<HTMLDivElement>(null),
+ host = useRef<TelosHost | null>(null);
+ const latest = useRef(props);
+ const [diagnostic, setDiagnostic] = useState<string | null>(null);
+ const lastModel = useRef<unknown>(undefined);
+ const apply = () => {
+ const current = host.current;
+ if (!current) return;
+ const value = latest.current,
+ theme = value.theme ?? ATELIER_VIEWPORT_THEME;
+ current.setScene(cadmataTelosScene(value));
+ current.background = clearColor(theme.sceneBackground);
+ current.grid = value.showGrid !== false && theme.gridStyle.enabled;
+ const model = value.assemblyPacket ?? value.displayScene;
+ if (lastModel.current !== model) {
+ lastModel.current = model;
+ current.fit();
+ }
+ current.invalidate();
+ };
+ useEffect(() => {
+ let disposed = false;
+ const element = canvas.current;
+ if (!element) return;
+ const click = (event: MouseEvent) => {
+ const current = host.current;
+ if (!current) return;
+ const rect = element.getBoundingClientRect(),
+ pixel: [number, number] = [
+ event.clientX - rect.left,
+ event.clientY - rect.top,
+ ];
+ 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);
+ };
+ element.addEventListener("click", click);
+ void TelosHost.create(element, setDiagnostic)
+ .then((current) => {
+ if (disposed) {
+ current.dispose();
+ return;
+ }
+ host.current = current;
+ current.camera.mode = "orthographic";
+ current.attach(container.current!);
+ apply();
+ })
+ .catch((error) => {
+ if (!disposed) setDiagnostic(String(error));
+ });
+ return () => {
+ disposed = true;
+ element.removeEventListener("click", click);
+ host.current?.dispose();
+ host.current = null;
+ };
+ }, []);
+ useEffect(() => {
+ latest.current = props;
+ apply();
+ }, [props]);
+ return (
+ <div
+ ref={container}
+ style={{ width: "100%", height: "100%", position: "relative" }}
+ data-display-host="three-telos"
+ >
+ <canvas
+ ref={canvas}
+ aria-label="Engineering WebGPU viewport"
+ style={{ display: "block", width: "100%", height: "100%" }}
+ />
+ {diagnostic && <div role="alert">{diagnostic}</div>}
+ </div>
+ );
}
diff --git a/aetheris.client/src/viewer/LegacyAetherisViewport.tsx b/aetheris.client/src/viewer/LegacyAetherisViewport.tsx
new file mode 100644
index 00000000..4e811ce4
--- /dev/null
+++ b/aetheris.client/src/viewer/LegacyAetherisViewport.tsx
@@ -0,0 +1,712 @@
+/* eslint-disable react-hooks/immutability -- Three.js cameras/renderers are intentionally configured through their imperative mutable API. */
+import { Line, OrbitControls, Text } from "@react-three/drei";
+import { Canvas, useFrame, useThree } from "@react-three/fiber";
+import { matchKind } from "machinalayout/match";
+import { useEffect, useMemo, useRef, useState } from "react";
+import {
+ ACESFilmicToneMapping,
+ BufferAttribute,
+ BufferGeometry,
+ DoubleSide,
+ Float32BufferAttribute,
+ LineBasicMaterial,
+ MeshStandardMaterial,
+ Matrix4,
+ OrthographicCamera,
+ Raycaster,
+ SRGBColorSpace,
+ Vector2,
+ Vector3,
+} from "three";
+import type { DisplayScene } from "./displayRenderables";
+import {
+ computeDisplaySceneBounds,
+ computeOrthographicCameraFit,
+ sceneBoundsFromExtents,
+} from "./displaySceneBounds";
+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 { ATELIER_VIEWPORT_THEME, type ViewportTheme } from "./viewportTheme";
+import { DEFAULT_PMI_VISIBILITY, PmiAnnotationLayer, type PmiVisibility } from "./PmiAnnotationLayer";
+import { ThemeBackground } from "./ThemeBackground";
+
+function intersectGround(origin: Vector3, direction: Vector3, y: number): Vector3 | null {
+ if (Math.abs(direction.y) < 1e-6) return null;
+ const distance = (y - origin.y) / direction.y;
+ return Number.isFinite(distance) ? origin.clone().addScaledVector(direction, distance) : null;
+}
+
+function visibleGroundBounds(
+ camera: OrthographicCamera,
+ y: number,
+ extentScale: number,
+): GridBounds {
+ const zoom = Math.max(camera.zoom, 0.0001);
+ const halfWidth = Math.abs(camera.right - camera.left) / (2 * zoom);
+ const halfHeight = Math.abs(camera.top - camera.bottom) / (2 * zoom);
+ const right = new Vector3();
+ const up = new Vector3();
+ const forward = new Vector3();
+ camera.updateMatrixWorld(false);
+ camera.matrixWorld.extractBasis(right, up, forward);
+ const direction = forward.negate().normalize();
+ const hits = [-1, 1]
+ .flatMap((x) =>
+ [-1, 1].map((z) =>
+ intersectGround(
+ camera.position
+ .clone()
+ .addScaledVector(right, x * halfWidth)
+ .addScaledVector(up, z * halfHeight),
+ direction,
+ y,
+ ),
+ ),
+ )
+ .filter((hit): hit is Vector3 => hit !== null);
+
+ if (hits.length < 2) {
+ const extent = Math.max(12 / zoom, 4);
+ return {
+ minX: camera.position.x - extent,
+ maxX: camera.position.x + extent,
+ minZ: camera.position.z - extent,
+ maxZ: camera.position.z + extent,
+ };
+ }
+ const minX = Math.min(...hits.map((hit) => hit.x));
+ const maxX = Math.max(...hits.map((hit) => hit.x));
+ const minZ = Math.min(...hits.map((hit) => hit.z));
+ const maxZ = Math.max(...hits.map((hit) => hit.z));
+ const margin = Math.max(maxX - minX, maxZ - minZ) * Math.max(0, extentScale - 1) * 0.5;
+ return { minX: minX - margin, maxX: maxX + margin, minZ: minZ - margin, maxZ: maxZ + margin };
+}
+
+function GridSegments({
+ positions,
+ color,
+ opacity,
+}: {
+ positions: Float32Array;
+ color: string;
+ opacity: number;
+}) {
+ const geometry = useMemo(() => {
+ const next = new BufferGeometry();
+ next.setAttribute("position", new Float32BufferAttribute(positions, 3));
+ return next;
+ }, [positions]);
+ const material = useMemo(
+ () => new LineBasicMaterial({ color, transparent: true, opacity, depthWrite: false }),
+ [color, opacity],
+ );
+ useEffect(
+ () => () => {
+ geometry.dispose();
+ material.dispose();
+ },
+ [geometry, material],
+ );
+ return <lineSegments geometry={geometry} material={material} frustumCulled={false} />;
+}
+
+function AdaptiveLogGrid({ theme }: { theme: ViewportTheme }) {
+ const { camera, gl } = useThree();
+ const [revision, setRevision] = useState(0);
+ const last = useMemo(() => ({ x: Number.NaN, z: Number.NaN, zoom: Number.NaN }), []);
+
+ useFrame(() => {
+ const orthographic = camera as OrthographicCamera;
+ const zoom = Math.max(orthographic.zoom, 0.0001);
+ const visibleSpan = Math.max(Math.abs(orthographic.right - orthographic.left) / zoom, 1);
+ const moved =
+ !Number.isFinite(last.x) ||
+ Math.hypot(camera.position.x - last.x, camera.position.z - last.z) > visibleSpan * 0.04;
+ const zoomed =
+ !Number.isFinite(last.zoom) ||
+ Math.abs(zoom - last.zoom) / Math.max(last.zoom, 0.0001) > 0.04;
+ if (moved || zoomed) {
+ last.x = camera.position.x;
+ last.z = camera.position.z;
+ last.zoom = zoom;
+ setRevision((value) => value + 1);
+ }
+ });
+
+ const plan = useMemo(() => {
+ void revision;
+ const style = theme.gridStyle;
+ return buildAdaptiveGridPlan({
+ bounds: visibleGroundBounds(camera as OrthographicCamera, style.yOffset, style.extentScale),
+ targetCellCount: style.targetCellCount,
+ maxLinesPerAxis: style.maxLinesPerAxis,
+ majorStep: style.majorStep,
+ y: style.yOffset,
+ });
+ }, [camera, revision, theme]);
+ useEffect(() => {
+ if (typeof window !== "undefined" && new URLSearchParams(window.location.search).has("perf")) {
+ publishPerformance(gl.domElement, {
+ ...(window.__cadmataPerformance ?? {}),
+ gridLineCount: plan.lineCount,
+ gridDrawCalls: plan.drawCallCount,
+ gridAllocatedBytes: plan.allocatedBytes,
+ });
+ }
+ }, [gl, plan]);
+
+ return (
+ <group
+ name="adaptive-log-grid"
+ userData={{
+ lineCount: plan.lineCount,
+ drawCallCount: plan.drawCallCount,
+ allocatedBytes: plan.allocatedBytes,
+ }}
+ >
+ {plan.layers.map((layer, index) => (
+ <group key={`${layer.spacing}-${index}`}>
+ {layer.minorLineCount > 0 ? (
+ <GridSegments
+ positions={layer.minorPositions}
+ color={theme.gridStyle.minorColor}
+ opacity={theme.gridStyle.minorOpacity * layer.weight}
+ />
+ ) : null}
+ {layer.majorLineCount > 0 ? (
+ <GridSegments
+ positions={layer.majorPositions}
+ color={theme.gridStyle.majorColor}
+ opacity={theme.gridStyle.majorOpacity * layer.weight}
+ />
+ ) : null}
+ </group>
+ ))}
+ </group>
+ );
+}
+
+function publishPerformance(
+ canvas: HTMLCanvasElement,
+ patch: NonNullable<Window["__cadmataPerformance"]>,
+) {
+ let current: NonNullable<Window["__cadmataPerformance"]> = {};
+ try {
+ current = JSON.parse(canvas.dataset.cadmataPerformance ?? "{}") as typeof current;
+ } catch {
+ current = {};
+ }
+ const next = { ...current, ...patch };
+ canvas.dataset.cadmataPerformance = JSON.stringify(next);
+ window.__cadmataPerformance = next;
+}
+
+declare global {
+ interface Window {
+ __cadmataPerformance?: {
+ averageFrameMs?: number;
+ frameSamples?: number;
+ drawCalls?: number;
+ triangles?: number;
+ geometries?: number;
+ textures?: number;
+ shaderPrograms?: number;
+ themeId?: string;
+ gridLineCount?: number;
+ gridDrawCalls?: number;
+ gridAllocatedBytes?: number;
+ };
+ }
+}
+
+function ViewportPerformanceProbe({ resetKey }: { resetKey: unknown }) {
+ const { gl } = useThree();
+ const previousTime = useRef<number | null>(null);
+ const totalFrameTime = useRef(0);
+ const samples = useRef(0);
+ const enabled = useMemo(
+ () => typeof window !== "undefined" && new URLSearchParams(window.location.search).has("perf"),
+ [],
+ );
+ useEffect(() => {
+ previousTime.current = null;
+ totalFrameTime.current = 0;
+ samples.current = 0;
+ }, [resetKey]);
+
+ useFrame(() => {
+ if (!enabled) return;
+ const now = performance.now();
+ if (previousTime.current !== null) {
+ const frameTime = now - previousTime.current;
+ if (frameTime < 250) {
+ totalFrameTime.current += frameTime;
+ samples.current += 1;
+ }
+ }
+ previousTime.current = now;
+ if (samples.current > 0 && samples.current % 30 === 0) {
+ publishPerformance(gl.domElement, {
+ averageFrameMs: totalFrameTime.current / samples.current,
+ frameSamples: samples.current,
+ drawCalls: gl.info.render.calls,
+ triangles: gl.info.render.triangles,
+ geometries: gl.info.memory.geometries,
+ textures: gl.info.memory.textures,
+ shaderPrograms: gl.info.programs?.length ?? 0,
+ });
+ }
+ });
+
+ 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;
+}
+
+function FaceMesh({
+ positions,
+ normals,
+ indices,
+ isHighlighted,
+ theme,
+}: {
+ positions: Float32Array;
+ normals: Float32Array;
+ indices: Uint32Array;
+ isHighlighted: boolean;
+ theme: ViewportTheme;
+}) {
+ const geometry = useMemo(() => {
+ const next = new BufferGeometry();
+ next.setAttribute("position", new BufferAttribute(positions, 3));
+ next.setAttribute("normal", new BufferAttribute(normals, 3));
+ next.setIndex(new BufferAttribute(indices, 1));
+ next.computeBoundingSphere();
+ return next;
+ }, [indices, normals, positions]);
+ const material = useMemo(
+ () =>
+ new MeshStandardMaterial({
+ color: isHighlighted ? theme.selectedMaterial.color : theme.objectMaterial.color,
+ emissive: isHighlighted ? theme.selectedMaterial.emissive : "#000000",
+ emissiveIntensity: isHighlighted ? theme.selectedMaterial.emissiveIntensity : 0,
+ metalness: theme.objectMaterial.metalness,
+ roughness: theme.objectMaterial.roughness,
+ side: DoubleSide,
+ }),
+ [isHighlighted, theme],
+ );
+ useEffect(
+ () => () => {
+ geometry.dispose();
+ material.dispose();
+ },
+ [geometry, material],
+ );
+ return (
+ <mesh
+ geometry={geometry}
+ material={material}
+ castShadow={theme.shadowStyle.enabled}
+ receiveShadow={theme.shadowStyle.enabled}
+ />
+ );
+}
+
+function AxisGuide({ theme }: { theme: ViewportTheme }) {
+ const end = 2;
+ return (
+ <group>
+ <Line
+ points={[
+ [0, 0, 0],
+ [end, 0, 0],
+ ]}
+ color={theme.axis.x}
+ lineWidth={1}
+ />
+ <Line
+ points={[
+ [0, 0, 0],
+ [0, end, 0],
+ ]}
+ color={theme.axis.y}
+ lineWidth={1}
+ />
+ <Line
+ points={[
+ [0, 0, 0],
+ [0, 0, end],
+ ]}
+ color={theme.axis.z}
+ lineWidth={1}
+ />
+ {(["X", "Y", "Z"] as const).map((label, index) => (
+ <Text
+ key={label}
+ position={index === 0 ? [2.14, 0, 0] : index === 1 ? [0, 2.14, 0] : [0, 0, 2.14]}
+ fontSize={0.16}
+ color={theme.axis.label}
+ >
+ {label}
+ </Text>
+ ))}
+ </group>
+ );
+}
+
+function EdgeLine({
+ points,
+ isHighlighted,
+ theme,
+}: {
+ points: Float32Array;
+ isHighlighted: boolean;
+ theme: ViewportTheme;
+}) {
+ const linePoints = useMemo(
+ () =>
+ Array.from(
+ { length: points.length / 3 },
+ (_, index) =>
+ [points[index * 3], points[index * 3 + 1], points[index * 3 + 2]] as [
+ number,
+ number,
+ number,
+ ],
+ ),
+ [points],
+ );
+ return (
+ <Line
+ points={linePoints}
+ color={isHighlighted ? theme.edgeStyle.selectedColor : theme.edgeStyle.color}
+ lineWidth={isHighlighted ? theme.edgeStyle.selectedWidth : theme.edgeStyle.width}
+ />
+ );
+}
+
+function PickRayCapture({ onPickRay }: { onPickRay?: AetherisViewportProps["onPickRay"] }) {
+ const { camera, gl } = useThree();
+ useEffect(() => {
+ if (!onPickRay) return;
+ const raycaster = new Raycaster();
+ const pointer = new Vector2();
+ const handleClick = (event: MouseEvent) => {
+ if (event.button !== 0) return;
+ const rect = gl.domElement.getBoundingClientRect();
+ pointer.set(
+ ((event.clientX - rect.left) / rect.width) * 2 - 1,
+ -((event.clientY - rect.top) / rect.height) * 2 + 1,
+ );
+ raycaster.setFromCamera(pointer, camera);
+ onPickRay({ ...raycaster.ray.origin }, { ...raycaster.ray.direction });
+ };
+ gl.domElement.addEventListener("click", handleClick);
+ return () => gl.domElement.removeEventListener("click", handleClick);
+ }, [camera, gl.domElement, onPickRay]);
+ return null;
+}
+
+function FitCameraToScene({ displayScene }: { displayScene: DisplayScene | null }) {
+ const { camera, controls, size } = useThree();
+ const bounds = useMemo(() => computeDisplaySceneBounds(displayScene), [displayScene]);
+ useEffect(() => {
+ if (!(camera instanceof OrthographicCamera) || !bounds.isValid) return;
+ const fit = computeOrthographicCameraFit(
+ bounds,
+ Math.abs(camera.right - camera.left) || size.width || 1,
+ Math.abs(camera.top - camera.bottom) || size.height || 1,
+ );
+ if (!fit) return;
+ camera.position.set(...fit.position);
+ camera.zoom = fit.zoom;
+ camera.near = fit.near;
+ camera.far = fit.far;
+ camera.lookAt(...fit.target);
+ camera.updateProjectionMatrix();
+ camera.updateMatrixWorld(false);
+ if (controls && typeof controls === "object" && "target" in controls) {
+ const orbit = controls as { target: Vector3; update?: () => void };
+ orbit.target.set(...fit.target);
+ orbit.update?.();
+ }
+ }, [bounds, camera, controls, size.height, size.width]);
+ return null;
+}
+
+function FitCameraToAssembly({ packet }: { packet: AssemblyDisplayPacketDto | null }) {
+ const { camera, controls, size } = useThree();
+ const bounds = useMemo(
+ () =>
+ packet
+ ? sceneBoundsFromExtents(packet.bounds.minimum, packet.bounds.maximum)
+ : sceneBoundsFromExtents([], []),
+ [packet],
+ );
+ useEffect(() => {
+ if (!(camera instanceof OrthographicCamera) || !bounds.isValid) return;
+ const fit = computeOrthographicCameraFit(
+ bounds,
+ Math.abs(camera.right - camera.left) || size.width || 1,
+ Math.abs(camera.top - camera.bottom) || size.height || 1,
+ );
+ if (!fit) return;
+ camera.position.set(...fit.position);
+ camera.zoom = fit.zoom;
+ camera.near = fit.near;
+ camera.far = fit.far;
+ camera.lookAt(...fit.target);
+ camera.updateProjectionMatrix();
+ camera.updateMatrixWorld(false);
+ if (controls && typeof controls === "object" && "target" in controls) {
+ const orbit = controls as { target: Vector3; update?: () => void };
+ orbit.target.set(...fit.target);
+ orbit.update?.();
+ }
+ }, [bounds, camera, controls, size.height, size.width]);
+ return null;
+}
+
+function AssemblyMeshes({
+ packet,
+ selectedId,
+ onSelect,
+ theme,
+}: {
+ packet: AssemblyDisplayPacketDto;
+ selectedId: string | null;
+ onSelect: (stableId: string) => void;
+ theme: ViewportTheme;
+}) {
+ const definitions = useMemo(
+ () =>
+ new Map(
+ packet.definitions.map((definition) => [
+ definition.stableId,
+ definition.facePatches.map(mapFacePatchToRenderFacePatch),
+ ]),
+ ),
+ [packet],
+ );
+ const selectedMembers = useMemo(
+ () =>
+ new Set(
+ packet.occurrences.find((item) => item.stableId === selectedId)?.selectionMembers ??
+ (selectedId ? [selectedId] : []),
+ ),
+ [packet, selectedId],
+ );
+ return packet.occurrences
+ .filter((occurrence) => occurrence.kind === "Part" && occurrence.definitionStableId)
+ .map((occurrence) => {
+ const matrix = new Matrix4().fromArray(occurrence.worldTransform);
+ return (
+ <group
+ key={occurrence.stableId}
+ matrix={matrix}
+ matrixAutoUpdate={false}
+ onClick={(event) => {
+ event.stopPropagation();
+ onSelect(occurrence.stableId);
+ }}
+ >
+ {(definitions.get(occurrence.definitionStableId!) ?? []).map((patch) => (
+ <FaceMesh
+ key={`${occurrence.stableId}-${patch.faceId}`}
+ positions={patch.positions}
+ normals={patch.normals}
+ indices={patch.indices}
+ isHighlighted={selectedMembers.has(occurrence.stableId)}
+ theme={theme}
+ />
+ ))}
+ </group>
+ );
+ });
+}
+
+function RendererConfiguration({ theme }: { theme: ViewportTheme }) {
+ const { gl } = useThree();
+ useEffect(() => {
+ gl.outputColorSpace = SRGBColorSpace;
+ gl.toneMapping = ACESFilmicToneMapping;
+ gl.toneMappingExposure = theme.environment.toneMappingExposure;
+ }, [gl, theme]);
+ return null;
+}
+
+export function LegacyAetherisViewport({
+ displayScene = null,
+ highlightedFaceId = null,
+ highlightedEdgeId = null,
+ highlightedFaceIds,
+ highlightedEdgeIds,
+ showGrid = true,
+ showAxisGuide = true,
+ theme = ATELIER_VIEWPORT_THEME,
+ onPickRay,
+ cadmataArtifact = null,
+ cadmataLayers,
+ selectedCadmataIds = new Set(),
+ onCadmataSelect = () => undefined,
+ showPmi = true,
+ pmiVisibility = DEFAULT_PMI_VISIBILITY,
+ assemblyPacket = null,
+ selectedAssemblyOccurrenceId = null,
+ onAssemblyOccurrenceSelect = () => undefined,
+}: AetherisViewportProps) {
+ return (
+ <Canvas
+ style={{ display: "block", width: "100%", height: "100%", background: theme.sceneBackground }}
+ orthographic
+ shadows={theme.shadowStyle.enabled}
+ camera={{
+ position: [...theme.cameraPresentation.position],
+ zoom: theme.cameraPresentation.zoom,
+ near: -10000,
+ far: 10000,
+ }}
+ gl={{ alpha: false, antialias: true }}
+ onCreated={({ gl }) => {
+ if (new URLSearchParams(window.location.search).has("perf")) {
+ publishPerformance(gl.domElement, {
+ drawCalls: gl.info.render.calls,
+ triangles: gl.info.render.triangles,
+ geometries: gl.info.memory.geometries,
+ textures: gl.info.memory.textures,
+ });
+ }
+ }}
+ >
+ <color attach="background" args={[theme.sceneBackground]} />
+ <ThemeBackground theme={theme} />
+ {theme.fog.enabled ? (
+ <fog attach="fog" args={[theme.fog.color, theme.fog.near, theme.fog.far]} />
+ ) : null}
+ <RendererConfiguration theme={theme} />
+ <ViewportPerformanceProbe resetKey={`${theme.id}:${displayScene?.renderables.length ?? 0}`} />
+ <ambientLight intensity={theme.lights.ambient} />
+ <hemisphereLight
+ args={[
+ theme.lights.hemisphereSky,
+ theme.lights.hemisphereGround,
+ theme.lights.hemisphereIntensity,
+ ]}
+ />
+ <directionalLight
+ position={[...theme.lights.keyPosition]}
+ color={theme.lights.keyColor}
+ intensity={theme.lights.keyIntensity}
+ castShadow={theme.shadowStyle.enabled}
+ />
+ <directionalLight
+ position={[...theme.lights.rimPosition]}
+ color={theme.lights.rimColor}
+ intensity={theme.lights.rimIntensity}
+ />
+ <directionalLight
+ position={[...theme.lights.fillPosition]}
+ color={theme.lights.fillColor}
+ intensity={theme.lights.fillIntensity}
+ />
+ <FitCameraToScene displayScene={displayScene} />
+ <FitCameraToAssembly packet={assemblyPacket} />
+ {showGrid && theme.gridStyle.enabled ? <AdaptiveLogGrid theme={theme} /> : null}
+ {showAxisGuide ? <AxisGuide theme={theme} /> : null}
+ {displayScene?.renderables.flatMap((renderable) =>
+ matchKind(renderable, {
+ AnalyticPatch: (patch) => [
+ <FaceMesh
+ key={`analytic-${patch.faceId}`}
+ positions={patch.previewMesh.positions}
+ normals={patch.previewMesh.normals}
+ indices={patch.previewMesh.indices}
+ isHighlighted={
+ highlightedFaceIds?.has(patch.faceId) ?? highlightedFaceId === patch.faceId
+ }
+ theme={theme}
+ />,
+ ],
+ MeshPatch: (patch) => [
+ <FaceMesh
+ key={`mesh-${patch.faceId}`}
+ positions={patch.mesh.positions}
+ normals={patch.mesh.normals}
+ indices={patch.mesh.indices}
+ isHighlighted={
+ highlightedFaceIds?.has(patch.faceId) ?? highlightedFaceId === patch.faceId
+ }
+ theme={theme}
+ />,
+ ],
+ WirePatch: (patch) =>
+ patch.wires.map((wire) => (
+ <EdgeLine
+ key={`wire-${patch.faceId}-${wire.edgeId}`}
+ points={wire.points}
+ isHighlighted={
+ (highlightedFaceIds?.has(patch.faceId) ?? highlightedFaceId === patch.faceId) ||
+ (highlightedEdgeIds?.has(wire.edgeId) ?? highlightedEdgeId === wire.edgeId)
+ }
+ theme={theme}
+ />
+ )),
+ DiagnosticPatch: () => [],
+ }),
+ )}
+ {assemblyPacket ? (
+ <AssemblyMeshes
+ packet={assemblyPacket}
+ selectedId={selectedAssemblyOccurrenceId}
+ onSelect={onAssemblyOccurrenceSelect}
+ theme={theme}
+ />
+ ) : null}
+ {cadmataLayers ? (
+ <CadmataOverlay
+ artifact={cadmataArtifact}
+ layers={cadmataLayers}
+ selectedIds={selectedCadmataIds}
+ onSelect={onCadmataSelect}
+ theme={theme}
+ />
+ ) : null}
+ <PmiAnnotationLayer
+ artifact={cadmataArtifact}
+ visible={showPmi}
+ visibility={pmiVisibility}
+ selectedIds={selectedCadmataIds}
+ onSelect={onCadmataSelect}
+ theme={theme}
+ />
+ <PickRayCapture onPickRay={onPickRay} />
+ <OrbitControls makeDefault enablePan enableZoom />
+ </Canvas>
+ );
+}
diff --git a/aetheris.client/src/viewer/cadmataTelos.ts b/aetheris.client/src/viewer/cadmataTelos.ts
new file mode 100644
index 00000000..6ee1114f
--- /dev/null
+++ b/aetheris.client/src/viewer/cadmataTelos.ts
@@ -0,0 +1,137 @@
+import {
+ materialFromAppearance,
+ identityTransform,
+ type TelosScene,
+ type TelosMesh,
+ type TelosLine,
+ type NumericArray,
+} from "@aetheris/three-telos";
+import type { AetherisViewportProps } from "./LegacyAetherisViewport";
+import { ATELIER_VIEWPORT_THEME } from "./viewportTheme";
+import {
+ mapFacePatchToRenderFacePatch,
+ type RenderFacePatch,
+} from "./tessellationMapper";
+import type { AssemblyDisplayPacketDto } from "../api/aetherisApi";
+
+// Definitions are immutable within a packet. Selection updates reuse both CPU arrays and GPU buffers.
+const assemblyGeometry = new WeakMap<
+ AssemblyDisplayPacketDto,
+ Map<string, RenderFacePatch[]>
+>();
+
+/** Product packet interpretation only. Camera, drawing and engineering picking live in Telos. */
+export function cadmataTelosScene(props: AetherisViewportProps): TelosScene {
+ const theme = props.theme ?? ATELIER_VIEWPORT_THEME;
+ const meshes: TelosMesh[] = [],
+ lines: TelosLine[] = [];
+ const material = materialFromAppearance(theme.objectMaterial);
+ const addFace = (
+ patch: RenderFacePatch,
+ id: string,
+ occurrenceId: string,
+ transform: NumericArray = identityTransform(),
+ selected = false,
+ ) => {
+ meshes.push({
+ definition: {
+ id,
+ positions: patch.positions,
+ normals: patch.normals,
+ indices: patch.indices,
+ },
+ identity: { occurrenceId, faceId: patch.faceId },
+ transform,
+ material,
+ selected,
+ });
+ };
+ for (const renderable of props.displayScene?.renderables ?? []) {
+ const selected =
+ props.highlightedFaceIds?.has(renderable.faceId) ??
+ props.highlightedFaceId === renderable.faceId;
+ if (renderable.kind === "MeshPatch")
+ addFace(
+ renderable.mesh,
+ "face:" + renderable.faceId,
+ "part",
+ identityTransform(),
+ selected,
+ );
+ else if (renderable.kind === "AnalyticPatch")
+ addFace(
+ renderable.previewMesh,
+ "face:" + renderable.faceId,
+ "part",
+ identityTransform(),
+ selected,
+ );
+ else if (renderable.kind === "WirePatch")
+ for (const edge of renderable.wires)
+ lines.push({
+ id: "edge:" + edge.edgeId,
+ points: edge.points,
+ identity: {
+ occurrenceId: "part",
+ faceId: renderable.faceId,
+ edgeId: edge.edgeId,
+ },
+ widthPixels: theme.edgeStyle.width,
+ color: materialFromAppearance({
+ color: theme.edgeStyle.color,
+ }).baseColor.concat(1),
+ selected:
+ selected ||
+ (props.highlightedEdgeIds?.has(edge.edgeId) ??
+ props.highlightedEdgeId === edge.edgeId),
+ });
+ }
+ const packet = props.assemblyPacket;
+ if (packet) {
+ let definitions = assemblyGeometry.get(packet);
+ if (!definitions) {
+ definitions = new Map(
+ packet.definitions.map((definition) => [
+ definition.stableId,
+ definition.facePatches.map(mapFacePatchToRenderFacePatch),
+ ]),
+ );
+ assemblyGeometry.set(packet, definitions);
+ }
+ const selection = new Set(
+ packet.occurrences.find(
+ (item) => item.stableId === props.selectedAssemblyOccurrenceId,
+ )?.selectionMembers ?? [props.selectedAssemblyOccurrenceId],
+ );
+ for (const occurrence of packet.occurrences)
+ if (occurrence.definitionStableId)
+ for (const patch of definitions.get(occurrence.definitionStableId) ??
+ []) {
+ addFace(
+ patch,
+ occurrence.definitionStableId + ":" + patch.faceId,
+ occurrence.stableId,
+ occurrence.worldTransform,
+ selection.has(occurrence.stableId),
+ );
+ }
+ }
+ if (props.showAxisGuide !== false)
+ for (const [axis, color] of [
+ theme.axis.x,
+ theme.axis.y,
+ theme.axis.z,
+ ].entries()) {
+ const endpoint = [0, 0, 0];
+ endpoint[axis] = 2;
+ lines.push({
+ id: "axis:" + axis,
+ points: [0, 0, 0, ...endpoint],
+ identity: { occurrenceId: "axis:" + axis },
+ widthPixels: 1,
+ color: materialFromAppearance({ color }).baseColor.concat(1),
+ overlay: true,
+ });
+ }
+ return { meshes, lines, fields: [] };
+}
diff --git a/aetheris.client/vite.config.ts b/aetheris.client/vite.config.ts
index aca63307..9119358d 100644
--- a/aetheris.client/vite.config.ts
+++ b/aetheris.client/vite.config.ts
@@ -70,6 +70,9 @@ export default defineConfig(({ command }) => ({
server:
command === "serve"
? {
+ fs: env.AETHERIS_TELOS_WITNESS === "1" ? {
+ allow: [fileURLToPath(new URL(".", import.meta.url)), fileURLToPath(new URL("../fixtures/three-telos", import.meta.url))],
+ } : undefined,
proxy: {
"^/api": {
target,
diff --git a/demos/Aetherion.Helios/package-lock.json b/demos/Aetherion.Helios/package-lock.json
index 6e74a67c..ad099a1e 100644
--- a/demos/Aetherion.Helios/package-lock.json
+++ b/demos/Aetherion.Helios/package-lock.json
@@ -9,10 +9,11 @@
"version": "0.1.0",
"dependencies": {
"@aetheris/cad": "file:../../artifacts/local/helios-sdk/aetheris-cad-2.0.0-preview.3.tgz",
+ "@aetheris/three-telos": "file:../../Aetheris.Web.Runtime/telos",
"@vitejs/plugin-react": "latest",
"react": "latest",
"react-dom": "latest",
- "three": "latest",
+ "three": "0.183.2",
"typescript": "latest",
"vite": "latest"
},
@@ -21,11 +22,25 @@
"@testing-library/react": "latest",
"@types/react": "latest",
"@types/react-dom": "latest",
- "@types/three": "latest",
+ "@types/three": "0.183.1",
"jsdom": "latest",
"vitest": "latest"
}
},
+ "../../Aetheris.Web.Runtime/telos": {
+ "name": "@aetheris/three-telos",
+ "version": "0.1.0",
+ "license": "AGPL-3.0-only",
+ "dependencies": {
+ "@types/three": "0.183.1",
+ "@webgpu/types": "0.1.69",
+ "three": "0.183.2"
+ },
+ "devDependencies": {
+ "@types/node": "24.10.1",
+ "typescript": "~5.9.3"
+ }
+ },
"node_modules/@adobe/css-tools": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.5.0.tgz",
@@ -36,12 +51,16 @@
"node_modules/@aetheris/cad": {
"version": "2.0.0-preview.3",
"resolved": "file:../../artifacts/local/helios-sdk/aetheris-cad-2.0.0-preview.3.tgz",
- "integrity": "sha512-wuLetfhvqZLflQaWyL410pVMiOuNMKfXMBsdIkBV0bn5/u7GSFUBh70XtYEr5+RtnCdj5qCJIUK7fZJ7YJIQnw==",
+ "integrity": "sha512-AGoMhvc/+jAFqb7zDw7G7gZAPgr/DvGZ0c0NHQks4Ejtmg8qUUujp0W8IjZ6JLSIjasa8OlQRLhpPFNW5KCT0g==",
"license": "AGPL-3.0-only",
"engines": {
"node": ">=20"
}
},
+ "node_modules/@aetheris/three-telos": {
+ "resolved": "../../Aetheris.Web.Runtime/telos",
+ "link": true
+ },
"node_modules/@asamuzakjp/css-color": {
"version": "6.0.7",
"resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-6.0.7.tgz",
@@ -744,9 +763,9 @@
"license": "MIT"
},
"node_modules/@types/three": {
- "version": "0.186.0",
- "resolved": "https://registry.npmjs.org/@types/three/-/three-0.186.0.tgz",
- "integrity": "sha512-mxYSBpDC+D0pLfSP6sW4WZTcT+nrtmZcimMqnVmy36Hte3XpeYSrvgg4TRdaM1GemGog1AWzI5qL2VoIfMXbJQ==",
+ "version": "0.183.1",
+ "resolved": "https://registry.npmjs.org/@types/three/-/three-0.183.1.tgz",
+ "integrity": "sha512-f2Pu5Hrepfgavttdye3PsH5RWyY/AvdZQwIVhrc4uNtvF7nOWJacQKcoVJn0S4f0yYbmAE6AR+ve7xDcuYtMGw==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -754,8 +773,9 @@
"@tweenjs/tween.js": "~23.1.3",
"@types/stats.js": "*",
"@types/webxr": ">=0.5.17",
- "fflate": "~0.8.3",
- "meshoptimizer": "~1.1.1"
+ "@webgpu/types": "*",
+ "fflate": "~0.8.2",
+ "meshoptimizer": "~1.0.1"
}
},
"node_modules/@types/webxr": {
@@ -1152,6 +1172,13 @@
"url": "https://opencollective.com/vitest"
}
},
+ "node_modules/@webgpu/types": {
+ "version": "0.1.74",
+ "resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.74.tgz",
+ "integrity": "sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA==",
+ "dev": true,
+ "license": "BSD-3-Clause"
+ },
"node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
@@ -1765,9 +1792,9 @@
"license": "CC0-1.0"
},
"node_modules/meshoptimizer": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz",
- "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==",
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.0.1.tgz",
+ "integrity": "sha512-Vix+QlA1YYT3FwmBBZ+49cE5y/b+pRrcXKqGpS5ouh33d3lSp2PoTpCw19E0cKDFWalembrHnIaZetf27a+W2g==",
"dev": true,
"license": "MIT"
},
@@ -2054,9 +2081,9 @@
"license": "MIT"
},
"node_modules/three": {
- "version": "0.186.0",
- "resolved": "https://registry.npmjs.org/three/-/three-0.186.0.tgz",
- "integrity": "sha512-cr/fIM2ddMSVbYVgkfD4jLJv7Fh/8ZTjvo+7gQeSVGUZHxpx9FDwoL5iC7hUz/LiRA8wMbqfnb90xKfm1/HHkQ==",
+ "version": "0.183.2",
+ "resolved": "https://registry.npmjs.org/three/-/three-0.183.2.tgz",
+ "integrity": "sha512-di3BsL2FEQ1PA7Hcvn4fyJOlxRRgFYBpMTcyOgkwJIaDOdJMebEFPA+t98EvjuljDx4hNulAGwF6KIjtwI5jgQ==",
"license": "MIT"
},
"node_modules/tinybench": {
diff --git a/demos/Aetherion.Helios/package.json b/demos/Aetherion.Helios/package.json
index 421bb591..5097992d 100644
--- a/demos/Aetherion.Helios/package.json
+++ b/demos/Aetherion.Helios/package.json
@@ -5,27 +5,30 @@
"type": "module",
"scripts": {
"sdk:install": "node scripts/install-local-sdk.mjs",
+ "sdk:install:production": "node scripts/install-local-sdk.mjs --production",
"dev": "vite",
"build": "tsc -b && vite build",
+ "build:fast": "tsc -b && vite build --mode development",
"test": "vitest run",
"test:watch": "vitest",
"preview": "vite preview"
},
"dependencies": {
"@aetheris/cad": "file:../../artifacts/local/helios-sdk/aetheris-cad-2.0.0-preview.3.tgz",
+ "@aetheris/three-telos": "file:../../Aetheris.Web.Runtime/telos",
"@vitejs/plugin-react": "latest",
- "vite": "latest",
- "typescript": "latest",
"react": "latest",
"react-dom": "latest",
- "three": "latest"
+ "three": "0.183.2",
+ "typescript": "latest",
+ "vite": "latest"
},
"devDependencies": {
"@testing-library/jest-dom": "latest",
"@testing-library/react": "latest",
"@types/react": "latest",
"@types/react-dom": "latest",
- "@types/three": "latest",
+ "@types/three": "0.183.1",
"jsdom": "latest",
"vitest": "latest"
}
diff --git a/demos/Aetherion.Helios/scripts/install-local-sdk.mjs b/demos/Aetherion.Helios/scripts/install-local-sdk.mjs
index ba1997c9..31792de1 100644
--- a/demos/Aetherion.Helios/scripts/install-local-sdk.mjs
+++ b/demos/Aetherion.Helios/scripts/install-local-sdk.mjs
@@ -8,11 +8,12 @@ const sdk = resolve(repo, 'Aetheris.Web.Runtime', 'sdk');
const output = resolve(repo, 'artifacts', 'local', 'helios-sdk');
await mkdir(output, { recursive: true });
-run('npm', ['run', 'build'], sdk);
+run('npm', ['run', process.argv.includes('--production') ? 'build:production' : 'build'], sdk);
run('npm', ['pack', '--pack-destination', output], sdk);
const packages = (await readdir(output)).filter(name => name.endsWith('.tgz')).sort();
if (!packages.length) throw new Error('The local @aetheris/cad pack did not produce a tarball.');
-run('npm', ['install'], helios);
+// A freshly packed same-version tarball must replace the cached SDK snapshot.
+run('npm', ['install', '--force', '@aetheris/cad@file:../../artifacts/local/helios-sdk/aetheris-cad-2.0.0-preview.3.tgz'], helios);
function run(command, args, cwd) {
const result = spawnSync(command, args, { cwd, stdio: 'inherit', shell: process.platform === 'win32' });
diff --git a/demos/Aetherion.Helios/src/viewport/LegacyViewport.tsx b/demos/Aetherion.Helios/src/viewport/LegacyViewport.tsx
new file mode 100644
index 00000000..76e61f30
--- /dev/null
+++ b/demos/Aetherion.Helios/src/viewport/LegacyViewport.tsx
@@ -0,0 +1,200 @@
+import { useEffect, useRef } from 'react';
+import * as THREE from 'three';
+import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
+import type { ModelSession } from '@aetheris/cad';
+import type { DisplayMode, ThemeName, ViewMode } from '../app/types';
+
+interface Props {
+ model: ModelSession | null;
+ selectedEntityId: string | null;
+ theme: ThemeName;
+ displayMode: DisplayMode;
+ viewMode: ViewMode;
+ viewCommand: string;
+ onSelect(entityId: string | null, faceId: string | null): void;
+}
+
+type MeshMeta = { definitionId: string; occurrenceId: string; edge?: boolean };
+
+export function LegacyViewport(props: Props) {
+ const host = useRef<HTMLDivElement>(null);
+ const state = useRef<ReturnType<typeof createScene> | null>(null);
+
+ useEffect(() => {
+ if (!host.current) return;
+ const sceneState = createScene(host.current, props.onSelect);
+ state.current = sceneState;
+ return () => { sceneState.dispose(); state.current = null; };
+ }, []);
+
+ useEffect(() => { if (state.current) loadModel(state.current, props.model); }, [props.model, props.model?.revision]);
+ useEffect(() => { if (state.current) selectEntity(state.current, props.model, props.selectedEntityId); }, [props.model, props.selectedEntityId]);
+ useEffect(() => { if (state.current) applyAppearance(state.current, props.theme, props.displayMode); }, [props.theme, props.displayMode]);
+ useEffect(() => { if (state.current) applyViewCommand(state.current, props.viewMode, props.viewCommand); }, [props.viewMode, props.viewCommand]);
+
+ return <section className="viewport-shell" aria-label="3D viewport">
+ <div className="viewport-canvas" ref={host} data-testid="viewport" />
+ <div className="axis-labels" aria-hidden="true"><span className="axis-x">X</span><span className="axis-y">Y</span><span className="axis-z">Z</span></div>
+ {!props.model && <div className="viewport-empty">Firmament geometry will appear here.</div>}
+ </section>;
+}
+
+function createScene(host: HTMLDivElement, onSelect: Props['onSelect']) {
+ const scene = new THREE.Scene();
+ const renderer = new THREE.WebGLRenderer({ antialias: true });
+ renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+ host.appendChild(renderer.domElement);
+ const perspective = new THREE.PerspectiveCamera(35, 1, 0.1, 10000);
+ const orthographic = new THREE.OrthographicCamera(-70, 70, 70, -70, 0.1, 10000);
+ perspective.position.set(90, 70, 90);
+ orthographic.position.copy(perspective.position);
+ let camera: THREE.Camera = perspective;
+ const controls = new OrbitControls(perspective, renderer.domElement);
+ controls.enableDamping = true;
+ controls.dampingFactor = 0.12;
+ const ambient = new THREE.HemisphereLight(0xffffff, 0x263128, 2.1);
+ const key = new THREE.DirectionalLight(0xffffff, 2.8); key.position.set(60, 100, 80);
+ scene.add(ambient, key);
+ const grid = new THREE.GridHelper(400, 40, 0x6a715f, 0x414942); grid.rotation.x = Math.PI / 2; scene.add(grid);
+ const axes = new THREE.AxesHelper(25); scene.add(axes);
+ const group = new THREE.Group(); scene.add(group);
+ const raycaster = new THREE.Raycaster();
+ const pointer = new THREE.Vector2();
+ let hovered: THREE.Mesh | null = null;
+ let selectedIds = new Set<string>();
+ let dirty = true;
+ let raf = 0;
+ const invalidate = () => { dirty = true; if (!raf) raf = requestAnimationFrame(render); };
+ const render = () => {
+ raf = 0;
+ const damping = controls.update();
+ if (dirty || damping) renderer.render(scene, camera);
+ dirty = false;
+ if (damping) raf = requestAnimationFrame(render);
+ };
+ controls.addEventListener('change', invalidate);
+ const resize = new ResizeObserver(() => {
+ const width = Math.max(host.clientWidth, 1), height = Math.max(host.clientHeight, 1);
+ renderer.setSize(width, height, false);
+ perspective.aspect = width / height; perspective.updateProjectionMatrix();
+ const extent = 70; orthographic.left = -extent * width / height; orthographic.right = extent * width / height; orthographic.top = extent; orthographic.bottom = -extent; orthographic.updateProjectionMatrix();
+ invalidate();
+ });
+ resize.observe(host);
+ const hitTest = (event: PointerEvent) => {
+ const rect = renderer.domElement.getBoundingClientRect();
+ pointer.set(((event.clientX - rect.left) / rect.width) * 2 - 1, -((event.clientY - rect.top) / rect.height) * 2 + 1);
+ raycaster.setFromCamera(pointer, camera);
+ return raycaster.intersectObjects(group.children, false)[0];
+ };
+ renderer.domElement.addEventListener('pointermove', event => {
+ const next = hitTest(event)?.object as THREE.Mesh | undefined;
+ if (hovered !== next) { hovered = next ?? null; updateMaterials(group, selectedIds, hovered); invalidate(); }
+ });
+ renderer.domElement.addEventListener('click', event => {
+ const hit = hitTest(event);
+ if (!hit) { onSelect(null, null); return; }
+ const meta = hit.object.userData as MeshMeta;
+ const resolved = (state.model as ModelSession | null)?.resolveSelection(meta.definitionId, hit.faceIndex ?? 0, meta.occurrenceId);
+ onSelect(resolved?.semanticEntityId ?? null, resolved?.faceId ?? null);
+ });
+ const state = { scene, renderer, perspective, orthographic, get camera() { return camera; }, set camera(value) { camera = value; }, controls, grid, group, model: null as ModelSession | null, selectedIds, hovered, invalidate,
+ dispose() { cancelAnimationFrame(raf); resize.disconnect(); controls.dispose(); renderer.dispose(); host.replaceChildren(); } };
+ invalidate();
+ return state;
+}
+
+function loadModel(state: ReturnType<typeof createScene>, model: ModelSession | null) {
+ for (const child of [...state.group.children]) { state.group.remove(child); disposeObject(child); }
+ state.model = model;
+ if (!model) { state.invalidate(); return; }
+ const geometries = new Map(model.mesh.definitions.map(definition => {
+ const geometry = new THREE.BufferGeometry();
+ geometry.setAttribute('position', new THREE.BufferAttribute(Float32Array.from(definition.positions), 3));
+ geometry.setAttribute('normal', new THREE.BufferAttribute(Float32Array.from(definition.normals), 3));
+ geometry.setIndex(new THREE.BufferAttribute(definition.indices, 1));
+ geometry.computeBoundingSphere();
+ return [definition.id, geometry];
+ }));
+ for (const occurrence of model.mesh.occurrences) {
+ const geometry = occurrence.definitionId ? geometries.get(occurrence.definitionId) : undefined;
+ if (!geometry || !occurrence.definitionId) continue;
+ const mesh = new THREE.Mesh(geometry, material(false, false));
+ mesh.matrix.fromArray(occurrence.transform); mesh.matrixAutoUpdate = false;
+ mesh.userData = { definitionId: occurrence.definitionId, occurrenceId: occurrence.id } satisfies MeshMeta;
+ state.group.add(mesh);
+ const edges = new THREE.LineSegments(new THREE.EdgesGeometry(geometry, 25), new THREE.LineBasicMaterial({ color: 0x323a35, transparent: true, opacity: 0.72 }));
+ edges.matrix.copy(mesh.matrix); edges.matrixAutoUpdate = false;
+ edges.userData = { definitionId: occurrence.definitionId, occurrenceId: occurrence.id, edge: true } satisfies MeshMeta;
+ edges.raycast = () => undefined;
+ state.group.add(edges);
+ }
+ fit(state);
+}
+
+function selectEntity(state: ReturnType<typeof createScene>, model: ModelSession | null, entityId: string | null) {
+ const selection = entityId && model ? model.selectionForEntity(entityId) : { occurrenceIds: [] };
+ state.selectedIds = new Set(selection.occurrenceIds);
+ updateMaterials(state.group, state.selectedIds, state.hovered);
+ state.invalidate();
+}
+
+function updateMaterials(group: THREE.Group, selectedIds: Set<string>, hovered: THREE.Mesh | null) {
+ for (const object of group.children) if (object instanceof THREE.Mesh) {
+ const selected = selectedIds.has((object.userData as MeshMeta).occurrenceId);
+ (object.material as THREE.MeshStandardMaterial).color.set(selected ? 0xe7ad45 : object === hovered ? 0x78b9a4 : 0xb8beb3);
+ (object.material as THREE.MeshStandardMaterial).emissive.set(selected ? 0x382406 : 0x000000);
+ } else if (object instanceof THREE.LineSegments) {
+ const selected = selectedIds.has((object.userData as MeshMeta).occurrenceId);
+ (object.material as THREE.LineBasicMaterial).color.set(selected ? 0xffca63 : 0x323a35);
+ }
+}
+
+function applyAppearance(state: ReturnType<typeof createScene>, theme: ThemeName, mode: DisplayMode) {
+ state.scene.background = new THREE.Color(theme === 'mars' ? 0x111814 : 0xe9ece8);
+ (state.grid.material as THREE.Material).opacity = theme === 'mars' ? 0.28 : 0.4;
+ (state.grid.material as THREE.Material).transparent = true;
+ for (const object of state.group.children) if (object instanceof THREE.Mesh) {
+ const mat = object.material as THREE.MeshStandardMaterial;
+ mat.wireframe = mode === 'wireframe';
+ mat.flatShading = mode !== 'shaded'; mat.needsUpdate = true;
+ } else if (object instanceof THREE.LineSegments) {
+ object.visible = mode === 'edges';
+ (object.material as THREE.LineBasicMaterial).color.set(theme === 'mars' ? 0x323a35 : 0x69716d);
+ }
+ state.invalidate();
+}
+
+function applyViewCommand(state: ReturnType<typeof createScene>, mode: ViewMode, command: string) {
+ command = command.split('-')[0];
+ const prior = state.camera;
+ state.camera = mode === 'orthographic' ? state.orthographic : state.perspective;
+ state.controls.object = state.camera as THREE.PerspectiveCamera;
+ if (prior !== state.camera) state.camera.position.copy(prior.position);
+ const distance = Math.max(state.camera.position.length(), 100);
+ const positions: Record<string, THREE.Vector3> = { front: new THREE.Vector3(0, -distance, 0), top: new THREE.Vector3(0, 0, distance), right: new THREE.Vector3(distance, 0, 0), iso: new THREE.Vector3(distance, distance, distance) };
+ if (positions[command]) state.camera.position.copy(positions[command]);
+ if (command === 'fit') fit(state);
+ else if (command === 'fitselection') fitSelection(state);
+ else { state.camera.lookAt(0, 0, 0); state.controls.update(); state.invalidate(); }
+}
+
+function fit(state: ReturnType<typeof createScene>, objects: readonly THREE.Object3D[] = [state.group]) {
+ const box = new THREE.Box3();
+ for (const object of objects) box.expandByObject(object);
+ if (box.isEmpty()) { state.invalidate(); return; }
+ const center = box.getCenter(new THREE.Vector3());
+ const size = box.getSize(new THREE.Vector3()).length();
+ state.controls.target.copy(center);
+ state.camera.position.copy(center).add(new THREE.Vector3(1, 0.8, 1).normalize().multiplyScalar(Math.max(size * 1.5, 30)));
+ state.camera.lookAt(center); state.controls.update(); state.invalidate();
+}
+
+function fitSelection(state: ReturnType<typeof createScene>) {
+ const selected = state.group.children.filter(object => object instanceof THREE.Mesh && state.selectedIds.has((object.userData as MeshMeta).occurrenceId));
+ fit(state, selected.length ? selected : [state.group]);
+}
+
+function material(selected: boolean, wireframe: boolean) { return new THREE.MeshStandardMaterial({ color: selected ? 0xe7ad45 : 0xb8beb3, metalness: 0.15, roughness: 0.62, side: THREE.DoubleSide, wireframe }); }
+function disposeObject(object: THREE.Object3D) { if (object instanceof THREE.Mesh || object instanceof THREE.LineSegments) { object.geometry.dispose(); (object.material as THREE.Material).dispose(); } }
diff --git a/demos/Aetherion.Helios/src/viewport/Viewport.tsx b/demos/Aetherion.Helios/src/viewport/Viewport.tsx
index 2f76eb8b..933b581f 100644
--- a/demos/Aetherion.Helios/src/viewport/Viewport.tsx
+++ b/demos/Aetherion.Helios/src/viewport/Viewport.tsx
@@ -1,200 +1,246 @@
-import { useEffect, useRef } from 'react';
-import * as THREE from 'three';
-import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
-import type { ModelSession } from '@aetheris/cad';
-import type { DisplayMode, ThemeName, ViewMode } from '../app/types';
+import { useEffect, useRef, useState, type MutableRefObject } from "react";
+import {
+ TelosHost,
+ fromDisplayMesh,
+ clearColor,
+ type TelosScene,
+ type TelosMesh,
+} from "@aetheris/three-telos";
+import type { ModelSession, SelectionDescription } from "@aetheris/cad";
+import type { DisplayMode, ThemeName, ViewMode } from "../app/types";
+import { LegacyViewport } from "./LegacyViewport";
interface Props {
model: ModelSession | null;
selectedEntityId: string | null;
+ selectedTopologyId?: string | null;
theme: ThemeName;
displayMode: DisplayMode;
viewMode: ViewMode;
viewCommand: string;
- onSelect(entityId: string | null, faceId: string | null): void;
+ selectionMode?: "face" | "edge";
+ onSelect(
+ entityId: string | null,
+ faceId: string | null,
+ selection?: SelectionDescription | null,
+ ): void;
+ captureRef?: MutableRefObject<(() => string) | null>;
}
-type MeshMeta = { definitionId: string; occurrenceId: string; edge?: boolean };
-
+/** Legacy is explicitly transitional and used only when WebGPU is unavailable. */
export function Viewport(props: Props) {
- const host = useRef<HTMLDivElement>(null);
- const state = useRef<ReturnType<typeof createScene> | null>(null);
-
- useEffect(() => {
- if (!host.current) return;
- const sceneState = createScene(host.current, props.onSelect);
- state.current = sceneState;
- return () => { sceneState.dispose(); state.current = null; };
- }, []);
-
- useEffect(() => { if (state.current) loadModel(state.current, props.model); }, [props.model, props.model?.revision]);
- useEffect(() => { if (state.current) selectEntity(state.current, props.model, props.selectedEntityId); }, [props.model, props.selectedEntityId]);
- useEffect(() => { if (state.current) applyAppearance(state.current, props.theme, props.displayMode); }, [props.theme, props.displayMode]);
- useEffect(() => { if (state.current) applyViewCommand(state.current, props.viewMode, props.viewCommand); }, [props.viewMode, props.viewCommand]);
-
- return <section className="viewport-shell" aria-label="3D viewport">
- <div className="viewport-canvas" ref={host} data-testid="viewport" />
- <div className="axis-labels" aria-hidden="true"><span className="axis-x">X</span><span className="axis-y">Y</span><span className="axis-z">Z</span></div>
- {!props.model && <div className="viewport-empty">Firmament geometry will appear here.</div>}
- </section>;
+ if (typeof navigator === "undefined" || !("gpu" in navigator))
+ return (
+ <div data-display-host="transitional-webgl">
+ <LegacyViewport {...props} />
+ <small>Transitional WebGL: WebGPU unavailable</small>
+ </div>
+ );
+ return <TelosViewport {...props} />;
}
-function createScene(host: HTMLDivElement, onSelect: Props['onSelect']) {
- const scene = new THREE.Scene();
- const renderer = new THREE.WebGLRenderer({ antialias: true });
- renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
- renderer.outputColorSpace = THREE.SRGBColorSpace;
- host.appendChild(renderer.domElement);
- const perspective = new THREE.PerspectiveCamera(35, 1, 0.1, 10000);
- const orthographic = new THREE.OrthographicCamera(-70, 70, 70, -70, 0.1, 10000);
- perspective.position.set(90, 70, 90);
- orthographic.position.copy(perspective.position);
- let camera: THREE.Camera = perspective;
- const controls = new OrbitControls(perspective, renderer.domElement);
- controls.enableDamping = true;
- controls.dampingFactor = 0.12;
- const ambient = new THREE.HemisphereLight(0xffffff, 0x263128, 2.1);
- const key = new THREE.DirectionalLight(0xffffff, 2.8); key.position.set(60, 100, 80);
- scene.add(ambient, key);
- const grid = new THREE.GridHelper(400, 40, 0x6a715f, 0x414942); grid.rotation.x = Math.PI / 2; scene.add(grid);
- const axes = new THREE.AxesHelper(25); scene.add(axes);
- const group = new THREE.Group(); scene.add(group);
- const raycaster = new THREE.Raycaster();
- const pointer = new THREE.Vector2();
- let hovered: THREE.Mesh | null = null;
- let selectedIds = new Set<string>();
- let dirty = true;
- let raf = 0;
- const invalidate = () => { dirty = true; if (!raf) raf = requestAnimationFrame(render); };
- const render = () => {
- raf = 0;
- const damping = controls.update();
- if (dirty || damping) renderer.render(scene, camera);
- dirty = false;
- if (damping) raf = requestAnimationFrame(render);
- };
- controls.addEventListener('change', invalidate);
- const resize = new ResizeObserver(() => {
- const width = Math.max(host.clientWidth, 1), height = Math.max(host.clientHeight, 1);
- renderer.setSize(width, height, false);
- perspective.aspect = width / height; perspective.updateProjectionMatrix();
- const extent = 70; orthographic.left = -extent * width / height; orthographic.right = extent * width / height; orthographic.top = extent; orthographic.bottom = -extent; orthographic.updateProjectionMatrix();
- invalidate();
- });
- resize.observe(host);
- const hitTest = (event: PointerEvent) => {
- const rect = renderer.domElement.getBoundingClientRect();
- pointer.set(((event.clientX - rect.left) / rect.width) * 2 - 1, -((event.clientY - rect.top) / rect.height) * 2 + 1);
- raycaster.setFromCamera(pointer, camera);
- return raycaster.intersectObjects(group.children, false)[0];
+function TelosViewport(props: Props) {
+ const container = useRef<HTMLDivElement>(null),
+ canvas = useRef<HTMLCanvasElement>(null),
+ host = useRef<TelosHost | null>(null);
+ const latest = useRef(props);
+ latest.current = props;
+ const modelKey = useRef<string | null>(null),
+ viewKey = useRef<string | null>(null);
+ const [diagnostic, setDiagnostic] = useState<string | null>(null);
+ const apply = () => {
+ const current = host.current;
+ if (!current) return;
+ const value = latest.current;
+ const scene: TelosScene = value.model
+ ? fromDisplayMesh(value.model.mesh)
+ : { meshes: [], lines: [], fields: [] };
+ const selected =
+ value.model && value.selectedEntityId
+ ? value.model.selectionForEntity(value.selectedEntityId)
+ : { occurrenceIds: [], ranges: [] };
+ const selectedIds = new Set(selected.occurrenceIds);
+ const meshes: TelosMesh[] = scene.meshes.map((mesh) => ({
+ ...mesh,
+ selected: selectedIds.has(mesh.identity.occurrenceId),
+ visible: value.displayMode !== "wireframe",
+ }));
+ if (
+ value.model &&
+ value.selectedTopologyId &&
+ !value.selectedTopologyId.startsWith("edge:")
+ ) {
+ for (const mesh of scene.meshes)
+ for (const range of mesh.definition.ranges ?? [])
+ if (range.faceId === value.selectedTopologyId) {
+ meshes.push({
+ ...mesh,
+ definition: {
+ ...mesh.definition,
+ id: mesh.definition.id + ":selection:" + range.faceId,
+ indices: Array.from(mesh.definition.indices).slice(
+ range.startTriangle * 3,
+ (range.startTriangle + range.triangleCount) * 3,
+ ),
+ },
+ selected: true,
+ overlay: true,
+ });
+ }
+ }
+ const lines = scene.lines.map((line) => ({
+ ...line,
+ selected:
+ line.identity.edgeId === value.selectedTopologyId ||
+ selectedIds.has(line.identity.occurrenceId),
+ visible: value.displayMode !== "shaded",
+ color:
+ value.theme === "mars"
+ ? [0.18, 0.22, 0.2, 0.85]
+ : [0.3, 0.35, 0.32, 0.85],
+ }));
+ current.setScene({ ...scene, meshes, lines });
+ current.grid = true;
+ current.gridPlane = "xy";
+ current.background = clearColor(value.theme === "mars" ? "#111814" : "#e9ece8");
+ const key = value.model
+ ? value.model.id + ":" + value.model.revision
+ : null;
+ if (modelKey.current !== key) {
+ modelKey.current = key;
+ current.fit();
+ }
+ const view = value.viewMode + ":" + value.viewCommand;
+ if (viewKey.current !== view) {
+ viewKey.current = view;
+ current.camera.mode = value.viewMode;
+ const command = value.viewCommand.split("-")[0];
+ const directions: Record<string, [number, number, number]> = {
+ front: [0, -1, 0],
+ top: [0, 0, 1],
+ right: [1, 0, 0],
+ iso: [1, 1, 1],
+ };
+ if (directions[command]) {
+ if (command !== "iso") current.camera.mode = "orthographic";
+ const distance = Math.max(
+ current.camera.position.distanceTo(current.camera.target),
+ current.camera.near * 10,
+ );
+ current.camera.position
+ .set(...directions[command])
+ .normalize()
+ .multiplyScalar(distance)
+ .add(current.camera.target);
+ current.camera.up.set(
+ 0,
+ command === "top" ? 1 : 0,
+ command === "top" ? 0 : 1,
+ );
+ }
+ if (command === "fit") current.fit();
+ current.camera.update();
+ }
+ current.invalidate();
};
- renderer.domElement.addEventListener('pointermove', event => {
- const next = hitTest(event)?.object as THREE.Mesh | undefined;
- if (hovered !== next) { hovered = next ?? null; updateMaterials(group, selectedIds, hovered); invalidate(); }
- });
- renderer.domElement.addEventListener('click', event => {
- const hit = hitTest(event);
- if (!hit) { onSelect(null, null); return; }
- const meta = hit.object.userData as MeshMeta;
- const resolved = (state.model as ModelSession | null)?.resolveSelection(meta.definitionId, hit.faceIndex ?? 0, meta.occurrenceId);
- onSelect(resolved?.semanticEntityId ?? null, resolved?.faceId ?? null);
- });
- const state = { scene, renderer, perspective, orthographic, get camera() { return camera; }, set camera(value) { camera = value; }, controls, grid, group, model: null as ModelSession | null, selectedIds, hovered, invalidate,
- dispose() { cancelAnimationFrame(raf); resize.disconnect(); controls.dispose(); renderer.dispose(); host.replaceChildren(); } };
- invalidate();
- return state;
-}
-
-function loadModel(state: ReturnType<typeof createScene>, model: ModelSession | null) {
- for (const child of [...state.group.children]) { state.group.remove(child); disposeObject(child); }
- state.model = model;
- if (!model) { state.invalidate(); return; }
- const geometries = new Map(model.mesh.definitions.map(definition => {
- const geometry = new THREE.BufferGeometry();
- geometry.setAttribute('position', new THREE.BufferAttribute(Float32Array.from(definition.positions), 3));
- geometry.setAttribute('normal', new THREE.BufferAttribute(Float32Array.from(definition.normals), 3));
- geometry.setIndex(new THREE.BufferAttribute(definition.indices, 1));
- geometry.computeBoundingSphere();
- return [definition.id, geometry];
- }));
- for (const occurrence of model.mesh.occurrences) {
- const geometry = occurrence.definitionId ? geometries.get(occurrence.definitionId) : undefined;
- if (!geometry || !occurrence.definitionId) continue;
- const mesh = new THREE.Mesh(geometry, material(false, false));
- mesh.matrix.fromArray(occurrence.transform); mesh.matrixAutoUpdate = false;
- mesh.userData = { definitionId: occurrence.definitionId, occurrenceId: occurrence.id } satisfies MeshMeta;
- state.group.add(mesh);
- const edges = new THREE.LineSegments(new THREE.EdgesGeometry(geometry, 25), new THREE.LineBasicMaterial({ color: 0x323a35, transparent: true, opacity: 0.72 }));
- edges.matrix.copy(mesh.matrix); edges.matrixAutoUpdate = false;
- edges.userData = { definitionId: occurrence.definitionId, occurrenceId: occurrence.id, edge: true } satisfies MeshMeta;
- edges.raycast = () => undefined;
- state.group.add(edges);
- }
- fit(state);
-}
-
-function selectEntity(state: ReturnType<typeof createScene>, model: ModelSession | null, entityId: string | null) {
- const selection = entityId && model ? model.selectionForEntity(entityId) : { occurrenceIds: [] };
- state.selectedIds = new Set(selection.occurrenceIds);
- updateMaterials(state.group, state.selectedIds, state.hovered);
- state.invalidate();
-}
-
-function updateMaterials(group: THREE.Group, selectedIds: Set<string>, hovered: THREE.Mesh | null) {
- for (const object of group.children) if (object instanceof THREE.Mesh) {
- const selected = selectedIds.has((object.userData as MeshMeta).occurrenceId);
- (object.material as THREE.MeshStandardMaterial).color.set(selected ? 0xe7ad45 : object === hovered ? 0x78b9a4 : 0xb8beb3);
- (object.material as THREE.MeshStandardMaterial).emissive.set(selected ? 0x382406 : 0x000000);
- } else if (object instanceof THREE.LineSegments) {
- const selected = selectedIds.has((object.userData as MeshMeta).occurrenceId);
- (object.material as THREE.LineBasicMaterial).color.set(selected ? 0xffca63 : 0x323a35);
- }
-}
-
-function applyAppearance(state: ReturnType<typeof createScene>, theme: ThemeName, mode: DisplayMode) {
- state.scene.background = new THREE.Color(theme === 'mars' ? 0x111814 : 0xe9ece8);
- (state.grid.material as THREE.Material).opacity = theme === 'mars' ? 0.28 : 0.4;
- (state.grid.material as THREE.Material).transparent = true;
- for (const object of state.group.children) if (object instanceof THREE.Mesh) {
- const mat = object.material as THREE.MeshStandardMaterial;
- mat.wireframe = mode === 'wireframe';
- mat.flatShading = mode !== 'shaded'; mat.needsUpdate = true;
- } else if (object instanceof THREE.LineSegments) {
- object.visible = mode === 'edges';
- (object.material as THREE.LineBasicMaterial).color.set(theme === 'mars' ? 0x323a35 : 0x69716d);
- }
- state.invalidate();
-}
-
-function applyViewCommand(state: ReturnType<typeof createScene>, mode: ViewMode, command: string) {
- command = command.split('-')[0];
- const prior = state.camera;
- state.camera = mode === 'orthographic' ? state.orthographic : state.perspective;
- state.controls.object = state.camera as THREE.PerspectiveCamera;
- if (prior !== state.camera) state.camera.position.copy(prior.position);
- const distance = Math.max(state.camera.position.length(), 100);
- const positions: Record<string, THREE.Vector3> = { front: new THREE.Vector3(0, -distance, 0), top: new THREE.Vector3(0, 0, distance), right: new THREE.Vector3(distance, 0, 0), iso: new THREE.Vector3(distance, distance, distance) };
- if (positions[command]) state.camera.position.copy(positions[command]);
- if (command === 'fit') fit(state);
- else if (command === 'fitselection') fitSelection(state);
- else { state.camera.lookAt(0, 0, 0); state.controls.update(); state.invalidate(); }
-}
-
-function fit(state: ReturnType<typeof createScene>, objects: readonly THREE.Object3D[] = [state.group]) {
- const box = new THREE.Box3();
- for (const object of objects) box.expandByObject(object);
- if (box.isEmpty()) { state.invalidate(); return; }
- const center = box.getCenter(new THREE.Vector3());
- const size = box.getSize(new THREE.Vector3()).length();
- state.controls.target.copy(center);
- state.camera.position.copy(center).add(new THREE.Vector3(1, 0.8, 1).normalize().multiplyScalar(Math.max(size * 1.5, 30)));
- state.camera.lookAt(center); state.controls.update(); state.invalidate();
-}
-
-function fitSelection(state: ReturnType<typeof createScene>) {
- const selected = state.group.children.filter(object => object instanceof THREE.Mesh && state.selectedIds.has((object.userData as MeshMeta).occurrenceId));
- fit(state, selected.length ? selected : [state.group]);
+ useEffect(() => {
+ let disposed = false;
+ const element = canvas.current;
+ if (!element) return;
+ const pixel = (event: MouseEvent): [number, number] => {
+ const rect = element.getBoundingClientRect();
+ return [event.clientX - rect.left, event.clientY - rect.top];
+ };
+ const click = (event: MouseEvent) => {
+ const current = host.current;
+ if (!current) return;
+ const value = latest.current,
+ hit = current.picker.pick(pixel(event), value.selectionMode);
+ const selection =
+ hit && hit.definitionId
+ ? hit.edgeId
+ ? value.model?.describeEdgeSelection(
+ hit.definitionId,
+ String(hit.edgeId),
+ hit.occurrenceId,
+ )
+ : value.model?.describeSelection(
+ hit.definitionId,
+ hit.triangleIndex ?? 0,
+ hit.occurrenceId,
+ )
+ : null;
+ value.onSelect(
+ selection?.semanticEntityId ?? null,
+ selection?.faceId ?? null,
+ selection,
+ );
+ };
+ const move = (event: PointerEvent) => {
+ const current = host.current;
+ if (!current) return;
+ const hit = current.picker.pick(pixel(event));
+ for (const mesh of current.scene.meshes)
+ mesh.hovered = mesh.identity.occurrenceId === hit?.occurrenceId;
+ current.invalidate();
+ };
+ element.addEventListener("click", click);
+ element.addEventListener("pointermove", move);
+ void TelosHost.create(element, setDiagnostic)
+ .then((current) => {
+ if (disposed) {
+ current.dispose();
+ return;
+ }
+ host.current = current;
+ current.camera.up.set(0, 0, 1);
+ current.attach(container.current!);
+ apply();
+ if (latest.current.captureRef)
+ latest.current.captureRef.current = () => {
+ current.render();
+ return element.toDataURL("image/png");
+ };
+ })
+ .catch((error) => {
+ if (!disposed) setDiagnostic(String(error));
+ });
+ return () => {
+ disposed = true;
+ element.removeEventListener("click", click);
+ element.removeEventListener("pointermove", move);
+ if (latest.current.captureRef) latest.current.captureRef.current = null;
+ host.current?.dispose();
+ host.current = null;
+ };
+ }, []);
+ useEffect(() => {
+ apply();
+ }, [props]);
+ return (
+ <section
+ className="viewport-shell"
+ aria-label="3D viewport"
+ data-display-host="three-telos"
+ >
+ <div className="viewport-canvas" ref={container} data-testid="viewport">
+ <canvas
+ ref={canvas}
+ aria-label="Engineering WebGPU viewport"
+ style={{ width: "100%", height: "100%", display: "block" }}
+ />
+ </div>
+ <div className="axis-labels" aria-hidden="true">
+ <span className="axis-x">X</span>
+ <span className="axis-y">Y</span>
+ <span className="axis-z">Z</span>
+ </div>
+ {!props.model && (
+ <div className="viewport-empty">
+ Firmament geometry will appear here.
+ </div>
+ )}
+ {diagnostic && <div role="alert">{diagnostic}</div>}
+ </section>
+ );
}
-
-function material(selected: boolean, wireframe: boolean) { return new THREE.MeshStandardMaterial({ color: selected ? 0xe7ad45 : 0xb8beb3, metalness: 0.15, roughness: 0.62, side: THREE.DoubleSide, wireframe }); }
-function disposeObject(object: THREE.Object3D) { if (object instanceof THREE.Mesh || object instanceof THREE.LineSegments) { object.geometry.dispose(); (object.material as THREE.Material).dispose(); } }
diff --git a/docs/public/README.md b/docs/public/README.md
index 0bb9800e..a290af7d 100644
--- a/docs/public/README.md
+++ b/docs/public/README.md
@@ -10,7 +10,7 @@ Start with [Getting Started](getting-started.md), then use these guides:
- Interoperability: [Forge Host Protocol v1](forge/interop.md)
- Mechanisms: [Editable V8, prescribed motion and assembly mesh export](firmament/editable-mechanisms.md)
- Showcase: [Difference Engine, real hierarchical CAD and prescribed browser animation](demos/difference-engine-showcase.md), [single-cut carved electric guitar, STEP/USD and Cycles](demos/guitar-surfacing-x0.md)
-- Inspection: [Cadmata](cadmata/overview.md) and [Cadmata PMI](cadmata/pmi.md)
+- Inspection: [Cadmata](cadmata/overview.md), [Cadmata PMI](cadmata/pmi.md), and [Three Telos display migration](three-telos.md)
- Reference: [CLI](reference/cli.md), [wireframe SVG previews](reference/wireframe.md), [targets/selectors](reference/targets.md), [diagnostics](reference/diagnostics.md), [supported features](reference/supported-features.md), [known issues](reference/known-issues.md), and [release notes](reference/release-notes.md)
The Windows ZIP begins with the tested [release-bundle walkthrough](release-bundle.md).
diff --git a/docs/public/three-telos.md b/docs/public/three-telos.md
new file mode 100644
index 00000000..f868f7ae
--- /dev/null
+++ b/docs/public/three-telos.md
@@ -0,0 +1,7 @@
+# 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.
+
+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.
+
+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.
diff --git a/docs/release/THREE-TELOS-X0.md b/docs/release/THREE-TELOS-X0.md
new file mode 100644
index 00000000..c59fa228
--- /dev/null
+++ b/docs/release/THREE-TELOS-X0.md
@@ -0,0 +1,147 @@
+# THREE-TELOS-X0
+
+Verdict: **Meaningful progression**, 2026-10-05. The external-attachment blocker is removed by an owned raw WebGPU substrate, implemented in strict TypeScript. Real Edge browser tests qualify a direct-WGSL CIR cylinder, an ordinary mesh, shared depth in both occlusion directions, thick topology lines, resource reuse and recreation. Cadmata's normal DisplayScene/assembly path and Helios use the same package. Full acceptance is withheld: Cadmata's semantic authoring overlays and PMI still require the explicitly transitional R3F viewport.
+
+## Audit before implementation
+
+The primary Helios application is the sibling `HeliosCAD` repository, not only the older `demos/Aetherion.Helios` example. Both were inspected and integrated. This mission explicitly includes Helios; no Copeland source, kernel semantics, or unrelated repository was changed.
+
+| Area | Cadmata before | Actual Helios before | Telos owner / retained dependency |
+| --- | --- | --- | --- |
+| Three | installed 0.183.2; caret range | installed 0.186.0; `latest` | all three clients and Telos pinned to 0.183.2; Helios types also pinned |
+| Renderer / loop | R3F Canvas and useFrame | WebGLRenderer and dirty/damping RAF | TelosDevice, TelosHost invalidation, no Three GPU renderer |
+| Background / grid | ShaderMaterial background; adaptive orthographic grid | scene color, GridHelper rotated to XY | solid clear and camera-ray reference grid; animated themes remain a legacy feature |
+| Mesh / appearance | per-face MeshStandardMaterial; assembly shared definitions | BufferGeometry shared per definition; MeshStandardMaterial | immutable definition buffers and occurrence uniforms; small TelosMaterial |
+| BRep edges | Drei Line / WebGL LineMaterial and artifact overlays | SDK edge polylines; LineSegments; selected TubeGeometry | screen-space segment quads; SDK edges retain their IDs |
+| Pick / highlight | camera Raycaster ray to server BRep query; R3F occurrence events | CPU Raycaster, SDK describeSelection/describeEdgeSelection | Telos worldRay and TelosPick; server/SDK semantic selection authority retained |
+| Camera / navigation | R3F authoritative orthographic camera and OrbitControls | perspective/orthographic cameras and OrbitControls | TelosCamera and direct input navigation; output-only Three camera adapter |
+| Scene ownership | R3F hierarchy including authoring/PMI layers | Three Group built from WASM mesh snapshots | plain typed TelosScene, independent input adapters |
+| Lifetime / resize | R3F lifetime plus material effects | renderer, observer, RAF, geometries, materials in wrapper | Telos resources, depth recreation, navigation listeners and observer disposal |
+| WASM | server display packets | ModelSession typed-array snapshot, SDK selection resolution | unchanged; graphics does not interpret Firmament/CIR semantics |
+
+Duplicated product code included camera creation, ray construction, resize, render scheduling, geometry upload, material conversion and edge rendering. Those graphics responsibilities now reside in Telos. Product wrappers still interpret their own packet and selection contracts and route DOM events. Legacy implementations are retained in files named `Legacy*`, with a visible transitional diagnostic.
+
+Three remains useful for matrices, vectors, quaternion math, geometry containers, CPU triangle queries and loaders via the Three scene adapter. The DISPLAY-HOST-X0 retained probe documents external attachment format metadata and lifetime limitations in the installed Three WebGPU renderer. Cadmata's WebGL thick lines/background and Text/Html layer dependencies also block a renderer-only substitution. Telos avoids the attachment limitation entirely by submitting raw WebGPU passes. No backend maps, renderer private state, monkey-patches or Three fork are used.
+
+## Ownership and contracts
+
+Installed dependency inspection also finds Three 0.170.0 nested under Cadmata's Drei `stats-gl` dependency. This is a bounded legacy profiler dependency, not the version used by Telos or either product's main Three import. Direct product/Telos versions are unified at 0.183.2. Forcing an unrelated profiler upgrade was not required for the shared host; the nested version remains documented until the R3F compatibility dependency is removed.
+
+The standalone package is `Aetheris.Web.Runtime/telos`, named `@aetheris/three-telos`. It builds TypeScript with strict checking, emits declarations, and can be packed independently. Its browser implementation has no dependency on the Aetheris WASM runtime, Firmament, CIR parsing or a Copeland checkout.
+
+`TelosDevice` owns adapter/device/context, the preferred canvas format, actual device features/limits, validation diagnostics and loss handling. One device is created per viewport through this owner; product wrappers never request devices. Multiple simultaneous viewport device sharing is not an X0 capability.
+
+`TelosFrame` owns the presented color texture/view and one `depth32float` attachment. Canvas color is acquired per frame; depth is retained until dimensions change. Depth clears to 1, mesh/field compare `less` and write depth, topology compares `less-equal` without writing, and overlays compare `always` without writing. Passes load/store the same attachments. Single-sample only; MSAA is deferred. Resize uses CSS size/DPR, clamps texture dimensions to device limits, destroys the old depth texture and increments an observable generation. Pass viewport/scissor defaults cover those attachment dimensions.
+
+The explicit order is background clear, optional reference grid, opaque mesh, field, topology and overlay, then submission/presentation. Selection tint is incorporated in mesh/field/line inputs. Pipeline construction is separated in `pipelines.ts`; pass kinds determine formats, vertex layouts, bindings, depth behavior and cache identity. This is a bounded pass sequence, not a general render graph.
+
+`TelosCamera` owns position, target/up, perspective/orthographic projection, aspect, span, near/far and view/projection inverses. Matrices are column-major, the world is right-handed, clip depth is WebGPU [0,1], and screen coordinates are CSS pixels. Project/unproject and canonical near-plane world rays are shared by picking, fields, grids and navigation. `toThree()` returns compatibility state; mutating it cannot change Telos. The reference grid intersects these rays with XY/XZ planes and bounds its generated segment count, including near-horizon views. It has no orthographic-only camera cast.
+
+The mesh path uploads positions, normals and uint32 indices per immutable definition ID. Occurrences carry separate model/inverse-transpose normal transforms and material uniforms. Base color, opacity, roughness and metallic drive a small directional shading model, not full MeshStandardMaterial/ACES/PBR parity. Transparency uses ordinary blending without sorting; advanced transparency and shadow parity are unqualified. Geometry IDs must identify immutable geometry within a scene. Assembly selection updates retain mapped arrays through a WeakMap packet cache.
+
+Topology lines use one instanced quad per segment. Width is in CSS pixels and is independent of zoom/DPR. Near-plane crossings are clipped before division by w. The documented normalized-depth bias is 2e-6; lines do not alter authoritative surface depth. This is display bias, not engineering geometry. Hidden-edge occlusion is checked in the browser witness. Field overlays use supplied BRep data, never inferred tessellation diagonals.
+
+`TelosIdentity` carries occurrence/body/definition/face/edge identities from the source. `TelosPick` exposes a CPU implementation behind a typed hit contract, uses Telos rays, resolves mesh face ranges, transforms world normals, and admits engineering mesh proxies for field picking. Edge queries use projected pixel distance and nearest-surface rejection. Direct field face semantics remain deferred. Helios resolves hits through the SDK; Cadmata's server BRep query receives the same canonical ray. Graphics does not invent source selectors.
+
+`fromDisplayMesh` adapts SDK definitions, occurrences, transforms, ranges and kernel edge polylines. Cadmata adapts its DisplayScene/assembly packets separately. `fromThree` is a one-way data adapter from hierarchy/BufferGeometry, including GLTF-loader results; Telos does not store Object3D scene state. Multiple Three materials/interleaved attributes are not qualified by this adapter. No USD loader or additional scene ecosystem is introduced.
+
+## Direct WGSL / CIR field witness
+
+The retained compiler qualification path is:
+
+```text
+existing CIR SdfCylinderNode(0.8, 2)
+ -> CirVisualTsLowerer (existing CIR tape)
+ -> Field + typed fixtures/three-telos/field-pass.v.ts
+ -> Copeland parser/binder -> VD-MIR -> WgslGraphicsBackend
+ -> artifact -> Telos Field pass -> real Edge WebGPU
+```
+
+The artifact includes semantic shader hash, WGSL, vertex/fragment entrypoints, canonical binding metadata, capabilities, CIR source identity and compiler source mappings. The browser consumes WGSL without DXC, Naga, native compiler processes or CIR interpretation. The qualification script takes an explicit Copeland checkout only as an offline compiler input, and changes no files there.
+
+The direct compiler currently permits named canonical material shapes rather than arbitrary uniform records. An initial depth-row uniform record was rejected with `COPE-GPU-MATERIAL-0003`. X0 therefore uses the supported 32-byte tint/roughness material binding at group 0/binding 0. Camera-local near/far ray data, local-to-clip Z/W rows and scale-relative epsilon use typed vertex attributes in the documented 72-byte field ABI. These six vertices are updated per occurrence/frame; WGSL and pipelines are never generated per camera or occurrence. Field tint/opacity are consumed; roughness is transported but the smoke shader does not implement a full material model.
+
+The cylinder shader conservatively steps the existing qualified distance function along the local ray, computes a hit normal, and writes `clipZ / clipW` at the actual hit point. Mesh and field thus use the same camera and depth convention. Rigid occurrence transforms are admitted; affine scale/shear is explicitly rejected with `telos-field-transform-not-rigid`. Bounds and a mesh proxy are part of the field contract. Bounds currently control epsilon and fitting, not ray-box acceleration. The smoke shader has a fixed 512-step budget. Full CIR-DISPLAY-X1B packet/admission/field default qualification is not claimed.
+
+Shader modules reject an ID reused with different WGSL. Pipeline keys include semantic shader identity, pass state, color/depth formats and sample count. Immutable buffers, modules and pipelines belong to the device resource manager. Viewport disposal destroys buffers/textures and clears caches; device loss stops scheduling and emits a diagnostic. Remounting the viewport creates a new device/frame while product model state remains outside the graphics owner. Automatic loss recovery is deferred.
+
+## Product integration and exact remaining blocker
+
+Cadmata's `AetherisViewport.tsx` routes normal DisplayScene and assembly packets to Telos on WebGPU browsers. Grid, axis strokes, face/edge highlighting, orbit/pan/zoom, canonical server pick ray and occurrence picking use this host. The actual Helios wrapper and the older demo also use this package for compiled meshes, kernel edges, navigation, model refresh, hover, face/edge selection and a basic overlay slot. FRONT/TOP/RIGHT commands explicitly choose orthographic projection. Wireframe currently displays semantic topology strokes rather than tessellation diagonals. Screenshot capture remains a product canvas operation.
+
+**The next isolated blocker is the Cadmata authoring/PMI scene adapter.** `CadmataOverlay.tsx` uses Drei Line and R3F mesh event handlers for concept points/planes/profile guides; `PmiAnnotationLayer.tsx` uses Drei Html/Line plus useThree/useFrame for screen label layout. Their existing stable entity selection, draggable callouts and visibility rules need a Telos overlay/DOM projection adapter using `camera.project`, canonical picking and shared line/mesh inputs. The new wrapper deliberately selects `LegacyAetherisViewport` when `cadmataArtifact` is supplied and labels this reason. This preserves working authoring views instead of dropping annotations or making a second new GPU renderer. Concrete dependency remains visible in these two modules; neither is accepted as migrated.
+
+The smallest next repair is that adapter, including screen labels and authoring-entity hit routing, followed by the existing PMI/overlay tests and a real authored-model selection/label witness. Full product parity and removal of the authoring fallback remain required for Accepted. CIR smoke is qualified in the shared substrate witness; automatic product field packet construction/default selection remains the stated X1B work.
+
+## Qualification
+
+Evidence is generated under ignored `artifacts/local/three-telos/`, with build/unit/.NET logs in `artifacts/local/three-telos-*.log`.
+
+| Gate | Evidence / limit |
+| --- | --- |
+| Shared camera | TypeScript tests: perspective/orthographic project-unproject, ray, aspect, scales 1e-5/1/1e6, output-only Three adapter |
+| Mixed depth | Real Edge/NVIDIA Ampere: center-pixel readback matches field-only when field is ahead, mesh-only when mesh is ahead; both projections; mesh-mesh control passes. Bounded smoke, not full image/corpus qualification |
+| Lines | 4 CSS px measures 4 device px at DPR 1 and 8 at DPR 2, at spans 3 and 10; transformed lines, hidden-line rejection, selected style |
+| Reuse | Two mesh occurrences: one definition buffer set. Two fields: shared shader module/pipeline. Three total mesh/line/field modules and pipelines |
+| Lifecycle | Depth generation increases on resize; disposal clears tracked buffers/textures; recreated viewport renders the same scene without captured GPU errors |
+| Grid / camera stress | Orthographic span 0.01 and 10000 with reference grid; orbit-view matrix and unusual clipping; no captured validation error. This is not exhaustive large-coordinate visual qualification |
+| Helios real wrapper | Browser WASM compiles fixture Box, renders through actual product Viewport, picks SDK `face(+Z)`, mouse orbit and wheel zoom redraw, rebuilds 40mm to 45mm, picks same selector at revision 2; no page errors/alerts |
+| Cadmata real wrapper | Browser DisplayScene fixture renders mesh/edge, highlights and emits canonical pick ray; no errors/alerts. This does not prove full backend import UI or authoring/PMI |
+| Unit regressions | Telos 4 passed; Cadmata 83 passed; actual Helios 29 passed; demo Helios 26 passed |
+| Builds | Telos strict TypeScript, Cadmata production/lint, actual Helios and demo development bundles pass. Demo production now explicitly requires the existing AOT SDK; production AOT packaging is not claimed |
+| .NET | Release solution build: zero errors; final incremental build retains two pre-existing WebAssembly SQLite warnings. Fast kernel 1,005 passed. Full serial lane: 4,312 passed across 20 suites, zero failed/skipped |
+
+One full corpus test rewrote only line endings in a generated STEP fixture; the byte content was verified apart from line endings and restored. No kernel implementation changed.
+
+Representative browser measurement: device init 181 ms, first mesh+field submission completion 43 ms, mesh upload CPU 0.3 ms, field pipeline creation CPU below 0.1 ms timer resolution, steady submission completion mean 2.86 ms across 20 frames. These are one-machine smoke measurements at small resolution, not GPU timestamp profiling or product throughput claims. Line upload timing is collected separately during line witnesses; CPU timer granularity can report zero. No large house/warehouse qualification or performance gain is claimed.
+
+## Friction log / permanent owners
+
+| Friction | Workaround / Telos fix | Permanent owner / disposition |
+| --- | --- | --- |
+| Three external attachment format metadata | raw mesh/field/line pipelines avoid its GPU backend | Telos attachments; no upstream patch needed |
+| WebGL LineMaterial/background | owned quads and solid clear/reference grid | Telos; animated background parity deferred |
+| Camera/grid orthographic assumptions | one owned projection/ray API, bounded plane-ray grid | Telos; tests cover projections/scales |
+| Direct compiler canonical-only material records | supported tint/roughness uniform, typed ray/depth vertex payload | general frame uniforms belong to Copeland; no compiler rewrite or unrelated material-shape abuse |
+| Product authoring Text/Html/events | explicit legacy route preserves current behavior | Cadmata overlay/PMI adapter; next acceptance blocker |
+| Resource lifetime / queued frame race | explicit render consumes pending invalidation; readback snapshots dimensions before awaiting mapping | Telos; resize/dispose/recreate browser witness |
+| Selection reset TOP camera up vector | initialize product world-up only on viewport creation; selection updates preserve owned camera state | Helios wrapper; live selection/orbit/zoom/rebuild witness rerun |
+| Helios demo stale local SDK tarball | refresh explicit local package after packing | SDK install workflow; `npm install` alone reused cached same-version tarball |
+| Demo production build requirement | use development bundle for this renderer gate | existing SDK requires AOT for production; no false production claim |
+| Cadmata fixture outside Vite root | opt-in `AETHERIS_TELOS_WITNESS=1` narrowly admits fixture directory; standard React dev preamble | qualification only; current fixture policy preserved |
+| Thin-line / hidden-edge and transform uncertainty | pixel-width and occlusion readbacks; rigid field admission | Telos; extreme depth-bias/large model qualification remains bounded |
+| Field selection semantics | typed hit abstraction accepts engineering mesh proxy | SDK/BRep correspondence; perfect field face picking deferred |
+
+## Cleanup and fork decision
+
+Cleanup separated pipeline descriptors from host sequencing, kept math/camera/rays in one module, moved product packet interpretation to adapters, retained immutable assembly geometry across selection changes, and centralized device/frame/resources/navigation. All new implementation and test logic is TypeScript; WGSL is shader source and C# is the offline compiler witness. HTML contains only normal browser module/development bootstrap.
+
+**Is Three.js still helping more than it hurts? Yes, as a utility and ecosystem dependency.** Maintained Three patches: **0**. Patch invasiveness: **none**. Renderer internals depended upon by Telos: **0**. Upgrade risk is concentrated in public math/geometry/raycast/input adapter APIs, with one pinned version and camera/picking regressions. Legacy R3F views retain their existing dependencies until removed. A hard fork is not justified. Three can be reduced later without changing the plain scene/shader contracts or raw WebGPU passes.
+
+Executive answer: **the shared, Three-renderer-independent WebGPU substrate now works, including direct-WGSL CIR and mixed depth; full Cadmata/Helios X0 product acceptance is not yet earned because Cadmata authoring/PMI still selects the legacy host.** This is Meaningful progression, not Accepted.
+
+## Reproduce
+
+```powershell
+# Aetheris root
+./scripts/prepare-three-telos-cir.ps1 -CopelandRoot ../Copeland
+cd Aetheris.Web.Runtime/telos
+npm ci
+npm test
+npm run build:witness
+cd ../..
+node scripts/qualify-three-telos-browser.mts ../HeliosCAD/node_modules/playwright/index.mjs
+
+# Product witness: foreground terminals, stop after qualification
+# HeliosCAD: npm run dev -- --host 127.0.0.1
+# Aetheris/aetheris.client:
+# $env:AETHERIS_VITE_HTTP='1'; $env:AETHERIS_TELOS_WITNESS='1'
+# npm run dev -- --host 127.0.0.1
+node scripts/qualify-three-telos-products.mts ../HeliosCAD/node_modules/playwright/index.mjs http://127.0.0.1:5173
+
+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
+```
+
+Build Telos before installing/building a consumer; npm file dependencies reference its compiled `dist` export. Fresh consumers need their ordinary dependencies and local SDK package installed. The browser script owns its temporary HTTP server and closes it in `finally`. No persistent/background service, scheduled task or startup hook is created.
diff --git a/fixtures/three-telos/cadmata.html b/fixtures/three-telos/cadmata.html
new file mode 100644
index 00000000..edf77684
--- /dev/null
+++ b/fixtures/three-telos/cadmata.html
@@ -0,0 +1,9 @@
+<!doctype html><html lang="en"><meta charset="utf-8"><title>Cadmata Telos wrapper</title><div id="root"></div>
+<!-- /@fs serves HTML verbatim. This is Vite's standard React development preamble. -->
+<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-witness.tsx"></script></html>
diff --git a/fixtures/three-telos/field-pass.v.ts b/fixtures/three-telos/field-pass.v.ts
new file mode 100644
index 00000000..a65d1dd1
--- /dev/null
+++ b/fixtures/three-telos/field-pass.v.ts
@@ -0,0 +1,52 @@
+@space(clip.position) type ClipPosition = float4;
+@material @binding(0)
+record FieldFrame { tint: float4; roughness: f32; }
+stream Resources { @binding(0) frame: FieldFrame; }
+stream Input {
+ @location(0) position: float3;
+ @location(1) origin: float3;
+ @location(2) delta: float3;
+ @location(3) depthRow: float4;
+ @location(4) wRow: float4;
+ @location(5) epsilon: f32;
+}
+stream Varyings {
+ @builtin(position) position: ClipPosition;
+ @location(0) origin: float3;
+ @location(1) delta: float3;
+ @location(2) depthRow: float4;
+ @location(3) wRow: float4;
+ @location(4) epsilon: f32;
+}
+stream Output { @target(0) color: float4; @builtin(frag_depth) depth: f32; }
+@vertex function VertexMain(input: Input): Varyings {
+ return { position: float4(input.position, 1.0), origin: input.origin, delta: input.delta, depthRow: input.depthRow, wRow: input.wRow, epsilon: input.epsilon };
+}
+@pixel function PixelMain(input: Varyings, resources: Resources): Output {
+ const length: f32 = Sqrt(input.delta.x * input.delta.x + input.delta.y * input.delta.y + input.delta.z * input.delta.z);
+ const dx: f32 = input.delta.x / length;
+ const dy: f32 = input.delta.y / length;
+ const dz: f32 = input.delta.z / length;
+ var t: f32 = 0.0;
+ for (var i: u32 = 0; i < 512; i = i + 1) {
+ const x: f32 = input.origin.x + t * dx;
+ const y: f32 = input.origin.y + t * dy;
+ const z: f32 = input.origin.z + t * dz;
+ const d: f32 = Field(x, y, z);
+ if (Abs(d) < input.epsilon) {
+ const h: f32 = input.epsilon * 2.0;
+ const gx: f32 = Field(x+h,y,z)-Field(x-h,y,z);
+ const gy: f32 = Field(x,y+h,z)-Field(x,y-h,z);
+ const gz: f32 = Field(x,y,z+h)-Field(x,y,z-h);
+ const n: f32 = Max(Sqrt(gx*gx+gy*gy+gz*gz),0.00000001);
+ const light: f32 = 0.28 + 0.72 * Abs((gx*0.3+gy*0.8+gz*0.6)/n);
+ const clipZ: f32 = input.depthRow.x*x+input.depthRow.y*y+input.depthRow.z*z+input.depthRow.w;
+ const clipW: f32 = input.wRow.x*x+input.wRow.y*y+input.wRow.z*z+input.wRow.w;
+ return { color: float4(resources.frame.tint.x*light,resources.frame.tint.y*light,resources.frame.tint.z*light,resources.frame.tint.w), depth: clipZ/clipW };
+ }
+ t = t + Abs(d) * 0.9;
+ if (t > length) { break; }
+ }
+ Discard();
+ return { color: float4(0.0,0.0,0.0,0.0), depth: 1.0 };
+}
diff --git a/fixtures/three-telos/model.firmament b/fixtures/three-telos/model.firmament
new file mode 100644
index 00000000..eba02f89
--- /dev/null
+++ b/fixtures/three-telos/model.firmament
@@ -0,0 +1,4 @@
+Model TelosWitness {
+ Units: mm
+ Box Body { Size: [40mm, 30mm, 8mm] }
+}
diff --git a/scripts/prepare-three-telos-cir.ps1 b/scripts/prepare-three-telos-cir.ps1
new file mode 100644
index 00000000..86085b18
--- /dev/null
+++ b/scripts/prepare-three-telos-cir.ps1
@@ -0,0 +1,17 @@
+param([Parameter(Mandatory=$true)][string]$CopelandRoot)
+$ErrorActionPreference = 'Stop'
+$repo = Split-Path $PSScriptRoot -Parent
+$output = Join-Path $repo 'artifacts/local/three-telos/cir'
+New-Item -ItemType Directory -Force -Path $output | Out-Null
+$continuum = [Security.SecurityElement]::Escape((Join-Path $repo 'Aetheris.Continuum/Aetheris.Continuum.csproj'))
+$backend = [Security.SecurityElement]::Escape((Join-Path $CopelandRoot 'src/Copeland/Copeland.TS.Backend.Wgsl/Copeland.TS.Backend.Wgsl.csproj'))
+if (-not (Test-Path -LiteralPath $backend)) { throw 'CopelandRoot must contain the direct managed WGSL backend.' }
+@"
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
+ <ItemGroup><ProjectReference Include="$continuum"/><ProjectReference Include="$backend"/></ItemGroup>
+</Project>
+"@ | Set-Content -LiteralPath (Join-Path $output 'Qualification.csproj') -Encoding utf8
+Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'qualify-three-telos-cir.cs') -Destination (Join-Path $output 'Program.cs')
+dotnet run --project (Join-Path $output 'Qualification.csproj') -c Release -- $output (Join-Path $repo 'fixtures/three-telos/field-pass.v.ts')
+if ($LASTEXITCODE -ne 0) { throw 'Direct CIR WGSL compilation failed.' }
diff --git a/scripts/qualify-three-telos-browser.mts b/scripts/qualify-three-telos-browser.mts
new file mode 100644
index 00000000..a4910cc5
--- /dev/null
+++ b/scripts/qualify-three-telos-browser.mts
@@ -0,0 +1,85 @@
+import { createServer } from "node:http";
+import { readFile, mkdir, writeFile } from "node:fs/promises";
+import { resolve, extname, sep } from "node:path";
+import { pathToFileURL, fileURLToPath } from "node:url";
+
+const repo = resolve(fileURLToPath(new URL("..", import.meta.url)));
+const modulePath = process.argv[2];
+if (!modulePath) throw new Error("Pass an explicit Playwright module path.");
+const { chromium } = await import(pathToFileURL(resolve(modulePath)).href);
+const server = createServer(async (request, response) => {
+ try {
+ const file = resolve(
+ repo,
+ "." +
+ decodeURIComponent(new URL(request.url!, "http://localhost").pathname),
+ );
+ if (!file.startsWith(repo + sep)) throw new Error("outside repo");
+ const data = await readFile(file);
+ const type: Record<string, string> = {
+ ".js": "text/javascript",
+ ".html": "text/html",
+ ".json": "application/json",
+ ".wasm": "application/wasm",
+ };
+ response.setHeader(
+ "Content-Type",
+ type[extname(file)] ?? "application/octet-stream",
+ );
+ response.end(data);
+ } catch {
+ response.statusCode = 404;
+ response.end("not found");
+ }
+});
+await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
+const address = server.address();
+if (!address || typeof address === "string") throw new Error("no port");
+const output = resolve(repo, "artifacts/local/three-telos");
+await mkdir(output, { recursive: true });
+let browser;
+try {
+ browser = await chromium.launch({
+ executablePath:
+ "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe",
+ headless: true,
+ });
+ const page = await browser.newPage({
+ viewport: { width: 1100, height: 1000 },
+ });
+ const consoleErrors: string[] = [];
+ page.on("pageerror", (error: Error) => consoleErrors.push(String(error)));
+ await page.goto(
+ `http://127.0.0.1:${address.port}/Aetheris.Web.Runtime/telos/tests/browser.html`,
+ );
+ await page.waitForFunction(
+ () =>
+ Boolean(
+ (window as unknown as { telosQualification?: unknown })
+ .telosQualification,
+ ),
+ null,
+ { timeout: 60000 },
+ );
+ const report = await page.evaluate(
+ () =>
+ (window as unknown as { telosQualification: { status: string } })
+ .telosQualification,
+ );
+ await page.screenshot({
+ path: resolve(output, "witness.png"),
+ fullPage: true,
+ });
+ await page.locator('canvas').screenshot({ path: resolve(output, 'witness-canvas.png') });
+ await writeFile(
+ resolve(output, "browser-report.json"),
+ JSON.stringify({ ...report, consoleErrors }, null, 2),
+ );
+ console.log(JSON.stringify({ ...report, consoleErrors }, null, 2));
+ if (report.status !== "PASS" || consoleErrors.length) process.exitCode = 1;
+} finally {
+ await browser?.close();
+ await new Promise<void>((done, reject) =>
+ server.close((error) => (error ? reject(error) : done())),
+ );
+}
diff --git a/scripts/qualify-three-telos-cir.cs b/scripts/qualify-three-telos-cir.cs
new file mode 100644
index 00000000..8a90e406
--- /dev/null
+++ b/scripts/qualify-three-telos-cir.cs
@@ -0,0 +1,25 @@
+using System.Text.Json;
+using Aetheris.Continuum.Backends.Sdf;
+using Copeland.TS.Gpu;
+using Copeland.TS.Gpu.VdMir;
+using Copeland.TS.Gpu.Wgsl;
+
+// Explicit external compiler checkout is a qualification input, not a runtime dependency.
+var lowering = CirVisualTsLowerer.Lower(new SdfCylinderNode(0.8, 2));
+if (!lowering.Success) throw new InvalidOperationException(lowering.FallbackReason);
+string source = lowering.Program!.FieldSource + File.ReadAllText(args[1]);
+var compiled = WgslGraphicsBackend.Compile(new GpuCompilationRequest([new GpuSourceFile("TelosCylinder.v.ts", source)]));
+if (!compiled.Success) throw new InvalidOperationException(string.Join("\n", compiled.Diagnostics.Select(d => d.Code + ": " + d.Message)));
+var program = compiled.Program!;
+Directory.CreateDirectory(args[0]);
+File.WriteAllText(Path.Combine(args[0], "Cylinder.v.ts"), source);
+File.WriteAllText(Path.Combine(args[0], "Cylinder.wgsl"), program.Code);
+File.WriteAllText(Path.Combine(args[0], "cylinder.json"), JsonSerializer.Serialize(new {
+ shaderId = program.SemanticHash, wgsl = program.Code,
+ vertexEntryPoint = program.VertexEntryPoint, fragmentEntryPoint = program.FragmentEntryPoint,
+ bindings = new[] { new { group = 0, binding = 0, kind = "uniform", byteSize = program.Semantics.Material!.Size } },
+ capabilities = new[] { "fragment-depth", "telos-field-rays/1", "rigid-occurrence" },
+ sourceIdentity = lowering.Program.StructuralHash,
+ compiler = WgslGraphicsBackend.CompatibilityVersion, program.SourceMappings,
+}, new JsonSerializerOptions { WriteIndented = true }));
+Console.WriteLine($"CIR Cylinder -> VD-MIR -> direct WGSL: {program.SemanticHash}; uniform {program.Semantics.Material!.Size} bytes");
diff --git a/scripts/qualify-three-telos-products.mts b/scripts/qualify-three-telos-products.mts
new file mode 100644
index 00000000..8657249a
--- /dev/null
+++ b/scripts/qualify-three-telos-products.mts
@@ -0,0 +1,136 @@
+import { resolve } from "node:path";
+import { pathToFileURL } from "node:url";
+import { writeFile } from "node:fs/promises";
+const { chromium } = await import(pathToFileURL(resolve(process.argv[2])).href);
+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: 1100, height: 900 },
+ });
+ const errors: string[] = [];
+ page.on("pageerror", (error: Error) => errors.push(String(error)));
+ await page.goto("http://127.0.0.1:4173/tests/three-telos-witness.html");
+ await page.waitForFunction(
+ () =>
+ (
+ window as unknown as {
+ heliosTelosQualification?: { compiled: boolean };
+ }
+ ).heliosTelosQualification?.compiled,
+ null,
+ { timeout: 120000 },
+ );
+ await page.locator("[data-display-host=three-telos] canvas").waitFor();
+ await page.getByRole("button", { name: "Top", exact: true }).click();
+ await page.waitForTimeout(300);
+ const canvas = page.locator("[data-display-host=three-telos] canvas");
+ const bounds = await canvas.boundingBox();
+ if (!bounds) throw new Error("no canvas");
+ await canvas.click({
+ position: { x: bounds.width / 2, y: bounds.height / 2 },
+ });
+ await page.waitForFunction(() =>
+ Boolean(
+ (
+ window as unknown as {
+ heliosTelosQualification: { selected?: unknown };
+ }
+ ).heliosTelosQualification.selected,
+ ),
+ );
+ const before = await page.evaluate(
+ () =>
+ (window as unknown as { heliosTelosQualification: unknown })
+ .heliosTelosQualification,
+ );
+ if (!JSON.stringify(before).includes("face(+Z)"))
+ throw new Error(
+ "canonical top face selection failed: " + JSON.stringify(before),
+ );
+ const beforeNavigation = await canvas.screenshot();
+ await page.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(bounds.x + bounds.width / 2 + 90, bounds.y + bounds.height / 2 + 35, { steps: 8 });
+ await page.mouse.up();
+ await page.waitForTimeout(150);
+ const afterOrbit = await canvas.screenshot();
+ if (beforeNavigation.equals(afterOrbit)) throw new Error('Helios orbit did not redraw');
+ await page.mouse.wheel(0, -250);
+ await page.waitForTimeout(150);
+ if (afterOrbit.equals(await canvas.screenshot())) throw new Error('Helios zoom did not redraw');
+ await page.getByRole("button", { name: "Refresh", exact: true }).click();
+ await page.waitForFunction(
+ () =>
+ (window as unknown as { heliosTelosQualification: { revision: number } })
+ .heliosTelosQualification.revision > 0,
+ );
+ await page.getByRole("button", { name: "Top", exact: true }).click();
+ await page.waitForTimeout(300);
+ await canvas.click({
+ position: { x: bounds.width / 2, y: bounds.height / 2 },
+ });
+ const after = await page.evaluate(
+ () =>
+ (window as unknown as { heliosTelosQualification: unknown })
+ .heliosTelosQualification,
+ );
+ const alerts = await page.getByRole("alert").allTextContents();
+ if (errors.length || alerts.length)
+ throw new Error(JSON.stringify({ errors, alerts }));
+ await page.screenshot({
+ path: "artifacts/local/three-telos/helios-wrapper.png",
+ });
+ const report = { status: "PASS", before, after, errors, alerts };
+ await writeFile(
+ "artifacts/local/three-telos/helios-wrapper.json",
+ JSON.stringify(report, null, 2),
+ );
+ console.log(JSON.stringify(report, null, 2));
+ if (process.argv[3]) {
+ const fixture = resolve("fixtures/three-telos/cadmata.html").replaceAll(
+ "\\",
+ "/",
+ );
+ await page.goto(process.argv[3] + "/@fs/" + fixture);
+ await page.locator("[data-display-host=three-telos] canvas").waitFor();
+ await page.waitForTimeout(300);
+ const cadmataCanvas = page.locator(
+ "[data-display-host=three-telos] canvas",
+ ),
+ rect = await cadmataCanvas.boundingBox();
+ if (!rect) throw new Error("Cadmata canvas missing");
+ await cadmataCanvas.click({
+ position: { x: rect.width / 2, y: rect.height / 2 },
+ });
+ const ray = await page.evaluate(
+ () => (window as unknown as { cadmataTelosRay: unknown }).cadmataTelosRay,
+ );
+ if (!ray) throw new Error("Cadmata canonical pick ray missing");
+ await page.getByRole("button", { name: "Select", exact: true }).click();
+ await page.waitForTimeout(300);
+ const cadmataAlerts = await page.getByRole("alert").allTextContents();
+ if (cadmataAlerts.length || errors.length)
+ throw new Error(JSON.stringify({ cadmataAlerts, errors }));
+ await page.screenshot({
+ path: "artifacts/local/three-telos/cadmata-wrapper.png",
+ });
+ const cadmataReport = {
+ status: "PASS",
+ ray,
+ errors,
+ alerts: cadmataAlerts,
+ scope: "real wrapper, bounded DisplayScene fixture",
+ };
+ await writeFile(
+ "artifacts/local/three-telos/cadmata-wrapper.json",
+ JSON.stringify(cadmataReport, null, 2),
+ );
+ console.log(JSON.stringify(cadmataReport, null, 2));
+ }
+} finally {
+ await browser.close();
+}