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
perf(bake): a bake uses every core
esengine33742bb7b6f0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5ff48da17..b28eb4249 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,7 @@ published separately; it ships inside the editor.### Added- **Baked light is a lit surface's indirect light.** A lit renderer — every imported model's is — reads its patch of the atlas in place of the environment's diffuse light and a probe volume's, and keeps its lamps, shadows and reflections live. The bake holds the sky as it reaches each point past whatever stands in the way, plus what the surfaces around give off, over as many bounces as asked: under ORCA Bistro's awnings and in its side streets the sky is now mostly hidden, where before every point got all of it. Before, a model's material never read the atlas at all, and a mesh drawn without one added it on top of the sky and the lamps and was lit twice. The sky a bake gathers is the environment's own irradiance, turned and tinted as the frame reads it, so an open floor bakes to exactly what the frame would light it with. An atlas holds light up to eight times a flat ambient of one, where eight plain bits stopped at one. A cutout lets the share of rays that meets its holes through, both faces of a two-sided surface give off light, and a layer lying closer above a surface than half a lumel — a decal, a wet sheen — no longer walls it off from the sky. A scene baked before reads as stale: its atlas is in the old encoding and must be baked again.+- **A bake uses every core.** Each pass is split across a pool of worker threads, one per core but one, sharing the scene in shared memory; every lumel is solved on its own, so the atlas is byte for byte what one thread writes. ORCA Bistro — 1.2 million lumels, 2.8 million triangles — bakes in about five minutes on a 20-thread machine, where it took twenty-five to fifty-five. The editor and `bake-scene` both use it.- **A model whose second UV set cannot be baked into gets a lightmap UV in its place.** One that covers under 5% of its square pays for the empty rest — ORCA Bistro's road, 3533 m² in 0.5% of it, asked for more atlas than the rest of the town together — and one that lies on itself gives every copy the same texel's light: Bistro's curbs share one strip eighty layers deep, and a building's facades a hundred. Import unwraps either instead and says why; `import-model --lightmap-uv` turns generation on from the command line. A bake names a surface whose UVs overlap, and one that does not fit names the three surfaces taking the most room and how much of their square their UVs cover.### Fixeddiff --git a/desktop b/desktopindex 421d3144e..b7907bf2c 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 421d3144e2f826ba3db92464fb29c261289465c9+Subproject commit b7907bf2c6255bfa516e3e01bee8b86b775b564bdiff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 503813695..8debc7474 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 115,"beta": 103,- "experimental": 2130,+ "experimental": 2138,"deprecated": 3},- "total": 2348,+ "total": 2356,"subsystems": [{"id": "ecs",diff --git a/pipeline/bin/estella.mjs b/pipeline/bin/estella.mjsindex d985aeca3..3b9dba1e1 100644--- a/pipeline/bin/estella.mjs+++ b/pipeline/bin/estella.mjs@@ -339,10 +339,20 @@ async function bakeScene(baker, meta, sceneFile, check) {reflections: reflectionProbes.map((p) => p.center),ambient, options,});- const result = baker.bakeSceneLightmap({- surfaces, lights, probeVolumes: volumes, reflectionProbes, environment,- options: { ...options, ambient },- });+ // Each pass split across every core but one: a lumel is solved on its own.+ const worker = await bundlePipeline(path.join(PIPELINE, 'src', 'assets', 'lightmapWorker.ts'),+ 'lightmapWorker.mjs');+ const pool = new baker.BakePool(worker.outfile);+ let result;+ try {+ result = await baker.bakeSceneLightmapParallel({+ surfaces, lights, probeVolumes: volumes, reflectionProbes, environment,+ options: { ...options, ambient },+ }, pool);+ } finally {+ await pool.close();+ worker.cleanup();+ }for (const w of result.warnings) console.warn(` ! ${w}`);const stem = path.basename(sceneFile).replace(/\.esscene$/i, '');@@ -526,6 +536,17 @@ function sweepStaleBuildDirs(srcDir) {}async function loadPipeline(entry, outName) {+ const { outfile, cleanup } = await bundlePipeline(entry, outName);+ try {+ return { mod: await import(fileUrl(outfile)), cleanup };+ } catch (err) {+ cleanup();+ throw err;+ }+}++/** A pipeline module bundled to a runnable file, for a worker thread to start from. */+async function bundlePipeline(entry, outName) {const require = createRequire(path.join(PIPELINE, 'package.json'));const esbuild = require('esbuild');// As deep in the package as the cook is: the Basis encoder is kept external so@@ -562,12 +583,7 @@ async function loadPipeline(entry, outName) {// sitting where every source-scanning gate reads. A caller's own cleanup is a// path that can be missed — 277 had been — so the exit is what guarantees it.process.on('exit', cleanup);- try {- return { mod: await import(fileUrl(outfile)), cleanup };- } catch (err) {- cleanup();- throw err;- }+ return { outfile, cleanup };}const PROJECT_FILES = ['project.esproject', 'project.esproj', 'project.json'];diff --git a/pipeline/src/assets/lightmapBake.ts b/pipeline/src/assets/lightmapBake.tsindex 32f59a0be..7a9b48257 100644--- a/pipeline/src/assets/lightmapBake.ts+++ b/pipeline/src/assets/lightmapBake.ts@@ -10,10 +10,12 @@*/import { readFileSync } from 'node:fs';import { PNG } from 'pngjs';-import { bakeLightmap, decodeMesh, unwrapLightmapUV, builtinMeshTemplate, MeshChannel,- type MeshData, type BakeSurface, type BakeLight, type BakeOptions,- type CapturedPanorama, type ProbeGrid } from 'esengine';+import { bakeLightmapSteps, bakeRunner, decodeMesh, unwrapLightmapUV, builtinMeshTemplate, MeshChannel,+ type MeshData, type BakeSurface, type BakeLight, type BakeOptions, type BakeAlloc,+ type BakeStep, type CapturedPanorama, type ProbeGrid } from 'esengine';import { encodeRgbaPng } from './png';++export { BakePool } from './lightmapPool';import { bakeSceneReflections, bakeSky, irradianceSky, type BakeEnvironment,type ReflectionBakeResult } from './reflectionBake';@@ -248,6 +250,36 @@ function albedoOf(s: SceneBakeSurface, cutoff: number, cache: Map<string, Textur* and silently lighting everything else would look like the bake simply missed it.*/export function bakeSceneLightmap(input: SceneBakeInput): SceneBakeResult {+ const steps = sceneBakeSteps(input);+ let runner: ReturnType<typeof bakeRunner> | null = null;+ for (;;) {+ const next = steps.next();+ if (next.done) return next.value;+ runner ??= bakeRunner(next.value.scene);+ runner(next.value.job, 0, next.value.scene.lumels.count);+ }+}++/** How {@link bakeSceneLightmapParallel} hands a pass to its threads. */+export interface BakeExecutor {+ /** Where the arrays a pass touches must live for its threads to see them. */+ alloc: BakeAlloc;+ run(step: BakeStep): Promise<void>;+}++/** {@link bakeSceneLightmap} with each pass split across `executor`'s threads. */+export async function bakeSceneLightmapParallel(input: SceneBakeInput,+ executor: BakeExecutor): Promise<SceneBakeResult> {+ const steps = sceneBakeSteps(input, executor.alloc);+ for (;;) {+ const next = steps.next();+ if (next.done) return next.value;+ await executor.run(next.value);+ }+}++function* sceneBakeSteps(input: SceneBakeInput,+ alloc?: BakeAlloc): Generator<BakeStep, SceneBakeResult, void> {const warnings: string[] = [];const surfaces: BakeSurface[] = [];const slot: number[] = [];@@ -344,8 +376,8 @@ export function bakeSceneLightmap(input: SceneBakeInput): SceneBakeResult {warnings.push('nothing in this scene can receive baked light');// The volumes are still solved: a scene whose only light is ambient has// nothing to bake into an atlas and still has somewhere to stand.- const empty = bakeLightmap([], input.lights,- { ...input.options, probeGrids: grids, ...reflectionOptions });+ const empty = yield* bakeLightmapSteps([], input.lights,+ { ...input.options, probeGrids: grids, ...reflectionOptions }, alloc);gridSlot.forEach((at, k) => { probes[at] = asDocument(grids[k], empty.probes[k]); });return {atlasBytes: encodeRgbaPng(1, 1, new Uint8Array([0, 0, 0, 255])),@@ -356,8 +388,8 @@ export function bakeSceneLightmap(input: SceneBakeInput): SceneBakeResult {};}- const result = bakeLightmap(surfaces, input.lights,- { ...input.options, probeGrids: grids, ...reflectionOptions });+ const result = yield* bakeLightmapSteps(surfaces, input.lights,+ { ...input.options, probeGrids: grids, ...reflectionOptions }, alloc);result.shared.forEach((share, k) => {if (share > 0.25) {warnings.push(`${surfaces[k]!.label ?? `surface ${k}`}: its lightmap UVs lay`diff --git a/pipeline/src/assets/lightmapPool.ts b/pipeline/src/assets/lightmapPool.tsnew file mode 100644index 000000000..338cd6e6e--- /dev/null+++ b/pipeline/src/assets/lightmapPool.ts@@ -0,0 +1,66 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file lightmapPool.ts+ * @brief A bake's passes split across worker threads. Every lumel is solved on+ * its own, so the threads share one scene in shared memory and each takes+ * ranges of lumels until a pass runs out.+ */++import { Worker } from 'node:worker_threads';+import { availableParallelism } from 'node:os';+import type { BakeAlloc, BakeScene, BakeStep } from 'esengine';+import type { BakeExecutor } from './lightmapBake';++export const sharedAlloc: BakeAlloc = {+ f32: (n) => new Float32Array(new SharedArrayBuffer(n * 4)),+ i32: (n) => new Int32Array(new SharedArrayBuffer(n * 4)),+ u8: (n) => new Uint8Array(new SharedArrayBuffer(n)),+};++/** Ranges per thread per pass: enough that one slow range does not idle the rest. */+const RANGES_PER_THREAD = 16;++export class BakePool implements BakeExecutor {+ readonly alloc = sharedAlloc;+ private readonly workers: Worker[];+ private scene: BakeScene | null = null;++ /**+ * @param workerFile A module that runs `lightmapWorker.ts`: each host builds its+ * own, since a thread cannot start from TypeScript source.+ */+ constructor(workerFile: string | URL, threads = Math.max(1, availableParallelism() - 1)) {+ this.workers = Array.from({ length: threads }, () => new Worker(workerFile));+ }++ get threads(): number { return this.workers.length; }++ async run({ scene, job }: BakeStep): Promise<void> {+ if (scene !== this.scene) {+ if (typeof scene.sky === 'function') {+ throw new Error('BakePool: a bake split across threads needs its sky as a SkySpec');+ }+ for (const w of this.workers) w.postMessage({ scene });+ this.scene = scene;+ }+ const count = scene.lumels.count;+ const range = Math.max(64, Math.ceil(count / (this.workers.length * RANGES_PER_THREAD)));+ let next = 0;+ await Promise.all(this.workers.map((w) => new Promise<void>((resolve, reject) => {+ const give = (): void => {+ if (next >= count) { w.off('message', give); w.off('error', reject); resolve(); return; }+ const from = next;+ next = Math.min(count, next + range);+ w.postMessage({ job, from, to: next });+ };+ w.on('message', give);+ w.on('error', reject);+ give();+ })));+ }++ async close(): Promise<void> {+ await Promise.all(this.workers.map((w) => w.terminate()));+ }+}diff --git a/pipeline/src/assets/lightmapWorker.ts b/pipeline/src/assets/lightmapWorker.tsnew file mode 100644index 000000000..c59b9f884--- /dev/null+++ b/pipeline/src/assets/lightmapWorker.ts@@ -0,0 +1,18 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file lightmapWorker.ts+ * @brief One thread of a {@link BakePool}: holds the scene it was handed, solves+ * the ranges it is sent, and says when each is done.+ */++import { parentPort } from 'node:worker_threads';+import { bakeRunner, type BakeJob, type BakeScene } from 'esengine';++let run: ReturnType<typeof bakeRunner> | null = null;++parentPort?.on('message', (m: { scene?: BakeScene; job?: BakeJob; from?: number; to?: number }) => {+ if (m.scene) { run = bakeRunner(m.scene); return; }+ run!(m.job!, m.from!, m.to!);+ parentPort!.postMessage(0);+});diff --git a/pipeline/src/assets/reflectionBake.ts b/pipeline/src/assets/reflectionBake.tsindex 3b5af75ad..f5ea103bc 100644--- a/pipeline/src/assets/reflectionBake.ts+++ b/pipeline/src/assets/reflectionBake.ts@@ -13,7 +13,7 @@* carries which column an object reflects as a number per instance, and* a hundred shiny things in a room still merge into one draw.*/-import { type CapturedPanorama, flatSky, evalIrradianceSH, SH_COSINE_BAND, type SkyRadiance } from 'esengine';+import { type CapturedPanorama, flatSky, type SkyRadiance, type SkySpec } from 'esengine';import { atlasLayout, decodeRgbm, mipCountFor, octEncode, prefilterOctahedral,type EnvironmentAssetData } from './environmentImport';import { encodeRgbaPng } from './png';@@ -88,23 +88,15 @@ export function environmentSky(environment: BakeEnvironment): SkyRadiance | null}/**- * The sky a lumel or a probe gathers: radiance whose cosine-weighted mean over an- * open hemisphere is the environment's irradiance as the frame reads it. Not the- * reflection atlas, which clips the HDR sun that is most of a sunny sky.+ * The sky a lumel or a probe gathers: the environment's irradiance as the frame+ * reads it, turned and tinted the same way. Not the reflection atlas, which clips+ * the HDR sun that is most of a sunny sky.*/export function irradianceSky(environment: BakeEnvironment | null | undefined,- ambient: readonly [number, number, number]): SkyRadiance {+ ambient: readonly [number, number, number]): SkySpec {const sh = environment?.document.irradiance;- if (!environment || !Array.isArray(sh) || sh.length < 27) return flatSky(ambient);- const radiance = Float32Array.from(sh.slice(0, 27), (v, i) => v / SH_COSINE_BAND[Math.floor(i / 3)]!);- const yaw = -((environment.rotation ?? 0) * Math.PI) / 180;- const c = Math.cos(yaw), s = Math.sin(yaw);- return (dx, dy, dz, out, at) => {- const [r, g, b] = evalIrradianceSH(radiance, c * dx + s * dz, dy, -s * dx + c * dz);- out[at] = Math.max(0, r) * ambient[0];- out[at + 1] = Math.max(0, g) * ambient[1];- out[at + 2] = Math.max(0, b) * ambient[2];- };+ if (!environment || !Array.isArray(sh) || sh.length < 27) return { kind: 'flat', rgb: ambient };+ return { kind: 'sh', irradiance: sh.slice(0, 27), yaw: -((environment.rotation ?? 0) * Math.PI) / 180, tint: ambient };}/** The sky a capture should use: the environment's own where there is one. */diff --git a/pipeline/tests/lightmap-parallel.test.ts b/pipeline/tests/lightmap-parallel.test.tsnew file mode 100644index 000000000..80a2f2664--- /dev/null+++ b/pipeline/tests/lightmap-parallel.test.ts@@ -0,0 +1,86 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A bake split across threads is the same bake: every lumel is solved on+ * its own, so the atlas comes out byte for byte what one thread writes.+ */+import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { build } from 'esbuild';+import { encodeMesh, unwrapLightmapUV, MeshChannel, MeshChannelType, type MeshData, type BakeLight } from 'esengine';+import { bakeSceneLightmap, bakeSceneLightmapParallel, type SceneBakeInput } from '../src/assets/lightmapBake';+import { BakePool } from '../src/assets/lightmapPool';+import { encodeRgbaPng } from '../src/assets/png';++let dir = '';+let pool: BakePool;++function quad(half: number, y: number, facing: 1 | -1): MeshData {+ const p = [[-half, y, -half], [half, y, -half], [half, y, half], [-half, y, half]];+ const vertices = new Uint8Array(4 * 24);+ const view = new DataView(vertices.buffer);+ p.forEach((q, i) => {+ q.forEach((v, k) => view.setFloat32(i * 24 + k * 4, v, true));+ view.setFloat32(i * 24 + 16, facing, true);+ });+ return unwrapLightmapUV({+ channels: [+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32, offset: 0 },+ { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.Float32, offset: 12 },+ ],+ vertexStride: 24, vertexCount: 4, vertices,+ indices: Uint32Array.from(facing > 0 ? [0, 2, 1, 0, 3, 2] : [0, 1, 2, 0, 2, 3]),+ aabbMin: [-half, y, -half], aabbMax: [half, y, half],+ }).mesh;+}++beforeAll(async () => {+ dir = await mkdtemp(path.join(tmpdir(), 'estella-parallel-'));+ await writeFile(path.join(dir, 'floor.esmesh'), encodeMesh(quad(4, 0, 1)));+ await writeFile(path.join(dir, 'roof.esmesh'), encodeMesh(quad(1.5, 1, -1)));+ const holes = new Uint8Array(4 * 4 * 4).fill(200);+ for (let i = 8; i < 16; i++) holes[i * 4 + 3] = 0;+ await writeFile(path.join(dir, 'holes.png'), encodeRgbaPng(4, 4, holes));+ await writeFile(path.join(dir, 'cutout.esmaterial'), JSON.stringify(+ { version: '1.0', type: 'material', shader: 'builtin:model', properties: { u_alphaCutoff: 0.5 } }));+ const worker = path.join(dir, 'lightmapWorker.mjs');+ await build({ entryPoints: [path.resolve(__dirname, '../src/assets/lightmapWorker.ts')],+ outfile: worker, bundle: true, format: 'esm', platform: 'node', logLevel: 'error' });+ pool = new BakePool(worker, 3);+});++afterAll(async () => {+ await pool?.close();+ await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });+});++const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];+const LAMP: BakeLight[] = [{ kind: 'point', position: [2, 3, 1], color: [1, 0.8, 0.6], intensity: 5, radius: 20 }];++function scene(): SceneBakeInput {+ return {+ surfaces: [+ { meshFile: path.join(dir, 'floor.esmesh'), label: 'Floor', transform: IDENTITY,+ baseColor: [0.7, 0.6, 0.5], realtimeDirect: true },+ { meshFile: path.join(dir, 'roof.esmesh'), label: 'Roof', transform: IDENTITY,+ baseColorTexture: path.join(dir, 'holes.png'), material: path.join(dir, 'cutout.esmaterial'),+ twoSided: true },+ ],+ lights: LAMP,+ probeVolumes: [{ label: 'Air', center: [0, 0.5, 0], halfExtents: [2, 0.4, 2], spacing: 1 }],+ options: { atlasSize: 128, texelsPerUnit: 6, bounces: 2, samples: 16, ambient: [0.3, 0.4, 0.5] },+ } as SceneBakeInput;+}++describe('a bake split across threads', () => {+ it('writes the atlas and the probes one thread writes', async () => {+ const one = bakeSceneLightmap(scene());+ const many = await bakeSceneLightmapParallel(scene(), pool);+ expect(many.lumels).toBe(one.lumels);+ expect(many.lumels).toBeGreaterThan(pool.threads * 64);+ expect(Buffer.from(many.atlasBytes).equals(Buffer.from(one.atlasBytes))).toBe(true);+ expect(many.probes).toEqual(one.probes);+ });+});diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 52b84abcc..fde02b1be 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 91 beta · 1516 experimental · 3 deprecated+Symbols: 115 public · 91 beta · 1524 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1384,6 +1384,13 @@ resolveUrl: (path: string) => stringsetBaseUrl: ((url: string) => void) | undefined```+## BakeAlloc — interface @experimental+```+f32: (length: number) => Float32Array+i32: (length: number) => Int32Array+u8: (length: number) => Uint8Array+```+## BakeInputs — interface @experimental```ambient: readonly [number, number, number] | undefined@@ -1394,6 +1401,12 @@ surfaces: readonly { mesh: string; transform: ArrayLike<number>; albedo?: readonvolumes: readonly { center: readonly [number, number, number]; halfExtents: readonly [number, number, number]; spacing: number; }[]```+## BakeJob — type @experimental+```+| { kind: 'direct'; out: Float32Array }+ | { kind: 'gather'; atlas: Float32Array; out: Float32Array }+```+## BakeLight — interface @experimental```color: readonly [number, number, number]@@ -1430,7 +1443,7 @@ reflectionProbes: readonly (readonly [number, number, number])[] | undefinedreflectionSky: SkyRadiance | undefinedreflectionWidth: number | undefinedsamples: number | undefined-sky: SkyRadiance | undefined+sky: SkySpec | SkyRadiance | undefinedtexelsPerUnit: number | undefined```@@ -1445,6 +1458,23 @@ shared: Float32Array<ArrayBufferLike>size: number```+## BakeScene — interface @experimental+```+atlasSize: number+bvh: BvhParts+lights: readonly BakeLight[]+lookup: HitLookup+lumels: LumelField+samples: number+sky: SkySpec | SkyRadiance+```++## BakeStep — interface @experimental+```+job: BakeJob+scene: BakeScene+```+## BakeSurface — interface @experimental```albedo: readonly [number, number, number] | undefined@@ -7570,6 +7600,14 @@ vertices: Uint8Array<ArrayBufferLike>out: Float32Array, at: number) => void```+## SkySpec — type @experimental+```+| { kind: 'flat'; rgb: readonly [number, number, number] }+ /** An environment's nine irradiance coefficients as the frame reads them:+ * turned `yaw` radians about +Y and scaled by `tint`. */+ | { kind: 'sh'; irradiance: readonly number[]; yaw: number; tint: readonly [number, number, number] }+```+## SliceBorder — interface @experimental```bottom: number@@ -10067,6 +10105,16 @@ AudioPlugin(surfaces: readonly BakeSurface[], lights: readonly BakeLight[], options?: BakeOptions): BakeResult```+## bakeLightmapSteps — function @experimental+```+(surfaces: readonly BakeSurface[], lights: readonly BakeLight[], options?: BakeOptions, alloc?: BakeAlloc): Generator<BakeStep, BakeResult, void>+```++## bakeRunner — function @experimental+```+(scene: BakeScene): (job: BakeJob, from: number, to: number) => void+```+## bind — function @experimental```<C extends object, K extends keyof C>(world: World, entity: Entity, component: ComponentDef<C>, field: K, source: ReadonlySignal<C[K]>): () => void@@ -12462,6 +12510,11 @@ ServicesPlugin<T>(initial: T): Signal<T>```+## skyRadiance — function @experimental+```+(spec: SkySpec): SkyRadiance+```+## solveAnimatorIK — function @experimental```(world: World, rigRoot: Entity, pose: Pose, constraints: readonly AnimatorIK[], params: MotionParams, resolveJoint?: JointResolver): voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex f641a434b..458249a8e 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 96 beta · 1535 experimental · 3 deprecated+Symbols: 115 public · 96 beta · 1543 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1384,6 +1384,13 @@ resolveUrl: (path: string) => stringsetBaseUrl: ((url: string) => void) | undefined```+## BakeAlloc — interface @experimental+```+f32: (length: number) => Float32Array+i32: (length: number) => Int32Array+u8: (length: number) => Uint8Array+```+## BakeInputs — interface @experimental```ambient: readonly [number, number, number] | undefined@@ -1394,6 +1401,12 @@ surfaces: readonly { mesh: string; transform: ArrayLike<number>; albedo?: readonvolumes: readonly { center: readonly [number, number, number]; halfExtents: readonly [number, number, number]; spacing: number; }[]```+## BakeJob — type @experimental+```+| { kind: 'direct'; out: Float32Array }+ | { kind: 'gather'; atlas: Float32Array; out: Float32Array }+```+## BakeLight — interface @experimental```color: readonly [number, number, number]@@ -1430,7 +1443,7 @@ reflectionProbes: readonly (readonly [number, number, number])[] | undefinedreflectionSky: SkyRadiance | undefinedreflectionWidth: number | undefinedsamples: number | undefined-sky: SkyRadiance | undefined+sky: SkySpec | SkyRadiance | undefinedtexelsPerUnit: number | undefined```@@ -1445,6 +1458,23 @@ shared: Float32Array<ArrayBufferLike>size: number```+## BakeScene — interface @experimental+```+atlasSize: number+bvh: BvhParts+lights: readonly BakeLight[]+lookup: HitLookup+lumels: LumelField+samples: number+sky: SkySpec | SkyRadiance+```++## BakeStep — interface @experimental+```+job: BakeJob+scene: BakeScene+```+## BakeSurface — interface @experimental```albedo: readonly [number, number, number] | undefined@@ -7771,6 +7801,14 @@ vertices: Uint8Array<ArrayBufferLike>out: Float32Array, at: number) => void```+## SkySpec — type @experimental+```+| { kind: 'flat'; rgb: readonly [number, number, number] }+ /** An environment's nine irradiance coefficients as the frame reads them:+ * turned `yaw` radians about +Y and scaled by `tint`. */+ | { kind: 'sh'; irradiance: readonly number[]; yaw: number; tint: readonly [number, number, number] }+```+## SliceBorder — interface @experimental```bottom: number@@ -10283,6 +10321,16 @@ AudioPlugin(surfaces: readonly BakeSurface[], lights: readonly BakeLight[], options?: BakeOptions): BakeResult```+## bakeLightmapSteps — function @experimental+```+(surfaces: readonly BakeSurface[], lights: readonly BakeLight[], options?: BakeOptions, alloc?: BakeAlloc): Generator<BakeStep, BakeResult, void>+```++## bakeRunner — function @experimental+```+(scene: BakeScene): (job: BakeJob, from: number, to: number) => void+```+## bind — function @experimental```<C extends object, K extends keyof C>(world: World, entity: Entity, component: ComponentDef<C>, field: K, source: ReadonlySignal<C[K]>): () => void@@ -12713,6 +12761,11 @@ ServicesPlugin<T>(initial: T): Signal<T>```+## skyRadiance — function @experimental+```+(spec: SkySpec): SkyRadiance+```+## solveAnimatorIK — function @experimental```(world: World, rigRoot: Entity, pose: Pose, constraints: readonly AnimatorIK[], params: MotionParams, resolveJoint?: JointResolver): voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex d141fee67..31517f338 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 93 beta · 1515 experimental · 3 deprecated+Symbols: 115 public · 93 beta · 1523 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1379,6 +1379,13 @@ resolveUrl: (path: string) => stringsetBaseUrl: ((url: string) => void) | undefined```+## BakeAlloc — interface @experimental+```+f32: (length: number) => Float32Array+i32: (length: number) => Int32Array+u8: (length: number) => Uint8Array+```+## BakeInputs — interface @experimental```ambient: readonly [number, number, number] | undefined@@ -1389,6 +1396,12 @@ surfaces: readonly { mesh: string; transform: ArrayLike<number>; albedo?: readonvolumes: readonly { center: readonly [number, number, number]; halfExtents: readonly [number, number, number]; spacing: number; }[]```+## BakeJob — type @experimental+```+| { kind: 'direct'; out: Float32Array }+ | { kind: 'gather'; atlas: Float32Array; out: Float32Array }+```+## BakeLight — interface @experimental```color: readonly [number, number, number]@@ -1425,7 +1438,7 @@ reflectionProbes: readonly (readonly [number, number, number])[] | undefinedreflectionSky: SkyRadiance | undefinedreflectionWidth: number | undefinedsamples: number | undefined-sky: SkyRadiance | undefined+sky: SkySpec | SkyRadiance | undefinedtexelsPerUnit: number | undefined```@@ -1440,6 +1453,23 @@ shared: Float32Array<ArrayBufferLike>size: number```+## BakeScene — interface @experimental+```+atlasSize: number+bvh: BvhParts+lights: readonly BakeLight[]+lookup: HitLookup+lumels: LumelField+samples: number+sky: SkySpec | SkyRadiance+```++## BakeStep — interface @experimental+```+job: BakeJob+scene: BakeScene+```+## BakeSurface — interface @experimental```albedo: readonly [number, number, number] | undefined@@ -7565,6 +7595,14 @@ vertices: Uint8Array<ArrayBufferLike>out: Float32Array, at: number) => void```+## SkySpec — type @experimental+```+| { kind: 'flat'; rgb: readonly [number, number, number] }+ /** An environment's nine irradiance coefficients as the frame reads them:+ * turned `yaw` radians about +Y and scaled by `tint`. */+ | { kind: 'sh'; irradiance: readonly number[]; yaw: number; tint: readonly [number, number, number] }+```+## SliceBorder — interface @experimental```bottom: number@@ -10062,6 +10100,16 @@ AudioPlugin(surfaces: readonly BakeSurface[], lights: readonly BakeLight[], options?: BakeOptions): BakeResult```+## bakeLightmapSteps — function @experimental+```+(surfaces: readonly BakeSurface[], lights: readonly BakeLight[], options?: BakeOptions, alloc?: BakeAlloc): Generator<BakeStep, BakeResult, void>+```++## bakeRunner — function @experimental+```+(scene: BakeScene): (job: BakeJob, from: number, to: number) => void+```+## bind — function @experimental```<C extends object, K extends keyof C>(world: World, entity: Entity, component: ComponentDef<C>, field: K, source: ReadonlySignal<C[K]>): () => void@@ -12467,6 +12515,11 @@ ServicesPlugin<T>(initial: T): Signal<T>```+## skyRadiance — function @experimental+```+(spec: SkySpec): SkyRadiance+```+## solveAnimatorIK — function @experimental```(world: World, rigRoot: Entity, pose: Pose, constraints: readonly AnimatorIK[], params: MotionParams, resolveJoint?: JointResolver): voiddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 3125691b3..cf995b1f4 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 91 beta · 1537 experimental · 3 deprecated+Symbols: 115 public · 91 beta · 1545 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1379,6 +1379,13 @@ resolveUrl: (path: string) => stringsetBaseUrl: ((url: string) => void) | undefined```+## BakeAlloc — interface @experimental+```+f32: (length: number) => Float32Array+i32: (length: number) => Int32Array+u8: (length: number) => Uint8Array+```+## BakeInputs — interface @experimental```ambient: readonly [number, number, number] | undefined@@ -1389,6 +1396,12 @@ surfaces: readonly { mesh: string; transform: ArrayLike<number>; albedo?: readonvolumes: readonly { center: readonly [number, number, number]; halfExtents: readonly [number, number, number]; spacing: number; }[]```+## BakeJob — type @experimental+```+| { kind: 'direct'; out: Float32Array }+ | { kind: 'gather'; atlas: Float32Array; out: Float32Array }+```+## BakeLight — interface @experimental```color: readonly [number, number, number]@@ -1425,7 +1438,7 @@ reflectionProbes: readonly (readonly [number, number, number])[] | undefinedreflectionSky: SkyRadiance | undefinedreflectionWidth: number | undefinedsamples: number | undefined-sky: SkyRadiance | undefined+sky: SkySpec | SkyRadiance | undefinedtexelsPerUnit: number | undefined```@@ -1440,6 +1453,23 @@ shared: Float32Array<ArrayBufferLike>size: number```+## BakeScene — interface @experimental+```+atlasSize: number+bvh: BvhParts+lights: readonly BakeLight[]+lookup: HitLookup+lumels: LumelField+samples: number+sky: SkySpec | SkyRadiance+```++## BakeStep — interface @experimental+```+job: BakeJob+scene: BakeScene+```+## BakeSurface — interface @experimental```albedo: readonly [number, number, number] | undefined@@ -7835,6 +7865,14 @@ vertices: Uint8Array<ArrayBufferLike>out: Float32Array, at: number) => void```+## SkySpec — type @experimental+```+| { kind: 'flat'; rgb: readonly [number, number, number] }+ /** An environment's nine irradiance coefficients as the frame reads them:+ * turned `yaw` radians about +Y and scaled by `tint`. */+ | { kind: 'sh'; irradiance: readonly number[]; yaw: number; tint: readonly [number, number, number] }+```+## SliceBorder — interface @experimental```bottom: number@@ -10338,6 +10376,16 @@ AudioPlugin(surfaces: readonly BakeSurface[], lights: readonly BakeLight[], options?: BakeOptions): BakeResult```+## bakeLightmapSteps — function @experimental+```+(surfaces: readonly BakeSurface[], lights: readonly BakeLight[], options?: BakeOptions, alloc?: BakeAlloc): Generator<BakeStep, BakeResult, void>+```++## bakeRunner — function @experimental+```+(scene: BakeScene): (job: BakeJob, from: number, to: number) => void+```+## bind — function @experimental```<C extends object, K extends keyof C>(world: World, entity: Entity, component: ComponentDef<C>, field: K, source: ReadonlySignal<C[K]>): () => void@@ -12748,6 +12796,11 @@ ServicesPlugin<T>(initial: T): Signal<T>```+## skyRadiance — function @experimental+```+(spec: SkySpec): SkyRadiance+```+## solveAnimatorIK — function @experimental```(world: World, rigRoot: Entity, pose: Pose, constraints: readonly AnimatorIK[], params: MotionParams, resolveJoint?: JointResolver): voiddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 06a26ed5d..aa8b9cbc1 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 91 beta · 1528 experimental · 3 deprecated+Symbols: 115 public · 91 beta · 1536 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1379,6 +1379,13 @@ resolveUrl: (path: string) => stringsetBaseUrl: ((url: string) => void) | undefined```+## BakeAlloc — interface @experimental+```+f32: (length: number) => Float32Array+i32: (length: number) => Int32Array+u8: (length: number) => Uint8Array+```+## BakeInputs — interface @experimental```ambient: readonly [number, number, number] | undefined@@ -1389,6 +1396,12 @@ surfaces: readonly { mesh: string; transform: ArrayLike<number>; albedo?: readonvolumes: readonly { center: readonly [number, number, number]; halfExtents: readonly [number, number, number]; spacing: number; }[]```+## BakeJob — type @experimental+```+| { kind: 'direct'; out: Float32Array }+ | { kind: 'gather'; atlas: Float32Array; out: Float32Array }+```+## BakeLight — interface @experimental```color: readonly [number, number, number]@@ -1425,7 +1438,7 @@ reflectionProbes: readonly (readonly [number, number, number])[] | undefinedreflectionSky: SkyRadiance | undefinedreflectionWidth: number | undefinedsamples: number | undefined-sky: SkyRadiance | undefined+sky: SkySpec | SkyRadiance | undefinedtexelsPerUnit: number | undefined```@@ -1440,6 +1453,23 @@ shared: Float32Array<ArrayBufferLike>size: number```+## BakeScene — interface @experimental+```+atlasSize: number+bvh: BvhParts+lights: readonly BakeLight[]+lookup: HitLookup+lumels: LumelField+samples: number+sky: SkySpec | SkyRadiance+```++## BakeStep — interface @experimental+```+job: BakeJob+scene: BakeScene+```+## BakeSurface — interface @experimental```albedo: readonly [number, number, number] | undefined@@ -7572,6 +7602,14 @@ vertices: Uint8Array<ArrayBufferLike>out: Float32Array, at: number) => void```+## SkySpec — type @experimental+```+| { kind: 'flat'; rgb: readonly [number, number, number] }+ /** An environment's nine irradiance coefficients as the frame reads them:+ * turned `yaw` radians about +Y and scaled by `tint`. */+ | { kind: 'sh'; irradiance: readonly number[]; yaw: number; tint: readonly [number, number, number] }+```+## SliceBorder — interface @experimental```bottom: number@@ -10093,6 +10131,16 @@ AudioPlugin(surfaces: readonly BakeSurface[], lights: readonly BakeLight[], options?: BakeOptions): BakeResult```+## bakeLightmapSteps — function @experimental+```+(surfaces: readonly BakeSurface[], lights: readonly BakeLight[], options?: BakeOptions, alloc?: BakeAlloc): Generator<BakeStep, BakeResult, void>+```++## bakeRunner — function @experimental+```+(scene: BakeScene): (job: BakeJob, from: number, to: number) => void+```+## bind — function @experimental```<C extends object, K extends keyof C>(world: World, entity: Entity, component: ComponentDef<C>, field: K, source: ReadonlySignal<C[K]>): () => void@@ -12498,6 +12546,11 @@ ServicesPlugin<T>(initial: T): Signal<T>```+## skyRadiance — function @experimental+```+(spec: SkySpec): SkyRadiance+```+## solveAnimatorIK — function @experimental```(world: World, rigRoot: Entity, pose: Pose, constraints: readonly AnimatorIK[], params: MotionParams, resolveJoint?: JointResolver): voiddiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex e5dab32d8..9809dd3dc 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -157,6 +157,8 @@ export {type ProbeGrid, bakeHoldsStill, type BakeMobility, BAKE_DEFAULTS,captureReflection, flatSky, type CapturedPanorama, type SkyRadiance,LIGHTMAP_RANGE, encodeLightmap, decodeLightmap,+ bakeLightmapSteps, bakeRunner, type BakeScene, type BakeJob, type BakeStep,+ skyRadiance, type SkySpec, type BakeAlloc,} from './lightmap';/*** What a scene declares about its baked light: the knobs, and the fingerprint ofdiff --git a/sdk/src/lightmap/alloc.ts b/sdk/src/lightmap/alloc.tsnew file mode 100644index 000000000..9ea1566b2--- /dev/null+++ b/sdk/src/lightmap/alloc.ts@@ -0,0 +1,27 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file alloc.ts+ * @brief Where a bake's large arrays live: ordinary memory on one thread, memory+ * every worker can see when the solve is split across several.+ */++export interface BakeAlloc {+ f32(length: number): Float32Array;+ i32(length: number): Int32Array;+ u8(length: number): Uint8Array;+}++export const plainAlloc: BakeAlloc = {+ f32: (n) => new Float32Array(n),+ i32: (n) => new Int32Array(n),+ u8: (n) => new Uint8Array(n),+};++/** A copy of `src` in memory `alloc` hands out. */+export function adopt<T extends Float32Array | Int32Array | Uint8Array>(src: T, alloc: BakeAlloc): T {+ const out = (src instanceof Float32Array ? alloc.f32(src.length)+ : src instanceof Int32Array ? alloc.i32(src.length) : alloc.u8(src.length)) as T;+ out.set(src as never);+ return out;+}diff --git a/sdk/src/lightmap/bake.ts b/sdk/src/lightmap/bake.tsindex 4a7c18df3..7a3a411df 100644--- a/sdk/src/lightmap/bake.ts+++ b/sdk/src/lightmap/bake.ts@@ -15,6 +15,10 @@ import {layoutAtlas, rasterizeLumels, atlasDemand, SPARSE_LIGHTMAP_UV, type BakeSurface, type SurfacePatch,} from './atlas';import { solveDirect, solveGather, type BakeLight, type HitLookup } from './solve';+import { plainAlloc, adopt, type BakeAlloc } from './alloc';+import { skyRadiance, type SkySpec } from './sky';+import type { LumelField } from './atlas';+import type { BvhParts } from './bvh';import { solveProbes, type ProbeGrid } from './probes';import { captureReflection, flatSky, type CapturedPanorama, type SkyRadiance }from './reflection';@@ -36,8 +40,9 @@ export interface BakeOptions {* direction, and still only reaching what can see it. */ambient?: readonly [number, number, number];/** What a lumel or a probe receives along a ray that escapes the scene — the- * environment as the frame lights by it, tint and turn included. */- sky?: SkyRadiance;+ * environment as the frame lights by it, tint and turn included. A bake split+ * across threads needs it as data. */+ sky?: SkySpec | SkyRadiance;/** Texels the solved edges are smeared outwards, so a bilinear tap near a* chart's border does not read the empty atlas beside it. */dilate?: number;@@ -99,17 +104,18 @@ const chan = (m: MeshData, s: number): MeshChannelDesc | undefined =>/** Every surface's triangles in world space, plus what a ray hit has to know. */function collect(surfaces: readonly BakeSurface[], patches: readonly SurfacePatch[],- size: number, texelsPerUnit: number): { soup: TriangleSoup; lookup: HitLookup } {+ size: number, texelsPerUnit: number,+ alloc: BakeAlloc): { soup: TriangleSoup; lookup: HitLookup } {let total = 0;for (const s of surfaces) total += Math.floor(s.mesh.indices.length / 3);- const positions = new Float32Array(total * 9);- const triUV = new Float32Array(total * 6);- const triSurface = new Int32Array(total);- const patch = new Float32Array(surfaces.length * 4);- const albedo = new Float32Array(surfaces.length * 3);- const triNormal = new Float32Array(total * 3);- const twoSided = new Uint8Array(surfaces.length);- const coverage = new Float32Array(surfaces.length);+ const positions = alloc.f32(total * 9);+ const triUV = alloc.f32(total * 6);+ const triSurface = alloc.i32(total);+ const patch = alloc.f32(surfaces.length * 4);+ const albedo = alloc.f32(surfaces.length * 3);+ const triNormal = alloc.f32(total * 3);+ const twoSided = alloc.u8(surfaces.length);+ const coverage = alloc.f32(surfaces.length);let at = 0;for (let s = 0; s < surfaces.length; s++) {@@ -258,32 +264,75 @@ function refusal(surfaces: readonly BakeSurface[], size: number, texelsPerUnit:+ ` The largest: ${named}${sparse}`;}+/** Everything a solve step reads, as arrays another thread can be handed. */+export interface BakeScene {+ lumels: LumelField;+ bvh: BvhParts;+ lookup: HitLookup;+ lights: readonly BakeLight[];+ sky: SkySpec | SkyRadiance;+ atlasSize: number;+ samples: number;+}++/** One pass over every lumel. Each writes only its own lumels' entries of `out`,+ * so any split of the range gives the same result. */+export type BakeJob =+ | { kind: 'direct'; out: Float32Array }+ | { kind: 'gather'; atlas: Float32Array; out: Float32Array };++export interface BakeStep {+ scene: BakeScene;+ job: BakeJob;+}++/** Runs jobs against one scene over any range of its lumels; one per thread. */+export function bakeRunner(scene: BakeScene): (job: BakeJob, from: number, to: number) => void {+ const bvh = new Bvh(scene.bvh);+ const sky = typeof scene.sky === 'function' ? scene.sky : skyRadiance(scene.sky);+ return (job, from, to) => {+ if (job.kind === 'direct') solveDirect(scene.lumels, bvh, scene.lookup, scene.lights, job.out, from, to);+ else solveGather(scene.lumels, bvh, scene.lookup, job.atlas, scene.atlasSize, scene.samples, sky, job.out, from, to);+ };+}+/**- * Bakes `lights` into an atlas the surfaces can be read through.- *- * Throws when the surfaces do not fit: a bake that quietly shrank someone would- * light one wall at a different resolution from the next, and the caller is the- * one who can decide between a bigger atlas and a coarser density.+ * A bake as its passes, in order: the driver runs each yielded job over every+ * lumel, on one thread or many, before asking for the next; `alloc` decides where+ * a job's arrays live. Throws when the surfaces do not fit rather than shrinking+ * one, which would light it at a different resolution from its neighbours.*/-export function bakeLightmap(surfaces: readonly BakeSurface[], lights: readonly BakeLight[],- options: BakeOptions = {}): BakeResult {+export function* bakeLightmapSteps(surfaces: readonly BakeSurface[], lights: readonly BakeLight[],+ options: BakeOptions = {},+ alloc: BakeAlloc = plainAlloc): Generator<BakeStep, BakeResult, void> {const opts = { ...BAKE_DEFAULTS, ...options };const size = opts.atlasSize;const patches = layoutAtlas(surfaces, size, opts.texelsPerUnit);if (!patches) throw new Error(refusal(surfaces, size, opts.texelsPerUnit));- const lumels = rasterizeLumels(surfaces, patches, size);- const { soup, lookup } = collect(surfaces, patches, size, opts.texelsPerUnit);- const bvh = new Bvh(soup);+ const raster = rasterizeLumels(surfaces, patches, size);+ const lumels: LumelField = {+ count: raster.count,+ position: adopt(raster.position, alloc),+ normal: adopt(raster.normal, alloc),+ texel: adopt(raster.texel, alloc),+ surface: adopt(raster.surface, alloc),+ shared: raster.shared,+ };+ const { soup, lookup } = collect(surfaces, patches, size, opts.texelsPerUnit, alloc);+ const bvh = new Bvh(soup, alloc);+ const skyOf = options.sky ?? { kind: 'flat', rgb: opts.ambient };+ const scene: BakeScene = { lumels, bvh: bvh.parts(), lookup, lights, sky: skyOf,+ atlasSize: size, samples: opts.samples };+ const sky = typeof skyOf === 'function' ? skyOf : skyRadiance(skyOf);- const direct = new Float32Array(lumels.count * 3);- solveDirect(lumels, bvh, lookup, lights, direct);+ const direct = alloc.f32(lumels.count * 3);+ yield { scene, job: { kind: 'direct', out: direct } };// Each pass gathers against what every texel gave off after the pass before,// so pass n carries light n surfaces along. With no bounce the surfaces give// off nothing and the pass is the sky alone, still shadowed by them.- const sky = options.sky ?? flatSky(opts.ambient);- const outgoing = new Float32Array(size * size * 3);- const indirect = new Float32Array(lumels.count * 3);+ const outgoing = alloc.f32(size * size * 3);+ const indirect = alloc.f32(lumels.count * 3);for (let pass = 0; pass < Math.max(1, opts.bounces); pass++) {if (opts.bounces > 0) {for (let i = 0; i < lumels.count; i++) {@@ -291,7 +340,7 @@ export function bakeLightmap(surfaces: readonly BakeSurface[], lights: readonlyfor (let k = 0; k < 3; k++) outgoing[at + k] = direct[i * 3 + k] + indirect[i * 3 + k];}}- solveGather(lumels, bvh, lookup, outgoing, size, opts.samples, sky, indirect);+ yield { scene, job: { kind: 'gather', atlas: outgoing, out: indirect } };}// Two fields: what each texel gives off, which probes and captures read, and@@ -335,3 +384,16 @@ export function bakeLightmap(surfaces: readonly BakeSurface[], lights: readonlyreflections,};}++/** {@link bakeLightmapSteps} driven on this thread. */+export function bakeLightmap(surfaces: readonly BakeSurface[], lights: readonly BakeLight[],+ options: BakeOptions = {}): BakeResult {+ const steps = bakeLightmapSteps(surfaces, lights, options);+ let runner: ReturnType<typeof bakeRunner> | null = null;+ for (;;) {+ const next = steps.next();+ if (next.done) return next.value;+ runner ??= bakeRunner(next.value.scene);+ runner(next.value.job, 0, next.value.scene.lumels.count);+ }+}diff --git a/sdk/src/lightmap/bvh.ts b/sdk/src/lightmap/bvh.tsindex 9e9a238ec..1e8ae15c7 100644--- a/sdk/src/lightmap/bvh.ts+++ b/sdk/src/lightmap/bvh.ts@@ -10,12 +10,24 @@* cost of the pass.*/+import { plainAlloc, type BakeAlloc } from './alloc';+/** Triangles as `9 * count` floats: three world-space corners each. */export interface TriangleSoup {positions: Float32Array;count: number;}+/** A built tree as plain arrays, which another thread can walk without rebuilding. */+export interface BvhParts {+ tris: TriangleSoup;+ bounds: Float32Array;+ node: Int32Array;+ order: Int32Array;+ used: number;+ depth: number;+}+const LEAF_TRIS = 4;/** The count an inner node carries: a leaf's is never negative, an empty one included. */const INNER = -1;@@ -36,18 +48,33 @@ export class Bvh {* fixed stack drops the deepest ones without a word. */private readonly stack: Int32Array;- constructor(tris: TriangleSoup) {- this.tris = tris;- this.order = new Int32Array(tris.count);- for (let i = 0; i < tris.count; i++) this.order[i] = i;- const maxNodes = Math.max(1, tris.count * 2);- this.bounds = new Float32Array(maxNodes * 6);- this.node = new Int32Array(maxNodes * 2);- this.used = 1;- this.build(0, 0, tris.count, 0);+ constructor(tris: TriangleSoup | BvhParts, alloc: BakeAlloc = plainAlloc) {+ if ('bounds' in tris) {+ this.tris = tris.tris;+ this.order = tris.order;+ this.bounds = tris.bounds;+ this.node = tris.node;+ this.used = tris.used;+ this.depth = tris.depth;+ } else {+ this.tris = tris;+ this.order = alloc.i32(tris.count);+ for (let i = 0; i < tris.count; i++) this.order[i] = i;+ const maxNodes = Math.max(1, tris.count * 2);+ this.bounds = alloc.f32(maxNodes * 6);+ this.node = alloc.i32(maxNodes * 2);+ this.used = 1;+ this.build(0, 0, tris.count, 0);+ }this.stack = new Int32Array(this.depth + 2);}+ /** The tree as arrays, to walk from another thread with `new Bvh(parts)`. */+ parts(): BvhParts {+ return { tris: this.tris, bounds: this.bounds, node: this.node, order: this.order,+ used: this.used, depth: this.depth };+ }+private centroid(tri: number, axis: number): number {const at = this.order[tri] * 9;return (this.tris.positions[at + axis] + this.tris.positions[at + 3 + axis]diff --git a/sdk/src/lightmap/index.ts b/sdk/src/lightmap/index.tsindex 63a6634d2..242aa99b9 100644--- a/sdk/src/lightmap/index.ts+++ b/sdk/src/lightmap/index.ts@@ -1,7 +1,10 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamexport { unwrapLightmapUV, type UnwrapOptions, type UnwrapResult } from './unwrap';-export { bakeLightmap, LIGHTMAP_RANGE, encodeLightmap, decodeLightmap, type BakeOptions, type BakeResult } from './bake';+export { bakeLightmap, bakeLightmapSteps, bakeRunner, LIGHTMAP_RANGE, encodeLightmap, decodeLightmap,+ type BakeOptions, type BakeResult, type BakeScene, type BakeJob, type BakeStep } from './bake';+export { skyRadiance, type SkySpec } from './sky';+export type { BakeAlloc } from './alloc';export type { BakeSurface } from './atlas';export type { BakeLight } from './solve';export { solveProbes, probeAt, type ProbeGrid } from './probes';diff --git a/sdk/src/lightmap/sky.ts b/sdk/src/lightmap/sky.tsnew file mode 100644index 000000000..47b238cf8--- /dev/null+++ b/sdk/src/lightmap/sky.ts@@ -0,0 +1,38 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file sky.ts+ * @brief The sky a gather sees, as data: a bake that runs on several threads+ * hands each one the description, and a closure cannot cross.+ */++import type { SkyRadiance } from './reflection';+import { SH_COSINE_BAND, evalIrradianceSH } from './sh';++/** A sky a bake can pass between threads. */+export type SkySpec =+ | { kind: 'flat'; rgb: readonly [number, number, number] }+ /** An environment's nine irradiance coefficients as the frame reads them:+ * turned `yaw` radians about +Y and scaled by `tint`. */+ | { kind: 'sh'; irradiance: readonly number[]; yaw: number; tint: readonly [number, number, number] };++/**+ * The radiance along each direction whose cosine-weighted mean over an open+ * hemisphere is the spec's irradiance there: the coefficients unconvolved, so an+ * uncovered floor gathers exactly what the frame would light it with.+ */+export function skyRadiance(spec: SkySpec): SkyRadiance {+ if (spec.kind === 'flat') {+ const [r, g, b] = spec.rgb;+ return (_dx, _dy, _dz, out, at) => { out[at] = r; out[at + 1] = g; out[at + 2] = b; };+ }+ const radiance = Float32Array.from(spec.irradiance.slice(0, 27), (v, i) => v / SH_COSINE_BAND[Math.floor(i / 3)]!);+ const c = Math.cos(spec.yaw), s = Math.sin(spec.yaw);+ const [tr, tg, tb] = spec.tint;+ return (dx, dy, dz, out, at) => {+ const [r, g, b] = evalIrradianceSH(radiance, c * dx + s * dz, dy, -s * dx + c * dz);+ out[at] = Math.max(0, r) * tr;+ out[at + 1] = Math.max(0, g) * tg;+ out[at + 2] = Math.max(0, b) * tb;+ };+}diff --git a/sdk/src/lightmap/solve.ts b/sdk/src/lightmap/solve.tsindex 87b4bed60..c48cf8275 100644--- a/sdk/src/lightmap/solve.ts+++ b/sdk/src/lightmap/solve.ts@@ -152,9 +152,9 @@ function frame(nx: number, ny: number, nz: number, out: Float32Array): void {* here: it reaches a lumel past whatever stands in the way, so it is gathered.*/export function solveDirect(lumels: LumelField, bvh: Bvh, lookup: HitLookup,- lights: readonly BakeLight[], out: Float32Array): void {- out.fill(0);- for (let i = 0; i < lumels.count; i++) {+ lights: readonly BakeLight[], out: Float32Array,+ from = 0, to = lumels.count): void {+ for (let i = from; i < to; i++) {const px = lumels.position[i * 3], py = lumels.position[i * 3 + 1], pz = lumels.position[i * 3 + 2];const nx = lumels.normal[i * 3], ny = lumels.normal[i * 3 + 1], nz = lumels.normal[i * 3 + 2];let r = 0, g = 0, b = 0;@@ -207,12 +207,12 @@ export function solveDirect(lumels: LumelField, bvh: Bvh, lookup: HitLookup,*/export function solveGather(lumels: LumelField, bvh: Bvh, lookup: HitLookup,atlas: Float32Array, atlasSize: number, samples: number,- sky: SkyRadiance, out: Float32Array): void {+ sky: SkyRadiance, out: Float32Array, from = 0, to = lumels.count): void {const dirs = hemisphere(samples);const basis = new Float32Array(6);const seen = new Float32Array(3);const far = 1e7;- for (let i = 0; i < lumels.count; i++) {+ for (let i = from; i < to; i++) {const px = lumels.position[i * 3], py = lumels.position[i * 3 + 1], pz = lumels.position[i * 3 + 2];const nx = lumels.normal[i * 3], ny = lumels.normal[i * 3 + 1], nz = lumels.normal[i * 3 + 2];frame(nx, ny, nz, basis);diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 5fcb4a6f7..3035bfbfb 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -1278,6 +1278,10 @@ export const NOTED = {{ note: 'The editor stays responsive while it bakes' },'feat(bake): baked light is a lit surface\'s indirect light':{ note: 'Baked light is a lit surface\'s indirect light' },+ 'perf(bake): a bake uses every core':+ { note: 'A bake uses every core' },+ 'perf(bake): the editor bakes on every core':+ { note: 'A bake uses every core' },'fix(bake): a coloured light bakes the colour it lights with':{ note: 'A coloured light bakes the colour it lights with' },'fix(bake): the collector reads the colour space from the engine host':