feat(web): studio worlds, camera-view/offscreen environment parity, material and undo coverage
Environment lighting: - ship all eight desktop studiolights/world datasets (WBENV1 float32) and a shared loader used by both the main viewport and the offscreen worker - add the N-panel "studio 环境" selector - rotate the world background together with the environment (backgroundRotation/backgroundIntensity), so camera view and offscreen renders match the desktop Mapping-node behaviour Verification (Chromium, OPFS, NOT_CLAIMED): - environment lighting + 8 world pixel identity - camera-view rotation correspondence (camera matrices, 207 samples) - offscreen vs on-screen background parity after hiding geometry (1305 samples) - metals case extended with material-field OPFS roundtrip - material Principled edits and rename undo/redo - eight studio worlds: pairwise frame differences + luminance rank correlation - undo history depth capped at 64 steps and undo across OPFS save/reopen Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -8,6 +8,7 @@ import {
|
||||
InstancedMesh,
|
||||
LineBasicMaterial,
|
||||
LineSegments,
|
||||
Matrix3,
|
||||
Matrix4,
|
||||
Mesh,
|
||||
MeshBasicMaterial,
|
||||
@@ -22,7 +23,19 @@ import {
|
||||
Uint32BufferAttribute,
|
||||
Vector2,
|
||||
Vector3,
|
||||
DataTexture,
|
||||
EquirectangularReflectionMapping,
|
||||
FloatType,
|
||||
LinearSRGBColorSpace,
|
||||
PMREMGenerator,
|
||||
RGBAFormat,
|
||||
SRGBColorSpace,
|
||||
type Texture,
|
||||
} from "../vendor/three/three.module.js";
|
||||
import { applyStudioShading, usesStudioMaterial, type SolidShadingOptions } from "./studio-light";
|
||||
import { createStudioWorldTexture, fetchStudioWorld, isStudioWorldLight, studioWorldReport, STUDIO_WORLD_DEFAULT } from "./studio-environment";
|
||||
import { WorkbenchPost } from "./workbench-post";
|
||||
import { pickSurface, projectBrushRing, type BrushCursorRing, type SurfacePick } from "./viewport-surface-math";
|
||||
import {ViewportNavigation} from './viewport-navigation';
|
||||
import {nodeDisplayMatrix} from './node-display-matrix';
|
||||
import type { MaterialIR, SceneNodeIR, SceneSnapshotIR } from "../../../protocol/scene-ir";
|
||||
@@ -86,6 +99,8 @@ export function collectMeshInstanceGroups(snapshot: SceneSnapshotIR, minimumSize
|
||||
}
|
||||
|
||||
/** Three.js owns the browser viewport; Blender's Z-up coordinates are adapted at the boundary. */
|
||||
export type ViewportShadingMode = 'WIREFRAME' | 'SOLID' | 'MATERIAL' | 'RENDERED';
|
||||
|
||||
export class ViewportRenderer {
|
||||
readonly renderer: WebGLRenderer;
|
||||
readonly scene: Scene;
|
||||
@@ -96,6 +111,39 @@ export class ViewportRenderer {
|
||||
setCameraWriteHandler(handler:Parameters<ViewportNavigation['setCameraWriteHandler']>[0]){this.navigation.setCameraWriteHandler(handler);}
|
||||
toggleCameraView(){this.navigation.toggleCameraView();}
|
||||
setCameraLock(locked:boolean){this.navigation.setCameraLock(locked);}
|
||||
/** Navigation sensitivity preferences (orbit/zoom scale, wheel inversion). */
|
||||
setNavigationPrefs(prefs:Parameters<ViewportNavigation['setNavigationPrefs']>[0]){this.navigation.setNavigationPrefs(prefs);}
|
||||
/* Viewport shading mirrors the desktop header dropdown: WIREFRAME, SOLID,
|
||||
* MATERIAL and RENDERED. All four are display-only; geometry is untouched. */
|
||||
setShadingMode(mode:ViewportShadingMode){if(this.shadingMode===mode)return;this.shadingMode=mode;this.applyShadingMode();this.canvas.dataset.shadingMode=mode.toLowerCase();this.requestRender();}
|
||||
getShadingMode(){return this.shadingMode;}
|
||||
/** Solid-mode lighting: the studio rig preset, matcap layers, shadow mask. */
|
||||
setSolidShading(options:SolidShadingOptions){
|
||||
this.solidShading={...this.solidShading,...options};
|
||||
if(usesStudioMaterial(this.shadingMode)||this.shadingMode==='MATERIAL'){this.applyShadingMode();this.requestRender();}
|
||||
}
|
||||
getSolidShading(){return this.solidShading;}
|
||||
setXray(enabled:boolean){if(this.xray===enabled)return;this.xray=enabled;this.applyShadingMode();this.canvas.dataset.xray=enabled?'1':'0';this.requestRender();}
|
||||
/* Screen->surface pick for sculpt strokes: without a real hit the stroke
|
||||
* has no position on the mesh, only a screen coordinate. */
|
||||
pickSurfacePoint(clientX:number,clientY:number):SurfacePick|null{
|
||||
const bounds=this.canvas.getBoundingClientRect();
|
||||
if(bounds.width<=0||bounds.height<=0)return null;
|
||||
const ndc=viewportNDC(clientX,clientY,bounds);
|
||||
return pickSurface(this.raycaster,this.camera,this.importedRoot,ndc.x,ndc.y);
|
||||
}
|
||||
getXray(){return this.xray;}
|
||||
/**
|
||||
* Screen-space sculpt cursor ring. Blender projects two points on the brush
|
||||
* tangent plane and takes their pixel distance (paint_cursor/../paint_cursor.cc
|
||||
* brush_radius_project), so the ring stays correct under any camera distance.
|
||||
*/
|
||||
projectBrushCursor(clientX:number,clientY:number,radius:number):BrushCursorRing|null{
|
||||
const bounds=this.canvas.getBoundingClientRect();
|
||||
if(bounds.width<=0||bounds.height<=0)return null;
|
||||
const ndc=viewportNDC(clientX,clientY,bounds);
|
||||
return projectBrushRing(this.raycaster,this.camera,this.importedRoot,ndc.x,ndc.y,radius,bounds.width,bounds.height);
|
||||
}
|
||||
isCameraView(){return this.navigation.isCameraView();}
|
||||
isCameraLocked(){return this.navigation.isCameraLocked();}
|
||||
getCameraFraming(){return this.navigation.getCameraFraming();}
|
||||
@@ -128,6 +176,22 @@ export class ViewportRenderer {
|
||||
private volumeAssets: NanoVDBViewportAssetIR[] = [];
|
||||
private readonly volumeRenderCache = new Map<string, NanoVDBViewportRenderResultIR>();
|
||||
private volumeRenderGeneration = 0;
|
||||
private shadingMode: ViewportShadingMode = 'MATERIAL';
|
||||
private xray = false;
|
||||
private selectedObjectIds: ReadonlySet<string> = new Set();
|
||||
/* V3D_LIGHTING_STUDIO / V3D_LIGHTING_MATCAP, plus the chosen preset. */
|
||||
private solidShading: SolidShadingOptions = {};
|
||||
/* scene.environment saved while SOLID replaces it with analytic lighting. */
|
||||
private savedEnvironment: import("../vendor/three/three.module.js").Texture | null | undefined;
|
||||
/* Desktop Material Preview always lights PBR from a studio light; metals have
|
||||
* no diffuse term, so without an environment they render black. */
|
||||
private previewEnvironment: Texture | null = null;
|
||||
private previewFallbackEnvironment: Texture | null = null;
|
||||
private previewEnvironmentRequest: Promise<void> | null = null;
|
||||
/* Desktop Viewport Shading studio-light selection (studiolights/world/*.exr). */
|
||||
private previewStudioLight: string = STUDIO_WORLD_DEFAULT;
|
||||
/* Workbench screen-space cavity/curvature; idles as a pass-through. */
|
||||
private readonly workbenchPost = new WorkbenchPost();
|
||||
private readonly volumeRenderSession: NanoVDBViewportRenderSession;
|
||||
|
||||
constructor(
|
||||
@@ -170,7 +234,16 @@ export class ViewportRenderer {
|
||||
keyLight.shadow.bias = -0.0005;
|
||||
keyLight.shadow.normalBias = 0.03;
|
||||
this.scene.add(keyLight, keyLight.target);
|
||||
this.scene.add(new GridHelper(20, 20, 0x60656e, 0x383b42));
|
||||
/* Overlay semantics. Desktop draws the grid in the overlay engine
|
||||
* (`overlay_instance.cc:364`), after workbench has already consumed its own
|
||||
* depth buffer, so it never reaches `workbench_cavity.bsl.hh`. It also never
|
||||
* writes depth there. With depth writes on, the web grid lands in the cavity
|
||||
* depth texture: a line pixel's neighbours are all background, so the 3-tap
|
||||
* `view_normal` reconstructs a degenerate normal, the obscurance loop then
|
||||
* reads the grid as a fully occluded crease and darkens it to black. */
|
||||
const grid = new GridHelper(20, 20, 0x60656e, 0x383b42);
|
||||
grid.material.depthWrite = false;
|
||||
this.scene.add(grid);
|
||||
this.scene.add(this.importedRoot);
|
||||
this.scene.add(this.importedLights);
|
||||
|
||||
@@ -230,6 +303,11 @@ export class ViewportRenderer {
|
||||
if (materials.length === 0) materials.push(fallbackMaterial);
|
||||
let geometry: BufferGeometry = new BoxGeometry(2, 2, 2);
|
||||
const payload = binaryGeometry.get(summary.id);
|
||||
/* Vertex colour is an opt-in attribute: a mesh without a COLOR attribute must
|
||||
* keep the material base colour, otherwise the shader multiplies by the
|
||||
* (0,0,0) default and every uncoloured mesh renders black. */
|
||||
const usesVertexColor = Boolean(payload?.colors ?? summary.colors);
|
||||
for (const material of materials) material.vertexColors = usesVertexColor;
|
||||
const positionsData = payload ? new Float32Array(payload.positions) : summary.positions;
|
||||
const indicesData = payload ? new Uint32Array(payload.indices) : summary.indices;
|
||||
const normalsData = payload?.normals ? new Float32Array(payload.normals) : summary.normals;
|
||||
@@ -313,6 +391,7 @@ export class ViewportRenderer {
|
||||
this.coalesceMeshInstances(snapshot);
|
||||
this.populateObjectHelpers(snapshot);
|
||||
this.populateCollectionInstances(snapshot);
|
||||
this.applyShadingMode();
|
||||
void this.refreshVolumes();
|
||||
}
|
||||
|
||||
@@ -394,11 +473,9 @@ export class ViewportRenderer {
|
||||
this.canvas.dataset.textureBudgetGpuBytes = String(status.budget.decodedGPUBytes);
|
||||
if (!this.currentSnapshot) return;
|
||||
this.textureStore.applySnapshotMaterials(this.importedRoot, this.currentSnapshot);
|
||||
const worldId = this.currentSnapshot.scenes[0]?.worldId;
|
||||
const world = this.currentSnapshot.worlds.find((candidate) => candidate.id === worldId) ?? this.currentSnapshot.worlds[0];
|
||||
void this.textureStore.applyEnvironment(this.scene, this.renderer, world, true).then((ready) => {
|
||||
this.canvas.dataset.iblStatus = ready ? "ready" : world?.environmentImageId ? "blocked" : "none";
|
||||
});
|
||||
/* Only the paths that light from the scene world may replace the
|
||||
* Material Preview studio environment. */
|
||||
if (this.shadingMode === "RENDERED" || (this.shadingMode === "MATERIAL" && this.solidShading.useSceneWorld)) this.applyWorldEnvironment();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -502,6 +579,7 @@ export class ViewportRenderer {
|
||||
greasePencilSelectionRevision = 0,
|
||||
): void {
|
||||
this.requestRender();
|
||||
this.selectedObjectIds = objectIds;
|
||||
this.navigation.setSelection(objectIds);
|
||||
const visitedInstances = new Set<InstancedMesh>();
|
||||
for (const [objectId, object] of this.objectByBlenderId) {
|
||||
@@ -944,11 +1022,135 @@ export class ViewportRenderer {
|
||||
return createPBRMaterial(definition, active);
|
||||
}
|
||||
|
||||
/* SOLID/WIREFRAME swap in the ported workbench studio material; MATERIAL and
|
||||
* RENDERED restore the authored PBR material. Shared with the worker so the
|
||||
* two render paths stay identical. */
|
||||
private applyShadingMode(): void {
|
||||
applyStudioShading(this.importedRoot, this.shadingMode, this.xray, this.selectedObjectIds, this.solidShading);
|
||||
/* A studio-lit clay must not also receive the world HDRI, and the scene
|
||||
* lights only belong to the PBR path. */
|
||||
const studio = usesStudioMaterial(this.shadingMode);
|
||||
if (studio) {
|
||||
this.savedEnvironment = this.scene.environment;
|
||||
this.scene.environment = null;
|
||||
this.importedLights.visible = false;
|
||||
}
|
||||
else {
|
||||
if (this.savedEnvironment !== undefined) {
|
||||
this.scene.environment = this.savedEnvironment;
|
||||
this.savedEnvironment = undefined;
|
||||
}
|
||||
this.importedLights.visible = true;
|
||||
/* Material Preview uses the built-in studio light unless the user turns
|
||||
* on Scene World (`View3DShading.use_scene_world`); Rendered always
|
||||
* lights from the scene world. */
|
||||
if (this.shadingMode === "MATERIAL" && !this.solidShading.useSceneWorld) this.ensurePreviewEnvironment();
|
||||
else this.applyWorldEnvironment();
|
||||
}
|
||||
this.canvas.dataset.studioLighting = studio ? "studio-mvp" : "pbr";
|
||||
}
|
||||
|
||||
/* Material Preview equivalent of the desktop studio light. Desktop lights it
|
||||
* from the default studiolight world (blenkernel/intern/studiolight.cc:
|
||||
* STUDIOLIGHT_WORLD_DEFAULT, forest.exr); tools/web/import-studiolight-world.py
|
||||
* ships those exact float pixels. The bounded gradient is the immediate
|
||||
* fallback until that asset arrives, and stays if it cannot load. */
|
||||
private ensurePreviewEnvironment(): void {
|
||||
if (!this.previewEnvironment) {
|
||||
if (!this.previewFallbackEnvironment) {
|
||||
const width = 64, height = 32, data = new Uint8Array(width * height * 4);
|
||||
for (let y = 0; y < height; y++) {
|
||||
const v = y / (height - 1);
|
||||
const sky = 25 + Math.round(205 * (1 - v) ** 1.6);
|
||||
for (let x = 0; x < width; x++) {
|
||||
const u = x / width;
|
||||
const lobe = 120 * Math.exp(-(((u - 0.25) * 7) ** 2) - (((v - 0.22) * 7) ** 2))
|
||||
+ 90 * Math.exp(-(((u - 0.75) * 7) ** 2) - (((v - 0.3) * 7) ** 2));
|
||||
const index = (y * width + x) * 4;
|
||||
data[index] = Math.min(255, sky + lobe);
|
||||
data[index + 1] = Math.min(255, sky + lobe);
|
||||
data[index + 2] = Math.min(255, Math.round(sky * 1.05) + lobe);
|
||||
data[index + 3] = 255;
|
||||
}
|
||||
}
|
||||
const equirect = new DataTexture(data, width, height);
|
||||
equirect.mapping = EquirectangularReflectionMapping;
|
||||
equirect.colorSpace = SRGBColorSpace;
|
||||
equirect.needsUpdate = true;
|
||||
const pmrem = new PMREMGenerator(this.renderer);
|
||||
this.previewFallbackEnvironment = pmrem.fromEquirectangular(equirect).texture;
|
||||
equirect.dispose();
|
||||
pmrem.dispose();
|
||||
}
|
||||
this.scene.environment = this.previewFallbackEnvironment;
|
||||
this.canvas.dataset.previewEnvironment = "studio-fallback";
|
||||
this.previewEnvironmentRequest ??= this.loadStudioEnvironment().catch(() => undefined);
|
||||
}
|
||||
else {
|
||||
this.scene.environment = this.previewEnvironment;
|
||||
this.canvas.dataset.previewEnvironment = "studio-exr";
|
||||
}
|
||||
if (!this.scene.environmentIntensity) this.scene.environmentIntensity = 1;
|
||||
}
|
||||
|
||||
/* Load the selected desktop studiolight world pixels (`WBENV1` header + RGB
|
||||
* float32) and prefilter them once. The raw pixel block hash doubles as the
|
||||
* pixel-identity check against tools/web/import-studiolight-world.py. */
|
||||
private async loadStudioEnvironment(): Promise<void> {
|
||||
const requested = this.previewStudioLight;
|
||||
const world = await fetchStudioWorld(requested).catch(() => null);
|
||||
/* A newer selection may have superseded this load while it was fetching. */
|
||||
if (!world || requested !== this.previewStudioLight) return;
|
||||
this.previewEnvironment = createStudioWorldTexture(this.renderer, world);
|
||||
if (typeof window !== "undefined") {
|
||||
(window as unknown as { __webStudioEnvironment?: unknown }).__webStudioEnvironment = await studioWorldReport(world);
|
||||
}
|
||||
if (this.shadingMode === "MATERIAL" && !this.solidShading.useSceneWorld) {
|
||||
this.scene.environment = this.previewEnvironment;
|
||||
this.canvas.dataset.previewEnvironment = "studio-exr";
|
||||
this.requestRender();
|
||||
}
|
||||
}
|
||||
|
||||
/* Desktop Viewport Shading > Studio Light: switch the Material Preview world
|
||||
* (`studiolights/world/*.exr`). The fallback gradient shows until the new
|
||||
* dataset arrives. */
|
||||
setPreviewStudioLight(name: string): void {
|
||||
if (!isStudioWorldLight(name) || name === this.previewStudioLight) return;
|
||||
this.previewStudioLight = name;
|
||||
this.previewEnvironment?.dispose();
|
||||
this.previewEnvironment = null;
|
||||
this.previewEnvironmentRequest = null;
|
||||
this.canvas.dataset.studioLight = name;
|
||||
if (this.shadingMode === "MATERIAL" && !this.solidShading.useSceneWorld) this.ensurePreviewEnvironment();
|
||||
this.requestRender();
|
||||
}
|
||||
|
||||
/* Scene World lighting: the World colour or environment image with its
|
||||
* strength and rotation, shared with the offscreen render paths. */
|
||||
private applyWorldEnvironment(): void {
|
||||
const snapshot = this.currentSnapshot;
|
||||
const worldId = snapshot?.scenes[0]?.worldId;
|
||||
const world = snapshot?.worlds.find((candidate) => candidate.id === worldId) ?? snapshot?.worlds[0];
|
||||
if (!world) return;
|
||||
/* Material Preview with Scene World shows the world background too, like
|
||||
* the desktop studiolight-or-world background in the viewport. */
|
||||
void this.textureStore.applyEnvironment(this.scene, this.renderer, world, true).then((ready) => {
|
||||
this.canvas.dataset.previewEnvironment = ready ? "world" : "none";
|
||||
this.canvas.dataset.iblStatus = ready ? (world.environmentImageId ? "ready" : "color") : "blocked";
|
||||
});
|
||||
}
|
||||
|
||||
private applyWorld(snapshot: SceneSnapshotIR): void {
|
||||
const sceneDefinition = snapshot.scenes.find((scene) => scene.id === snapshot.sceneId) ?? snapshot.scenes[0];
|
||||
const worldId = snapshot.scenes[0]?.worldId;
|
||||
const world = snapshot.worlds.find((candidate) => candidate.id === worldId) ?? snapshot.worlds[0];
|
||||
this.scene.background = world ? new Color().setRGB(...world.color) : new Color("#25272b");
|
||||
/* Desktop Background = colour x Strength; the strength scales the visible
|
||||
* world colour as well as its lighting contribution. */
|
||||
this.scene.background = world
|
||||
? new Color().setRGB(...world.color).multiplyScalar(Math.max(0, world.environmentStrength ?? 1))
|
||||
: new Color("#25272b");
|
||||
if (this.shadingMode === "RENDERED" || (this.shadingMode === "MATERIAL" && this.solidShading.useSceneWorld)) this.applyWorldEnvironment();
|
||||
const colorManagement = sceneDefinition?.colorManagement;
|
||||
this.canvas.dataset.toneMapping = configurePBRRenderer(this.renderer, {
|
||||
viewTransform: colorManagement?.viewTransform,
|
||||
@@ -1138,7 +1340,33 @@ export class ViewportRenderer {
|
||||
if (this.renderRequested) {
|
||||
this.renderRequested = false;
|
||||
this.lodAdapter.update(this.camera, Math.max(1, this.canvas.clientHeight));
|
||||
this.renderer.render(this.scene, this.camera);
|
||||
/* Cavity/curvature read back the frame they just shaded, so they run as
|
||||
* a post pass; when disabled `render` returns without drawing. */
|
||||
const cavity = this.solidShading.cavity;
|
||||
/* Cavity belongs to solid shading only. It also has to stay there: the
|
||||
* studio shaders write `gl_FragColor` directly, whereas the PBR
|
||||
* materials rely on the renderer's tonemap/encode, which three skips
|
||||
* when drawing into a render target. Running the pass in MATERIAL or
|
||||
* RENDERED would therefore wash those modes out. The WORLD bake needs a
|
||||
* per-object ray evaluation the web path lacks, so a WORLD request runs
|
||||
* the screen-space estimator instead of nothing. */
|
||||
const solid = usesStudioMaterial(this.shadingMode);
|
||||
this.workbenchPost.setOptions({ ...cavity, enabled: solid && Boolean(cavity?.enabled) });
|
||||
const posted = this.workbenchPost.render(this.renderer, this.scene, this.camera);
|
||||
if (!posted) this.renderer.render(this.scene, this.camera);
|
||||
/* Camera-view parity probes read the exact view used for this frame. */
|
||||
if (typeof window !== "undefined") {
|
||||
this.camera.updateMatrixWorld();
|
||||
const perspective = this.camera as PerspectiveCamera;
|
||||
(window as unknown as { __webViewportCamera?: unknown }).__webViewportCamera = {
|
||||
matrixWorld: Array.from(this.camera.matrixWorld.elements),
|
||||
fov: perspective.fov ?? 0,
|
||||
zoom: perspective.zoom ?? 1,
|
||||
aspect: perspective.aspect ?? (this.canvas.width / Math.max(1, this.canvas.height)),
|
||||
width: this.canvas.width,
|
||||
height: this.canvas.height,
|
||||
};
|
||||
}
|
||||
this.publishCurveGizmoFrame();
|
||||
if (this.canvas.dataset.deviceStatus === "restoring") {
|
||||
this.canvas.dataset.deviceStatus = "ready";
|
||||
@@ -1209,6 +1437,7 @@ export class ViewportRenderer {
|
||||
this.volumeRenderGeneration++;
|
||||
this.volumeRenderCache.clear();
|
||||
this.volumeRenderSession.dispose();
|
||||
this.workbenchPost.dispose();
|
||||
this.textureStore.dispose();
|
||||
this.renderer.dispose();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user