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(net): correction smoothing for prediction; fail-loud .tmx guidance

yhh10536a3c70e0
diff --git a/docs/astro/src/content/docs/guides/networking.mdx b/docs/astro/src/content/docs/guides/networking.mdx
index 6d1a321c6..7e9123709 100644
--- a/docs/astro/src/content/docs/guides/networking.mdx
+++ b/docs/astro/src/content/docs/guides/networking.mdx
@@ -189,6 +189,10 @@ never re-sends snap back. Owned entities bypass snapshot interpolation.
payload.
- `apply` must depend only on world state + actions + dt: it re-runs during
reconciliation.
+- **Smoothing**: `prediction: { apply, smoothing: { halfLife: 0.08 } }` eases
+ corrections out (the visual error halves every `halfLife` seconds) instead
+ of hard-snapping; add `maxError` so a genuine teleport still snaps. Purely
+ presentational — the simulation state can't drift.
## Best practices
diff --git a/docs/astro/src/content/docs/zh-cn/guides/networking.mdx b/docs/astro/src/content/docs/zh-cn/guides/networking.mdx
index 9f1fb2188..9bb24247d 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/networking.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/networking.mdx
@@ -174,6 +174,9 @@ clientNet.client.sendInput({ move: { x: 1, y: 0 } }); // pawn 立刻动
队列干涸时服务器会重复上一条指令,沉默意味着"继续保持",不是"停"。
- **`Replicated.owner` 在 spawn 时就要赋好**——归属随 spawn 载荷走。
- `apply` 只能依赖世界状态 + actions + dt:和解时它会被重放。
+- **平滑**:`prediction: { apply, smoothing: { halfLife: 0.08 } }` 让修正
+ 渐出(视觉误差每 `halfLife` 秒减半)而不是硬 snap;加 `maxError` 让真正的
+ 传送仍然瞬移。纯表现层——模拟状态不可能因此漂移。
## 最佳实践
diff --git a/examples/multiplayer-arena/src/net.ts b/examples/multiplayer-arena/src/net.ts
index 4de8f908a..81b01a4a4 100644
--- a/examples/multiplayer-arena/src/net.ts
+++ b/examples/multiplayer-arena/src/net.ts
@@ -116,7 +116,9 @@ export const sendInputSystem = defineSystem(
(net, input) => {
if (net.role !== 'client' || !net.client) return;
if (!net.client.predictionEnabled) {
- net.client.enablePrediction({ apply: applyMove });
+ // smoothing eases rare corrections out over ~80ms instead of
+ // snapping (both ends run the same rule, so they stay rare).
+ net.client.enablePrediction({ apply: applyMove, smoothing: { halfLife: 0.08 } });
}
net.client.sendInput({ move: readMove(input) });
},
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 6a63079c0..8d0b9bb39 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: 1116 stable · 17 beta · 1 deprecated
+Symbols: 1117 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -4337,6 +4337,13 @@ width: number
```
apply: (world: World, entity: Entity, actions: Record<string, unknown>, dt: number) => void
maxPendingInputs: number | undefined
+smoothing: PredictionSmoothing | undefined
+```
+
+## PredictionSmoothing — interface
+```
+halfLife: number
+maxError: number | undefined
```
## PrefabComponentData — interface
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index a4f954f1e..9a3f23b49 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: 1115 stable · 19 beta · 1 deprecated
+Symbols: 1116 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -4332,6 +4332,13 @@ width: number
```
apply: (world: World, entity: Entity, actions: Record<string, unknown>, dt: number) => void
maxPendingInputs: number | undefined
+smoothing: PredictionSmoothing | undefined
+```
+
+## PredictionSmoothing — interface
+```
+halfLife: number
+maxError: number | undefined
```
## PrefabComponentData — interface
diff --git a/sdk/src/asset/loaders/TilemapAssetLoader.ts b/sdk/src/asset/loaders/TilemapAssetLoader.ts
index 35a708d89..dea076562 100644
--- a/sdk/src/asset/loaders/TilemapAssetLoader.ts
+++ b/sdk/src/asset/loaders/TilemapAssetLoader.ts
@@ -12,6 +12,14 @@ export class TilemapAssetLoader implements AssetLoader<TilemapResult> {
async load(path: string, ctx: LoadContext): Promise<TilemapResult> {
const buildPath = ctx.catalog.getBuildPath(path);
const text = await ctx.loadText(buildPath);
+ // The engine has ONE Tiled parser and it speaks the JSON format. A
+ // .tmx (XML) map fails loud with the fix, not with a JSON syntax error
+ // — Tiled exports .tmj natively (File → Export As → JSON map files).
+ if (text.trimStart().startsWith('<')) {
+ throw new Error(
+ `[tilemap] "${path}" is a Tiled XML map — the engine parses the JSON format only. ` +
+ 'In Tiled: File → Export As → "JSON map files (*.tmj)", then reference the .tmj.');
+ }
// External .tsj tilesets resolve relative to the map, through the same
// text channel as the map itself.
const mapData = await parseTmjWithExternals(JSON.parse(text), (source) =>
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.ts
index 5c8242a4e..07e98c355 100644
--- a/sdk/src/core-sys.ts
+++ b/sdk/src/core-sys.ts
@@ -95,7 +95,7 @@ export {
radiusInterest,
type NetRoleKind, type ReplicatedData,
type InterestPolicy, type InterestView, type RadiusInterestOptions,
- type PredictionOptions,
+ type PredictionOptions, type PredictionSmoothing,
} from './net/replication';
// =============================================================================
diff --git a/sdk/src/net/replication/client.ts b/sdk/src/net/replication/client.ts
index 6572eedff..40c90d85c 100644
--- a/sdk/src/net/replication/client.ts
+++ b/sdk/src/net/replication/client.ts
@@ -35,7 +35,7 @@ import {
} from './protocol';
import {
buildReplicationTable, cloneValue, decodeStateFrame, tableSchemas,
- type EntityRefMap, type ReplicationTable, type StateFrame,
+ type EntityRefMap, type FieldShape, type ReplicationTable, type StateFrame,
} from './codec';
import { NetGhost, Replicated, type ReplicatedData } from './components';
import { NetIds } from './NetIds';
@@ -54,6 +54,50 @@ export interface PredictionOptions {
apply: (world: World, entity: Entity, actions: Record<string, unknown>, dt: number) => void;
/** Cap on unacknowledged commands kept for replay (default 120). */
maxPendingInputs?: number;
+ /**
+ * Ease reconciliation corrections out instead of hard-snapping: the
+ * numeric fields of owned entities keep a decaying visual error toward
+ * their pre-correction value. Purely presentational — the simulation
+ * rebuilds from the authority copy every tick regardless, so the error can
+ * never accumulate. Off by default (corrections snap).
+ */
+ smoothing?: PredictionSmoothing;
+}
+
+export interface PredictionSmoothing {
+ /** Seconds for the visual error to halve (typical: 0.05–0.15). */
+ halfLife: number;
+ /**
+ * Corrections larger than this (per numeric component) snap immediately —
+ * a teleport must look like a teleport. Default: no limit.
+ */
+ maxError?: number;
+}
+
+/** next + decayed (prev − next) over the numeric parts of a replicated field —
+ * shape-driven (the codec's FieldShape is the single source of what's numeric). */
+function smoothValue(shape: FieldShape, prev: unknown, next: unknown, keep: number, maxError: number): unknown {
+ if (shape.kind === 'f32') {
+ if (typeof prev !== 'number' || typeof next !== 'number') return next;
+ const err = prev - next;
+ if (Math.abs(err) > maxError) return next;
+ return next + err * keep;
+ }
+ if (shape.kind === 'object') {
+ if (prev === null || next === null || typeof prev !== 'object' || typeof next !== 'object') return next;
+ const out: Record<string, unknown> = { ...(next as Record<string, unknown>) };
+ for (let i = 0; i < shape.keys.length; i++) {
+ const k = shape.keys[i];
+ out[k] = smoothValue(
+ shape.shapes[i],
+ (prev as Record<string, unknown>)[k],
+ (next as Record<string, unknown>)[k],
+ keep, maxError,
+ );
+ }
+ return out;
+ }
+ return next;
}
export interface ReplicationClientOptions {
@@ -243,12 +287,31 @@ export class ReplicationClient {
}
}
- /** Rebuild every owned entity's live state as authority ⊕ pending replay.
- * Idempotent — running it on a tick with no new data reproduces the same
- * values, so it runs unconditionally each fixed step. */
+ /** Rebuild every owned entity's live state as authority ⊕ pending replay
+ * (⊕ a decaying visual error when smoothing is on). Idempotent modulo the
+ * error decay — it runs unconditionally each fixed step. */
private reconcilePredicted_(): void {
const owned = this.ownedEntities_();
if (owned.length === 0) return;
+
+ // Smoothing: what the player SAW before this rebuild. The snap below
+ // replaces field references (never mutates them), so these stay valid.
+ const smoothing = this.prediction_!.smoothing;
+ const seen = smoothing ? new Map<Entity, Map<number, Record<string, unknown>>>() : null;
+ if (seen) {
+ for (const e of owned) {
+ const perComp = new Map<number, Record<string, unknown>>();
+ for (const te of this.table.entries) {
+ if (!this.world_.has(e, te.def)) continue;
+ const data = this.world_.tryGet(e, te.def) as Record<string, unknown>;
+ const prev: Record<string, unknown> = {};
+ for (const f of te.fields) prev[f] = data[f];
+ perComp.set(te.id, prev);
+ }
+ seen.set(e, perComp);
+ }
+ }
+
for (const e of owned) {
const netId = this.netIds_.netIdOf(e);
if (netId === undefined) continue;
@@ -278,6 +341,34 @@ export class ReplicationClient {
this.prediction_!.apply(this.world_, e, input.actions, this.fixedDelta_);
}
}
+
+ // Smoothing: blend the rebuilt state toward what was on screen, with
+ // the error halving every halfLife seconds. Next tick's rebuild wipes
+ // it, so the error decays instead of compounding.
+ if (smoothing && seen) {
+ const keep = Math.pow(0.5, this.fixedDelta_ / smoothing.halfLife);
+ const maxError = smoothing.maxError ?? Infinity;
+ for (const e of owned) {
+ const perComp = seen.get(e);
+ if (!perComp) continue;
+ for (const [componentId, prev] of perComp) {
+ const te = this.table.entries[componentId];
+ if (!te || !this.world_.has(e, te.def)) continue;
+ const data = this.world_.tryGet(e, te.def) as Record<string, unknown>;
+ let changed = false;
+ for (let i = 0; i < te.fields.length; i++) {
+ const f = te.fields[i];
+ if (!(f in prev)) continue;
+ const blended = smoothValue(te.shapes[i], prev[f], data[f], keep, maxError);
+ if (blended !== data[f]) {
+ data[f] = blended;
+ changed = true;
+ }
+ }
+ if (changed) this.world_.set(e, te.def, data);
+ }
+ }
+ }
}
private ownedEntities_(): Entity[] {
diff --git a/sdk/src/net/replication/index.ts b/sdk/src/net/replication/index.ts
index 03585d73b..f07782fac 100644
--- a/sdk/src/net/replication/index.ts
+++ b/sdk/src/net/replication/index.ts
@@ -40,7 +40,12 @@ export {
} from './interest';
export { NetIds } from './NetIds';
export { ReplicationServer } from './server';
-export { ReplicationClient, type ReplicationClientOptions, type PredictionOptions } from './client';
+export {
+ ReplicationClient,
+ type ReplicationClientOptions,
+ type PredictionOptions,
+ type PredictionSmoothing,
+} from './client';
export { lerpValue, InterpolationState, ComponentBuffer } from './interpolation';
export {
ReplicationPlugin,
diff --git a/sdk/tests/replication-prediction.test.ts b/sdk/tests/replication-prediction.test.ts
index e20f21eed..4e6ef95c7 100644
--- a/sdk/tests/replication-prediction.test.ts
+++ b/sdk/tests/replication-prediction.test.ts
@@ -209,6 +209,83 @@ describe('client prediction', () => {
});
});
+describe('correction smoothing', () => {
+ async function makeSmoothedPair(smoothing: { halfLife: number; maxError?: number }) {
+ const serverApp = makeApp();
+ const clientApp = makeApp();
+ const server = serverApp.getResource(Net).startServer();
+ addServerInputSystem(serverApp, server);
+ const [ta, tb] = MemoryTransport.pair();
+ const connId = server.attachConnection(ta);
+ const client = await clientApp.getResource(Net).connect(tb, {
+ interpolationDelayTicks: 0,
+ prediction: { apply: applyMove, smoothing },
+ });
+ const pawn = serverApp.world.spawn('pawn');
+ serverApp.world.insert(pawn, Replicated, { owner: connId });
+ serverApp.world.insert(pawn, NetPos, {});
+ await serverApp.tick(STEP);
+ await clientApp.tick(STEP);
+ const ghost = clientApp.world.getEntitiesWithComponents([Replicated])[0];
+ return { serverApp, clientApp, server, client, pawn, ghost };
+ }
+
+ it('eases a correction out instead of snapping, and converges on the authority', async () => {
+ // Error halves every 4 ticks — slow enough to observe.
+ const { serverApp, clientApp, pawn, ghost, client } = await makeSmoothedPair({ halfLife: 4 * STEP });
+
+ // Server-only wall at x=25; the client optimistically predicts to 30.
+ serverApp.addSystemToSchedule(Schedule.FixedUpdate, defineSystem(
+ [GetWorld()],
+ (world) => {
+ const pos = world.tryGet(pawn, NetPos) as { x: number; y: number } | null;
+ if (pos && pos.x > 25) { pos.x = 25; world.set(pawn, NetPos, pos); }
+ },
+ { name: 'WallClamp' },
+ ));
+ for (let i = 0; i < 3; i++) client.sendInput({ move: { x: 1, y: 0 } });
+ expect(posX(clientApp, ghost)).toBeCloseTo(30, 5);
+
+ // While the replay still accounts for the prediction there is NO error
+ // (deterministic replay); the correction materialises the tick the
+ // server clamps — and lands BETWEEN authority (25) and prediction (30).
+ for (let i = 0; i < 3; i++) {
+ await serverApp.tick(STEP);
+ await clientApp.tick(STEP);
+ }
+ const eased = posX(clientApp, ghost);
+ expect(eased).toBeGreaterThan(25.5);
+ expect(eased).toBeLessThan(30);
+
+ // The error decays monotonically to the authoritative value.
+ let prev = eased;
+ for (let i = 0; i < 40; i++) {
+ await serverApp.tick(STEP);
+ await clientApp.tick(STEP);
+ const x = posX(clientApp, ghost);
+ expect(x).toBeLessThanOrEqual(prev + 1e-6);
+ prev = x;
+ }
+ expect(prev).toBeCloseTo(25, 1);
+ });
+
+ it('a correction beyond maxError snaps — a teleport must look like one', async () => {
+ const { serverApp, clientApp, pawn, ghost, client } = await makeSmoothedPair({ halfLife: 4 * STEP, maxError: 50 });
+
+ client.sendInput({ move: { x: 1, y: 0 } });
+ await serverApp.tick(STEP);
+ await clientApp.tick(STEP);
+ expect(posX(clientApp, ghost)).toBeCloseTo(10, 5);
+
+ // The server teleports the pawn far beyond maxError.
+ serverApp.world.set(pawn, NetPos, { x: 500, y: 0 });
+ client.sendInput({ move: { x: 0, y: 0 } });
+ await serverApp.tick(STEP);
+ await clientApp.tick(STEP);
+ expect(posX(clientApp, ghost)).toBeCloseTo(500, 5); // no easing
+ });
+});
+
describe('late enablePrediction (host-connected realms)', () => {
it('seeds authority for already-spawned owned entities and predicts from then on', async () => {
const serverApp = makeApp();
diff --git a/sdk/tests/tilemap.test.ts b/sdk/tests/tilemap.test.ts
index b46088998..3c98584b0 100644
--- a/sdk/tests/tilemap.test.ts
+++ b/sdk/tests/tilemap.test.ts
@@ -22,6 +22,8 @@ import type { TiledMapData } from '../src/tilemap/tiledLoader';
import { resolveTilesetModel } from '../src/tilemap/tilesetResolve';
import type { TilesetAsset } from '../src/tilemap/tilesetAsset';
import { mergeCollisionTiles } from '../src/tilemap/collisionMerge';
+import { TilemapAssetLoader } from '../src/asset/loaders/TilemapAssetLoader';
+import type { LoadContext } from '../src/asset/AssetLoader';
import { BodyType } from '../src/physics/PhysicsComponents';
import { clearUserComponents } from '../src/component';
import type { World } from '../src/world';
@@ -87,6 +89,17 @@ describe('Tilemap Components', () => {
});
});
+describe('TilemapAssetLoader — .tmx fails loud with the fix', () => {
+ it('a Tiled XML map errors with the JSON-export guidance, not a JSON syntax error', async () => {
+ const loader = new TilemapAssetLoader();
+ const ctx = {
+ catalog: { getBuildPath: (p: string) => p },
+ loadText: async () => '<?xml version="1.0" encoding="UTF-8"?>\n<map version="1.10"></map>',
+ } as unknown as LoadContext;
+ await expect(loader.load('maps/level.tmx', ctx)).rejects.toThrow(/JSON map files \(\*\.tmj\)/);
+ });
+});
+
describe('TilemapSource cache', () => {
beforeEach(() => {
clearTilemapSourceCache();