Files
workinf_Blender_Wasm/web/tests/e2e/collada-model-pipeline.spec.ts
mes123456 63db6caf1f
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
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>
2026-11-23 09:27:47 +08:00

342 lines
18 KiB
TypeScript

import { expect, test } from '@playwright/test';
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { observeNative, exposeWebTools, captureNativeWorkflowState, resolveProjectReplacement } from '../fixtures/native-ui-workflow';
import { nativeRequest, readNativeHistory, focusNativeViewport } from '../fixtures/native-modeling-workflow';
import type { Page } from '@playwright/test';
const root = path.resolve(import.meta.dirname, '../../..');
const emptyBlend = path.join(root, 'blender-5.2.0/tests/files/io_tests/empty.blend');
const yt2 = path.join(root, 'doc2/YT2.dae');
/* Frozen import result of doc2/YT2.dae (238 objects / 236 meshes / 133,926 triangles,
* hierarchy Scene -> YT2-HA_______ -> 236 meshes). Each single-feature case starts here so
* only the feature under test pays for scene setup. */
const preparedBlend = path.join(root, 'web/tests/fixtures/collada/yt2-imported.blend');
type SceneSnapshot = {
revision: number;
nodes: Array<{ id: string; name: string; type: string; parentId: string | null; dataId: string | null; worldMatrix: number[]; transform?: { translation?: number[]; location?: number[] } }>;
meshes: Array<{ id: string; triangleCount?: number; faceCount: number; materialSlotIds?: string[]; bounds?: { min: [number, number, number]; max: [number, number, number] } }>;
materials: Array<{ id: string; name: string }>;
};
type Summary = {
revision: number;
objects: number;
meshes: number;
tris: number;
empties: string[];
parents: string[];
materials: string[];
slotCounts: number[];
locations: string[];
bounds: [[number, number], [number, number], [number, number]];
};
async function snapshotOf(page: Page): Promise<SceneSnapshot> {
const response = await nativeRequest(page, { type: 'snapshot' }, 300000);
const snapshot = response.result?.snapshot as SceneSnapshot | undefined;
if (!snapshot || !Array.isArray(snapshot.nodes)) throw new Error('SceneIR snapshot unavailable');
return snapshot;
}
function summarize(snapshot: SceneSnapshot): Summary {
const meshById = new Map(snapshot.meshes.map(mesh => [mesh.id, mesh]));
const nodeById = new Map(snapshot.nodes.map(node => [node.id, node]));
const meshNodes = snapshot.nodes.filter(node => node.type === 'MESH');
const materials = snapshot.materials ?? [];
const bounds: [[number, number], [number, number], [number, number]] = [[Infinity, -Infinity], [Infinity, -Infinity], [Infinity, -Infinity]];
for (const node of meshNodes) {
const mesh = meshById.get(node.dataId ?? '');
if (!mesh?.bounds || !Array.isArray(node.worldMatrix) || node.worldMatrix.length < 16) continue;
const m = node.worldMatrix;
for (const cx of [mesh.bounds.min[0], mesh.bounds.max[0]]) {
for (const cy of [mesh.bounds.min[1], mesh.bounds.max[1]]) {
for (const cz of [mesh.bounds.min[2], mesh.bounds.max[2]]) {
const wx = m[0] * cx + m[4] * cy + m[8] * cz + m[12];
const wy = m[1] * cx + m[5] * cy + m[9] * cz + m[13];
const wz = m[2] * cx + m[6] * cy + m[10] * cz + m[14];
bounds[0][0] = Math.min(bounds[0][0], wx); bounds[0][1] = Math.max(bounds[0][1], wx);
bounds[1][0] = Math.min(bounds[1][0], wy); bounds[1][1] = Math.max(bounds[1][1], wy);
bounds[2][0] = Math.min(bounds[2][0], wz); bounds[2][1] = Math.max(bounds[2][1], wz);
}
}
}
}
const tris = meshNodes.reduce((total, node) => total + Number(meshById.get(node.dataId ?? '')?.triangleCount ?? meshById.get(node.dataId ?? '')?.faceCount ?? 0), 0);
const materialNames = (ids: string[]) => ids.map(id => materials.find(material => material.id === id)?.name ?? '');
return {
revision: snapshot.revision,
objects: snapshot.nodes.length,
meshes: meshNodes.length,
tris,
empties: snapshot.nodes.filter(node => node.type === 'EMPTY').map(node => node.name).sort(),
parents: [...new Set(meshNodes.map(node => node.parentId ? nodeById.get(node.parentId)?.name ?? '' : ''))].sort(),
materials: [...new Set(meshNodes.flatMap(node => materialNames(meshById.get(node.dataId ?? '')?.materialSlotIds ?? [])))].sort(),
slotCounts: [...new Set(meshNodes.map(node => (meshById.get(node.dataId ?? '')?.materialSlotIds ?? []).length))].sort((a, b) => a - b),
locations: meshNodes.map(node => (node.transform?.translation ?? node.transform?.location ?? [node.worldMatrix[12], node.worldMatrix[13], node.worldMatrix[14]]).map((value: number) => value.toFixed(5)).join(',')),
bounds,
};
}
async function summary(page: Page): Promise<Summary> {
return summarize(await snapshotOf(page));
}
async function applyCommand(page: Page, payload: Record<string, unknown>): Promise<SceneSnapshot> {
const response = await nativeRequest(page, { type: 'applyCommand', payload } as never, 300000);
const snapshot = response.result?.snapshot as SceneSnapshot | undefined;
if (!snapshot) throw new Error(`applyCommand ${String(payload.type)} returned no SceneIR`);
return snapshot;
}
async function runPython(page: Page, source: string, timeoutMs = 600000): Promise<void> {
/* Mutating native batch: the readback fixture asserts `changed === false`, so call the
* Python route directly and let the next SceneIR snapshot publish the result. */
const response = await nativeRequest(page, {
type: 'jsonCommand', cmd: 'pythonExec',
params: { source: `exec(${JSON.stringify(source)}, {'__name__': '__main__'})`, filename: 'collada_batch.py', console: false },
}, timeoutMs);
const payload = response.result?.json as { state?: string; error?: string } | undefined;
if (payload?.state === 'ERROR') throw new Error(payload.error ?? 'pythonExec failed');
}
async function openBlend(page: Page, file: string, expectedMeshes: number) {
await exposeWebTools(page);
const before = await snapshotOf(page);
await page.getByTestId('blend-file-input').setInputFiles(file);
const dialog = page.getByRole('dialog', { name: '保存当前工程的修改?', exact: true });
for (let attempt = 0; attempt < 12; attempt++) {
if (await dialog.isVisible().catch(() => false)) { await resolveProjectReplacement(page, 'discard'); break; }
await page.waitForTimeout(500);
}
/* An empty target scene already has zero meshes, so wait for the open to publish first. */
await expect.poll(async () => (await snapshotOf(page)).revision, { timeout: 300000 }).not.toBe(before.revision);
await expect.poll(async () => (await summary(page)).meshes, { timeout: 300000 }).toBe(expectedMeshes);
}
async function bootstrap(page: Page, file: string, expectedMeshes: number) {
await observeNative(page);
await page.goto('/?ui=native');
await expect(page.locator('canvas[aria-label="Blender desktop"]')).toHaveAttribute('data-native-input-ready', 'true', { timeout: 60000 });
await openBlend(page, file, expectedMeshes);
}
function glbSummary(file: string) {
const bytes = fs.readFileSync(file);
const jsonLength = bytes.readUInt32LE(12);
const json = JSON.parse(bytes.subarray(20, 20 + jsonLength).toString('utf8'));
const meshes = json.meshes ?? [];
return {
version: json.asset?.version,
nodes: (json.nodes ?? []).length,
meshNodes: (json.nodes ?? []).filter((node: { mesh?: unknown }) => node.mesh !== undefined).length,
meshes: meshes.length,
primitives: meshes.reduce((total: number, mesh: { primitives?: unknown[] }) => total + (mesh.primitives?.length ?? 0), 0),
materials: (json.materials ?? []).length,
sha256: createHash('sha256').update(bytes).digest('hex'),
bytes: bytes.length,
};
}
async function exportGlb(page: Page, file: string) {
const response = await nativeRequest(page, { type: 'jsonCommand', cmd: 'exportScene', params: { format: 'GLB', fileName: 'yt2.glb' } }, 300000);
const payload = response.result?.json as { text?: string } | undefined;
if (typeof payload?.text !== 'string') throw new Error('native GLB export returned no payload');
fs.writeFileSync(file, Buffer.from(payload.text, 'base64'));
return glbSummary(file);
}
test.afterEach(async ({ page }, info) => {
fs.writeFileSync(info.outputPath('collada-pipeline-state.json'), JSON.stringify(await captureNativeWorkflowState(page), null, 2));
});
test('COLLADA import assembles the production asset', async ({ page }, info) => {
test.setTimeout(600000);
await bootstrap(page, emptyBlend, 0);
await exposeWebTools(page);
await page.getByTestId('blend-file-input').setInputFiles(yt2);
await expect.poll(async () => (await summary(page)).meshes, { timeout: 300000 }).toBe(236);
const imported = await summary(page);
fs.writeFileSync(info.outputPath('yt2-imported.json'), JSON.stringify(imported, null, 2));
expect(imported.tris).toBe(133926);
expect(imported.empties).toContain('YT2-HA_______');
expect(imported.parents).toEqual(['YT2-HA_______']);
const sizes = imported.bounds.map(([min, max]) => +(max - min).toFixed(3));
expect(sizes[0]).toBeCloseTo(0.639, 2);
expect(sizes[1]).toBeCloseTo(0.792, 2);
expect(sizes[2]).toBeCloseTo(0.487, 2);
});
test('COLLADA hierarchy reparents to the model empty', async ({ page }) => {
test.setTimeout(300000);
await bootstrap(page, preparedBlend, 236);
const snapshot = await snapshotOf(page);
const meshNodes = snapshot.nodes.filter(node => node.type === 'MESH');
const modelEmpty = snapshot.nodes.find(node => node.type === 'EMPTY' && node.name === 'YT2-HA_______');
expect(modelEmpty).toBeTruthy();
const before = await summary(page);
await applyCommand(page, { type: 'setParents', objectIds: meshNodes.map(node => node.id), parentId: null, keepTransform: true });
await expect.poll(async () => (await summary(page)).parents, { timeout: 180000 }).toEqual(['']);
const unparented = await summary(page);
const boundsClose = (a: Summary['bounds'], b: Summary['bounds']) =>
a.every(([min, max], axis) => Math.abs(min - b[axis][0]) < 1e-5 && Math.abs(max - b[axis][1]) < 1e-5);
expect(boundsClose(unparented.bounds, before.bounds)).toBe(true);
await applyCommand(page, { type: 'setParents', objectIds: meshNodes.map(node => node.id), parentId: modelEmpty!.id, keepTransform: true });
await expect.poll(async () => (await summary(page)).parents, { timeout: 180000 }).toEqual(['YT2-HA_______']);
});
test('COLLADA origin uses the median center', async ({ page }) => {
test.setTimeout(300000);
await bootstrap(page, preparedBlend, 236);
const before = await summary(page);
await runPython(page, `import bpy, json
meshes = [o for o in bpy.context.scene.objects if o.type == 'MESH']
for o in meshes: o.select_set(True)
bpy.context.view_layer.objects.active = meshes[0]
bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='MEDIAN')
print(json.dumps({'count': len(meshes)}))`);
const centered = await summary(page);
const moved = centered.locations.filter((location, index) => location !== before.locations[index]).length;
expect(moved).toBeGreaterThan(200);
expect(centered.bounds.map(([min, max]) => +(max - min).toFixed(3)))
.toEqual(before.bounds.map(([min, max]) => +(max - min).toFixed(3)));
});
test('COLLADA decimate reduces the model', async ({ page }, info) => {
test.setTimeout(600000);
await bootstrap(page, preparedBlend, 236);
const before = await summary(page);
await runPython(page, `import bpy, json
meshes = [o for o in bpy.context.scene.objects if o.type == 'MESH']
for o in meshes:
o.select_set(True)
bpy.context.view_layer.objects.active = o
modifier = o.modifiers.new('WebDecimate', 'DECIMATE')
modifier.ratio = 0.5
bpy.ops.object.modifier_apply(modifier=modifier.name)
print(json.dumps({'count': len(meshes)}))`);
const after = await summary(page);
fs.writeFileSync(info.outputPath('yt2-decimated.json'), JSON.stringify(after, null, 2));
expect(after.tris).toBeGreaterThan(before.tris * 0.4);
expect(after.tris).toBeLessThan(before.tris * 0.6);
});
test('COLLADA material assignment covers every mesh', async ({ page }, info) => {
test.setTimeout(300000);
await bootstrap(page, preparedBlend, 236);
await runPython(page, `import bpy, json
material = bpy.data.materials.get('ColladaMaterial') or bpy.data.materials.new('ColladaMaterial')
meshes = [o for o in bpy.context.scene.objects if o.type == 'MESH']
for o in meshes:
if len(o.data.materials) == 0: o.data.materials.append(material)
else: o.data.materials[0] = material
print(json.dumps({'count': len(meshes), 'material': material.name}))`);
const shaded = await summary(page);
fs.writeFileSync(info.outputPath('yt2-shaded.json'), JSON.stringify(shaded, null, 2));
expect(shaded.materials).toEqual(['ColladaMaterial']);
expect(shaded.slotCounts).toEqual([1]);
});
const fixtureRoot = path.join(root, 'web/tests/fixtures/collada');
const fixtureExpectations = JSON.parse(fs.readFileSync(path.join(fixtureRoot, 'expected.json'), 'utf8')) as
Record<string, { objects: number; triangles: number; materials?: number; size_m?: number[] }>;
for (const [name, want] of Object.entries(fixtureExpectations)) {
test(`COLLADA fixture ${name} imports with expected structure`, async ({ page }, info) => {
test.setTimeout(300000);
await bootstrap(page, emptyBlend, 0);
await page.getByTestId('blend-file-input').setInputFiles(path.join(fixtureRoot, `${name}.dae`));
await expect.poll(async () => (await summary(page)).meshes, { timeout: 120000 }).toBe(want.objects);
const imported = await summary(page);
fs.writeFileSync(info.outputPath(`${name}.json`), JSON.stringify(imported, null, 2));
expect(imported.tris).toBe(want.triangles);
if (want.materials !== undefined) expect(imported.materials.length).toBe(want.materials);
if (want.size_m !== undefined) {
const sizes = imported.bounds.map(([min, max]) => +(max - min).toFixed(2));
sizes.forEach((size, axis) => expect(size).toBeCloseTo(want.size_m![axis], 1));
}
});
}
test('COLLADA edits undo and redo through native history', async ({ page }) => {
test.setTimeout(300000);
/* Undo reopens the whole Main, so this case uses a small imported scene; the full YT2
* history rebuild is recorded as a residual outside the per-run window. */
await bootstrap(page, emptyBlend, 0);
await page.getByTestId('blend-file-input').setInputFiles(path.join(fixtureRoot, 'nested_hierarchy.dae'));
await expect.poll(async () => (await summary(page)).meshes, { timeout: 120000 }).toBe(2);
const before = await summary(page);
const snapshot = await snapshotOf(page);
const target = snapshot.nodes.find(node => node.type === 'MESH');
expect(target).toBeDefined();
const sortedLocations = (entry: Summary) => [...entry.locations].sort();
const edited = summarize(await applyCommand(page, { type: 'setObjectOrigin', objectId: target!.id, mode: 'GEOMETRY' }));
expect(sortedLocations(edited)).not.toEqual(sortedLocations(before));
await applyCommand(page, { type: 'undo' });
const undone = await summary(page);
expect(sortedLocations(undone)).toEqual(sortedLocations(before));
expect(undone.bounds.map(([min, max]) => +(max - min).toFixed(3)))
.toEqual(before.bounds.map(([min, max]) => +(max - min).toFixed(3)));
await applyCommand(page, { type: 'redo' });
const redone = await summary(page);
expect(sortedLocations(redone)).toEqual(sortedLocations(edited));
});
test('COLLADA exports native glTF 2.0', async ({ page }, info) => {
test.setTimeout(300000);
await bootstrap(page, preparedBlend, 236);
const glb = await exportGlb(page, info.outputPath('yt2-exported.glb'));
fs.writeFileSync(info.outputPath('yt2-exported.json'), JSON.stringify(glb, null, 2));
expect(glb.version).toBe('2.0');
expect(glb.meshNodes).toBeGreaterThanOrEqual(236);
expect(glb.materials).toBeGreaterThanOrEqual(1);
});
test('COLLADA saves to OPFS and reopens', async ({ page }) => {
test.setTimeout(600000);
await bootstrap(page, preparedBlend, 236);
const before = await summary(page);
await exposeWebTools(page);
await page.getByRole('button', { name: '保存项目', exact: true }).click();
await expect.poll(() => page.locator('main').getAttribute('data-save-transaction-status'), { timeout: 300000 }).not.toBe('RUNNING');
const projectId = await page.locator('main').getAttribute('data-project-id');
expect(projectId).toBeTruthy();
await page.getByLabel('最近项目').selectOption(projectId!);
await expect.poll(async () => (await summary(page)).meshes, { timeout: 300000 }).toBe(236);
const reopened = await summary(page);
expect(reopened.tris).toBe(before.tris);
});
test('COLLADA GLB round-trip reimports', async ({ page }, info) => {
test.setTimeout(600000);
await bootstrap(page, preparedBlend, 236);
const glbPath = info.outputPath('yt2-roundtrip.glb');
await exportGlb(page, glbPath);
await openBlend(page, emptyBlend, 0);
await exposeWebTools(page);
await page.getByTestId('blend-file-input').setInputFiles(glbPath);
await expect.poll(async () => (await summary(page)).meshes, { timeout: 300000 }).toBe(236);
});
test('COLLADA truncated input is rejected', async ({ page }) => {
test.setTimeout(300000);
await bootstrap(page, preparedBlend, 236);
const historyBefore = await readNativeHistory(page, 180000);
const before = await summary(page);
await exposeWebTools(page);
await page.getByTestId('blend-file-input').setInputFiles({
name: 'truncated.dae', mimeType: 'model/vnd.collada+xml', buffer: fs.readFileSync(yt2).subarray(0, 512),
});
await page.waitForTimeout(15000);
const statusText = await page.getByTestId('engine-status').textContent();
expect(statusText).toContain('COLLADA 导入失败');
expect(statusText).not.toMatch(/\n\s+at /);
expect((await summary(page)).meshes).toBe(before.meshes);
expect((await summary(page)).tris).toBe(before.tris);
const historyAfter = await readNativeHistory(page, 180000);
expect(historyAfter.cursor).toBe(historyBefore.cursor);
expect(historyAfter.entries).toEqual(historyBefore.entries);
});