chore: checkpoint web Blender migration source, tools and docs
Some checks failed
M6 deployable RC / quick (push) Has been cancelled
M6 deployable RC / chromium (push) Has been cancelled
M6 deployable RC / release (push) Has been cancelled

Accumulated uncommitted work: GHOST Web backend, WebGL/GPU web layer,
web workflow engine and protocol, tooling, docs and task records.
Large generated evidence, user-testing archives, build snapshots and
imported test assets remain untracked.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
mes123456
2026-11-10 11:18:01 +08:00
parent 122142c26c
commit f3e21c6b98
6887 changed files with 257154 additions and 12294 deletions

View File

@@ -0,0 +1,12 @@
import {Matrix4,Vector3} from '../vendor/three/three.module.js';
import type {SceneNodeIR} from '../../../protocol/scene-ir';
const basis=new Matrix4().set(1,0,0,0, 0,0,1,0, 0,-1,0,0, 0,0,0,1);
const inverse=basis.clone().invert();
// Native SceneIR owns hierarchy and transform evaluation; Three only changes display basis.
export function nodeDisplayMatrix(node:SceneNodeIR,visible=true):Matrix4 {
const result=basis.clone().multiply(new Matrix4().fromArray(node.worldMatrix)).multiply(inverse);
if(!visible)result.scale(new Vector3(0,0,0));
return result;
}

View File

@@ -14,6 +14,7 @@ import {
type Object3D,
} from "../vendor/three/three.module.js";
import type { NonMeshDataIR, SceneNodeIR } from "../../../protocol/scene-ir";
import {nodeDisplayMatrix} from './node-display-matrix';
import type { NonMeshGeometryChunk } from "../../../protocol/nonmesh-binary";
import type { CurveGizmoHandleIR } from "../../../protocol/nonmesh-interaction";
@@ -165,11 +166,9 @@ export function createNonMeshObject(data: NonMeshDataIR, chunks: readonly NonMes
}
export function applyNonMeshTransform(object: Object3D, node: SceneNodeIR): void {
const [x, y, z] = node.transform.translation;
const [rx, ry, rz] = node.transform.rotationEuler;
object.position.set(x, z, -y);
object.rotation.set(rx, rz, -ry);
object.scale.set(...node.transform.scale);
object.matrixAutoUpdate=false;
object.matrix.copy(nodeDisplayMatrix(node));
object.matrixWorldNeedsUpdate=true;
object.name = node.name;
object.userData.sceneNodeId = node.id;
object.userData.blenderId = node.id;

View File

@@ -8,10 +8,12 @@ import type { GreasePencilPointPreview, GreasePencilPointRef } from "./grease-pe
import type { CurveGizmoFrameIR, CurveGizmoHandleIR, CurveGizmoScreenFrameIR } from "../../../protocol/nonmesh-interaction";
import type { NanoVDBViewportAssetIR } from "../volume/nanovdb-viewport";
import type { ViewportCameraState } from "../../../protocol/viewport-camera";
import type {ViewportNavigationCamera} from '../../../protocol/viewport-camera';
import type { GreasePencilDrawingScopeIR, GreasePencilMarqueeBoxIR, GreasePencilMarqueeResultIR } from "../../../protocol/grease-pencil-marquee";
import type { PaintDepthVisibilityRequestIR, PaintDepthVisibilityResultIR } from "../../../protocol/paint-depth-visibility";
export type OffscreenViewportRequest =
| {type:'navigation';camera:ViewportNavigationCamera}
| { type: "init"; canvas: OffscreenCanvas; width: number; height: number; pixelRatio: number }
| { type: "snapshot"; snapshot: SceneSnapshotIR; geometryBuffers: MeshGeometryBuffer[]; nonMeshGeometryBuffers: NonMeshGeometryChunk[] }
| { type: "textureAssets"; assets: GPUTextureAsset[] }
@@ -23,8 +25,8 @@ export type OffscreenViewportRequest =
| { type: "greasePencilPointPreview"; dataId: string; layerId: string; frame: number; points: GreasePencilPointPreview[] | null }
| { type: "curveGizmoFrame"; dataId: string | null; frame: CurveGizmoFrameIR | null }
| { type: "orbit"; deltaX: number; deltaY: number; zoom: number }
| { type: "pick"; x: number; y: number; additive: boolean; baseSelectionRevision: number }
| { type: "greasePencilMarquee"; drawing: GreasePencilDrawingScopeIR; box: GreasePencilMarqueeBoxIR; baseRevision: number; baseSelectionRevision: number; additive: boolean }
| { type: "pick"; x: number; y: number; mode: "REPLACE" | "ADD" | "SUBTRACT"; baseSelectionRevision: number }
| { type: "greasePencilMarquee"; drawing: GreasePencilDrawingScopeIR; box: GreasePencilMarqueeBoxIR; baseRevision: number; baseSelectionRevision: number; mode: "REPLACE" | "ADD" | "SUBTRACT" }
| { type: "paintDepthVisibility"; requestId: string; request: PaintDepthVisibilityRequestIR }
| { type: "dispose" };
@@ -37,9 +39,9 @@ export type OffscreenViewportResponse =
| { type: "volumeStatus"; status: "none" | "loading" | "ready" | "blocked"; count: number; errorCode?: string }
| { type: "selected"; objectId: string; additive: boolean }
| { type: "elementSelected"; meshId: string; mode: MeshElementMode; index: number; additive: boolean; nonMeshKind?: NonMeshElementKind }
| { type: "greasePencilPointSelected"; point: GreasePencilPointRef; additive: boolean; baseSelectionRevision: number }
| { type: "greasePencilPointSelected"; point: GreasePencilPointRef; mode: "REPLACE" | "ADD" | "SUBTRACT"; baseSelectionRevision: number }
| { type: "greasePencilSelectionStatus"; selectionRevision: number; pointIds: string[] }
| { type: "greasePencilMarqueeSelected"; result: GreasePencilMarqueeResultIR; additive: boolean }
| { type: "greasePencilMarqueeSelected"; result: GreasePencilMarqueeResultIR; mode: "REPLACE" | "ADD" | "SUBTRACT" }
| { type: "paintDepthVisibilityResult"; requestId: string; result: PaintDepthVisibilityResultIR }
| { type: "paintDepthVisibilityError"; requestId: string; message: string }
| { type: "curveGizmoScreenFrame"; frame: CurveGizmoScreenFrameIR | null }

View File

@@ -9,6 +9,7 @@ import type { OffscreenViewportRequest, OffscreenViewportResponse } from "./offs
import { PBR_PROFILE, PBR_SHADOW_PROFILE, PBR_TONE_MAPPING } from "./pbr";
import { resolveViewportPixelMetrics, viewportNDC } from "../../../protocol/viewport-dpr";
import { observePointerEvent } from "../../../protocol/pointer-contract";
import {ViewportNavigation} from './viewport-navigation';
import { createInputModalState, reduceInputModal, type InputModalState } from "../../../protocol/input-modal";
import type { NonMeshElementKind } from "./nonmesh";
import type { GreasePencilPointPreview, GreasePencilPointRef } from "./grease-pencil";
@@ -29,7 +30,7 @@ export interface ViewportBackend {
setSelection(objectIds: ReadonlySet<string>, elementSelection?: ReadonlyMap<string, ReadonlyMap<NonMeshElementKind, ReadonlySet<number>>>, greasePencilPoints?: readonly GreasePencilPointRef[], greasePencilSelectionRevision?: number): void;
setInteractionMode(editMode: boolean, selectionMode: MeshElementMode): void;
samplePaintVisibility(request: PaintDepthVisibilityRequestIR): Promise<PaintDepthVisibilityResultIR>;
selectGreasePencilMarquee(drawing: GreasePencilDrawingScopeIR, box: GreasePencilMarqueeBoxIR, baseRevision: number, baseSelectionRevision: number, additive: boolean): void;
selectGreasePencilMarquee(drawing: GreasePencilDrawingScopeIR, box: GreasePencilMarqueeBoxIR, baseRevision: number, baseSelectionRevision: number, mode: "REPLACE" | "ADD" | "SUBTRACT"): void;
setCurveHandlePreview(dataId: string, handles: readonly CurveGizmoHandleIR[] | null): void;
setGreasePencilPointPreview(dataId: string, layerId: string, frame: number, points: readonly GreasePencilPointPreview[] | null): void;
setCurveGizmoFrame(dataId: string | null, frame: CurveGizmoFrameIR | null): void;
@@ -53,8 +54,8 @@ export function acquireOffscreenViewportRenderer(
canvas: HTMLCanvasElement,
onSelect?: (objectId: string, additive: boolean) => void,
onElementSelect?: (meshId: string, mode: MeshElementMode, index: number, additive: boolean, nonMeshKind?: NonMeshElementKind) => void,
onGreasePencilPointSelect?: (point: GreasePencilPointRef, additive: boolean, baseSelectionRevision: number) => void,
onGreasePencilMarqueeSelect?: (result: GreasePencilMarqueeResultIR, additive: boolean) => void,
onGreasePencilPointSelect?: (point: GreasePencilPointRef, mode: "REPLACE" | "ADD" | "SUBTRACT", baseSelectionRevision: number) => void,
onGreasePencilMarqueeSelect?: (result: GreasePencilMarqueeResultIR, mode: "REPLACE" | "ADD" | "SUBTRACT") => void,
): OffscreenViewportRenderer {
const existing = sharedBackends.get(canvas);
if (existing) {
@@ -86,9 +87,10 @@ export class OffscreenViewportRenderer implements ViewportBackend {
private readonly resizeObserver: ResizeObserver;
private readonly onSelect?: (objectId: string, additive: boolean) => void;
private readonly onElementSelect?: (meshId: string, mode: MeshElementMode, index: number, additive: boolean, nonMeshKind?: NonMeshElementKind) => void;
private readonly onGreasePencilPointSelect?: (point: GreasePencilPointRef, additive: boolean, baseSelectionRevision: number) => void;
private readonly onGreasePencilMarqueeSelect?: (result: GreasePencilMarqueeResultIR, additive: boolean) => void;
private pointer: { id: number; x: number; y: number; moved: boolean } | null = null;
private readonly onGreasePencilPointSelect?: (point: GreasePencilPointRef, mode: "REPLACE" | "ADD" | "SUBTRACT", baseSelectionRevision: number) => void;
private readonly onGreasePencilMarqueeSelect?: (result: GreasePencilMarqueeResultIR, mode: "REPLACE" | "ADD" | "SUBTRACT") => void;
private pointer: { id: number; x: number; y: number; moved: boolean;button:number } | null = null;
private readonly navigation:ViewportNavigation;
private inputModal: InputModalState = createInputModalState();
private touchNavigationActive = false;
private lastSnapshot: SceneSnapshotIR | null = null;
@@ -106,8 +108,8 @@ export class OffscreenViewportRenderer implements ViewportBackend {
canvas: HTMLCanvasElement,
onSelect?: (objectId: string, additive: boolean) => void,
onElementSelect?: (meshId: string, mode: MeshElementMode, index: number, additive: boolean, nonMeshKind?: NonMeshElementKind) => void,
onGreasePencilPointSelect?: (point: GreasePencilPointRef, additive: boolean, baseSelectionRevision: number) => void,
onGreasePencilMarqueeSelect?: (result: GreasePencilMarqueeResultIR, additive: boolean) => void,
onGreasePencilPointSelect?: (point: GreasePencilPointRef, mode: "REPLACE" | "ADD" | "SUBTRACT", baseSelectionRevision: number) => void,
onGreasePencilMarqueeSelect?: (result: GreasePencilMarqueeResultIR, mode: "REPLACE" | "ADD" | "SUBTRACT") => void,
) {
if (!supportsOffscreenViewport(canvas)) throw new Error("OffscreenCanvas viewport is unavailable");
this.canvas = canvas;
@@ -126,13 +128,13 @@ export class OffscreenViewportRenderer implements ViewportBackend {
pixelRatio: resolveViewportPixelMetrics(1, 1, window.devicePixelRatio).pixelRatio,
};
this.worker.postMessage(request, [offscreen]);
this.navigation=new ViewportNavigation(canvas,camera=>this.worker.postMessage({type:'navigation',camera} satisfies OffscreenViewportRequest));
this.resizeObserver = new ResizeObserver(() => this.resize());
this.resizeObserver.observe(canvas);
canvas.addEventListener("pointerdown", this.pointerDown);
canvas.addEventListener("pointermove", this.pointerMove);
canvas.addEventListener("pointerup", this.pointerUp);
canvas.addEventListener("pointercancel", this.pointerUp);
canvas.addEventListener("wheel", this.wheel, { passive: false });
canvas.dataset.rendererBackend = "offscreen-worker";
canvas.dataset.pbrProfile = PBR_PROFILE;
canvas.dataset.toneMapping = PBR_TONE_MAPPING;
@@ -144,6 +146,7 @@ export class OffscreenViewportRenderer implements ViewportBackend {
setSnapshot(snapshot: SceneSnapshotIR, geometryBuffers: MeshGeometryBuffer[] = [], nonMeshGeometryBuffers: NonMeshGeometryChunk[] = []): void {
if (snapshot === this.lastSnapshot && geometryBuffers === this.lastGeometryBuffers && nonMeshGeometryBuffers === this.lastNonMeshGeometryBuffers) return;
this.lastSnapshot = snapshot;
this.navigation.setSnapshot(snapshot);
const udim = snapshot.images.find((image) => image.tiles && image.tiles.length > 0);
if (udim) {
const gate = gateUDIMImage(udim);
@@ -196,6 +199,7 @@ export class OffscreenViewportRenderer implements ViewportBackend {
}
setSelection(objectIds: ReadonlySet<string>, elementSelection?: ReadonlyMap<string, ReadonlyMap<NonMeshElementKind, ReadonlySet<number>>>, greasePencilPoints: readonly GreasePencilPointRef[] = [], greasePencilSelectionRevision = 0): void {
this.navigation.setSelection(objectIds);
const elements = [...(elementSelection ?? new Map())].flatMap(([dataId, kinds]) => [...kinds].flatMap(([kind, indices]) => [...indices].map((index) => ({ dataId, kind, index }))));
this.greasePencilSelectionRevision = greasePencilSelectionRevision;
this.worker.postMessage({ type: "selection", objectIds: [...objectIds], elements, greasePencilPoints: [...greasePencilPoints], greasePencilSelectionRevision } satisfies OffscreenViewportRequest);
@@ -219,9 +223,9 @@ export class OffscreenViewportRenderer implements ViewportBackend {
box: GreasePencilMarqueeBoxIR,
baseRevision: number,
baseSelectionRevision: number,
additive: boolean,
mode: "REPLACE" | "ADD" | "SUBTRACT",
): void {
this.worker.postMessage({ type: "greasePencilMarquee", drawing, box, baseRevision, baseSelectionRevision, additive } satisfies OffscreenViewportRequest);
this.worker.postMessage({ type: "greasePencilMarquee", drawing, box, baseRevision, baseSelectionRevision, mode } satisfies OffscreenViewportRequest);
}
setCurveHandlePreview(dataId: string, handles: readonly CurveGizmoHandleIR[] | null): void {
@@ -244,6 +248,7 @@ export class OffscreenViewportRenderer implements ViewportBackend {
}
private resize(): void {
this.navigation.resize();
const metrics = resolveViewportPixelMetrics(Math.max(1, this.canvas.clientWidth), Math.max(1, this.canvas.clientHeight), window.devicePixelRatio);
this.canvas.dataset.viewportCssSize = `${metrics.cssWidth}x${metrics.cssHeight}`;
this.canvas.dataset.viewportBackingSize = `${metrics.backingWidth}x${metrics.backingHeight}`;
@@ -259,7 +264,7 @@ export class OffscreenViewportRenderer implements ViewportBackend {
private pointerDown = (event: PointerEvent): void => {
const observation = this.recordInputModalEvent(event);
if (observation?.pointerType === "touch" && this.inputModal.activePointerIds.length >= 2) this.touchNavigationActive = true;
this.pointer = { id: event.pointerId, x: event.clientX, y: event.clientY, moved: false };
this.pointer = { id: event.pointerId, x: event.clientX, y: event.clientY, moved: false,button:event.button };
try {
this.canvas.setPointerCapture(event.pointerId);
}
@@ -275,7 +280,6 @@ export class OffscreenViewportRenderer implements ViewportBackend {
if (Math.abs(deltaX) + Math.abs(deltaY) > 1) this.pointer.moved = true;
this.pointer.x = event.clientX;
this.pointer.y = event.clientY;
this.worker.postMessage({ type: "orbit", deltaX, deltaY, zoom: 0 } satisfies OffscreenViewportRequest);
};
private pointerUp = (event: PointerEvent): void => {
@@ -291,10 +295,10 @@ export class OffscreenViewportRenderer implements ViewportBackend {
return;
}
if (!this.pointer || this.pointer.id !== event.pointerId) return;
if (!this.pointer.moved) {
if (!this.pointer.moved&&this.pointer.button===0) {
const bounds = this.canvas.getBoundingClientRect();
const ndc = viewportNDC(event.clientX, event.clientY, bounds);
this.worker.postMessage({ type: "pick", x: ndc.x, y: ndc.y, additive: event.shiftKey || event.ctrlKey || event.metaKey, baseSelectionRevision: this.greasePencilSelectionRevision } satisfies OffscreenViewportRequest);
this.worker.postMessage({ type: "pick", x: ndc.x, y: ndc.y, mode: event.ctrlKey || event.metaKey ? "SUBTRACT" : event.shiftKey ? "ADD" : "REPLACE", baseSelectionRevision: this.greasePencilSelectionRevision } satisfies OffscreenViewportRequest);
}
this.pointer = null;
};
@@ -342,7 +346,7 @@ export class OffscreenViewportRenderer implements ViewportBackend {
}
else if (message.type === "selected") this.onSelect?.(message.objectId, message.additive);
else if (message.type === "elementSelected") this.onElementSelect?.(message.meshId, message.mode, message.index, message.additive, message.nonMeshKind);
else if (message.type === "greasePencilPointSelected") this.onGreasePencilPointSelect?.(message.point, message.additive, message.baseSelectionRevision);
else if (message.type === "greasePencilPointSelected") this.onGreasePencilPointSelect?.(message.point, message.mode, message.baseSelectionRevision);
else if (message.type === "greasePencilSelectionStatus") {
this.canvas.dataset.greasePencilSelectionRevision = String(message.selectionRevision);
this.canvas.dataset.greasePencilSelectionPointIds = message.pointIds.join(",");
@@ -353,7 +357,7 @@ export class OffscreenViewportRenderer implements ViewportBackend {
this.canvas.dataset.greasePencilMarqueePointIds = message.result.selectedPoints.map((point) => point.pointId).join(",");
this.canvas.dataset.greasePencilMarqueeStrokeIds = message.result.selectedStrokeIds.join(",");
this.canvas.dataset.greasePencilMarqueeCount = String(message.result.selectedPoints.length);
this.onGreasePencilMarqueeSelect?.(message.result, message.additive);
this.onGreasePencilMarqueeSelect?.(message.result, message.mode);
}
else if (message.type === "paintDepthVisibilityResult") {
const pending = this.pendingPaintDepth.get(message.requestId);
@@ -370,13 +374,6 @@ export class OffscreenViewportRenderer implements ViewportBackend {
}
else if (message.type === "frame") {
this.canvas.dataset.rendererPixels = String(message.visiblePixels);
if (message.camera) {
this.canvas.dataset.cameraPosition = message.camera.position.map((value) => Number(value.toFixed(6))).join(",");
this.canvas.dataset.cameraTarget = message.camera.target.map((value) => Number(value.toFixed(6))).join(",");
this.canvas.dataset.cameraYaw = message.camera.yaw.toFixed(6);
this.canvas.dataset.cameraPitch = message.camera.pitch.toFixed(6);
this.canvas.dataset.cameraDistance = message.camera.distance.toFixed(6);
}
}
else if (message.type === "snapshotStatus") {
this.canvas.dataset.nonMeshCount = String(message.nonMeshCount);
@@ -424,6 +421,7 @@ export class OffscreenViewportRenderer implements ViewportBackend {
this.canvas.removeEventListener("pointerup", this.pointerUp);
this.canvas.removeEventListener("pointercancel", this.pointerUp);
this.canvas.removeEventListener("wheel", this.wheel);
this.navigation.dispose();
this.worker.postMessage({ type: "dispose" } satisfies OffscreenViewportRequest);
this.worker.terminate();
for (const pending of this.pendingPaintDepth.values()) pending.reject(new Error("PAINT_DEPTH_UNAVAILABLE: Offscreen viewport disposed"));

View File

@@ -9,6 +9,7 @@ import {
WebGLRenderTarget,
type Object3D,
type PerspectiveCamera,
type OrthographicCamera,
type Scene,
type WebGLRenderer,
} from "../vendor/three/three.module.js";
@@ -74,7 +75,7 @@ export function samplePaintDepthVisibilityGPU({
}: {
renderer: WebGLRenderer;
scene: Scene;
camera: PerspectiveCamera;
camera: PerspectiveCamera|OrthographicCamera;
object: Object3D;
request: PaintDepthVisibilityRequestIR;
backend: PaintDepthVisibilityBackend;
@@ -153,7 +154,7 @@ export function samplePaintDepthVisibilityGPU({
const x = Math.max(0, Math.min(width - 1, Math.round((projected.x * 0.5 + 0.5) * (width - 1))));
const y = Math.max(0, Math.min(height - 1, Math.round((projected.y * 0.5 + 0.5) * (height - 1))));
const depth = unpackRGBADepth(pixels, (y * width + x) * 4);
const sampledDistance = perspectiveDistance(depth, camera.near, camera.far);
const sampledDistance = 'isOrthographicCamera' in camera ? camera.near+depth*(camera.far-camera.near) : perspectiveDistance(depth, camera.near, camera.far);
const tolerance = Math.max(1e-4, viewDistance * DEPTH_TOLERANCE_RATIO);
if (viewDistance <= sampledDistance + tolerance) visibleVertexIndices.push(index);
}

View File

@@ -0,0 +1,189 @@
import {Box3,Matrix4,MOUSE,OrthographicCamera,PerspectiveCamera,Quaternion,Vector3} from '../vendor/three/three.module.js';
import {OrbitControls} from '../vendor/three/addons/controls/OrbitControls.js';
import type {SceneSnapshotIR} from '../../../protocol/scene-ir';
import type {NDOFCamera,NDOFViewportEvent} from '../../../protocol/ndof';
import type {BlenderViewportCamera} from '../../../protocol/viewport-camera';
import {VIEWPORT_DEFAULT_ORBIT,VIEWPORT_ORBIT_MAX_DISTANCE,VIEWPORT_ORBIT_MIN_DISTANCE,VIEWPORT_ORBIT_ROTATE_SENSITIVITY,VIEWPORT_ORBIT_ZOOM_SENSITIVITY,orbitPosition,orbitStateFromPosition,type ViewportNavigationCamera,type ViewportNavigationCommand,type ViewportView} from '../../../protocol/viewport-camera';
const basis=new Matrix4().set(1,0,0,0, 0,0,1,0, 0,-1,0,0, 0,0,0,1);
const fromDisplay=(v:Vector3):[number,number,number]=>[v.x,-v.z,v.y];
const directions:Record<Exclude<ViewportView,'USER'>,[number,number,number]>={FRONT:[0,0,1],BACK:[0,0,-1],RIGHT:[1,0,0],LEFT:[-1,0,0],TOP:[0,1,1e-7],BOTTOM:[0,-1,1e-7]};
export class ViewportNavigation {
camera:PerspectiveCamera|OrthographicCamera=new PerspectiveCamera(45,1,.001,10000);
controls:OrbitControls;
private snapshot:SceneSnapshotIR|null=null;
private selected=new Set<string>();
private hover=false;
private view:ViewportView='USER';
private changing=false;
private disposed=false;
private fov=45;
private orthoHeight=5;
private gesture=false;
private navigationVersion=0;
private ndofPending:NDOFViewportEvent|null=null;
private ndofProcessing=false;
constructor(private readonly canvas:HTMLCanvasElement,private readonly changed:(state:ViewportNavigationCamera)=>void){
const [x,y,z]=orbitPosition(VIEWPORT_DEFAULT_ORBIT);this.camera.position.set(x,z,-y);
canvas.tabIndex=0;
canvas.addEventListener('pointerdown',this.pointerDown,true);
canvas.addEventListener('pointerenter',this.enter);canvas.addEventListener('pointerleave',this.leave);
window.addEventListener('keydown',this.keyDown);window.addEventListener('pointerup',this.pointerEnd);window.addEventListener('pointercancel',this.pointerEnd);window.addEventListener('blur',this.pointerEnd);
canvas.addEventListener('viewport-command',this.commandEvent);
canvas.addEventListener('viewport-ndof',this.ndofEvent);
canvas.addEventListener('viewport-restore',this.restoreEvent);
canvas.addEventListener('viewport-capture',this.captureEvent);
this.controls=this.createControls(new Vector3());this.resize();
}
private createControls(target:Vector3):OrbitControls {
const controls=new OrbitControls(this.camera,this.canvas);
controls.target.copy(target);controls.enableDamping=false;controls.enablePan=true;controls.screenSpacePanning=true;
controls.mouseButtons={LEFT:undefined,MIDDLE:MOUSE.ROTATE,RIGHT:undefined};
const distance=this.camera.position.distanceTo(target);
controls.minDistance=Math.min(VIEWPORT_ORBIT_MIN_DISTANCE,distance);controls.maxDistance=Math.max(VIEWPORT_ORBIT_MAX_DISTANCE,distance);
controls.minZoom=.0001;controls.maxZoom=1e5;
controls.zoomSpeed=VIEWPORT_ORBIT_ZOOM_SENSITIVITY/(.01*-Math.log(.95));
controls.addEventListener('change',this.onChange);
controls.update();return controls;
}
private onChange=()=>{if(!this.changing&&this.controls)this.publish();};
private captureEvent=(event:Event)=>{
const reply=(event as CustomEvent<{reply:(camera:BlenderViewportCamera)=>void}>).detail.reply;
const orientation=new Quaternion().setFromRotationMatrix(basis).invert().multiply(this.camera.quaternion);
reply({position:fromDisplay(this.camera.position),target:fromDisplay(this.controls.target),orientation:[orientation.w,orientation.x,orientation.y,orientation.z],projection:this.camera instanceof OrthographicCamera?'ORTHOGRAPHIC':'PERSPECTIVE',fov:this.fov,near:this.camera.near,far:this.camera.far,zoom:this.camera.zoom,orthoHeight:this.orthoHeight});
};
private restoreEvent=(event:Event)=>{
const value=(event as CustomEvent<BlenderViewportCamera>).detail;
if(!value||![...value.position,...value.target,...value.orientation,value.fov,value.near,value.far,value.zoom,value.orthoHeight].every(Number.isFinite)||value.far<=value.near)return;
this.changing=true;this.ndofPending=null;this.navigationVersion++;
this.controls.removeEventListener('change',this.onChange);this.controls.dispose();
this.fov=value.fov;this.orthoHeight=value.orthoHeight;
this.camera=value.projection==='ORTHOGRAPHIC'?new OrthographicCamera(-1,1,1,-1,value.near,value.far):new PerspectiveCamera(value.fov,1,value.near,value.far);
this.camera.position.set(value.position[0],value.position[2],-value.position[1]);
const orientation=new Quaternion().setFromRotationMatrix(basis).multiply(new Quaternion(value.orientation[1],value.orientation[2],value.orientation[3],value.orientation[0]));
this.camera.quaternion.copy(orientation);this.camera.up.set(0,1,0).applyQuaternion(orientation);
this.camera.zoom=value.zoom;this.view='USER';
this.controls=this.createControls(new Vector3(value.target[0],value.target[2],-value.target[1]));
this.changing=false;this.resize();
};
private enter=()=>{this.hover=true;};
private leave=()=>{this.hover=false;};
private pointerEnd=(event?:Event)=>{this.gesture=false;if(event?.type==='blur'){this.ndofPending=null;this.navigationVersion++;}};
private pointerDown=(event:PointerEvent)=>{
if(event.pointerType==='mouse'&&event.button!==1)return;
if(event.button===1){event.preventDefault();this.canvas.focus({preventScroll:true});this.gesture=true;this.controls.mouseButtons.MIDDLE=event.ctrlKey?MOUSE.DOLLY:MOUSE.ROTATE;
if(!event.shiftKey&&!event.ctrlKey){this.view='USER';if(this.camera instanceof OrthographicCamera)this.setProjection(false);}
}
};
private keyDown=(event:KeyboardEvent)=>{
const target=event.target as HTMLElement|null;
if((target?.closest('input,textarea,select,[contenteditable=true],[role=dialog]'))||event.altKey||(!this.hover&&document.activeElement!==this.canvas))return;
let command:ViewportNavigationCommand|undefined;
if(event.code==='Numpad1')command=event.ctrlKey?'BACK':'FRONT';
if(event.code==='Numpad3')command=event.ctrlKey?'LEFT':'RIGHT';
if(event.code==='Numpad7')command=event.ctrlKey?'BOTTOM':'TOP';
if(event.code==='Numpad5')command='PROJECTION';
if(event.code==='NumpadDecimal')command='FRAME_SELECTED';
if(event.code==='Home')command='FRAME_ALL';
if(event.code==='NumpadAdd')command='ZOOM_IN';if(event.code==='NumpadSubtract')command='ZOOM_OUT';
if(command){event.preventDefault();event.stopImmediatePropagation();this.command(command);}
else if(['Numpad2','Numpad4','Numpad6','Numpad8'].includes(event.code)){
event.preventDefault();event.stopImmediatePropagation();this.view='USER';this.setProjection(false);
const offset=this.camera.position.clone().sub(this.controls.target),axis=event.code==='Numpad4'||event.code==='Numpad6'?new Vector3(0,1,0):new Vector3(1,0,0).applyQuaternion(this.camera.quaternion);
offset.applyQuaternion(new Quaternion().setFromAxisAngle(axis,(event.code==='Numpad4'||event.code==='Numpad8'?1:-1)*Math.PI/12));this.camera.position.copy(this.controls.target).add(offset);this.controls.update();this.publish();
}
};
private commandEvent=(event:Event)=>{const command=(event as CustomEvent<ViewportNavigationCommand>).detail;if(['USER','FRONT','BACK','RIGHT','LEFT','TOP','BOTTOM','PROJECTION','FRAME_ALL','FRAME_SELECTED','ZOOM_IN','ZOOM_OUT'].includes(command))this.command(command);};
private ndofEvent=(event:Event)=>{
const detail=(event as CustomEvent<NDOFViewportEvent>).detail;
this.ndofPending={...detail,dt:Math.min(.1,(this.ndofPending?.dt??0)+detail.dt)};
if(!this.ndofProcessing)void this.applyNDOF();
};
private async applyNDOF():Promise<void>{
this.ndofProcessing=true;
let onError:((error:unknown)=>void)|undefined;
try{while(this.ndofPending&&!this.disposed){
const motion=this.ndofPending;this.ndofPending=null;
onError=motion.onError;
if(this.gesture)continue;
if(motion.settings.rotate&&motion.rotation.some(value=>Math.abs(value)>motion.settings.deadZone))this.setProjection(false);
const version=this.navigationVersion;
const basisRotation=new Quaternion().setFromRotationMatrix(basis);
const orientation=basisRotation.clone().invert().multiply(this.camera.quaternion);
const camera:NDOFCamera={position:fromDisplay(this.camera.position),target:fromDisplay(this.controls.target),orientation:[orientation.w,orientation.x,orientation.y,orientation.z],projection:this.camera instanceof OrthographicCamera?'ORTHOGRAPHIC':'PERSPECTIVE',fov:this.fov,orthoHeight:this.orthoHeight,zoom:this.camera.zoom,height:Math.max(1,this.canvas.clientHeight)};
const result=await motion.apply({camera,settings:motion.settings,translation:motion.translation,rotation:motion.rotation,dt:motion.dt});
if(this.disposed||this.gesture||version!==this.navigationVersion)continue;
this.changing=true;this.controls.removeEventListener('change',this.onChange);this.controls.dispose();
this.camera.position.set(result.position[0],result.position[2],-result.position[1]);
this.camera.quaternion.copy(basisRotation.multiply(new Quaternion(result.orientation[1],result.orientation[2],result.orientation[3],result.orientation[0])));
this.camera.up.set(0,1,0).applyQuaternion(this.camera.quaternion);
this.camera.zoom=result.zoom;this.orthoHeight=result.orthoHeight;this.view='USER';
this.controls=this.createControls(new Vector3(result.target[0],result.target[2],-result.target[1]));this.changing=false;this.resize();
}}catch(error){this.ndofPending=null;onError?.(error);}
finally{this.changing=false;this.ndofProcessing=false;}
}
private setProjection(orthographic:boolean):void {
if(orthographic===(this.camera instanceof OrthographicCamera))return;
const previous=this.camera,target=this.controls.target.clone(),distance=previous.position.distanceTo(target),aspect=Math.max(1,this.canvas.clientWidth)/Math.max(1,this.canvas.clientHeight);
this.changing=true;this.controls.removeEventListener('change',this.onChange);this.controls.dispose();
if(orthographic){this.orthoHeight=2*distance*Math.tan(this.fov*Math.PI/360);this.camera=new OrthographicCamera(-this.orthoHeight*aspect/2,this.orthoHeight*aspect/2,this.orthoHeight/2,-this.orthoHeight/2,previous.near,previous.far);}
else{const near=Math.max(.0001,previous.near);this.camera=new PerspectiveCamera(this.fov,aspect,near,Math.max(near+1,previous.far));const effective=this.orthoHeight/previous.zoom;this.camera.position.copy(previous.position).sub(target).setLength(effective/(2*Math.tan(this.fov*Math.PI/360))).add(target);}
if(orthographic)this.camera.position.copy(previous.position);
this.camera.quaternion.copy(previous.quaternion);this.camera.up.copy(previous.up);this.controls=this.createControls(target);this.changing=false;this.resize();
}
command(command:ViewportNavigationCommand):void{
if(command==='PROJECTION')this.setProjection(!(this.camera instanceof OrthographicCamera));
else if(command==='ZOOM_IN'||command==='ZOOM_OUT'){
const factor=command==='ZOOM_IN'?1/1.2:1.2;
if(this.camera instanceof OrthographicCamera){this.camera.zoom=Math.max(.0001,Math.min(1e5,this.camera.zoom/factor));this.camera.updateProjectionMatrix();}
else{const offset=this.camera.position.clone().sub(this.controls.target);offset.setLength(Math.max(this.controls.minDistance,Math.min(this.controls.maxDistance,offset.length()*factor)));this.camera.position.copy(this.controls.target).add(offset);}
this.controls.update();
}else if(command==='FRAME_ALL'||command==='FRAME_SELECTED')this.frame(command==='FRAME_SELECTED');
else if(command!=='USER'){
this.setProjection(true);this.view=command;
const distance=this.camera.position.distanceTo(this.controls.target);this.camera.up.set(0,1,0);this.camera.position.copy(this.controls.target).add(new Vector3(...directions[command]).normalize().multiplyScalar(distance));this.controls.update();
}
this.publish();
}
setSnapshot(snapshot:SceneSnapshotIR):void{this.snapshot=snapshot;}
setSelection(ids:ReadonlySet<string>):void{this.selected=new Set(ids);}
private frame(selected:boolean):void{
if(!this.snapshot)return;
const allowed=new Set(selected?this.selected:this.snapshot.nodes.map(n=>n.id));
if(selected){for(let pass=0;pass<this.snapshot.nodes.length;pass++){let added=false;for(const n of this.snapshot.nodes)if(n.parentId&&allowed.has(n.parentId)&&!allowed.has(n.id)){allowed.add(n.id);added=true;}if(!added)break;}}
const bounds=new Box3(),meshes=new Map(this.snapshot.meshes.map(m=>[m.id,m]));
for(const node of this.snapshot.nodes){if(!node.visible||!allowed.has(node.id))continue;
const matrix=basis.clone().multiply(new Matrix4().fromArray(node.worldMatrix)),mesh=node.dataId?meshes.get(node.dataId):undefined;
if(mesh?.bounds)bounds.union(new Box3(new Vector3(...mesh.bounds.min),new Vector3(...mesh.bounds.max)).applyMatrix4(matrix));
else bounds.expandByPoint(new Vector3().setFromMatrixPosition(matrix));
}
if(bounds.isEmpty())return;
const center=bounds.getCenter(new Vector3()),radius=Math.max(.05,bounds.getSize(new Vector3()).length()/2),aspect=Math.max(1,this.canvas.clientWidth)/Math.max(1,this.canvas.clientHeight);
const direction=this.camera.position.clone().sub(this.controls.target).normalize();
const distance=Math.max(VIEWPORT_ORBIT_MIN_DISTANCE,radius*1.2/Math.sin(Math.atan(Math.tan(this.fov*Math.PI/360)*Math.min(1,aspect))));
this.controls.target.copy(center);this.camera.position.copy(center).addScaledVector(direction,distance);
this.camera.near=Math.max(.0001,Math.min(.01,radius/1000));this.camera.far=Math.max(1000,distance+radius*10);
if(this.camera instanceof OrthographicCamera){this.orthoHeight=radius*2.4/Math.min(1,aspect);this.camera.zoom=1;}
this.resize();this.controls.update();
}
resize():void{
const width=Math.max(1,this.canvas.clientWidth),height=Math.max(1,this.canvas.clientHeight),aspect=width/height;
if(this.camera instanceof PerspectiveCamera)this.camera.aspect=aspect;
else{this.camera.left=-this.orthoHeight*aspect/2;this.camera.right=this.orthoHeight*aspect/2;this.camera.top=this.orthoHeight/2;this.camera.bottom=-this.orthoHeight/2;}
this.camera.updateProjectionMatrix();if(this.controls)this.controls.rotateSpeed=VIEWPORT_ORBIT_ROTATE_SENSITIVITY*height/(2*Math.PI);this.publish();
}
publish():void{
if(this.disposed||!this.controls)return;this.navigationVersion++;this.camera.updateMatrixWorld(true);
const position=fromDisplay(this.camera.position),target=fromDisplay(this.controls.target),orbit=orbitStateFromPosition(position,target);
Object.assign(this.canvas.dataset,{cameraPosition:position.map(v=>Number(v.toFixed(6))).join(','),cameraTarget:target.map(v=>Number(v.toFixed(6))).join(','),cameraYaw:orbit.yaw.toFixed(6),cameraPitch:orbit.pitch.toFixed(6),cameraDistance:orbit.distance.toFixed(6),cameraProjection:this.camera instanceof OrthographicCamera?'ORTHOGRAPHIC':'PERSPECTIVE',cameraZoom:this.camera.zoom.toFixed(6),cameraView:this.view});
const inverse=this.camera.quaternion.clone().invert(),axes=[[1,0,0],[0,0,-1],[0,1,0]].map(v=>new Vector3(...v).applyQuaternion(inverse).toArray());
this.canvas.dataset.cameraAxes=JSON.stringify(axes);
this.canvas.dispatchEvent(new CustomEvent('viewport-navigation',{detail:{view:this.view,projection:this.canvas.dataset.cameraProjection,axes}}));
this.changed({position:this.camera.position.toArray(),quaternion:this.camera.quaternion.toArray(),target:this.controls.target.toArray(),projection:this.camera instanceof OrthographicCamera?'ORTHOGRAPHIC':'PERSPECTIVE',fov:this.fov,aspect:Math.max(1,this.canvas.clientWidth)/Math.max(1,this.canvas.clientHeight),near:this.camera.near,far:this.camera.far,zoom:this.camera.zoom,orthoHeight:this.orthoHeight});
}
dispose():void{
this.canvas.removeEventListener('viewport-restore',this.restoreEvent);this.canvas.removeEventListener('viewport-capture',this.captureEvent);
this.canvas.removeEventListener('viewport-ndof',this.ndofEvent);this.ndofPending=null;
this.disposed=true;this.controls.dispose();this.canvas.removeEventListener('pointerdown',this.pointerDown,true);this.canvas.removeEventListener('pointerenter',this.enter);this.canvas.removeEventListener('pointerleave',this.leave);this.canvas.removeEventListener('viewport-command',this.commandEvent);window.removeEventListener('keydown',this.keyDown);window.removeEventListener('pointerup',this.pointerEnd);window.removeEventListener('pointercancel',this.pointerEnd);window.removeEventListener('blur',this.pointerEnd);
}
}

View File

@@ -6,7 +6,6 @@ import {
GridHelper,
Group,
InstancedMesh,
Matrix4,
Mesh,
MeshBasicMaterial,
HemisphereLight,
@@ -18,12 +17,11 @@ import {
WebGLRenderer,
Float32BufferAttribute,
Uint32BufferAttribute,
Euler,
Quaternion,
Vector2,
Vector3,
} from "../vendor/three/three.module.js";
import { OrbitControls } from "../vendor/three/addons/controls/OrbitControls.js";
import {ViewportNavigation} from './viewport-navigation';
import {nodeDisplayMatrix} from './node-display-matrix';
import type { MaterialIR, SceneSnapshotIR } from "../../../protocol/scene-ir";
import { applySceneDelta, sceneDeltaRequiresRendererRebuild, type SceneDelta } from "../../../protocol/scene-delta";
import type { MeshElementMode, MeshGeometryBuffer, WebEngineLODLevelResult } from "../../../protocol/web-engine";
@@ -66,7 +64,6 @@ import {
type GreasePencilMarqueeBoxIR,
type GreasePencilMarqueeResultIR,
} from "../../../protocol/grease-pencil-marquee";
import { VIEWPORT_DEFAULT_ORBIT, VIEWPORT_ORBIT_MAX_DISTANCE, VIEWPORT_ORBIT_MIN_DISTANCE, VIEWPORT_ORBIT_ROTATE_SENSITIVITY, VIEWPORT_ORBIT_ZOOM_SENSITIVITY, orbitPosition, orbitStateFromPosition } from "../../../protocol/viewport-camera";
import { validatePaintDepthVisibilityRequest, type PaintDepthVisibilityRequestIR, type PaintDepthVisibilityResultIR } from "../../../protocol/paint-depth-visibility";
import { samplePaintDepthVisibilityGPU } from "./paint-depth-visibility";
import { resolveViewportPixelMetrics, viewportNDC } from "../../../protocol/viewport-dpr";
@@ -89,14 +86,17 @@ export function collectMeshInstanceGroups(snapshot: SceneSnapshotIR, minimumSize
export class ViewportRenderer {
readonly renderer: WebGLRenderer;
readonly scene: Scene;
readonly camera: PerspectiveCamera;
readonly controls: OrbitControls;
private readonly navigation:ViewportNavigation;
get camera(){return this.navigation.camera;}
get controls(){return this.navigation.controls;}
private readonly canvas: HTMLCanvasElement;
private readonly importedRoot = new Group();
private readonly importedLights = new Group();
private readonly resizeObserver: ResizeObserver;
private animationFrame = 0;
private disposed = false;
private renderRequested = true;
private readonly requestRender = () => { this.renderRequested = true; };
private contextLost = false;
private currentSnapshot: SceneSnapshotIR | null = null;
private readonly objectByBlenderId = new Map<string, Object3D>();
@@ -108,8 +108,8 @@ export class ViewportRenderer {
private inputModal: InputModalState = createInputModalState();
private readonly onSelect?: (objectId: string, additive: boolean) => void;
private readonly onElementSelect?: (meshId: string, mode: MeshElementMode, index: number, additive: boolean, nonMeshKind?: NonMeshElementKind) => void;
private readonly onGreasePencilPointSelect?: (point: GreasePencilPointRef, additive: boolean, baseSelectionRevision: number) => void;
private readonly onGreasePencilMarqueeSelect?: (result: GreasePencilMarqueeResultIR, additive: boolean) => void;
private readonly onGreasePencilPointSelect?: (point: GreasePencilPointRef, mode: "REPLACE" | "ADD" | "SUBTRACT", baseSelectionRevision: number) => void;
private readonly onGreasePencilMarqueeSelect?: (result: GreasePencilMarqueeResultIR, mode: "REPLACE" | "ADD" | "SUBTRACT") => void;
private editMode = false;
private selectionMode: MeshElementMode = "FACE";
private greasePencilSelectionRevision = 0;
@@ -124,8 +124,8 @@ export class ViewportRenderer {
canvas: HTMLCanvasElement,
onSelect?: (objectId: string, additive: boolean) => void,
onElementSelect?: (meshId: string, mode: MeshElementMode, index: number, additive: boolean, nonMeshKind?: NonMeshElementKind) => void,
onGreasePencilPointSelect?: (point: GreasePencilPointRef, additive: boolean, baseSelectionRevision: number) => void,
onGreasePencilMarqueeSelect?: (result: GreasePencilMarqueeResultIR, additive: boolean) => void,
onGreasePencilPointSelect?: (point: GreasePencilPointRef, mode: "REPLACE" | "ADD" | "SUBTRACT", baseSelectionRevision: number) => void,
onGreasePencilMarqueeSelect?: (result: GreasePencilMarqueeResultIR, mode: "REPLACE" | "ADD" | "SUBTRACT") => void,
) {
this.canvas = canvas;
this.onSelect = onSelect;
@@ -149,15 +149,8 @@ export class ViewportRenderer {
this.canvas.dataset.shadowMap = PBR_SHADOW_PROFILE;
this.canvas.dataset.deviceStatus = "ready";
this.scene = new Scene();
this.camera = new PerspectiveCamera(45, 1, 0.01, 1000);
this.camera.position.set(...orbitPosition(VIEWPORT_DEFAULT_ORBIT));
this.controls = new OrbitControls(this.camera, canvas);
this.controls.target.set(...VIEWPORT_DEFAULT_ORBIT.target);
this.controls.enableDamping = false;
this.controls.enablePan = false;
this.controls.minDistance = VIEWPORT_ORBIT_MIN_DISTANCE;
this.controls.maxDistance = VIEWPORT_ORBIT_MAX_DISTANCE;
this.controls.zoomSpeed = VIEWPORT_ORBIT_ZOOM_SENSITIVITY / (0.01 * -Math.log(0.95));
this.navigation = new ViewportNavigation(canvas,()=>this.requestRender());
this.canvas.addEventListener("webglcontextrestored", this.requestRender);
this.scene.add(new HemisphereLight(0xf2f5ff, 0x3a4149, 0.55));
const keyLight = new DirectionalLight(0xffffff, 2.5);
@@ -187,6 +180,8 @@ export class ViewportRenderer {
}
setSnapshot(snapshot: SceneSnapshotIR, geometryBuffers: MeshGeometryBuffer[] = [], nonMeshGeometryBuffers: NonMeshGeometryChunk[] = []): void {
this.navigation.setSnapshot(snapshot);
this.requestRender();
this.currentSnapshot = snapshot;
const udim = snapshot.images.find((image) => image.tiles && image.tiles.length > 0);
if (udim) {
@@ -206,7 +201,6 @@ export class ViewportRenderer {
this.lodAdapter.clear();
this.clearImportedScene();
this.applyWorld(snapshot);
this.applyCamera(snapshot);
const lightingBudget = planPBRLightingBudget(snapshot, "THREE_WEBGL2");
this.publishLightingBudget(lightingBudget);
this.populateLights(snapshot, lightingBudget);
@@ -289,10 +283,8 @@ export class ViewportRenderer {
mesh.receiveShadow = true;
mesh.name = node.name;
// Summary-only meshes use a bounded proxy until their transferable geometry is available.
const [x, y, z] = node.transform.translation;
mesh.position.set(x, z, -y);
mesh.rotation.set(node.transform.rotationEuler[0], node.transform.rotationEuler[2], -node.transform.rotationEuler[1]);
mesh.scale.set(...node.transform.scale);
mesh.matrixAutoUpdate=false;
mesh.matrix.copy(nodeDisplayMatrix(node));
mesh.userData.sceneNodeId = node.id;
mesh.userData.blenderId = node.id;
mesh.userData.meshId = summary.id;
@@ -310,9 +302,6 @@ export class ViewportRenderer {
}
this.coalesceMeshInstances(snapshot);
void this.refreshVolumes();
if (this.importedRoot.children.length > 0) {
this.controls.target.set(0, 0, 0);
}
}
private populateNonMesh(snapshot: SceneSnapshotIR, nonMeshGeometryBuffers: readonly NonMeshGeometryChunk[]): void {
@@ -369,6 +358,7 @@ export class ViewportRenderer {
}
setTextureAssets(assets: readonly GPUTextureAsset[]): void {
this.requestRender();
if (assets.length === 0) {
this.canvas.dataset.textureStatus = "none";
this.canvas.dataset.textureLoaded = "0";
@@ -401,64 +391,70 @@ export class ViewportRenderer {
}
setVolumeAssets(assets: readonly NanoVDBViewportAssetIR[]): void {
this.requestRender();
this.volumeAssets = [...assets];
void this.refreshVolumes();
}
private async refreshVolumes(): Promise<void> {
const generation = ++this.volumeRenderGeneration;
for (const child of [...this.importedRoot.children]) {
if (!child.userData.nanoVDBVolume) continue;
this.importedRoot.remove(child);
child.traverse((object) => {
const mesh = object as Mesh;
mesh.geometry?.dispose?.();
const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
for (const material of materials) {
if (material instanceof MeshBasicMaterial) material.map?.dispose();
material?.dispose?.();
}
});
}
const snapshot = this.currentSnapshot;
const volumeNodes = snapshot?.nodes.filter((node) => node.visible && node.type === "VOLUME" && node.dataId) ?? [];
if (!snapshot || volumeNodes.length === 0) {
this.canvas.dataset.volumeStatus = "none";
this.canvas.dataset.volumeCount = "0";
return;
}
this.canvas.dataset.volumeStatus = "loading";
this.canvas.dataset.volumeCount = "0";
try {
let rendered = 0;
for (const node of volumeNodes) {
const asset = this.volumeAssets.find((candidate) => candidate.dataId === node.dataId);
if (!asset) continue;
const cacheKey = `${asset.dataId}:${asset.manifest.bundleSha256}:${JSON.stringify(asset.material ?? asset.manifest.material)}`;
let result = this.volumeRenderCache.get(cacheKey);
if (!result) {
result = await renderNanoVDBViewportAsset(asset, NANOVDB_VIEWPORT_PREVIEW_SIZE, NANOVDB_VIEWPORT_PREVIEW_SIZE, this.volumeRenderSession);
this.volumeRenderCache.set(cacheKey, result);
}
if (generation !== this.volumeRenderGeneration || this.currentSnapshot !== snapshot) return;
const object = createNanoVDBViewportObject(result, node);
this.importedRoot.add(object);
this.objectByBlenderId.set(node.id, object);
rendered++;
const generation = ++this.volumeRenderGeneration;
for (const child of [...this.importedRoot.children]) {
if (!child.userData.nanoVDBVolume) continue;
this.importedRoot.remove(child);
child.traverse((object) => {
const mesh = object as Mesh;
mesh.geometry?.dispose?.();
const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
for (const material of materials) {
if (material instanceof MeshBasicMaterial) material.map?.dispose();
material?.dispose?.();
}
});
}
if (generation !== this.volumeRenderGeneration) return;
this.canvas.dataset.volumeCount = String(rendered);
this.canvas.dataset.volumeStatus = rendered === volumeNodes.length ? "ready" : "blocked";
this.canvas.dataset.volumeErrorCode = rendered === volumeNodes.length ? "" : "NON_MESH_RESOURCE_MISSING";
}
catch (error) {
if (generation !== this.volumeRenderGeneration) return;
this.canvas.dataset.volumeStatus = "blocked";
this.canvas.dataset.volumeErrorCode = error instanceof Error ? error.message.split(":", 1)[0] : "VOLUME_SHADER_UNAVAILABLE";
const snapshot = this.currentSnapshot;
const volumeNodes = snapshot?.nodes.filter((node) => node.visible && node.type === "VOLUME" && node.dataId) ?? [];
if (!snapshot || volumeNodes.length === 0) {
this.canvas.dataset.volumeStatus = "none";
this.canvas.dataset.volumeCount = "0";
return;
}
this.canvas.dataset.volumeStatus = "loading";
this.canvas.dataset.volumeCount = "0";
try {
let rendered = 0;
for (const node of volumeNodes) {
const asset = this.volumeAssets.find((candidate) => candidate.dataId === node.dataId);
if (!asset) continue;
const cacheKey = `${asset.dataId}:${asset.manifest.bundleSha256}:${JSON.stringify(asset.material ?? asset.manifest.material)}`;
let result = this.volumeRenderCache.get(cacheKey);
if (!result) {
result = await renderNanoVDBViewportAsset(asset, NANOVDB_VIEWPORT_PREVIEW_SIZE, NANOVDB_VIEWPORT_PREVIEW_SIZE, this.volumeRenderSession);
this.volumeRenderCache.set(cacheKey, result);
}
if (generation !== this.volumeRenderGeneration || this.currentSnapshot !== snapshot) return;
const object = createNanoVDBViewportObject(result, node);
this.importedRoot.add(object);
this.objectByBlenderId.set(node.id, object);
rendered++;
}
if (generation !== this.volumeRenderGeneration) return;
this.canvas.dataset.volumeCount = String(rendered);
this.canvas.dataset.volumeStatus = rendered === volumeNodes.length ? "ready" : "blocked";
this.canvas.dataset.volumeErrorCode = rendered === volumeNodes.length ? "" : "NON_MESH_RESOURCE_MISSING";
}
catch (error) {
if (generation !== this.volumeRenderGeneration) return;
this.canvas.dataset.volumeStatus = "blocked";
this.canvas.dataset.volumeErrorCode = error instanceof Error ? error.message.split(":", 1)[0] : "VOLUME_SHADER_UNAVAILABLE";
}
} finally {
this.requestRender();
}
}
applyDelta(delta: SceneDelta, geometryBuffers: MeshGeometryBuffer[] = [], nonMeshGeometryBuffers: NonMeshGeometryChunk[] = []): void {
this.requestRender();
if (!this.currentSnapshot) throw new Error("Cannot apply a SceneDelta before a snapshot");
const next = applySceneDelta(this.currentSnapshot, delta);
const hasLifecycleChanges = sceneDeltaRequiresRendererRebuild(delta);
@@ -472,20 +468,19 @@ export class ViewportRenderer {
const instanceIndex = this.instanceIndexByBlenderId.get(change.id);
if (object instanceof InstancedMesh && instanceIndex !== undefined) {
const node = next.nodes.find((candidate) => candidate.id === change.id);
if (node) object.setMatrixAt(instanceIndex, this.instanceMatrix(node.transform, node.visible));
if (node) object.setMatrixAt(instanceIndex, nodeDisplayMatrix(node, node.visible));
object.instanceMatrix.needsUpdate = true;
}
else if (change.visible !== undefined) object.visible = change.visible;
if (change.visible !== undefined && typeof object.userData.meshId === "string") this.lodAdapter.setEnabled(object.userData.meshId, change.visible);
if (change.transform && !(object instanceof InstancedMesh)) {
const [x, y, z] = change.transform.translation;
object.position.set(x, z, -y);
object.rotation.set(change.transform.rotationEuler[0], change.transform.rotationEuler[2], -change.transform.rotationEuler[1]);
object.scale.set(...change.transform.scale);
if ((change.transform || change.worldMatrix || change.localMatrix) && !(object instanceof InstancedMesh)) {
const node=next.nodes.find(candidate=>candidate.id===change.id);
if(node){object.matrixAutoUpdate=false;object.matrix.copy(nodeDisplayMatrix(node));object.matrixWorldNeedsUpdate=true;}
}
object.userData.revision = next.revision;
}
this.currentSnapshot = next;
this.navigation.setSnapshot(next);
}
setSelection(
@@ -494,6 +489,8 @@ export class ViewportRenderer {
greasePencilPoints: readonly GreasePencilPointRef[] = [],
greasePencilSelectionRevision = 0,
): void {
this.requestRender();
this.navigation.setSelection(objectIds);
const visitedInstances = new Set<InstancedMesh>();
for (const [objectId, object] of this.objectByBlenderId) {
if (object instanceof InstancedMesh) {
@@ -521,6 +518,7 @@ export class ViewportRenderer {
}
setInteractionMode(editMode: boolean, selectionMode: MeshElementMode): void {
this.requestRender();
this.editMode = editMode;
this.selectionMode = selectionMode;
this.importedRoot.traverse((object) => {
@@ -529,18 +527,22 @@ export class ViewportRenderer {
}
async samplePaintVisibility(requestValue: PaintDepthVisibilityRequestIR): Promise<PaintDepthVisibilityResultIR> {
const request = validatePaintDepthVisibilityRequest(requestValue, this.currentSnapshot?.revision ?? -1);
const node = this.currentSnapshot?.nodes.find((candidate) => candidate.id === request.objectId && candidate.dataId === request.meshId && candidate.visible);
const object = node ? this.objectByBlenderId.get(node.id) : undefined;
if (!object) throw new Error("PAINT_DEPTH_UNAVAILABLE: Paint object is not available in the current viewport");
return samplePaintDepthVisibilityGPU({
renderer: this.renderer,
scene: this.scene,
camera: this.camera,
object,
request,
backend: "MAIN_THREAD_WEBGL2",
});
try {
const request = validatePaintDepthVisibilityRequest(requestValue, this.currentSnapshot?.revision ?? -1);
const node = this.currentSnapshot?.nodes.find((candidate) => candidate.id === request.objectId && candidate.dataId === request.meshId && candidate.visible);
const object = node ? this.objectByBlenderId.get(node.id) : undefined;
if (!object) throw new Error("PAINT_DEPTH_UNAVAILABLE: Paint object is not available in the current viewport");
return samplePaintDepthVisibilityGPU({
renderer: this.renderer,
scene: this.scene,
camera: this.camera,
object,
request,
backend: "MAIN_THREAD_WEBGL2",
});
} finally {
this.requestRender();
}
}
selectGreasePencilMarquee(
@@ -548,7 +550,7 @@ export class ViewportRenderer {
box: GreasePencilMarqueeBoxIR,
baseRevision: number,
baseSelectionRevision: number,
additive: boolean,
mode: "REPLACE" | "ADD" | "SUBTRACT",
): void {
const result = selectGreasePencilMarquee({
schemaVersion: 1,
@@ -563,29 +565,34 @@ export class ViewportRenderer {
this.canvas.dataset.greasePencilMarqueePointIds = result.selectedPoints.map((point) => point.pointId).join(",");
this.canvas.dataset.greasePencilMarqueeStrokeIds = result.selectedStrokeIds.join(",");
this.canvas.dataset.greasePencilMarqueeCount = String(result.selectedPoints.length);
this.onGreasePencilMarqueeSelect?.(result, additive);
this.onGreasePencilMarqueeSelect?.(result, mode);
}
setCurveHandlePreview(dataId: string, handles: readonly CurveGizmoHandleIR[] | null): void {
this.requestRender();
applyCurveHandlePreview(this.importedRoot, dataId, handles);
this.canvas.dataset.curveGizmoPreview = handles ? String(handles.length) : "0";
}
setGreasePencilPointPreview(dataId: string, layerId: string, frame: number, points: readonly GreasePencilPointPreview[] | null): void {
this.requestRender();
applyGreasePencilPointPreview(this.importedRoot, dataId, layerId, frame, points);
this.canvas.dataset.greasePencilPreview = points ? String(points.length) : "0";
}
setCurveGizmoFrame(dataId: string | null, frame: CurveGizmoFrameIR | null): void {
this.requestRender();
this.curveGizmoFrame = dataId && frame ? { dataId, frame } : null;
this.publishCurveGizmoFrame();
}
registerLOD(meshId: string, levels: readonly ThreeLODLevel[], radius: number): void {
this.requestRender();
this.lodAdapter.register(meshId, levels, radius);
}
unregisterLOD(meshId: string): void {
this.requestRender();
this.lodAdapter.unregister(meshId);
}
@@ -603,9 +610,7 @@ export class ViewportRenderer {
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.name = `${source.name} LOD ${level.level}`;
mesh.position.copy(source.position);
mesh.rotation.copy(source.rotation);
mesh.scale.copy(source.scale);
mesh.matrixAutoUpdate=false;mesh.matrix.copy(source.matrix);
mesh.userData.sceneNodeId = source.userData.sceneNodeId;
mesh.userData.blenderId = source.userData.blenderId;
mesh.userData.meshId = meshId;
@@ -674,17 +679,6 @@ export class ViewportRenderer {
return geometry;
}
private instanceMatrix(transform: SceneSnapshotIR["nodes"][number]["transform"], visible = true): Matrix4 {
const [x, y, z] = transform.translation;
const [rx, ry, rz] = transform.rotationEuler;
const scale = visible ? new Vector3(...transform.scale) : new Vector3(0, 0, 0);
return new Matrix4().compose(
new Vector3(x, z, -y),
new Quaternion().setFromEuler(new Euler(rx, rz, -ry)),
scale,
);
}
private coalesceMeshInstances(snapshot: SceneSnapshotIR): void {
const instanceGroups = collectMeshInstanceGroups(snapshot);
for (const [meshId, nodeIds] of instanceGroups) {
@@ -700,7 +694,7 @@ export class ViewportRenderer {
for (let index = 0; index < nodeIds.length; index++) {
const node = snapshot.nodes.find((candidate) => candidate.id === nodeIds[index]);
if (!node) continue;
instances.setMatrixAt(index, this.instanceMatrix(node.transform, node.visible));
instances.setMatrixAt(index, nodeDisplayMatrix(node, node.visible));
instances.setColorAt(index, new Color(0xffffff));
this.objectByBlenderId.set(node.id, instances);
this.instanceIndexByBlenderId.set(node.id, index);
@@ -760,7 +754,7 @@ export class ViewportRenderer {
const cameraNode = snapshot.nodes.find((node) => node.id === cameraObjectId && node.type === "CAMERA");
const definition = snapshot.cameras.find((camera) => camera.id === cameraNode?.dataId);
if (!cameraNode || !definition) return;
configurePBRCamera(this.camera, definition);
if(this.camera instanceof PerspectiveCamera)configurePBRCamera(this.camera, definition);
}
private publishLightingBudget(report: PBRLightingBudgetReport): void {
@@ -799,12 +793,11 @@ export class ViewportRenderer {
}
private resize(): void {
this.requestRender();
const width = Math.max(1, this.canvas.clientWidth);
const height = Math.max(1, this.canvas.clientHeight);
const metrics = resolveViewportPixelMetrics(width, height, window.devicePixelRatio);
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
this.controls.rotateSpeed = VIEWPORT_ORBIT_ROTATE_SENSITIVITY * height / (2 * Math.PI);
this.navigation.resize();
this.renderer.setSize(width, height, false);
this.canvas.dataset.viewportCssSize = `${metrics.cssWidth}x${metrics.cssHeight}`;
this.canvas.dataset.viewportBackingSize = `${metrics.backingWidth}x${metrics.backingHeight}`;
@@ -813,15 +806,11 @@ export class ViewportRenderer {
}
private publishCameraState(): void {
const orbit = orbitStateFromPosition(this.camera.position.toArray(), this.controls.target.toArray());
this.canvas.dataset.cameraPosition = this.camera.position.toArray().map((value) => Number(value.toFixed(6))).join(",");
this.canvas.dataset.cameraTarget = orbit.target.map((value) => Number(value.toFixed(6))).join(",");
this.canvas.dataset.cameraYaw = orbit.yaw.toFixed(6);
this.canvas.dataset.cameraPitch = orbit.pitch.toFixed(6);
this.canvas.dataset.cameraDistance = orbit.distance.toFixed(6);
this.navigation.publish();
}
private handleClick = (event: MouseEvent): void => {
if(event.button!==0)return;
if ("pointerType" in event) {
try { this.canvas.dataset.lastPointer = JSON.stringify(observePointerEvent(event as MouseEvent & { pointerType?: string; pointerId?: number; pressure?: number; tiltX?: number; tiltY?: number; buttons?: number; type?: string })); }
catch { this.canvas.dataset.lastPointer = "BLOCKED"; }
@@ -839,7 +828,7 @@ export class ViewportRenderer {
: undefined;
if (greasePencilHit?.index !== undefined) {
const point = greasePencilPointRef(greasePencilHit.object, greasePencilHit.index);
if (point) this.onGreasePencilPointSelect?.(point, event.shiftKey || event.ctrlKey || event.metaKey, this.greasePencilSelectionRevision);
if (point) this.onGreasePencilPointSelect?.(point, event.ctrlKey || event.metaKey ? "SUBTRACT" : event.shiftKey ? "ADD" : "REPLACE", this.greasePencilSelectionRevision);
return;
}
const preferredNonMeshHit = this.editMode ? hits.find((intersection) => intersection.index !== undefined && Array.isArray(intersection.object.userData.nonMeshPointKindMap)) : undefined;
@@ -935,13 +924,15 @@ export class ViewportRenderer {
if (this.disposed) return;
if (!this.contextLost) {
this.controls.update();
this.publishCameraState();
this.lodAdapter.update(this.camera, Math.max(1, this.canvas.clientHeight));
this.renderer.render(this.scene, this.camera);
this.publishCurveGizmoFrame();
if (this.canvas.dataset.deviceStatus === "restoring") {
this.canvas.dataset.deviceStatus = "ready";
this.canvas.dispatchEvent(new CustomEvent("viewport-device-restored"));
if (this.renderRequested) {
this.renderRequested = false;
this.lodAdapter.update(this.camera, Math.max(1, this.canvas.clientHeight));
this.renderer.render(this.scene, this.camera);
this.publishCurveGizmoFrame();
if (this.canvas.dataset.deviceStatus === "restoring") {
this.canvas.dataset.deviceStatus = "ready";
this.canvas.dispatchEvent(new CustomEvent("viewport-device-restored"));
}
}
}
this.animationFrame = window.requestAnimationFrame(this.renderLoop);
@@ -990,6 +981,8 @@ export class ViewportRenderer {
}
dispose(): void {
this.controls.removeEventListener("change", this.requestRender);
this.canvas.removeEventListener("webglcontextrestored", this.requestRender);
this.disposed = true;
window.cancelAnimationFrame(this.animationFrame);
this.resizeObserver.disconnect();
@@ -999,7 +992,7 @@ export class ViewportRenderer {
this.canvas.removeEventListener("pointercancel", this.handlePointerObservation);
this.canvas.removeEventListener("webglcontextlost", this.handleContextLost);
this.canvas.removeEventListener("webglcontextrestored", this.handleContextRestored);
this.controls.dispose();
this.navigation.dispose();
this.lodAdapter.clear();
this.clearImportedScene();
this.volumeRenderGeneration++;