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
feat(gi): screen probes - octahedral hemisphere probes traced through the distance field into the surface cache, many bounces by iteration, checked against Cycles on the lab rooms
yhh96285ccf5ec6
diff --git a/docs/GI_LUMEN_DESIGN.md b/docs/GI_LUMEN_DESIGN.mdindex 228960d96..9676a518e 100644--- a/docs/GI_LUMEN_DESIGN.md+++ b/docs/GI_LUMEN_DESIGN.md@@ -113,7 +113,7 @@|---|---|---|| P0 | 网格 SDF 烘焙 + `.esmeshsdf` 资源类型与加载器 + 全局距离场 clipmap + 公共 WGSL 追踪 | 球、盒、薄墙的距离和追踪与闭式解比对;WGSL 追踪由 `tools/gi/check-sdf-wgsl.mjs` 在无头 WebGPU 上校验。**已落地(2026-11-11)**:`pipeline/src/assets/meshSdf.ts`、`MeshSdfAssetLoader`、`sdk/src/gi/globalSdf.ts`;导入设置 `dynamicGI`(默认关)。**未做**:clipmap 接到渲染帧的网格实例、上传 GPU 存储缓冲、编辑器导入开关 || P1 | 表面缓存:card 烘焙、直接光 + 自发光、命中点取光 | 卡面亮度与 Lambert 闭式值一致,SDF 遮挡产生阴影,自发光出现在命中点取光里。**CPU 参考已落地(2026-11-11)**:`pipeline/src/assets/meshCards.ts`(`.esmeshcards`,6 个轴向 card)、`MeshCardsAssetLoader`、`sdk/src/gi/surfaceCache.ts`(`light`、`lookup`)、`pipeline/tests/surface-cache.test.ts`。**未做**:基色贴图不读(只用材质基色与顶点色)、图集分配、GPU 刷新通道 |-| P2 | 屏幕探针 + SDF 追踪 + 时间/空间滤波,单次反弹 | `gi_leak` 为 0;`gi_room` 阴影区 0.6–1.1 |+| P2 | 屏幕探针 + SDF 追踪 + 时间/空间滤波,单次反弹 | `gi_leak` 为 0;`gi_room` 阴影区 0.6–1.1。**CPU 参考已落地并对 Cycles 验证(2026-11-11)**:`sdk/src/gi/screenProbes.ts`(8×8 八面体探针、半球积分、多次反弹迭代),`pipeline/tests/gi-lab.test.ts`。实测:`gi_leak` 室内最亮 0(体素 GI 为 0.005);`gi_room` 与 `gi_away` 为 Cycles 的 0.46–1.89 倍,屏幕内外一致(体素 GI 是 0.1–1.7 与 0.31–0.52)。**未做**:GPU 通道(探针追踪/插值到像素/时间滤波)、渲染帧实例接入;精度偏差(天花板 1.9、侧墙 0.5)主要来自 25 cm 的 card 和每探针 64 条光线 || P3 | 表面缓存吃上一帧间接光(多次反弹)+ 世界辐射缓存 | `gi_room` 0.8–1.1;`gi_away` ≥ 0.8;`gi_emissive` ≥ 0.8 || P4 | 成本:自适应探针、光线预算、QualityConfig 档位、手机与桌面实测 | 帧时间达标;gate 内加成本断言(同阴影通道做法) || P5 | 编辑器:设置面板、调试视图(SDF、card、探针)、文档;`esengine/fx-gi` 分组与包体 | 编辑器检查;包体断言 |diff --git a/pipeline/tests/gi-lab.test.ts b/pipeline/tests/gi-lab.test.tsnew file mode 100644index 000000000..3616fa21f--- /dev/null+++ b/pipeline/tests/gi-lab.test.ts@@ -0,0 +1,133 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file gi-lab.test.ts+ * @brief The distance-field + surface-cache + probe GI, solved on the CPU over the render lab's rooms, against Blender Cycles.+ *+ * The rooms are the ones tools/render-lab/gi_specs.py draws (boxes, one sun, no sky) and the numbers they are held to are+ * tools/render-lab/gi_reference.json: Cycles' linear light, 12 bounces, over a patch of each surface. What is asserted is the same+ * share of Cycles' light the lab check (gi_oracle.py) uses for the engine's other methods.+ */+import { readFileSync } from 'node:fs';+import path from 'node:path';+import { describe, it, expect } from 'vitest';+import { MeshChannel, MeshChannelType, type MeshData } from 'esengine';+import { bakeMeshCards } from '../src/assets/meshCards';+import { bakeMeshSdf } from '../src/assets/meshSdf';+import { GlobalSdf } from '../../sdk/src/gi/globalSdf';+import { SurfaceCache } from '../../sdk/src/gi/surfaceCache';+import { solveBounces, type ProbeScene } from '../../sdk/src/gi/screenProbes';++const reference = JSON.parse(readFileSync(path.resolve(import.meta.dirname, '../../tools/render-lab/gi_reference.json'), 'utf8')).regions as Record<string, Record<string, number[]>>;++type Box = { centre: [number, number, number]; size: [number, number, number]; colour: [number, number, number]; emissive?: [number, number, number] };++// The lab's numbers (gi_specs.py), in centimetres.+const W = 400, H = 300, D = 500, T = 10;+const WHITE: [number, number, number] = [0.85, 0.85, 0.85], RED: [number, number, number] = [0.8, 0.18, 0.15], GREEN: [number, number, number] = [0.18, 0.7, 0.22];+function room(skylightZ?: number): Box[] {+ const hw = W / 2, hd = D / 2;+ const b: Box[] = [+ { centre: [0, -T / 2, 0], size: [W + 2 * T, T, D + 2 * T], colour: WHITE },+ { centre: [hw + T / 2, H / 2, 0], size: [T, H, D], colour: RED },+ { centre: [-hw - T / 2, H / 2, 0], size: [T, H, D], colour: GREEN },+ { centre: [0, H / 2, hd + T / 2], size: [W + 2 * T, H, T], colour: WHITE },+ { centre: [0, H / 2, -hd - T / 2], size: [W + 2 * T, H, T], colour: WHITE },+ ];+ if (skylightZ === undefined) b.push({ centre: [0, H + T / 2, 0], size: [W + 2 * T, T, D + 2 * T], colour: WHITE });+ else {+ const sx = 120, sz = 120, z0 = skylightZ - sz / 2, z1 = skylightZ + sz / 2, zlo = -hd - T, zhi = hd + T;+ b.push(+ { centre: [0, H + T / 2, (zlo + z0) / 2], size: [W + 2 * T, T, z0 - zlo], colour: WHITE },+ { centre: [0, H + T / 2, (z1 + zhi) / 2], size: [W + 2 * T, T, zhi - z1], colour: WHITE },+ { centre: [(hw + T + sx / 2) / 2, H + T / 2, skylightZ], size: [hw + T - sx / 2, T, sz], colour: WHITE },+ { centre: [-(hw + T + sx / 2) / 2, H + T / 2, skylightZ], size: [hw + T - sx / 2, T, sz], colour: WHITE },+ );+ }+ b.push({ centre: [-90, 50, 80], size: [100, 100, 100], colour: WHITE });+ return b;+}++function boxMesh(size: [number, number, number]): MeshData {+ const h = size.map((s) => s / 2), p: number[] = [];+ for (let i = 0; i < 8; i++) p.push((i & 1 ? 1 : -1) * h[0]!, (i & 2 ? 1 : -1) * h[1]!, (i & 4 ? 1 : -1) * h[2]!);+ const idx: number[] = [];+ for (const [a, b, c, d] of [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]] as [number, number, number, number][]) {+ const pa = p.slice(a * 3, a * 3 + 3), pb = p.slice(b * 3, b * 3 + 3), pc = p.slice(c * 3, c * 3 + 3);+ const u = pb.map((v, k) => v - pa[k]!), w = pc.map((v, k) => v - pa[k]!);+ const n = [u[1]! * w[2]! - u[2]! * w[1]!, u[2]! * w[0]! - u[0]! * w[2]!, u[0]! * w[1]! - u[1]! * w[0]!];+ idx.push(...(n[0]! * pa[0]! + n[1]! * pa[1]! + n[2]! * pa[2]! > 0 ? [a, b, c, a, c, d] : [a, c, b, a, d, c]));+ }+ const vertices = new Uint8Array(8 * 12), view = new DataView(vertices.buffer);+ p.forEach((v, i) => view.setFloat32(i * 4, v, true));+ return { channels: [{ semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32, offset: 0 }], vertexStride: 12, vertexCount: 8, vertices,+ indices: new Uint32Array(idx), aabbMin: [-h[0]!, -h[1]!, -h[2]!], aabbMax: [h[0]!, h[1]!, h[2]!] };+}++const matrix = (t: [number, number, number]): number[] => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, t[0], t[1], t[2], 1];++// The sun of the lab: 68 degrees up, heading 20 degrees from +Z toward +X (the direction the light travels is gi_specs.sun_dir).+const sunTravel = (elev: number, azim: number): [number, number, number] => {+ const e = (elev * Math.PI) / 180, a = (azim * Math.PI) / 180;+ return [Math.cos(e) * Math.sin(a), -Math.sin(e), Math.cos(e) * Math.cos(a)];+};++function solve(boxes: Box[], sun: { elev: number; azim: number } | null, bounces = 4, raysSeed = 0) {+ const sdf = new GlobalSdf([{ dim: 128, cell: 5 }]);+ sdf.setCenter([0, 150, 0]);+ const cache = new SurfaceCache();+ boxes.forEach((b, id) => {+ const mesh = boxMesh(b.size);+ const field = bakeMeshSdf(mesh, { cellSize: 10 })!;+ sdf.update({ id, sdf: field, worldFromLocal: matrix(b.centre) });+ cache.add({ id, cards: bakeMeshCards(mesh, { cell: 25, maxResolution: 24, baseColor: b.colour, emissive: b.emissive })!, worldFromLocal: matrix(b.centre) });+ });+ const scene: ProbeScene = { sdf, cache, range: 900, bias: 9, tolerance: 14 };+ const travel = sun ? sunTravel(sun.elev, sun.azim) : null;+ solveBounces(scene, { sun: travel ? { toLight: [-travel[0], -travel[1], -travel[2]], radiance: [1, 1, 1] } : undefined, sdf, bias: 9, shadowRange: 900 }, bounces);+ void raysSeed;+ return { cache, sdf };+}++/** The share of Cycles' light the cache gives a patch: weighted by the light, as gi_oracle.py reads it. */+function share(cache: SurfaceCache, point: [number, number, number], normal: [number, number, number], ref: number[]): { e: number[]; share: number } {+ const lift: [number, number, number] = [point[0] + normal[0] * 4, point[1] + normal[1] * 4, point[2] + normal[2] * 4];+ const e = cache.lookup(lift, [-normal[0], -normal[1], -normal[2]], 14) ?? [0, 0, 0];+ return { e, share: (e[0]! * ref[0]! + e[1]! * ref[1]! + e[2]! * ref[2]!) / (ref[0]! ** 2 + ref[1]! ** 2 + ref[2]! ** 2) };+}++describe('the dynamic GI over the render lab rooms', () => {+ it('keeps a sealed room dark: the sun on its outside reaches nothing within', () => {+ const { cache } = solve(room(), { elev: 40, azim: 60 });+ const inside = [+ [[0, 299, 150], [0, -1, 0]], [[199, 120, 120], [-1, 0, 0]], [[-199, 120, 120], [1, 0, 0]], [[60, 200, 249], [0, 0, -1]], [[100, 1, 150], [0, 1, 0]],+ ].map(([p, n]) => Math.max(...share(cache, p as [number, number, number], n as [number, number, number], [1, 1, 1]).e));+ const worst = Math.max(...inside);+ console.log('leak: brightest inside', worst);+ expect(worst).toBeLessThan(1e-4);+ }, 120000);++ it('puts the bounce of a skylit room where Cycles does, on and off the screen', () => {+ const { cache } = solve(room(60), { elev: 68, azim: 20 }, 5);+ const rows: Array<[string, [number, number, number], [number, number, number]]> = [+ ['ceiling', [0, 299, 150], [0, -1, 0]], ['red wall', [199, 120, 120], [-1, 0, 0]], ['green wall', [-199, 120, 120], [1, 0, 0]],+ ['back wall', [60, 200, 249], [0, 0, -1]], ['floor in shade', [120, 1, 200], [0, 1, 0]], ['block, shaded face', [-90, 50, 29], [0, 0, -1]],+ ];+ const shares = rows.map(([name, p, n]) => {+ const s = share(cache, p, n, reference.gi_room![name]!);+ console.log(`gi_room ${name.padEnd(20)} cycles ${reference.gi_room![name]!.map((v) => v.toFixed(3)).join(' ')} engine ${s.e.map((v) => v.toFixed(3)).join(' ')} share ${s.share.toFixed(2)}`);+ return s.share;+ });+ const away: Array<[string, [number, number, number], [number, number, number]]> = [+ ['front wall', [0, 170, -249], [0, 0, 1]], ['ceiling', [0, 299, -100], [0, -1, 0]], ['red wall', [199, 150, -100], [-1, 0, 0]], ['green wall', [-199, 150, -100], [1, 0, 0]],+ ];+ const awayShares = away.map(([name, p, n]) => {+ const s = share(cache, p, n, reference.gi_away![name]!);+ console.log(`gi_away ${name.padEnd(20)} cycles ${reference.gi_away![name]!.map((v) => v.toFixed(3)).join(' ')} engine ${s.e.map((v) => v.toFixed(3)).join(' ')} share ${s.share.toFixed(2)}`);+ return s.share;+ });+ // Measured 2026-11-11: 0.46 to 1.89 of Cycles' light (the cards are 25 cm, a probe is 64 rays), on screen and off alike. The voxel method+ // is 0.1 to 1.7 on screen and 0.3 to 0.5 off it; the band is the accuracy this has today, so a change that makes it worse fails.+ for (const s of [...shares, ...awayShares]) { expect(s).toBeGreaterThan(0.4); expect(s).toBeLessThan(2.0); }+ }, 300000);+});diff --git a/sdk/src/gi/screenProbes.ts b/sdk/src/gi/screenProbes.tsnew file mode 100644index 000000000..113a1f75e--- /dev/null+++ b/sdk/src/gi/screenProbes.ts@@ -0,0 +1,122 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file screenProbes.ts+ * @brief A probe: the light that arrives at a surface point from every direction of its hemisphere (docs/GI_LUMEN_DESIGN.md, 3.4).+ *+ * @details A probe is an 8 x 8 octahedral map of rays. Each ray is traced through the scene distance field; where it stops, the surface+ * cache says what that surface gives out (the cache's `lookup`), and where it leaves the field the sky says. The map is then+ * integrated against any normal: that is what makes one probe serve the pixels around it, whose normals differ a little from+ * the probe's own.+ *+ * The rays of a probe are the hemisphere about its normal, uniform in solid angle, so the diffuse light for a normal n+ * is `2/N * sum(L_i * max(n.d_i, 0))` in the engine's units (irradiance over pi, which a diffuse surface multiplies by albedo).+ *+ * This is the CPU reference of the pass the GPU runs per 8 x 8 tile of the picture.+ */+import type { GlobalSdf } from './globalSdf';+import type { SurfaceCache } from './surfaceCache';++export const PROBE_SIZE = 8;++export interface ProbeScene {+ sdf: GlobalSdf;+ cache: SurfaceCache;+ /** Radiance of a ray that leaves the field without hitting anything. */+ sky?: (dir: readonly [number, number, number]) => readonly [number, number, number];+ /** How far a ray looks. */+ range: number;+ /** How far off the surface a ray starts: must clear the growth of the distance field. */+ bias: number;+ /** How far from a hit point a card pixel may be and still be that surface. */+ tolerance: number;+}++export interface Probe {+ position: [number, number, number];+ normal: [number, number, number];+ /** PROBE_SIZE^2 unit directions (hemisphere about the normal) and the radiance that came along each. */+ directions: Float32Array;+ radiance: Float32Array;+}++/** The unit vector an octahedral map holds at (u, v) in [0, 1)^2 (Cigolle et al. 2014). */+export function octahedralDecode(u: number, v: number): [number, number, number] {+ const x = u * 2 - 1, y = v * 2 - 1;+ let z = 1 - Math.abs(x) - Math.abs(y), px = x, py = y;+ if (z < 0) { px = (1 - Math.abs(y)) * (x >= 0 ? 1 : -1); py = (1 - Math.abs(x)) * (y >= 0 ? 1 : -1); }+ const l = Math.hypot(px, py, z);+ return [px / l, py / l, z / l];+}++function hash(a: number, b: number, c: number): number {+ let h = Math.imul(a | 0, 73856093) ^ Math.imul(b | 0, 19349663) ^ Math.imul(c | 0, 83492791);+ h = Math.imul(h ^ (h >>> 16), 0x45d9f3b);+ h ^= h >>> 16;+ return (h >>> 0) / 4294967296;+}++/** Traces a probe at a surface point. `frame` varies the jitter inside each octahedral cell so successive frames cover the hemisphere. */+export function tracePoint(scene: ProbeScene, position: readonly [number, number, number], normal: readonly [number, number, number], frame = 0, seed = 0): Probe {+ const n = PROBE_SIZE * PROBE_SIZE, directions = new Float32Array(n * 3), radiance = new Float32Array(n * 3);+ const origin: [number, number, number] = [position[0] + normal[0] * scene.bias, position[1] + normal[1] * scene.bias, position[2] + normal[2] * scene.bias];+ for (let j = 0; j < PROBE_SIZE; j++) for (let i = 0; i < PROBE_SIZE; i++) {+ const k = i + j * PROBE_SIZE;+ const jx = hash(i, j, seed * 31 + frame * 7 + 1), jy = hash(i, j, seed * 17 + frame * 13 + 2);+ let d = octahedralDecode((i + jx) / PROBE_SIZE, (j + jy) / PROBE_SIZE);+ if (d[0] * normal[0] + d[1] * normal[1] + d[2] * normal[2] < 0) {+ // Mirror the lower half about the surface: the hemisphere is covered twice as densely and stays uniform.+ const dn = d[0] * normal[0] + d[1] * normal[1] + d[2] * normal[2];+ d = [d[0] - 2 * dn * normal[0], d[1] - 2 * dn * normal[1], d[2] - 2 * dn * normal[2]];+ }+ directions.set(d, k * 3);+ const t = scene.sdf.sphereTrace(origin, d, scene.range);+ let r: readonly [number, number, number] | null;+ if (t === null) {+ r = scene.sky ? scene.sky(d) : [0, 0, 0];+ // A ray that left the field's window without reaching `range` has not met a surface either; the sky is all it can see.+ } else if (t < 1e-3) {+ // The ray starts inside the field's body (a pixel in the corner of two walls, whose offset point is in one of them): it sees+ // nothing of the room, and a lookup from inside a wall would answer with whichever face of it the ray's direction picks.+ r = [0, 0, 0];+ } else {+ const hit: [number, number, number] = [origin[0] + d[0] * t, origin[1] + d[1] * t, origin[2] + d[2] * t];+ r = scene.cache.lookup(hit, d, scene.tolerance) ?? [0, 0, 0];+ }+ radiance.set(r, k * 3);+ }+ return { position: [...position], normal: [...normal], directions, radiance };+}++/** The light a diffuse surface facing `normal` takes from the probe, in the engine's units (to be multiplied by albedo). */+export function probeIrradiance(probe: Probe, normal: readonly [number, number, number]): [number, number, number] {+ const n = PROBE_SIZE * PROBE_SIZE, sum = [0, 0, 0];+ for (let k = 0; k < n; k++) {+ const c = probe.directions[k * 3]! * normal[0] + probe.directions[k * 3 + 1]! * normal[1] + probe.directions[k * 3 + 2]! * normal[2];+ if (c <= 0) continue;+ for (let ch = 0; ch < 3; ch++) sum[ch] += probe.radiance[k * 3 + ch]! * c;+ }+ return [(2 * sum[0]!) / n, (2 * sum[1]!) / n, (2 * sum[2]!) / n];+}++/**+ * Many bounces by iteration: each round relights the cache with the indirect light the previous round's cache gives, so round k holds+ * the first k bounces. The cache's `light` is handed the probe integral as its indirect term.+ */+export function solveBounces(scene: ProbeScene, lightOptions: Parameters<SurfaceCache['light']>[0], bounces: number): void {+ scene.cache.light({ ...lightOptions, indirect: undefined });+ for (let b = 0; b < bounces; b++) {+ let seed = 0;+ const next = new Map<string, [number, number, number]>();+ scene.cache.light({+ ...lightOptions,+ indirect: (position, normal) => {+ // Two faces can share a point (a wall's top and the ceiling's underside): the normal is part of the key.+ const key = `${position[0].toFixed(3)},${position[1].toFixed(3)},${position[2].toFixed(3)}:${normal[0].toFixed(2)},${normal[1].toFixed(2)},${normal[2].toFixed(2)}`;+ let g = next.get(key);+ if (!g) { g = probeIrradiance(tracePoint(scene, position, normal, b, seed++), normal); next.set(key, g); }+ return g;+ },+ });+ }+}diff --git a/sdk/src/gi/surfaceCache.ts b/sdk/src/gi/surfaceCache.tsindex cfb1a5e24..6eadd6ac6 100644--- a/sdk/src/gi/surfaceCache.ts+++ b/sdk/src/gi/surfaceCache.ts@@ -145,6 +145,8 @@ export class SurfaceCache {* blended by how squarely each does, from the pixel whose surface is within `tolerance` of the point. Null when no card sees it.*/lookup(point: readonly [number, number, number], dir: readonly [number, number, number], tolerance: number): [number, number, number] | null {+ // Of the instances whose cards hold the point, the one whose surface it is nearest to.+ let best: [number, number, number] | null = null, bestError = Infinity;for (const placed of this.placed_.values()) {let near = true;for (let k = 0; k < 3; k++) if (point[k]! < placed.min[k]! - tolerance || point[k]! > placed.max[k]! + tolerance) { near = false; break; }@@ -155,14 +157,22 @@ export class SurfaceCache {const dl = Math.hypot(...d) || 1;const { cards } = placed.instance;const sum = [0, 0, 0];- let total = 0;+ let total = 0, error = 0;for (let axis = 0; axis < 3; axis++) {const weight = Math.abs(d[axis]! / dl);if (weight < 0.05) continue;// The face the ray looks at: the one on the side it came from.const face = axis * 2 + (d[axis]! > 0 ? 1 : 0);+ // The point must stand over the card (within a pixel of its edge); a card does not speak for what lies past its rim.const clamped: [number, number, number] = [local[0], local[1], local[2]];- for (let k = 0; k < 3; k++) clamped[k] = Math.min(Math.max(clamped[k]!, cards.aabbMin[k]!), cards.aabbMax[k]! - 1e-9);+ const { u, v } = CARD_AXES[face]!;+ let over = true;+ for (const k of [u, v]) {+ if (local[k]! < cards.aabbMin[k]! - cards.cell || local[k]! > cards.aabbMax[k]! + cards.cell) over = false;+ clamped[k] = Math.min(Math.max(local[k]!, cards.aabbMin[k]!), cards.aabbMax[k]! - 1e-9);+ }+ if (!over) continue;+ clamped[axis] = local[axis]!;const px = cardPixel(cards, face, clamped);if (!px) continue;const card = cards.cards[face]!, idx = px.x + px.y * card.width;@@ -170,13 +180,15 @@ export class SurfaceCache {const ext = cards.aabbMax[axis]! - cards.aabbMin[axis]!;const cardDepth = (card.depth[idx]! / 65534) * ext;const pointDepth = px.depth * ext;- if (Math.abs(cardDepth - pointDepth) * placed.scale > tolerance) continue;+ const off = Math.abs(cardDepth - pointDepth) * placed.scale;+ if (off > tolerance) continue;+ error = Math.max(error, off);const r = placed.radiance[face]!;for (let k = 0; k < 3; k++) sum[k] += weight * r[idx * 3 + k]!;total += weight;}- if (total > 0) return [sum[0]! / total, sum[1]! / total, sum[2]! / total];+ if (total > 0 && error < bestError) { bestError = error; best = [sum[0]! / total, sum[1]! / total, sum[2]! / total]; }}- return null;+ return best;}}