A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix: preserve shadow participation when batching meshes
yhhd3fbf3b629a0
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 51b466cdf..5a51f8de2 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -107,6 +107,15 @@ jobs:run: node tools/tests/placement-bounds.e2e.mjs --webgl-only- name: Check instance and deformed shadow coverage with genuine headless Chromiumrun: node tools/tests/placement-shadows.e2e.mjs --webgl-only+ - name: Check composite lifecycle and mixed shadow policies with genuine headless Chromium+ run: node tools/tests/composite-batch.e2e.mjs --webgl-only+ - name: Upload composite batching observations+ if: always()+ uses: actions/upload-artifact@v7+ with:+ name: composite-batch-webgl2+ path: output/composite-batch/+ retention-days: 3- name: Upload native placement shadow observationsif: always()uses: actions/upload-artifact@v7@@ -1109,6 +1118,15 @@ jobs:env:ESTELLA_VERIFY_WEBGPU_ADAPTER: ''run: node tools/verify-render.mjs --tier pr --backend webgpu --host engine --no-build --budget 45+ - name: Check composite lifecycle and mixed shadow policies on the second backend+ run: node tools/tests/composite-batch.e2e.mjs --webgpu-only+ - name: Upload second-backend composite batching observations+ if: always()+ uses: actions/upload-artifact@v7+ with:+ name: composite-batch-webgpu+ path: output/composite-batch/+ retention-days: 3# The native runtime, judged by pixels on a machine with no GPU.#diff --git a/docs/astro/src/content/docs/performance/static-batching.mdx b/docs/astro/src/content/docs/performance/static-batching.mdxindex b742cf4f4..c18fdc157 100644--- a/docs/astro/src/content/docs/performance/static-batching.mdx+++ b/docs/astro/src/content/docs/performance/static-batching.mdx@@ -21,7 +21,7 @@ In the editor, select the meshes and choose **Static Batch** from the outliner's## What happens- Meshes are grouped by everything a draw owns — material, texture, normal map, colour,- layer, culling and lighting flags — and by the optional **group** on the component, so two+ layer, culling, lighting and shadow-casting flags — and by the optional **group** on the component, so tworooms can be kept apart.- Each group is cut into cells of the world, so a batch is a neighbourhood and culling stillhas something to cull. A cell is 1,600 world units on a side by default and never holds more than 262,144 vertices.@@ -99,6 +99,8 @@ them are the root's children:- Every other part is merged, by draw state, into chunks of the root's space. Adding, removing,re-meshing or re-placing a part re-merges only the chunk it is in, within half a second. Call`app.getResource(CompositeBatchingRes).refresh(root)` to look at once.+- Changing a part's `MeshRenderer.castShadows` regroups it on the next scan. Casters and+ non-casters stay in separate instance sets and merged chunks, even when their material matches.- A part that keeps moving inside the model, such as a door or a wheel, is let go after a fewlooks and draws itself, so it never costs a merge a frame.- The rules a static batch keeps still hold. Skinned, morphing, LOD, billboard and blended parts@@ -132,7 +134,9 @@ count: a ship of 108 parts costs about the same either way (0.65–0.67 ms plainbatched). At that size, the pass's own look at its parts, twice a second, is as large as whatit saves.-The `composite-batch` editor check holds the claims on that smaller ship. With mesh shadows off,-its frame matches the plain one within the scene's own frame-to-frame difference, moving the-root re-merges nothing, and an added part re-merges one chunk. With mesh shadows on, shadow edges-land about a pixel apart along roughly 2% of the frame; why is not yet established.+The `composite-batch` editor check keeps mesh shadows enabled on that smaller ship. The+headless runtime check also compares the ordinary and batched model on WebGL2 and WebGPU,+including root motion, a local edit, mixed shadow policies and restoring those policies.+Moving the root re-merges nothing; adding a part re-merges one chunk. Both checks verify that+removing the component restores the original parts. The runtime check also verifies that+static batches keep each part's shadow policy and compares their rendered result.diff --git a/docs/astro/src/content/docs/zh-cn/performance/static-batching.mdx b/docs/astro/src/content/docs/zh-cn/performance/static-batching.mdxindex fac5779fc..abffaff90 100644--- a/docs/astro/src/content/docs/zh-cn/performance/static-batching.mdx+++ b/docs/astro/src/content/docs/zh-cn/performance/static-batching.mdx@@ -19,7 +19,7 @@ world.insert(wall, StaticBatch, {});## 会发生什么-- 网格按一次绘制拥有的全部状态分组 —— 材质、贴图、法线贴图、颜色、层、剔除与光照开关 ——+- 网格按一次绘制拥有的全部状态分组 —— 材质、贴图、法线贴图、颜色、层、剔除、光照与投影开关 ——还可以用组件上的**分组**把两个房间分开。- 每一组再按世界里的格子切开,所以一个批是一小片区域,剔除仍然有东西可剔。格子默认边长 1600 世界单位,一个格子里的顶点不超过 262,144 个。@@ -91,6 +91,8 @@ world.insert(ship, CompositeBatch, {});作为一个实例化集合绘制,不复制任何顶点。- 其余部件按绘制状态合并成根节点空间里的若干块。增加、删除、换网格或挪动一个部件,半秒内只重新合并它所在的那一块。要立刻检查,调用 `app.getResource(CompositeBatchingRes).refresh(root)`。+- 修改部件的 `MeshRenderer.castShadows` 后,下一次检查会重新分组。即使材质相同,+ 投影与不投影的部件也会保留在不同的实例组和合并块里。- 在模型内部一直在动的部件(门、轮子)看几次之后会被放开,由它自己绘制,不会每帧都触发一次合并。- 静态合并的规则仍然适用:蒙皮、变形、LOD、公告板、半透明部件和动态刚体由自己绘制。组合模型下的部件不会再被静态合并。@@ -115,5 +117,7 @@ world.insert(ship, CompositeBatch, {});部件越多省得越多:108 个部件的小船两种方式差不多(不加 0.65–0.67 ms,加 0.68–0.90 ms),这个规模下合并过程每秒两次检查部件的开销,和它省下的差不多大。-编辑器检查 `composite-batch` 用这艘小船锁定了这些结论:关掉网格阴影时,合并后的画面与不加时的差别在场景自身逐帧差别之内;-移动根节点不会重新合并;加一个部件只重新合并一块。开着网格阴影时,约 2% 的画面上阴影边缘会差一个像素左右,原因还没有确认。+编辑器检查 `composite-batch` 保持这艘小船的网格阴影开启。无界面的运行时检查还会在 WebGL2 和 WebGPU 上+比较普通绘制与合批后的画面,覆盖根节点移动、局部编辑、混合投影开关及恢复投影开关。+移动根节点不会重新合并;加一个部件只重新合并一块。两种检查都会确认移除组件后恢复原有部件。+运行时检查也会验证静态合批保留每个部件的投影开关,并比较最终画面。diff --git a/sdk/src/render/compositeBatchPlugin.ts b/sdk/src/render/compositeBatchPlugin.tsindex 1c8e6ad7f..e964909a8 100644--- a/sdk/src/render/compositeBatchPlugin.ts+++ b/sdk/src/render/compositeBatchPlugin.ts@@ -108,7 +108,7 @@ interface RefusalDefs {/** Whether two renderers draw the same way: the state a part's key is made from. */function sameDrawState(a: MeshRendererData, b: MeshRendererData): boolean {return a.material === b.material && a.texture === b.texture && a.normalMap === b.normalMap && a.layer === b.layer- && a.cullBackfaces === b.cullBackfaces && a.lit === b.lit+ && a.cullBackfaces === b.cullBackfaces && a.lit === b.lit && (a.castShadows !== false) === (b.castShadows !== false)&& a.color.r === b.color.r && a.color.g === b.color.g && a.color.b === b.color.b && a.color.a === b.color.a&& a.parallax.x === b.parallax.x && a.parallax.y === b.parallax.y;}@@ -317,7 +317,7 @@ export class CompositeBatchPlugin implements Plugin {const known = c.parts.get(e);const key = known && known.mesh === mr.mesh && sameDrawState(known.mr, mr) ? known.key : staticBatchKey({material: mr.material, texture: mr.texture, normalMap: mr.normalMap, color: mr.color, layer: mr.layer,- cullBackfaces: mr.cullBackfaces, lit: mr.lit, parallax: mr.parallax, group: '',+ cullBackfaces: mr.cullBackfaces, lit: mr.lit, castShadows: mr.castShadows, parallax: mr.parallax, group: '',}, channelSignature(mesh.channels, mesh.vertexStride));const cx = (mesh.aabbMin[0] + mesh.aabbMax[0]) / 2, cy = (mesh.aabbMin[1] + mesh.aabbMax[1]) / 2, cz = (mesh.aabbMin[2] + mesh.aabbMax[2]) / 2;const center: [number, number, number] = [diff --git a/sdk/src/render/staticBatch.ts b/sdk/src/render/staticBatch.tsindex 08f41e883..0b7493cde 100644--- a/sdk/src/render/staticBatch.ts+++ b/sdk/src/render/staticBatch.ts@@ -55,6 +55,8 @@ export interface StaticBatchState {layer: number;cullBackfaces: boolean;lit: boolean;+ /** Shadow participation belongs to the draw; omitted keeps the MeshRenderer default of true. */+ castShadows?: boolean;parallax: { x: number; y: number };/** The author's own grouping (`StaticBatch.group`), so two rooms can be kept apart. */group: string;@@ -258,7 +260,8 @@ export const STATIC_BATCH_DEFAULTS: StaticBatchLimits = { cellSize: 1600, maxVerexport function staticBatchKey(state: StaticBatchState, layout: string): string {const c = state.color;return [state.material, state.texture, state.normalMap, c.r, c.g, c.b, c.a, state.layer,- state.cullBackfaces ? 1 : 0, state.lit ? 1 : 0, state.parallax.x, state.parallax.y, state.group, layout].join('|');+ state.cullBackfaces ? 1 : 0, state.lit ? 1 : 0, state.castShadows !== false ? 1 : 0,+ state.parallax.x, state.parallax.y, state.group, layout].join('|');}/**diff --git a/sdk/src/render/staticBatchPlugin.ts b/sdk/src/render/staticBatchPlugin.tsindex bea753085..ffb6523a1 100644--- a/sdk/src/render/staticBatchPlugin.ts+++ b/sdk/src/render/staticBatchPlugin.ts@@ -313,7 +313,7 @@ export class StaticBatchPlugin implements Plugin {];const key = staticBatchKey({material: mr.material, texture: mr.texture, normalMap: mr.normalMap, color: mr.color, layer: mr.layer,- cullBackfaces: mr.cullBackfaces, lit: mr.lit, parallax: mr.parallax, group: `${sb.group}@${scene}`,+ cullBackfaces: mr.cullBackfaces, lit: mr.lit, castShadows: mr.castShadows, parallax: mr.parallax, group: `${sb.group}@${scene}`,}, channelSignature(mesh.channels, mesh.vertexStride));candidates.push({ entity: e, key, center, vertices: mesh.vertexCount });info.set(e, { mr, mesh, world: matrix, scene });diff --git a/sdk/tests/static-batch.test.ts b/sdk/tests/static-batch.test.tsindex 11f99b0bb..840da0149 100644--- a/sdk/tests/static-batch.test.ts+++ b/sdk/tests/static-batch.test.ts@@ -96,7 +96,7 @@ describe('layoutRefusal', () => {});describe('planStaticBatches', () => {- const state = { material: 1, texture: 2, normalMap: 0, color: { r: 1, g: 1, b: 1, a: 1 }, layer: 0, cullBackfaces: true, lit: true, parallax: { x: 0, y: 0 }, group: '' };+ const state = { material: 1, texture: 2, normalMap: 0, color: { r: 1, g: 1, b: 1, a: 1 }, layer: 0, cullBackfaces: true, lit: true, castShadows: true, parallax: { x: 0, y: 0 }, group: '' };const layout = channelSignature(channels, vertexStride);const key = (over: Partial<typeof state> = {}) => staticBatchKey({ ...state, ...over }, layout);const at = (entity: number, x: number, k = key(), vertices = 100) => ({ entity, key: k, center: [x, 0, 0] as const, vertices });@@ -107,6 +107,16 @@ describe('planStaticBatches', () => {expect(plan.alone).toEqual([4]);});+ it('keeps shadow casters separate from otherwise identical non-casters', () => {+ const plan = planStaticBatches([at(1, 0), at(2, 10), at(3, 20, key({ castShadows: false })), at(4, 30, key({ castShadows: false }))]);+ expect(plan.batches.map(batch => batch.entities).sort((a, b) => a[0]! - b[0]!)).toEqual([[1, 2], [3, 4]]);+ });++ it('preserves the default shadow policy when an older caller omits it', () => {+ const { castShadows: _, ...legacy } = state;+ expect(staticBatchKey(legacy, layout)).toBe(key());+ });+it('keeps cells apart so culling still works, and caps a batch at the vertex limit', () => {const cell = STATIC_BATCH_DEFAULTS.cellSize;const far = planStaticBatches([at(1, 0), at(2, 10), at(3, cell * 3), at(4, cell * 3 + 10)]);diff --git a/tools/lib/compositeShip.mjs b/tools/lib/compositeShip.mjsnew file mode 100644index 000000000..ba893ccaf--- /dev/null+++ b/tools/lib/compositeShip.mjs@@ -0,0 +1,38 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file compositeShip.mjs+ * @brief Shared mixed instance/chunk ship fixture for runtime and editor checks.+ */+const wood = { r: 0.55, g: 0.38, b: 0.22, a: 1 };+const transform = (x, y, z, sx = 100, sy = 100, sz = 100) => ({+ type: 'Transform', data: { position: { x, y, z }, scale: { x: sx / 100, y: sy / 100, z: sz / 100 } },+});+const mesh = name => ({ type: 'MeshRenderer', data: { mesh: name, lit: true, opaque: true, color: { ...wood } } });++/** Eighty planks and 24 posts form two instance sets; four distinct props form two merged chunks. */+export function compositeShip(withComposite = false) {+ const entities = [];+ let id = 1000;+ const root = id++;+ const children = [];+ const add = (name, components) => {+ const entity = id++;+ children.push(entity);+ entities.push({ id: entity, name, parent: root, children: [], visible: true, components });+ };+ for (let i = 0; i < 10; i++) for (let j = 0; j < 8; j++) {+ add(`Plank ${i}.${j}`, [transform(-2.25 + i * 0.5, 0.4, -1.75 + j * 0.5, 0.45, 0.06, 0.45), mesh('builtin:cube')]);+ }+ for (let i = 0; i < 12; i++) for (const z of [-2, 2]) {+ add(`Post ${i}${z}`, [transform(-2.5 + i * 0.45, 0.7, z, 0.06, 0.6, 0.06), mesh('builtin:cylinder')]);+ }+ add('Barrel', [transform(-2, 0.8, 0, 0.3, 0.3, 0.3), mesh('builtin:sphere')]);+ add('Funnel', [transform(-2, 0.8, 0.8, 0.3, 0.4, 0.3), mesh('builtin:cone')]);+ add('Buoy', [transform(2, 0.8, 0, 0.2, 0.3, 0.2), mesh('builtin:capsule')]);+ add('Hatch', [transform(2, 0.45, 0.8, 0.6, 1, 0.6), mesh('builtin:plane')]);+ const components = [transform(0, 0, 0)];+ if (withComposite) components.push({ type: 'CompositeBatch', data: { instanceMin: 4, cellSize: 2 } });+ entities.unshift({ id: root, name: 'Ship', parent: null, children, visible: true, components });+ return entities;+}diff --git a/tools/render-host/host.ts b/tools/render-host/host.tsindex 5aaa21fc2..07c988d17 100644--- a/tools/render-host/host.ts+++ b/tools/render-host/host.ts@@ -22,6 +22,7 @@ import {getComponent, DeviceStatus, getDeviceStatus, getDeviceLostReport, recoverDevice,getContextLossGuardInfo, decodeImagePixels, captureFramePixels, captureFrame, replayDraw, BatchBreak,RenderTexture, Camera, Sprite, Time,+ Children, MeshRenderer, RuntimeOnly, CompositeBatch, CompositeBatchingRes, StaticBatchingRes,planarReflectionStatus,EditorViewLighting, EditorViewShading, EditorView, EditorGrid, installEditorGrid, editorViewHalfHeight, setEditorViewHalfHeight,ProfileRecorder, AnimatorController, Timeline, onDeviceRestored, Schedule, defineSystem,@@ -631,6 +632,47 @@ const api = {app!.world.set(entity, comp, data);},+ /** Adds or removes the real component so lifecycle checks use the shipped plugin. */+ setComponent(id: number, component: string, data: Record<string, unknown> | null): void {+ const entity = requireEntity(id);+ const definition = getComponent(component);+ if (!definition) throw new Error(`setComponent: no component named "${component}"`);+ if (data === null) app!.world.remove(entity, definition);+ else app!.world.insert(entity, definition, data);+ },++ setParent(id: number, parent: number): void {+ app!.world.setParent(requireEntity(id), requireEntity(parent));+ },++ refreshComposite(id: number): void {+ app!.getResource(CompositeBatchingRes).refresh(requireEntity(id));+ },++ compositeBatchReport(id: number) {+ const world = app!.world, root = requireEntity(id);+ const state = app!.getResource(CompositeBatchingRes);+ const children = world.tryGet(root, Children)?.entities ?? [];+ return {+ report: state.report(root), counts: { ...state.counts }, busy: state.busy_,+ component: world.tryGet(root, CompositeBatch),+ visibleParts: children.filter(entity => !world.has(entity, RuntimeOnly) && world.tryGet(entity, MeshRenderer)?.enabled).length,+ holders: children.filter(entity => world.has(entity, RuntimeOnly)).map(entity => ({+ name: world.tryGet(entity, Name)?.value, mesh: world.tryGet(entity, MeshRenderer)?.mesh,+ castShadows: world.tryGet(entity, MeshRenderer)?.castShadows,+ })),+ };+ },++ staticBatchReport() {+ const report = app!.getResource(StaticBatchingRes).report();+ return { refused: Array.from(report.refused), groups: report.groups.map(group => ({ ...group,+ partCount: group.parts.length,+ holderCastShadows: app!.world.tryGet(group.entity, MeshRenderer)?.castShadows,+ partCastShadows: group.parts.map(entity => app!.world.tryGet(entity, MeshRenderer)?.castShadows),+ })) };+ },+/*** Writes one animator parameter, the door gameplay uses. Not setField: a* parameter is not a component field, it is per-entity state the controllerdiff --git a/tools/tests/composite-batch.e2e.mjs b/tools/tests/composite-batch.e2e.mjsnew file mode 100644index 000000000..9b4f29def--- /dev/null+++ b/tools/tests/composite-batch.e2e.mjs@@ -0,0 +1,201 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file composite-batch.e2e.mjs+ * @brief Exercise mixed batching, root motion, local edits and shadow-state changes.+ */+import { chromium } from 'playwright';+import { readFile, writeFile, mkdir } from 'node:fs/promises';+import { createRequire } from 'node:module';+import { fileURLToPath } from 'node:url';+import path from 'node:path';+import assert from 'node:assert/strict';+import { serveHost } from '../lib/staticServer.mjs';+import { requireCurrentEngine } from '../lib/engineBuild.mjs';+import { compositeShip } from '../lib/compositeShip.mjs';++const { PNG } = createRequire(new URL('../../pipeline/package.json', import.meta.url))('pngjs');+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');+const host = path.join(root, 'build/render-host');+const out = path.join(root, 'output/composite-batch');+assert.ok(!(process.argv.includes('--webgl-only') && process.argv.includes('--webgpu-only')), 'Choose one backend filter');+const backends = process.argv.includes('--webgl-only') ? ['webgl2']+ : process.argv.includes('--webgpu-only') ? ['webgpu'] : ['webgl2', 'webgpu'];+requireCurrentEngine(root, path.join(host, 'wasm'));+await mkdir(out, { recursive: true });+const base = JSON.parse(await readFile(path.join(root, 'examples/device-quality/assets/scenes/main.esscene'), 'utf8'));+const furniture = base.entities.filter(entity => ['Camera', 'Lamp', 'Ambient', 'Floor'].includes(entity.name));+assert.equal(furniture.find(entity => entity.name === 'Lamp').components.find(c => c.type === 'Light').data.meshShadows, true);+const camera = furniture.find(entity => entity.name === 'Camera');+const authoredCamera = structuredClone(camera.components);+const yaw = Math.atan2(5, 7), pitch = -Math.atan2(4.5, Math.hypot(5, 7));+Object.assign(camera.components.find(c => c.type === 'Transform').data, {+ position: { x: 5, y: 4.5, z: 7 },+ rotation: { x: Math.sin(pitch / 2) * Math.cos(yaw / 2), y: Math.cos(pitch / 2) * Math.sin(yaw / 2),+ z: -Math.sin(pitch / 2) * Math.sin(yaw / 2), w: Math.cos(pitch / 2) * Math.cos(yaw / 2) },+});+Object.assign(camera.components.find(c => c.type === 'Camera').data, { fov: 48, farPlane: 40 });+if (process.argv.includes('--authored-camera')) camera.components = authoredCamera;+const ship = compositeShip();+const extra = structuredClone(ship.find(entity => entity.name === 'Barrel'));+extra.id = 2000; extra.name = 'Extra barrel'; extra.parent = null;+extra.components.find(c => c.type === 'Transform').data.position.z = 0.4;+extra.components.find(c => c.type === 'MeshRenderer').data.enabled = false;+const scene = { ...base, entities: [...furniture, ...ship, extra] };+const partIds = ship.filter(entity => entity.id !== 1000).map(entity => entity.id);+const nonCasters = [...ship.filter(entity => (/^(Plank|Post)/.test(entity.name) && entity.id % 2 === 0)+ || ['Barrel', 'Funnel'].includes(entity.name)).map(entity => entity.id), 2000];+const server = await serveHost(host);+const browser = await chromium.launch({ channel: 'chromium', headless: true,+ args: ['--enable-unsafe-webgpu', '--ignore-gpu-blocklist', '--enable-unsafe-swiftshader', '--mute-audio'] });+const report = { status: 'failed', checks: [], backends: [] };+try {+ for (const backend of backends) {+ const page = await browser.newPage({ viewport: { width: 512, height: 384 } });+ const errors = [];+ page.on('pageerror', error => errors.push(String(error)));+ page.on('console', event => { if (event.type() === 'error') errors.push(event.text()); });+ await page.route('**/favicon.ico', route => route.fulfill({ status: 204 }));+ await page.route('**/scenes/composite-ship.esscene', route => route.fulfill({ json: scene }));+ await page.goto(`http://127.0.0.1:${server.address().port}/?w=512&h=384&backend=${backend}`);+ await page.evaluate(async () => { await window.__estellaHeadless.ready; });+ const loaded = await page.evaluate(() => window.__estellaHeadless.api.loadScene('/scenes/composite-ship.esscene'));+ assert.deepEqual(loaded.missing, []);+ await page.evaluate(() => { const { api } = window.__estellaHeadless; api.setRunMode(true); api.setCpuProfiling(true); });+ const settle = async (parts, sets = null) => page.evaluate(async ({ parts, sets }) => {+ const { api } = window.__estellaHeadless;+ for (let i = 0; i < 90; i++) {+ await api.step(2);+ const state = api.compositeBatchReport(1000);+ if (!state.busy && (parts === 0 ? state.report === null : state.report?.parts === parts)+ && (sets === null || state.report?.sets === sets)) return state;+ }+ throw new Error(`Composite did not settle: ${JSON.stringify(api.compositeBatchReport(1000))}`);+ }, { parts, sets });+ const toggle = async (on, parts = 108) => {+ await page.evaluate(on => window.__estellaHeadless.api.setComponent(1000, 'CompositeBatch', on ? { instanceMin: 4, cellSize: 2 } : null), on);+ return settle(on ? parts : 0);+ };+ const capture = async label => {+ const raw = await page.evaluate(async () => {+ const { api } = window.__estellaHeadless;+ await api.step(3);+ if (!await api.waitForShaders()) throw new Error('Shader compilation did not finish');+ await api.step(2);+ const pixels = await api.captureViewportPixels();+ return { width: pixels.width, height: pixels.height, rgba: Array.from(pixels.rgba), counters: api.getCounters() };+ });+ const image = new PNG({ width: raw.width, height: raw.height });+ const bytes = Buffer.from(raw.rgba), stride = raw.width * 4;+ for (let y = 0; y < raw.height; y++) bytes.copy(image.data, y * stride, (raw.height - y - 1) * stride, (raw.height - y) * stride);+ await writeFile(path.join(out, `${backend}-${label}.png`), PNG.sync.write(image));+ return { image, counters: raw.counters };+ };+ const compare = (name, a, b) => {+ let changed = 0, maxChannel = 0, sum = 0;+ for (let i = 0; i < a.image.data.length; i += 4) {+ const differences = [0, 1, 2].map(c => Math.abs(a.image.data[i + c] - b.image.data[i + c]));+ const delta = Math.max(...differences);+ if (delta > 4) changed++;+ maxChannel = Math.max(maxChannel, delta);+ sum += differences.reduce((x, y) => x + y, 0);+ }+ const row = { backend, name, changed, fraction: changed / (a.image.width * a.image.height), maxChannel,+ meanChannel: sum / (a.image.width * a.image.height * 3) };+ report.checks.push(row); console.log(JSON.stringify(row));+ };+ await settle(0);+ const plain = await capture('plain');+ const colours = new Set();+ for (let i = 0; i < plain.image.data.length; i += 12) {+ colours.add((plain.image.data[i] >> 4) << 8 | (plain.image.data[i + 1] >> 4) << 4 | (plain.image.data[i + 2] >> 4));+ }+ assert.ok(colours.size > 40, 'The reference must show the shaded model rather than a flat frame');+ const initial = await toggle(true);+ const batched = await capture('batched');+ compare('initial', plain, batched);+ assert.equal(initial.report.sets, 2);+ assert.equal(initial.report.chunks, 2);+ assert.equal(initial.component.instanced, 104);+ assert.ok(plain.counters['render.meshes'] > 40 && batched.counters['render.meshes'] < plain.counters['render.meshes'] / 10);++ await page.evaluate(() => {+ const { api } = window.__estellaHeadless;+ api.setField(1000, 'Transform', 'position', '', { x: 1.5, y: 0, z: 0 }); api.refreshComposite(1000);+ });+ const moved = await settle(108);+ assert.equal(moved.counts.merges, initial.counts.merges);+ assert.deepEqual(moved.holders, initial.holders);+ const movedBatch = await capture('moved-batched');+ await toggle(false);+ compare('moved', await capture('moved-plain'), movedBatch);++ const beforeEdit = await toggle(true);+ await page.evaluate(() => {+ const { api } = window.__estellaHeadless;+ api.setParent(2000, 1000); api.setField(2000, 'MeshRenderer', 'enabled', '', true); api.refreshComposite(1000);+ });+ const edited = await settle(109);+ assert.equal(edited.counts.merges - beforeEdit.counts.merges, 1);+ const chunks = state => state.holders.filter(holder => /chunk/.test(holder.name)).map(holder => holder.mesh);+ assert.equal(chunks(edited).filter(mesh => chunks(beforeEdit).includes(mesh)).length, 1);+ const editedBatch = await capture('edited-batched');+ const restored = await toggle(false);+ assert.equal(restored.visibleParts, 109); assert.equal(restored.holders.length, 0);+ const editedPlain = await capture('edited-plain');+ compare('edited', editedPlain, editedBatch);++ await toggle(true, 109);+ await page.evaluate(ids => {+ const { api } = window.__estellaHeadless;+ for (const id of ids) api.setField(id, 'MeshRenderer', 'castShadows', '', false);+ }, nonCasters);+ const mixed = await settle(109, 4);+ assert.equal(mixed.holders.filter(holder => /chunk/.test(holder.name) && !holder.castShadows).length, 1);+ assert.equal(mixed.holders.filter(holder => /chunk/.test(holder.name) && holder.castShadows).length, 1);+ const mixedBatch = await capture('mixed-batched');+ await toggle(false);+ const mixedPlain = await capture('mixed-plain');+ compare('mixed-shadow-state', mixedPlain, mixedBatch);++ await toggle(true, 109);+ await page.evaluate(ids => {+ const { api } = window.__estellaHeadless;+ for (const id of ids) api.setField(id, 'MeshRenderer', 'castShadows', '', true);+ }, nonCasters);+ const shadowRestored = await settle(109, 2);+ assert.equal(shadowRestored.report.sets, 2);+ compare('restored-shadow-state', editedPlain, await capture('shadow-restored'));+ await toggle(false);+ await page.evaluate(ids => {+ for (const id of ids) window.__estellaHeadless.api.setField(id, 'MeshRenderer', 'castShadows', '', false);+ }, nonCasters);++ await page.evaluate(ids => { for (const id of ids) window.__estellaHeadless.api.setComponent(id, 'StaticBatch', {}); }, [...partIds, 2000]);+ const staticBatch = await page.evaluate(async () => {+ const { api } = window.__estellaHeadless;+ for (let i = 0; i < 100; i++) {+ await api.step(2);+ const state = api.staticBatchReport();+ if (state && state.groups.reduce((sum, group) => sum + group.partCount, 0) >= 100) return state;+ }+ throw new Error(`Static batch did not settle: ${JSON.stringify(api.staticBatchReport())}`);+ });+ assert.deepEqual(staticBatch.refused, []);+ assert.equal(new Set(staticBatch.groups.flatMap(group => group.parts)).size, 109);+ compare('static-mixed-shadow-state', mixedPlain, await capture('static-batched'));+ report.backends.push({ backend, initial, moved, edited, mixed, shadowRestored, staticBatch,+ visibleColours: colours.size, plainMeshes: plain.counters['render.meshes'], batchedMeshes: batched.counters['render.meshes'],+ shadowStateSeparated: mixed.report.sets === 4 && staticBatch.groups.every(group => group.partCastShadows.every(value => value === group.holderCastShadows)) });+ assert.deepEqual(errors, []);+ await page.close();+ }+ assert.ok(report.backends.every(row => row.shadowStateSeparated), 'Batching must preserve each part shadow policy');+ assert.ok(report.checks.every(row => row.fraction <= 0.001), 'Batching must preserve the visible geometry and shadows');+ report.status = 'checks-passed';+} catch (error) {+ report.error = String(error); throw error;+} finally {+ await writeFile(path.join(out, 'report.json'), JSON.stringify(report, null, 2));+ await browser.close(); await new Promise(resolve => server.close(resolve));+}