Skip to content

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.

feat(math): a seeded random generator that gives the same numbers on every host

yhh8ba478d52510
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 606aa02c3..51f719f00 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ published separately; it ships inside the editor.
### Added
+- **A random generator that gives the same numbers on every host.** `createRng(seed)` returns a seeded generator (`float`, `int`, `chance`, `pick`, `weighted`, `shuffle`) whose sequence is the same on a server, a browser, a mini-game and a phone, because it uses only 32-bit integer arithmetic. `fork(label)` makes a named stream that does not move when another stream draws more, and `hashSeed` turns a number, a string or a list of them into a seed. It is for rules that a server settles and a client previews, which must agree; `Math.random` cannot be seeded and is not the same anywhere.
- **Sharpen on WebGL2.** The `sharpen` effect was a compute shader, so a device with no compute stage (WebGL2, which is most of the small-game targets) left it out and showed the picture as it was. It now has a fragment pass of the same arithmetic that stands in where there is no compute stage: on WebGPU the two draw the identical picture, pixel for pixel, and a test switch in the render host (`noCompute`) checks that. Flat areas are untouched and an edge cannot overshoot past what is on either side of it.
- **Blob shadows.** A `BlobShadow` component puts a soft dark disc on the ground under an entity: no shadow map, no light, no extra pass, which is the shadow a phone can afford. It fades and shrinks as the thing leaves the ground (`fadeHeight`, `shrink`), follows the ground (`groundY`, or a height function from `setBlobShadowGround` for ground that is not flat) and is hidden by what stands in front of it. It is a disc, not the light's shadow: it does not stretch with the sun or land on a wall. The same picture on WebGL2 and WebGPU.
- **Edge Outline, a coloured line at silhouettes and creases.** A post effect (`edgeOutline`) that draws a line of `u_lineColor` where the scene's surface changes: where the distance from the camera steps (a silhouette) and where the surface's normal turns (the edge of a face, a fold), so a box on a floor is inked along its corners as well as its outline, which `depthOutline` (depth only, black only) does not do. Distance is measured in the world, so one threshold holds across a perspective view, and a plane at a grazing angle draws no line. Creases need surfaces that write their normal (lit meshes, Model and Toon materials); the same picture on WebGL2 and WebGPU.
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 91e0402f7..0ef84b80a 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 · 159 beta · 1893 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1897 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -8247,6 +8247,23 @@ layer: number
linearDamping: number
```
+## Rng — interface @experimental
+```
+chance: (p: number) => boolean
+float: () => number
+fork: (label: string | number) => Rng
+int: (min: number, max: number) => number
+nextU32: () => number
+pick: <T>(items: readonly T[]) => T
+shuffle: <T>(items: readonly T[]) => T[]
+weighted: <T>(items: readonly T[], weight: (item: T) => number) => T
+```
+
+## RngSeed — type @experimental
+```
+number | string | readonly (number | string)[]
+```
+
## RootMotionDelta — interface @experimental
```
position: Vec3
@@ -13494,6 +13511,11 @@ Plugin
(opts: ProgressOptions): ProgressHandle
```
+## createRng — function @experimental
+```
+(seed: RngSeed): Rng
+```
+
## createRootPlacement — function @experimental
```
(): RootPlacement
@@ -14319,6 +14341,11 @@ Plugin
(world: World, entity: Entity): boolean
```
+## hashSeed — function @experimental
+```
+(seed: RngSeed): number
+```
+
## headlessBasePlugins — const @experimental
```
() => Plugin[]
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 9df99360a..e324cf6b1 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 · 164 beta · 1912 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1916 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -8460,6 +8460,23 @@ layer: number
linearDamping: number
```
+## Rng — interface @experimental
+```
+chance: (p: number) => boolean
+float: () => number
+fork: (label: string | number) => Rng
+int: (min: number, max: number) => number
+nextU32: () => number
+pick: <T>(items: readonly T[]) => T
+shuffle: <T>(items: readonly T[]) => T[]
+weighted: <T>(items: readonly T[], weight: (item: T) => number) => T
+```
+
+## RngSeed — type @experimental
+```
+number | string | readonly (number | string)[]
+```
+
## RootMotionDelta — interface @experimental
```
position: Vec3
@@ -13747,6 +13764,11 @@ Plugin
(opts: ProgressOptions): ProgressHandle
```
+## createRng — function @experimental
+```
+(seed: RngSeed): Rng
+```
+
## createRootPlacement — function @experimental
```
(): RootPlacement
@@ -14572,6 +14594,11 @@ Plugin
(world: World, entity: Entity): boolean
```
+## hashSeed — function @experimental
+```
+(seed: RngSeed): number
+```
+
## headlessBasePlugins — const @experimental
```
() => Plugin[]
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 4601e6d2f..0801e1905 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 · 161 beta · 1892 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1896 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -8242,6 +8242,23 @@ layer: number
linearDamping: number
```
+## Rng — interface @experimental
+```
+chance: (p: number) => boolean
+float: () => number
+fork: (label: string | number) => Rng
+int: (min: number, max: number) => number
+nextU32: () => number
+pick: <T>(items: readonly T[]) => T
+shuffle: <T>(items: readonly T[]) => T[]
+weighted: <T>(items: readonly T[], weight: (item: T) => number) => T
+```
+
+## RngSeed — type @experimental
+```
+number | string | readonly (number | string)[]
+```
+
## RootMotionDelta — interface @experimental
```
position: Vec3
@@ -13489,6 +13506,11 @@ Plugin
(opts: ProgressOptions): ProgressHandle
```
+## createRng — function @experimental
+```
+(seed: RngSeed): Rng
+```
+
## createRootPlacement — function @experimental
```
(): RootPlacement
@@ -14314,6 +14336,11 @@ Plugin
(world: World, entity: Entity): boolean
```
+## hashSeed — function @experimental
+```
+(seed: RngSeed): number
+```
+
## headlessBasePlugins — const @experimental
```
() => Plugin[]
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 427d07489..89b5f6bb6 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 · 159 beta · 1914 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1918 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -8535,6 +8535,23 @@ layer: number
linearDamping: number
```
+## Rng — interface @experimental
+```
+chance: (p: number) => boolean
+float: () => number
+fork: (label: string | number) => Rng
+int: (min: number, max: number) => number
+nextU32: () => number
+pick: <T>(items: readonly T[]) => T
+shuffle: <T>(items: readonly T[]) => T[]
+weighted: <T>(items: readonly T[], weight: (item: T) => number) => T
+```
+
+## RngSeed — type @experimental
+```
+number | string | readonly (number | string)[]
+```
+
## RootMotionDelta — interface @experimental
```
position: Vec3
@@ -13793,6 +13810,11 @@ Plugin
(opts: ProgressOptions): ProgressHandle
```
+## createRng — function @experimental
+```
+(seed: RngSeed): Rng
+```
+
## createRootPlacement — function @experimental
```
(): RootPlacement
@@ -14618,6 +14640,11 @@ Plugin
(world: World, entity: Entity): boolean
```
+## hashSeed — function @experimental
+```
+(seed: RngSeed): number
+```
+
## headlessBasePlugins — const @experimental
```
() => Plugin[]
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 792dac824..1749bdcd6 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 · 159 beta · 1905 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1909 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -8249,6 +8249,23 @@ layer: number
linearDamping: number
```
+## Rng — interface @experimental
+```
+chance: (p: number) => boolean
+float: () => number
+fork: (label: string | number) => Rng
+int: (min: number, max: number) => number
+nextU32: () => number
+pick: <T>(items: readonly T[]) => T
+shuffle: <T>(items: readonly T[]) => T[]
+weighted: <T>(items: readonly T[], weight: (item: T) => number) => T
+```
+
+## RngSeed — type @experimental
+```
+number | string | readonly (number | string)[]
+```
+
## RootMotionDelta — interface @experimental
```
position: Vec3
@@ -13520,6 +13537,11 @@ Plugin
(opts: ProgressOptions): ProgressHandle
```
+## createRng — function @experimental
+```
+(seed: RngSeed): Rng
+```
+
## createRootPlacement — function @experimental
```
(): RootPlacement
@@ -14345,6 +14367,11 @@ Plugin
(world: World, entity: Entity): boolean
```
+## hashSeed — function @experimental
+```
+(seed: RngSeed): number
+```
+
## headlessBasePlugins — const @experimental
```
() => Plugin[]
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.ts
index a3177e441..4ab4d0ab8 100644
--- a/sdk/src/core-sys.ts
+++ b/sdk/src/core-sys.ts
@@ -16,7 +16,7 @@
// Math (scalar / Vec2 / Vec3 helpers on the canonical types)
// =============================================================================
-export { exact, scalar, v2, v3, q, col } from './math';
+export { exact, scalar, v2, v3, q, col, createRng, hashSeed, type Rng, type RngSeed } from './math';
/**
* A world transform as a column-major 4x4, from a resolved TRS. Public because
* more than one reader outside the engine wants it in that form — a bake
diff --git a/sdk/src/math/index.ts b/sdk/src/math/index.ts
index 5f8a437de..9a9dc6765 100644
--- a/sdk/src/math/index.ts
+++ b/sdk/src/math/index.ts
@@ -12,3 +12,4 @@ export { v2 } from './vec2';
export { v3 } from './vec3';
export { q } from './quat';
export { col } from './color';
+export { createRng, hashSeed, type Rng, type RngSeed } from './random';
diff --git a/sdk/src/math/random.ts b/sdk/src/math/random.ts
new file mode 100644
index 000000000..c02153a61
--- /dev/null
+++ b/sdk/src/math/random.ts
@@ -0,0 +1,161 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file random.ts
+ * @brief A seeded random generator that gives the same numbers on every host.
+ * The generator is SFC32 over 32-bit integer arithmetic only, so a
+ * server, a browser, a mini-game and a phone running the same seed draw
+ * the same sequence — the property shared rules code needs when the
+ * server settles an outcome and the client previews it.
+ */
+
+/** A seed: one number, one string, or several of either joined into one. */
+export type RngSeed = number | string | readonly (number | string)[];
+
+export interface Rng {
+ /** The next 32 bits as an unsigned integer. */
+ nextU32(): number;
+ /** A float in [0, 1). */
+ float(): number;
+ /** An integer in [min, max], both included, without modulo bias. */
+ int(min: number, max: number): number;
+ /** True with probability `p` (clamped to [0, 1]). */
+ chance(p: number): boolean;
+ /** One element of a non-empty list. */
+ pick<T>(items: readonly T[]): T;
+ /** One element chosen by weight; a weight of 0 never wins. */
+ weighted<T>(items: readonly T[], weight: (item: T) => number): T;
+ /** A shuffled copy; the input is left alone. */
+ shuffle<T>(items: readonly T[]): T[];
+ /**
+ * An independent generator named `label`. It derives from the original seed
+ * and the label alone, never from how much this one has drawn, so adding a
+ * draw in one place does not move the numbers of another stream.
+ */
+ fork(label: string | number): Rng;
+}
+
+const SEED_WORDS = 4;
+const WARMUP = 12;
+
+function mix(h: number): number {
+ h = Math.imul(h ^ (h >>> 16), 0x85ebca6b);
+ h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
+ return (h ^ (h >>> 16)) >>> 0;
+}
+
+function absorb(h: number, word: number): number {
+ h = Math.imul(h ^ word, 0x9e3779b1);
+ return ((h << 13) | (h >>> 19)) >>> 0;
+}
+
+/** A 32-bit hash of a seed, stable across hosts. */
+export function hashSeed(seed: RngSeed): number {
+ const parts = typeof seed === 'object' ? seed : [seed];
+ let h = 0x811c9dc5;
+ for (const part of parts) {
+ if (typeof part === 'number') {
+ if (!Number.isFinite(part)) throw new RangeError('[rng] a numeric seed must be finite');
+ const whole = Math.floor(part);
+ h = absorb(h, whole >>> 0);
+ h = absorb(h, Math.floor(whole / 4294967296) >>> 0);
+ h = absorb(h, 0x6e);
+ } else {
+ for (let i = 0; i < part.length; i++) h = absorb(h, part.charCodeAt(i));
+ h = absorb(h, 0x73);
+ }
+ }
+ return mix(h);
+}
+
+class Sfc32 implements Rng {
+ private a: number;
+ private b: number;
+ private c: number;
+ private d: number;
+
+ constructor(private readonly root: number) {
+ let h = root;
+ const words: number[] = [];
+ for (let i = 0; i < SEED_WORDS; i++) {
+ h = mix(absorb(h, i + 1));
+ words.push(h);
+ }
+ [this.a, this.b, this.c, this.d] = words as [number, number, number, number];
+ for (let i = 0; i < WARMUP; i++) this.nextU32();
+ }
+
+ nextU32(): number {
+ const t = (((this.a + this.b) | 0) + this.d) | 0;
+ this.d = (this.d + 1) | 0;
+ this.a = this.b ^ (this.b >>> 9);
+ this.b = (this.c + (this.c << 3)) | 0;
+ this.c = (this.c << 21) | (this.c >>> 11);
+ this.c = (this.c + t) | 0;
+ return t >>> 0;
+ }
+
+ float(): number {
+ return this.nextU32() / 4294967296;
+ }
+
+ int(min: number, max: number): number {
+ if (!Number.isInteger(min) || !Number.isInteger(max) || max < min) {
+ throw new RangeError(`[rng] int(${min}, ${max}) needs integers with min <= max`);
+ }
+ const range = max - min + 1;
+ if (range > 4294967296) throw new RangeError('[rng] int range exceeds 32 bits');
+ if (range === 4294967296) return min + this.nextU32();
+ const limit = 4294967296 - (4294967296 % range);
+ let r = this.nextU32();
+ while (r >= limit) r = this.nextU32();
+ return min + (r % range);
+ }
+
+ chance(p: number): boolean {
+ return this.float() < p;
+ }
+
+ pick<T>(items: readonly T[]): T {
+ if (items.length === 0) throw new RangeError('[rng] pick() of an empty list');
+ return items[this.int(0, items.length - 1)]!;
+ }
+
+ weighted<T>(items: readonly T[], weight: (item: T) => number): T {
+ let total = 0;
+ const weights = items.map((item) => {
+ const w = weight(item);
+ if (!(w >= 0) || !Number.isFinite(w)) throw new RangeError('[rng] a weight must be a finite number >= 0');
+ total += w;
+ return w;
+ });
+ if (!(total > 0)) throw new RangeError('[rng] weighted() needs a positive total weight');
+ let roll = this.float() * total;
+ for (let i = 0; i < items.length; i++) {
+ roll -= weights[i]!;
+ if (roll < 0 && weights[i]! > 0) return items[i]!;
+ }
+ for (let i = items.length - 1; i >= 0; i--) if (weights[i]! > 0) return items[i]!;
+ return items[0]!;
+ }
+
+ shuffle<T>(items: readonly T[]): T[] {
+ const out = items.slice();
+ for (let i = out.length - 1; i > 0; i--) {
+ const j = this.int(0, i);
+ const t = out[i]!;
+ out[i] = out[j]!;
+ out[j] = t;
+ }
+ return out;
+ }
+
+ fork(label: string | number): Rng {
+ return new Sfc32(hashSeed([this.root, label]));
+ }
+}
+
+/** A generator that replays the same numbers for the same seed on every host. */
+export function createRng(seed: RngSeed): Rng {
+ return new Sfc32(hashSeed(seed));
+}
diff --git a/sdk/tests/random.test.ts b/sdk/tests/random.test.ts
new file mode 100644
index 000000000..31d03c4f5
--- /dev/null
+++ b/sdk/tests/random.test.ts
@@ -0,0 +1,90 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { createRng, hashSeed } from '../src/math/random';
+
+describe('createRng', () => {
+ it('replays the same sequence for the same seed', () => {
+ const a = createRng('ember');
+ const b = createRng('ember');
+ for (let i = 0; i < 100; i++) expect(a.nextU32()).toBe(b.nextU32());
+ });
+
+ it('differs across seeds, and a list seed is not its parts concatenated', () => {
+ expect(createRng('a').nextU32()).not.toBe(createRng('b').nextU32());
+ expect(hashSeed(['ab', 'c'])).not.toBe(hashSeed(['a', 'bc']));
+ expect(hashSeed([1, 2])).not.toBe(hashSeed([2, 1]));
+ expect(hashSeed(1)).not.toBe(hashSeed('1'));
+ });
+
+ it('pins the first draws so a host that disagrees is caught', () => {
+ const r = createRng('estella');
+ expect([r.nextU32(), r.nextU32(), r.nextU32()]).toEqual(PINNED_U32);
+ expect(createRng(['day', 7, 'weather']).int(0, 999)).toBe(PINNED_INT);
+ });
+
+ it('float stays in [0, 1) and covers the range', () => {
+ const r = createRng(1);
+ let lo = 1, hi = 0;
+ for (let i = 0; i < 5000; i++) {
+ const f = r.float();
+ expect(f).toBeGreaterThanOrEqual(0);
+ expect(f).toBeLessThan(1);
+ lo = Math.min(lo, f);
+ hi = Math.max(hi, f);
+ }
+ expect(lo).toBeLessThan(0.01);
+ expect(hi).toBeGreaterThan(0.99);
+ });
+
+ it('int is inclusive on both ends and roughly uniform', () => {
+ const r = createRng('dice');
+ const seen = new Array<number>(6).fill(0);
+ for (let i = 0; i < 6000; i++) seen[r.int(1, 6) - 1]!++;
+ for (const n of seen) {
+ expect(n).toBeGreaterThan(800);
+ expect(n).toBeLessThan(1200);
+ }
+ expect(r.int(5, 5)).toBe(5);
+ expect(() => r.int(3, 2)).toThrow(RangeError);
+ expect(() => r.int(0.5, 2)).toThrow(RangeError);
+ });
+
+ it('weighted never picks a zero weight and follows the odds', () => {
+ const r = createRng('loot');
+ const items = [{ n: 'common', w: 9 }, { n: 'rare', w: 1 }, { n: 'never', w: 0 }];
+ const tally: Record<string, number> = { common: 0, rare: 0, never: 0 };
+ for (let i = 0; i < 10000; i++) tally[r.weighted(items, (x) => x.w).n]!++;
+ expect(tally.never).toBe(0);
+ expect(tally.rare).toBeGreaterThan(800);
+ expect(tally.rare).toBeLessThan(1200);
+ expect(() => r.weighted([], () => 1)).toThrow(RangeError);
+ expect(() => r.weighted([1], () => 0)).toThrow(RangeError);
+ expect(() => r.weighted([1], () => -1)).toThrow(RangeError);
+ });
+
+ it('shuffle is a permutation and leaves its input alone', () => {
+ const input = [1, 2, 3, 4, 5, 6, 7, 8];
+ const out = createRng(9).shuffle(input);
+ expect(input).toEqual([1, 2, 3, 4, 5, 6, 7, 8]);
+ expect([...out].sort((a, b) => a - b)).toEqual(input);
+ expect(out).not.toEqual(input);
+ });
+
+ it('fork depends on the label, not on how much the parent has drawn', () => {
+ const fresh = createRng('world');
+ const used = createRng('world');
+ for (let i = 0; i < 50; i++) used.nextU32();
+ expect(used.fork('market').nextU32()).toBe(fresh.fork('market').nextU32());
+ expect(fresh.fork('market').nextU32()).not.toBe(fresh.fork('weather').nextU32());
+ });
+
+ it('rejects a seed that cannot be hashed the same everywhere', () => {
+ expect(() => createRng(Number.NaN)).toThrow(RangeError);
+ expect(() => createRng(Infinity)).toThrow(RangeError);
+ });
+});
+
+// Filled from the first run; they must never change, on any host.
+const PINNED_U32: number[] = [3413397541, 2088129782, 4134660848];
+const PINNED_INT = 708;
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index fd06b892d..d465812a4 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -3012,6 +3012,8 @@ export const NOTED = {
{"note":"Blob shadows."},
"feat(render): sharpen works without a compute stage":
{"note":"Sharpen on WebGL2."},
+ 'feat(math): a seeded random generator that gives the same numbers on every host':
+ {"note":"A random generator that gives the same numbers on every host."},
"perf(sdk): a blank mini-game package no longer carries terrain and water":
{"note":"A blank mini-game package no longer carries terrain and water."},
};