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(replication): input uplink + ownership — RC11 N4

esengine8381947c4366
diff --git a/sdk/src/net/replication/client.ts b/sdk/src/net/replication/client.ts
index 839e63652..ad80f49da 100644
--- a/sdk/src/net/replication/client.ts
+++ b/sdk/src/net/replication/client.ts
@@ -18,13 +18,14 @@ import { NetChannel, type NetTransport } from '../NetChannel';
import { log } from '../../logger';
import {
REPLICATION_CHANNEL, REPLICATION_PROTOCOL_VERSION, ReplMsg,
- type ReplDespawnBatch, type ReplHelloRequest, type ReplHelloResponse, type ReplSpawnBatch, type ReplSpawnEntity,
+ type ReplDespawnBatch, type ReplHelloRequest, type ReplHelloResponse,
+ type ReplInputMsg, type ReplSpawnBatch, type ReplSpawnEntity,
} from './protocol';
import {
buildReplicationTable, decodeStateFrame, tableSchemas,
type EntityRefMap, type ReplicationTable, type StateFrame,
} from './codec';
-import { NetGhost } from './components';
+import { NetGhost, Replicated } from './components';
import { NetIds } from './NetIds';
import { InterpolationState } from './interpolation';
@@ -48,6 +49,7 @@ export class ReplicationClient {
private readonly pendingSpawns_: ReplSpawnBatch[] = [];
private readonly pendingDespawns_: ReplDespawnBatch[] = [];
private readonly interp_: InterpolationState | null;
+ private inputSeq_ = 0;
constructor(world: World, options: ReplicationClientOptions = {}) {
this.world_ = world;
@@ -126,6 +128,19 @@ export class ReplicationClient {
this.connectionId_ = 0;
}
+ /** Send an input command (typically the InputMap's evaluated action values,
+ * once per fixed tick). The seq stamp makes stale deliveries harmless. */
+ sendInput(actions: Record<string, unknown>): void {
+ if (!this.channel_) return;
+ this.channel_.send<ReplInputMsg>(ReplMsg.input, { seq: ++this.inputSeq_, actions });
+ }
+
+ /** True when this client's connection owns the entity (Replicated.owner). */
+ ownsEntity(entity: Entity): boolean {
+ const repl = this.world_.tryGet(entity, Replicated) as { owner: number } | null;
+ return repl !== null && repl.owner === this.connectionId_ && this.connectionId_ !== 0;
+ }
+
/** Apply everything received since the last fixed step. Spawns before
* state (a frame may reference an entity spawned in the same flush). */
applyPending(): void {
diff --git a/sdk/src/net/replication/index.ts b/sdk/src/net/replication/index.ts
index 292057743..adbd7006d 100644
--- a/sdk/src/net/replication/index.ts
+++ b/sdk/src/net/replication/index.ts
@@ -10,6 +10,7 @@ export {
type ReplSpawnEntity,
type ReplSpawnBatch,
type ReplDespawnBatch,
+ type ReplInputMsg,
} from './protocol';
export {
buildReplicationTable,
diff --git a/sdk/src/net/replication/protocol.ts b/sdk/src/net/replication/protocol.ts
index 46461e522..4e6d62fc8 100644
--- a/sdk/src/net/replication/protocol.ts
+++ b/sdk/src/net/replication/protocol.ts
@@ -21,6 +21,7 @@ export const ReplMsg = {
hello: 'repl:hello',
spawn: 'repl:spawn',
despawn: 'repl:despawn',
+ input: 'repl:input',
} as const;
/** One component's replication schema, as exchanged for handshake comparison. */
@@ -74,3 +75,15 @@ export interface ReplDespawnBatch {
tick: number;
netIds: number[];
}
+
+/**
+ * Client → server input command. `actions` is game-defined (typically one
+ * InputMap's evaluated values per fixed tick: booleans, axes, {x,y} pairs);
+ * `seq` is a client-monotonic counter so stale deliveries never overwrite
+ * newer state. The server keeps the latest per connection and gameplay reads
+ * it via `ReplicationServer.inputOf(connectionId)`.
+ */
+export interface ReplInputMsg {
+ seq: number;
+ actions: Record<string, unknown>;
+}
diff --git a/sdk/src/net/replication/server.ts b/sdk/src/net/replication/server.ts
index 11f8894d2..f7c51ea0f 100644
--- a/sdk/src/net/replication/server.ts
+++ b/sdk/src/net/replication/server.ts
@@ -18,7 +18,8 @@ import { NetChannel, type NetTransport } from '../NetChannel';
import { log } from '../../logger';
import {
REPLICATION_CHANNEL, REPLICATION_PROTOCOL_VERSION, ReplMsg,
- type ReplDespawnBatch, type ReplHelloRequest, type ReplHelloResponse, type ReplSpawnBatch, type ReplSpawnEntity,
+ type ReplDespawnBatch, type ReplHelloRequest, type ReplHelloResponse,
+ type ReplInputMsg, type ReplSpawnBatch, type ReplSpawnEntity,
} from './protocol';
import {
buildReplicationTable, diffSchemas, tableSchemas, FrameWriter,
@@ -32,6 +33,8 @@ interface Connection {
channel: NetChannel;
/** Handshake completed and the initial world spawn has been sent. */
ready: boolean;
+ /** Latest input command from this connection (stale seq never overwrites). */
+ input: ReplInputMsg | null;
}
function deepClone<T>(v: T): T {
@@ -99,9 +102,13 @@ export class ReplicationServer {
attachConnection(transport: NetTransport): number {
const id = this.nextConnectionId_++;
const channel = new NetChannel(transport);
- const conn: Connection = { id, channel, ready: false };
+ const conn: Connection = { id, channel, ready: false, input: null };
this.connections_.set(id, conn);
+ channel.on<ReplInputMsg>(ReplMsg.input, (msg) => {
+ if (!conn.input || msg.seq > conn.input.seq) conn.input = msg;
+ });
+
channel.handle<ReplHelloRequest, ReplHelloResponse>(ReplMsg.hello, (req) => {
if (req.protocolVersion !== REPLICATION_PROTOCOL_VERSION) {
return { ok: false, error: `protocol v${req.protocolVersion}, server runs v${REPLICATION_PROTOCOL_VERSION}` };
@@ -129,6 +136,13 @@ export class ReplicationServer {
this.connections_.delete(id);
}
+ /** The latest input command a connection sent (null before the first).
+ * Gameplay reads this in FixedUpdate and applies it to the entities the
+ * connection owns (Replicated.owner). */
+ inputOf(connectionId: number): ReplInputMsg | null {
+ return this.connections_.get(connectionId)?.input ?? null;
+ }
+
/** One replication tick: spawns/despawns on the control plane, dirty
* fields as one binary delta frame. Runs in FixedPostUpdate. */
sample(tick: number): void {
diff --git a/sdk/tests/replication-input.test.ts b/sdk/tests/replication-input.test.ts
new file mode 100644
index 000000000..a1fd3ea01
--- /dev/null
+++ b/sdk/tests/replication-input.test.ts
@@ -0,0 +1,130 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file RC11 N4: input uplink + ownership. Clients send seq-stamped input
+ * commands; the server keeps the latest per connection, gameplay
+ * applies it to the entities that connection owns (Replicated.owner),
+ * and the authoritative result replicates back — the full loop in one
+ * process.
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import { App } from '../src/app';
+import { defineComponent, clearUserComponents } from '../src/component';
+import { defineSystem, Schedule, GetWorld } from '../src/system';
+import { MemoryTransport } from '../src/net/MemoryTransport';
+import { replicationPlugin, Net, Replicated } from '../src/net/replication';
+
+const STEP = 1 / 60;
+
+let NetPos: ReturnType<typeof defineComponent<{ x: number; y: number }>>;
+
+beforeEach(() => {
+ clearUserComponents();
+ NetPos = defineComponent('NetPos', { x: 0, y: 0 }, { replicatedFields: ['x', 'y'] });
+});
+
+function makeApp(): App {
+ const app = App.new();
+ app.addPlugin(replicationPlugin);
+ return app;
+}
+
+describe('input uplink', () => {
+ it('the server sees the latest command; stale seq never overwrites', async () => {
+ const serverApp = makeApp();
+ const clientApp = makeApp();
+ const server = serverApp.getResource(Net).startServer();
+ const [ta, tb] = MemoryTransport.pair();
+ const connId = server.attachConnection(ta);
+ const client = await clientApp.getResource(Net).connect(tb, { interpolationDelayTicks: 0 });
+
+ expect(server.inputOf(connId)).toBeNull();
+
+ client.sendInput({ move: { x: 1, y: 0 }, jump: false });
+ client.sendInput({ move: { x: 0, y: 1 }, jump: true });
+ const latest = server.inputOf(connId)!;
+ expect(latest.actions).toEqual({ move: { x: 0, y: 1 }, jump: true });
+ expect(latest.seq).toBe(2);
+ });
+
+ it('drives the full loop: input → owned entity moves on the server → ghost follows', async () => {
+ const serverApp = makeApp();
+ const clientApp = makeApp();
+ const server = serverApp.getResource(Net).startServer();
+ const [ta, tb] = MemoryTransport.pair();
+ const connId = server.attachConnection(ta);
+ const client = await clientApp.getResource(Net).connect(tb, { interpolationDelayTicks: 0 });
+
+ // Server gameplay: each fixed tick, apply each connection's input to
+ // the entities it owns — plain ECS code against the server resource.
+ serverApp.addSystemToSchedule(Schedule.FixedUpdate, defineSystem(
+ [GetWorld()],
+ (world) => {
+ for (const e of world.getEntitiesWithComponents([Replicated, NetPos])) {
+ const repl = world.tryGet(e, Replicated)!;
+ if (repl.owner === 0) continue;
+ const input = server.inputOf(repl.owner);
+ const move = input?.actions.move as { x: number; y: number } | undefined;
+ if (!move) continue;
+ const pos = world.tryGet(e, NetPos)!;
+ pos.x += move.x * 10;
+ pos.y += move.y * 10;
+ world.set(e, NetPos, pos);
+ }
+ },
+ { name: 'ApplyPlayerInput' },
+ ));
+
+ // The player entity, owned by the client's connection.
+ const player = serverApp.world.spawn('player');
+ serverApp.world.insert(player, Replicated, { owner: connId });
+ serverApp.world.insert(player, NetPos, {});
+
+ await serverApp.tick(STEP);
+ await clientApp.tick(STEP);
+ const ghost = clientApp.world.getEntitiesWithComponents([Replicated])[0];
+ expect(client.ownsEntity(ghost)).toBe(true);
+
+ // Hold "right" for three ticks.
+ client.sendInput({ move: { x: 1, y: 0 } });
+ for (let i = 0; i < 3; i++) {
+ await serverApp.tick(STEP);
+ await clientApp.tick(STEP);
+ }
+ expect(serverApp.world.tryGet(player, NetPos)!.x).toBe(30);
+ expect(clientApp.world.tryGet(ghost, NetPos)!.x).toBe(30);
+
+ // Release: server stops integrating, ghost stays put.
+ client.sendInput({});
+ await serverApp.tick(STEP);
+ await clientApp.tick(STEP);
+ expect(clientApp.world.tryGet(ghost, NetPos)!.x).toBe(30);
+ });
+
+ it('ownership is per connection: a second client does not own the first player', async () => {
+ const serverApp = makeApp();
+ const server = serverApp.getResource(Net).startServer();
+
+ const clientA = makeApp();
+ const [a1, a2] = MemoryTransport.pair();
+ const connA = server.attachConnection(a1);
+ const ca = await clientA.getResource(Net).connect(a2, { interpolationDelayTicks: 0 });
+
+ const clientB = makeApp();
+ const [b1, b2] = MemoryTransport.pair();
+ server.attachConnection(b1);
+ const cb = await clientB.getResource(Net).connect(b2, { interpolationDelayTicks: 0 });
+
+ const player = serverApp.world.spawn('playerA');
+ serverApp.world.insert(player, Replicated, { owner: connA });
+ serverApp.world.insert(player, NetPos, {});
+ await serverApp.tick(STEP);
+ await clientA.tick(STEP);
+ await clientB.tick(STEP);
+
+ const ghostA = clientA.world.getEntitiesWithComponents([Replicated])[0];
+ const ghostB = clientB.world.getEntitiesWithComponents([Replicated])[0];
+ expect(ca.ownsEntity(ghostA)).toBe(true);
+ expect(cb.ownsEntity(ghostB)).toBe(false);
+ });
+});