@voicethere/agent 0.36.1 → 0.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -11
- package/dist/templates/game-sync/agent.js +256 -52
- package/dist/templates/registry.d.ts.map +1 -1
- package/dist/templates/registry.js +8 -3
- package/dist/templates/registry.js.map +1 -1
- package/dist/templates/world-sync/agent.js +22 -1
- package/dist/templates/world-sync-binary/agent.js +22 -1
- package/eject/llm/loop.ts +1 -1
- package/package.json +30 -1
- package/templates/README.md +11 -11
- package/templates/game-sync/README.md +13 -4
- package/templates/game-sync/agent.ts +175 -60
- package/templates/game-sync/protocol.ts +3 -0
- package/templates/game-sync/quantize.ts +53 -0
- package/templates/game-sync/redis.ts +51 -1
- package/templates/game-sync/sim.ts +6 -0
- package/templates/game-sync/world-layout.ts +191 -0
- package/templates/redis-sync/README.md +7 -5
- package/templates/redis-sync/agent.ts +77 -65
- package/templates/redis-sync/quantize.ts +53 -0
- package/templates/redis-sync/quantized-frames.vectors.json +249 -0
- package/templates/redis-sync/world-layout.ts +278 -116
- package/templates/world-sync/README.md +1 -1
- package/templates/world-sync/agent.ts +39 -4
- package/templates/world-sync-binary/README.md +1 -1
- package/templates/world-sync-binary/agent.ts +29 -2
|
@@ -6,32 +6,41 @@
|
|
|
6
6
|
* - each tracked object uses exactly 9 floats:
|
|
7
7
|
* [objectId, posX, posY, posZ, posW, dirX, dirY, dirZ, dirW]
|
|
8
8
|
*
|
|
9
|
-
* With project Redis (`AGENT_REDIS_URL`), the world blob is shared across
|
|
10
|
-
* workers (key `game-sync:world`). World writes (allocate/release Lua, sim
|
|
11
|
-
* serialize on `game-sync:sim-lock
|
|
9
|
+
* With project Redis (`AGENT_REDIS_URL`), the world blob (float32) is shared across
|
|
10
|
+
* runner workers (key `game-sync:world`). World writes (allocate/release Lua, sim
|
|
11
|
+
* commit) serialize on `game-sync:sim-lock`. The lock holds a random per-attempt token:
|
|
12
|
+
* it is released by compare-and-delete, and every world write is conditional on the
|
|
13
|
+
* token. The world is stored with `game-sync:sim-at` (Redis clock, ms); a step takes
|
|
14
|
+
* dt = now - sim-at and is skipped when dt is under one sim interval, so any number of
|
|
15
|
+
* pods simulate wall time once.
|
|
12
16
|
*
|
|
13
17
|
* Control messages:
|
|
14
18
|
* - `{ type: "register" }` -> allocates (or reuses) one 9-float slot
|
|
15
19
|
* - server replies `{ type: "register_ack", objectId }`
|
|
16
20
|
* - `{ type: "register_nack", reason: "world_full", maxObjects: 25 }` when cap reached
|
|
21
|
+
* - `{ type: "register_nack", reason: "busy" }` / `{ type: "unregister_nack", reason: "busy" }`
|
|
22
|
+
* when the Redis sim lock was lost twice in a row (the write was skipped; retry later)
|
|
17
23
|
* - `{ type: "remove", objectId }` or `{ type: "unregister", objectId?: number }` ->
|
|
18
24
|
* zeros that live slot (objectId required for click-to-remove; omit objectId on
|
|
19
25
|
* unregister to drop the highest object owned by this session)
|
|
20
26
|
* - `{ type: "unregister_ack", objectId }` or `{ type: "unregister_nack", reason }`
|
|
21
27
|
*
|
|
22
28
|
* Simulation:
|
|
23
|
-
* - server-authoritative movement at 60Hz
|
|
29
|
+
* - server-authoritative movement at 60Hz (SIM_HZ)
|
|
24
30
|
* - wall bounce + object-object elastic collisions on server
|
|
25
31
|
* - clients render server snapshots; client binary writes are ignored
|
|
26
32
|
* - with project Redis, the sim loop keeps running with zero connected clients so
|
|
27
33
|
* objects persist and keep moving after everyone disconnects
|
|
28
34
|
*
|
|
29
35
|
* Broadcast:
|
|
30
|
-
* -
|
|
36
|
+
* - 30Hz (BROADCAST_HZ, every 2nd sim tick) quantized world frame while the sim loop
|
|
37
|
+
* runs: u8 format 2, u8 version 1, u16le objectCount, then 18 B per live object (see
|
|
38
|
+
* world-layout.ts). Followers relay only when sim-at advanced.
|
|
31
39
|
*
|
|
32
40
|
* Build:
|
|
33
41
|
* npx @voicethere/agent build --entry templates/game-sync/agent.ts
|
|
34
42
|
*/
|
|
43
|
+
import { randomUUID } from "node:crypto";
|
|
35
44
|
import { Redis } from "ioredis";
|
|
36
45
|
import {
|
|
37
46
|
agentLog,
|
|
@@ -46,18 +55,27 @@ import {
|
|
|
46
55
|
parseRegisterCommand,
|
|
47
56
|
parseUnregisterCommand,
|
|
48
57
|
resolveRemoveTarget,
|
|
58
|
+
REGISTER_NACK_REASON_BUSY,
|
|
49
59
|
REGISTER_NACK_REASON_WORLD_FULL,
|
|
60
|
+
UNREGISTER_NACK_REASON_BUSY,
|
|
50
61
|
UNREGISTER_NACK_REASON_NOT_FOUND,
|
|
51
62
|
} from "./protocol.js";
|
|
52
63
|
import {
|
|
53
64
|
LUA_ALLOCATE_OBJECT,
|
|
65
|
+
LUA_COMMIT_WORLD,
|
|
66
|
+
LUA_READ_WORLD,
|
|
67
|
+
LUA_RELEASE_LOCK,
|
|
54
68
|
LUA_RELEASE_OBJECT,
|
|
55
69
|
REDIS_EVAL_KEYS,
|
|
56
70
|
} from "./redis.js";
|
|
57
71
|
import {
|
|
58
72
|
BOARD_HEIGHT,
|
|
59
73
|
BOARD_WIDTH,
|
|
74
|
+
BROADCAST_HZ,
|
|
75
|
+
MAX_SPEED,
|
|
76
|
+
MIN_SPEED,
|
|
60
77
|
OBJECT_RADIUS,
|
|
78
|
+
SIM_HZ,
|
|
61
79
|
simulateWorldStep,
|
|
62
80
|
} from "./sim.js";
|
|
63
81
|
import {
|
|
@@ -65,24 +83,31 @@ import {
|
|
|
65
83
|
collectActiveObjectIdsInto,
|
|
66
84
|
countLiveObjects,
|
|
67
85
|
createEmptyWorldBuffer,
|
|
86
|
+
encodeLiveObjectsInto,
|
|
68
87
|
findFirstEmptySlot,
|
|
69
88
|
liveWorldSnapshot,
|
|
70
89
|
markSlotFree,
|
|
71
90
|
normalizeWorldBuffer,
|
|
72
91
|
objectIdToSlot,
|
|
92
|
+
MAX_FRAME_BYTES,
|
|
73
93
|
planRedisSimTick,
|
|
94
|
+
planRedisStepDtSec,
|
|
95
|
+
REDIS_SIM_AT_KEY,
|
|
74
96
|
REDIS_SIM_LOCK_KEY,
|
|
75
97
|
REDIS_WORLD_KEY,
|
|
76
98
|
slotToObjectId,
|
|
77
99
|
writeObjectSlot,
|
|
78
100
|
} from "./world-layout.js";
|
|
79
101
|
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
const
|
|
102
|
+
const SIM_INTERVAL_MS = Math.floor(1000 / SIM_HZ);
|
|
103
|
+
/** Every 2nd sim tick broadcasts (60 Hz sim, 30 Hz send). */
|
|
104
|
+
const BROADCAST_EVERY_N_TICKS = Math.round(SIM_HZ / BROADCAST_HZ);
|
|
105
|
+
const SIM_LOCK_TTL_MS = SIM_INTERVAL_MS * 2;
|
|
83
106
|
const SIM_LOCK_RETRY_MS = 5;
|
|
84
|
-
|
|
85
|
-
const
|
|
107
|
+
/** Allocate/release Lua result when the lock no longer holds this pod's token. */
|
|
108
|
+
const LUA_LOCK_LOST = -3;
|
|
109
|
+
const LOCK_LOST = "lock_lost" as const;
|
|
110
|
+
type LockLost = typeof LOCK_LOST;
|
|
86
111
|
|
|
87
112
|
const connectedSessions = new Set<string>();
|
|
88
113
|
/** Same members as connectedSessions; array form lets the broadcast skip Set iteration. */
|
|
@@ -102,6 +127,14 @@ let redis: Redis | null = null;
|
|
|
102
127
|
let broadcastTimer: NodeJS.Timeout | null = null;
|
|
103
128
|
let worldMutationChain: Promise<void> = Promise.resolve();
|
|
104
129
|
let lastTickTimeMs = 0;
|
|
130
|
+
let tickCount = 0;
|
|
131
|
+
/** One broadcast scratch frame per pod; the frame sent is a subarray of it (IPC copies synchronously). */
|
|
132
|
+
const frameScratch = Buffer.alloc(MAX_FRAME_BYTES);
|
|
133
|
+
/** From the last Redis read: stored sim-at (0 = none) and Redis' clock, both ms. */
|
|
134
|
+
let lastReadSimAt = 0;
|
|
135
|
+
let lastReadNowMs = 0;
|
|
136
|
+
/** sim-at of the last frame this pod broadcast; followers relay only when it advanced. */
|
|
137
|
+
let lastRelayedSimAt = 0;
|
|
105
138
|
|
|
106
139
|
function withWorldMutation<T>(fn: () => Promise<T>): Promise<T> {
|
|
107
140
|
const run = worldMutationChain.then(fn);
|
|
@@ -118,29 +151,36 @@ function sleep(ms: number): Promise<void> {
|
|
|
118
151
|
});
|
|
119
152
|
}
|
|
120
153
|
|
|
154
|
+
async function releaseSimLock(token: string): Promise<void> {
|
|
155
|
+
if (!redis) return;
|
|
156
|
+
// Compare-and-delete: a holder whose TTL lapsed never deletes the next holder's lock.
|
|
157
|
+
await redis.eval(LUA_RELEASE_LOCK, 1, REDIS_SIM_LOCK_KEY, token);
|
|
158
|
+
}
|
|
159
|
+
|
|
121
160
|
async function withRedisSimLock<T>(
|
|
122
|
-
fn: () => Promise<T>,
|
|
161
|
+
fn: (token: string) => Promise<T>,
|
|
123
162
|
options?: { retryUntilAcquired?: boolean },
|
|
124
163
|
): Promise<T | null> {
|
|
125
164
|
if (!redis) {
|
|
126
|
-
return fn();
|
|
165
|
+
return fn("");
|
|
127
166
|
}
|
|
128
167
|
|
|
129
168
|
const retryUntilAcquired = options?.retryUntilAcquired ?? true;
|
|
169
|
+
const token = randomUUID();
|
|
130
170
|
|
|
131
171
|
while (true) {
|
|
132
172
|
const lockAcquired = await redis.set(
|
|
133
173
|
REDIS_SIM_LOCK_KEY,
|
|
134
|
-
|
|
174
|
+
token,
|
|
135
175
|
"PX",
|
|
136
176
|
SIM_LOCK_TTL_MS,
|
|
137
177
|
"NX",
|
|
138
178
|
);
|
|
139
179
|
if (lockAcquired === "OK") {
|
|
140
180
|
try {
|
|
141
|
-
return await fn();
|
|
181
|
+
return await fn(token);
|
|
142
182
|
} finally {
|
|
143
|
-
await
|
|
183
|
+
await releaseSimLock(token);
|
|
144
184
|
}
|
|
145
185
|
}
|
|
146
186
|
if (!retryUntilAcquired) {
|
|
@@ -249,23 +289,30 @@ function registerObjectInMemory(sessionId: string): number | null {
|
|
|
249
289
|
|
|
250
290
|
async function registerObjectInRedis(
|
|
251
291
|
sessionId: string,
|
|
252
|
-
|
|
292
|
+
token: string,
|
|
293
|
+
): Promise<number | null | LockLost> {
|
|
253
294
|
if (!redis) {
|
|
254
295
|
return registerObjectInMemory(sessionId);
|
|
255
296
|
}
|
|
256
297
|
|
|
257
298
|
const result = await redis.eval(
|
|
258
299
|
LUA_ALLOCATE_OBJECT,
|
|
259
|
-
|
|
300
|
+
2,
|
|
260
301
|
REDIS_EVAL_KEYS.worldKey,
|
|
302
|
+
REDIS_EVAL_KEYS.lockKey,
|
|
261
303
|
REDIS_EVAL_KEYS.worldByteLength,
|
|
262
304
|
REDIS_EVAL_KEYS.slotByteLength,
|
|
263
305
|
REDIS_EVAL_KEYS.maxSlots,
|
|
264
306
|
randomInitialTail(),
|
|
265
307
|
REDIS_EVAL_KEYS.headers,
|
|
308
|
+
token,
|
|
266
309
|
);
|
|
267
310
|
|
|
268
311
|
const objectId = Number(result);
|
|
312
|
+
if (objectId === LUA_LOCK_LOST) {
|
|
313
|
+
agentLog("warn", "register skipped: sim lock lost before the world write");
|
|
314
|
+
return LOCK_LOST;
|
|
315
|
+
}
|
|
269
316
|
if (!Number.isFinite(objectId) || objectId < 1) {
|
|
270
317
|
return null;
|
|
271
318
|
}
|
|
@@ -275,29 +322,51 @@ async function registerObjectInRedis(
|
|
|
275
322
|
return objectId;
|
|
276
323
|
}
|
|
277
324
|
|
|
278
|
-
async function releaseObjectInRedis(
|
|
279
|
-
|
|
325
|
+
async function releaseObjectInRedis(
|
|
326
|
+
objectId: number,
|
|
327
|
+
token: string,
|
|
328
|
+
): Promise<boolean | LockLost> {
|
|
280
329
|
if (!redis) {
|
|
330
|
+
detachObjectFromSession(objectId);
|
|
281
331
|
releaseObjectInMemory(objectId);
|
|
282
332
|
return true;
|
|
283
333
|
}
|
|
284
334
|
|
|
285
335
|
const released = await redis.eval(
|
|
286
336
|
LUA_RELEASE_OBJECT,
|
|
287
|
-
|
|
337
|
+
2,
|
|
288
338
|
REDIS_EVAL_KEYS.worldKey,
|
|
339
|
+
REDIS_EVAL_KEYS.lockKey,
|
|
289
340
|
REDIS_EVAL_KEYS.worldByteLength,
|
|
290
341
|
REDIS_EVAL_KEYS.slotByteLength,
|
|
291
342
|
REDIS_EVAL_KEYS.maxSlots,
|
|
292
343
|
String(objectId),
|
|
293
344
|
REDIS_EVAL_KEYS.headers,
|
|
345
|
+
token,
|
|
294
346
|
);
|
|
347
|
+
if (Number(released) === LUA_LOCK_LOST) {
|
|
348
|
+
// Nothing was written and nothing was detached: the owner stays as it was.
|
|
349
|
+
agentLog("warn", "release skipped: sim lock lost before the world write");
|
|
350
|
+
return LOCK_LOST;
|
|
351
|
+
}
|
|
352
|
+
detachObjectFromSession(objectId);
|
|
295
353
|
if (Number(released) === 1) {
|
|
296
354
|
await loadWorldFromRedis();
|
|
297
355
|
}
|
|
298
356
|
return Number(released) === 1;
|
|
299
357
|
}
|
|
300
358
|
|
|
359
|
+
/** Run a lock-guarded write; when the lock was lost mid-way, retry once with a new token. */
|
|
360
|
+
async function withSimLockRetryOnce<T>(
|
|
361
|
+
fn: (token: string) => Promise<T | LockLost>,
|
|
362
|
+
): Promise<T | LockLost> {
|
|
363
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
364
|
+
const result = await withRedisSimLock(fn);
|
|
365
|
+
if (result !== LOCK_LOST) return result as T;
|
|
366
|
+
}
|
|
367
|
+
return LOCK_LOST;
|
|
368
|
+
}
|
|
369
|
+
|
|
301
370
|
async function unregisterObject(
|
|
302
371
|
sessionId: string,
|
|
303
372
|
objectId?: number,
|
|
@@ -309,19 +378,21 @@ async function unregisterObject(
|
|
|
309
378
|
}
|
|
310
379
|
|
|
311
380
|
const previousOwner = objectOwners.get(target.objectId) ?? sessionId;
|
|
312
|
-
notifyObjectReleased(target.objectId, previousOwner);
|
|
313
381
|
const released = await withWorldMutation(async () => {
|
|
314
382
|
if (!redis) {
|
|
315
|
-
return releaseObjectInRedis(target.objectId);
|
|
383
|
+
return releaseObjectInRedis(target.objectId, "");
|
|
316
384
|
}
|
|
317
|
-
|
|
318
|
-
releaseObjectInRedis(target.objectId),
|
|
385
|
+
return withSimLockRetryOnce((token) =>
|
|
386
|
+
releaseObjectInRedis(target.objectId, token),
|
|
319
387
|
);
|
|
320
|
-
return result === true;
|
|
321
388
|
});
|
|
389
|
+
if (released === LOCK_LOST) {
|
|
390
|
+
return { ok: false, reason: UNREGISTER_NACK_REASON_BUSY };
|
|
391
|
+
}
|
|
322
392
|
if (!released) {
|
|
323
393
|
return { ok: false, reason: UNREGISTER_NACK_REASON_NOT_FOUND };
|
|
324
394
|
}
|
|
395
|
+
notifyObjectReleased(target.objectId, previousOwner);
|
|
325
396
|
return { ok: true, objectId: target.objectId };
|
|
326
397
|
}
|
|
327
398
|
|
|
@@ -359,23 +430,32 @@ function notifyObjectReleased(objectId: number, ownerSessionId: string): void {
|
|
|
359
430
|
|
|
360
431
|
function broadcastWorldBuffer(): void {
|
|
361
432
|
if (connectedSessionList.length === 0) return;
|
|
362
|
-
//
|
|
363
|
-
|
|
433
|
+
// Live objects only, quantized into the pod's one scratch buffer; one fan-out call.
|
|
434
|
+
const length = encodeLiveObjectsInto(frameScratch, worldState);
|
|
435
|
+
broadCastBinaryToClients(
|
|
436
|
+
frameScratch.subarray(0, length),
|
|
437
|
+
connectedSessionList,
|
|
438
|
+
"sync",
|
|
439
|
+
);
|
|
364
440
|
}
|
|
365
441
|
|
|
366
442
|
/**
|
|
367
|
-
*
|
|
368
|
-
*
|
|
443
|
+
* One Lua read of the world, the stored sim-at and Redis' clock. The world is copied into
|
|
444
|
+
* `worldState` in place (the reply is the only per-tick allocation we cannot avoid); sim-at
|
|
445
|
+
* and now land in `lastReadSimAt` / `lastReadNowMs`.
|
|
369
446
|
*/
|
|
370
447
|
async function loadWorldFromRedis(): Promise<void> {
|
|
371
448
|
if (!redis) return;
|
|
372
|
-
const
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
449
|
+
const reply = (await redis.callBuffer(
|
|
450
|
+
"EVAL",
|
|
451
|
+
LUA_READ_WORLD,
|
|
452
|
+
2,
|
|
453
|
+
REDIS_WORLD_KEY,
|
|
454
|
+
REDIS_SIM_AT_KEY,
|
|
455
|
+
)) as Buffer[];
|
|
456
|
+
normalizeWorldBuffer(reply[0], worldState);
|
|
457
|
+
lastReadSimAt = reply[1]!.byteLength > 0 ? Number(reply[1]!.toString()) : 0;
|
|
458
|
+
lastReadNowMs = Number(reply[2]!.toString());
|
|
379
459
|
}
|
|
380
460
|
|
|
381
461
|
/** Live object ids for the current tick; filled in place, never reallocated. */
|
|
@@ -392,48 +472,73 @@ function takeTickDtSec(): number {
|
|
|
392
472
|
const now = Date.now();
|
|
393
473
|
const dt = clampSimulationDtSec(
|
|
394
474
|
lastTickTimeMs === 0 ? 0 : now - lastTickTimeMs,
|
|
395
|
-
|
|
475
|
+
SIM_HZ,
|
|
396
476
|
);
|
|
397
477
|
lastTickTimeMs = now;
|
|
398
478
|
return dt;
|
|
399
479
|
}
|
|
400
480
|
|
|
401
|
-
function stepWorldInPlace(): void {
|
|
402
|
-
const dt = takeTickDtSec();
|
|
481
|
+
function stepWorldInPlace(dtSec: number): void {
|
|
403
482
|
const count = collectActiveObjectIdsInto(worldState, activeObjectIds);
|
|
404
|
-
simulateWorldStep(worldState,
|
|
483
|
+
simulateWorldStep(worldState, dtSec, activeObjectIds, count);
|
|
405
484
|
}
|
|
406
485
|
|
|
407
486
|
async function stepWorldInMemory(): Promise<void> {
|
|
408
|
-
stepWorldInPlace();
|
|
487
|
+
stepWorldInPlace(takeTickDtSec());
|
|
409
488
|
}
|
|
410
489
|
|
|
411
|
-
|
|
490
|
+
type StepOutcome = "stepped" | "skipped" | "lost";
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* Leader step under the sim lock: dt comes from the stored sim-at (Redis clock). Below one
|
|
494
|
+
* sim interval another pod already stepped this interval, so skip. The commit writes the
|
|
495
|
+
* world and sim-at together only while the lock still holds `token`.
|
|
496
|
+
*/
|
|
497
|
+
async function stepWorldWithRedis(token: string): Promise<StepOutcome> {
|
|
498
|
+
if (!redis) return "lost";
|
|
412
499
|
await loadWorldFromRedis();
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
500
|
+
const now = lastReadNowMs;
|
|
501
|
+
const dt = planRedisStepDtSec(lastReadSimAt, now);
|
|
502
|
+
if (dt === null) return "skipped";
|
|
503
|
+
stepWorldInPlace(dt);
|
|
504
|
+
const written = await redis.eval(
|
|
505
|
+
LUA_COMMIT_WORLD,
|
|
506
|
+
3,
|
|
507
|
+
REDIS_SIM_LOCK_KEY,
|
|
508
|
+
REDIS_WORLD_KEY,
|
|
509
|
+
REDIS_SIM_AT_KEY,
|
|
510
|
+
token,
|
|
511
|
+
worldStateBytes,
|
|
512
|
+
String(now),
|
|
513
|
+
);
|
|
514
|
+
if (Number(written) !== 1) return "lost";
|
|
515
|
+
lastReadSimAt = now;
|
|
516
|
+
return "stepped";
|
|
417
517
|
}
|
|
418
518
|
|
|
419
519
|
async function runRedisTick(): Promise<void> {
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
);
|
|
424
|
-
if (
|
|
425
|
-
|
|
426
|
-
|
|
520
|
+
tickCount += 1;
|
|
521
|
+
const broadcastDue = tickCount % BROADCAST_EVERY_N_TICKS === 0;
|
|
522
|
+
const outcome = await withRedisSimLock(stepWorldWithRedis, SIM_LOCK_TRY_ONCE);
|
|
523
|
+
if (outcome === "lost") return;
|
|
524
|
+
if (outcome === null) {
|
|
525
|
+
if (!broadcastDue) return;
|
|
526
|
+
if (planRedisSimTick(SIM_TICK_PLAN_INPUT) !== "relay") return;
|
|
427
527
|
await loadWorldFromRedis();
|
|
428
|
-
broadcastWorldBuffer();
|
|
429
528
|
}
|
|
529
|
+
if (!broadcastDue || connectedSessionList.length === 0) return;
|
|
530
|
+
// Relay only when sim-at advanced since this pod's last frame.
|
|
531
|
+
if (lastReadSimAt <= lastRelayedSimAt) return;
|
|
532
|
+
lastRelayedSimAt = lastReadSimAt;
|
|
533
|
+
broadcastWorldBuffer();
|
|
430
534
|
}
|
|
431
535
|
|
|
432
536
|
// Tick bodies are module-level functions (no per-tick closures or option objects).
|
|
433
537
|
async function runSimulationTick(): Promise<void> {
|
|
434
538
|
if (!redis) {
|
|
539
|
+
tickCount += 1;
|
|
435
540
|
await withWorldMutation(stepWorldInMemory);
|
|
436
|
-
broadcastWorldBuffer();
|
|
541
|
+
if (tickCount % BROADCAST_EVERY_N_TICKS === 0) broadcastWorldBuffer();
|
|
437
542
|
return;
|
|
438
543
|
}
|
|
439
544
|
await withWorldMutation(runRedisTick);
|
|
@@ -459,8 +564,11 @@ function startBroadcastLoopIfNeeded(): void {
|
|
|
459
564
|
if (broadcastTimer) return;
|
|
460
565
|
if (!redis && connectedSessions.size < 1) return;
|
|
461
566
|
|
|
462
|
-
broadcastTimer = setInterval(onBroadcastTick,
|
|
463
|
-
agentLog(
|
|
567
|
+
broadcastTimer = setInterval(onBroadcastTick, SIM_INTERVAL_MS);
|
|
568
|
+
agentLog(
|
|
569
|
+
"info",
|
|
570
|
+
`world loop started (sim ${SIM_HZ}Hz, broadcast ${BROADCAST_HZ}Hz)`,
|
|
571
|
+
);
|
|
464
572
|
}
|
|
465
573
|
|
|
466
574
|
function stopBroadcastLoopIfNeeded(): void {
|
|
@@ -542,11 +650,18 @@ defineAgent({
|
|
|
542
650
|
if (!redis) {
|
|
543
651
|
return registerObjectInMemory(ctx.sessionId);
|
|
544
652
|
}
|
|
545
|
-
|
|
546
|
-
registerObjectInRedis(ctx.sessionId),
|
|
653
|
+
return withSimLockRetryOnce((token) =>
|
|
654
|
+
registerObjectInRedis(ctx.sessionId, token),
|
|
547
655
|
);
|
|
548
|
-
return result;
|
|
549
656
|
});
|
|
657
|
+
if (objectId === LOCK_LOST) {
|
|
658
|
+
sendToClient(ctx.sessionId, {
|
|
659
|
+
type: "register_nack",
|
|
660
|
+
reason: REGISTER_NACK_REASON_BUSY,
|
|
661
|
+
});
|
|
662
|
+
agentLog("info", `register_nack busy session=${ctx.sessionId}`);
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
550
665
|
if (objectId === null) {
|
|
551
666
|
sendToClient(ctx.sessionId, {
|
|
552
667
|
type: "register_nack",
|
|
@@ -5,6 +5,9 @@
|
|
|
5
5
|
export const MAX_LIVE_OBJECTS = 25;
|
|
6
6
|
|
|
7
7
|
export const REGISTER_NACK_REASON_WORLD_FULL = "world_full" as const;
|
|
8
|
+
/** Redis sim lock lost twice in a row (another pod held it past our TTL); retry later. */
|
|
9
|
+
export const REGISTER_NACK_REASON_BUSY = "busy" as const;
|
|
10
|
+
export const UNREGISTER_NACK_REASON_BUSY = "busy" as const;
|
|
8
11
|
export const UNREGISTER_NACK_REASON_NOT_FOUND = "not_found" as const;
|
|
9
12
|
export const UNREGISTER_NACK_REASON_NOT_OWNER = "not_owner" as const;
|
|
10
13
|
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* int16 quantizer shared by the data-sync templates (plan 2026-11-20-sync-template-efficiency).
|
|
3
|
+
*
|
|
4
|
+
* A bounded range [min, max] maps onto [-32767, 32767] (-32768 is never produced), so the
|
|
5
|
+
* step is (max - min) / 65534 and a round trip is off by at most half a step. Values outside
|
|
6
|
+
* the range are clamped. NaN and +-Infinity are not quantizable: callers check
|
|
7
|
+
* {@link isQuantizable} and drop (and count) the pose instead of encoding it.
|
|
8
|
+
*
|
|
9
|
+
* game-sync carries a same-content copy of this file (templates are self-contained
|
|
10
|
+
* workspaces; a test keeps the two copies identical).
|
|
11
|
+
*/
|
|
12
|
+
export const QUANT_MAX = 32767;
|
|
13
|
+
export const QUANT_STEPS = QUANT_MAX * 2;
|
|
14
|
+
|
|
15
|
+
export function isQuantizable(v: number): boolean {
|
|
16
|
+
return Number.isFinite(v);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function assertQuantizable(v: number): void {
|
|
20
|
+
if (!Number.isFinite(v)) {
|
|
21
|
+
throw new RangeError(`cannot quantize non-finite value ${String(v)}`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Quantize `v` clamped to [min, max] into an int16 in [-32767, 32767]. */
|
|
26
|
+
export function quantize(v: number, min: number, max: number): number {
|
|
27
|
+
assertQuantizable(v);
|
|
28
|
+
const clamped = v < min ? min : v > max ? max : v;
|
|
29
|
+
const q =
|
|
30
|
+
Math.round(((clamped - min) / (max - min)) * QUANT_STEPS) - QUANT_MAX;
|
|
31
|
+
// `+ 0` turns -0 into 0.
|
|
32
|
+
return q + 0;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function dequantize(q: number, min: number, max: number): number {
|
|
36
|
+
return min + ((q + QUANT_MAX) / QUANT_STEPS) * (max - min);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Quantize a unit component (direction, rotation) in [-1, 1]. */
|
|
40
|
+
export function quantizeUnit(v: number): number {
|
|
41
|
+
assertQuantizable(v);
|
|
42
|
+
const clamped = v < -1 ? -1 : v > 1 ? 1 : v;
|
|
43
|
+
return Math.round(clamped * QUANT_MAX) + 0;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function dequantizeUnit(q: number): number {
|
|
47
|
+
return q / QUANT_MAX;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Size of one quantization step for [min, max]. */
|
|
51
|
+
export function quantStep(min: number, max: number): number {
|
|
52
|
+
return (max - min) / QUANT_STEPS;
|
|
53
|
+
}
|
|
@@ -6,6 +6,8 @@ import {
|
|
|
6
6
|
OBJECT_ID_HEADERS_BLOB,
|
|
7
7
|
OBJECT_SLOT_BYTE_LENGTH,
|
|
8
8
|
WORLD_BYTE_LENGTH,
|
|
9
|
+
REDIS_SIM_AT_KEY,
|
|
10
|
+
REDIS_SIM_LOCK_KEY,
|
|
9
11
|
REDIS_WORLD_KEY,
|
|
10
12
|
} from "./world-layout.js";
|
|
11
13
|
|
|
@@ -17,6 +19,8 @@ export { OBJECT_ID_HEADERS_BLOB };
|
|
|
17
19
|
*
|
|
18
20
|
* ARGV[4] = 32-byte tail (8 floats: pos + dir without objectId header)
|
|
19
21
|
* ARGV[5] = 100-byte objectId header lookup blob
|
|
22
|
+
* ARGV[6] = sim-lock token; KEYS[2] = sim-lock key. Returns -3 (writes nothing) when the
|
|
23
|
+
* lock no longer holds this token (TTL lapsed and another pod took it).
|
|
20
24
|
*/
|
|
21
25
|
export const LUA_ALLOCATE_OBJECT = `
|
|
22
26
|
local key = KEYS[1]
|
|
@@ -26,6 +30,10 @@ local max_slots = tonumber(ARGV[3])
|
|
|
26
30
|
local tail = ARGV[4]
|
|
27
31
|
local headers = ARGV[5]
|
|
28
32
|
|
|
33
|
+
if redis.call('GET', KEYS[2]) ~= ARGV[6] then
|
|
34
|
+
return -3
|
|
35
|
+
end
|
|
36
|
+
|
|
29
37
|
local world = redis.call('GET', key)
|
|
30
38
|
if not world then
|
|
31
39
|
world = string.rep(string.char(0), size)
|
|
@@ -66,7 +74,8 @@ return object_id
|
|
|
66
74
|
|
|
67
75
|
/**
|
|
68
76
|
* Zero the fixed slot for objectId when the header matches.
|
|
69
|
-
* Returns 1 on success, 0 when slot empty or objectId mismatch
|
|
77
|
+
* Returns 1 on success, 0 when slot empty or objectId mismatch, -3 (writes nothing) when
|
|
78
|
+
* the sim lock (KEYS[2]) no longer holds the token in ARGV[6].
|
|
70
79
|
*/
|
|
71
80
|
export const LUA_RELEASE_OBJECT = `
|
|
72
81
|
local key = KEYS[1]
|
|
@@ -76,6 +85,10 @@ local max_slots = tonumber(ARGV[3])
|
|
|
76
85
|
local object_id = tonumber(ARGV[4])
|
|
77
86
|
local headers = ARGV[5]
|
|
78
87
|
|
|
88
|
+
if redis.call('GET', KEYS[2]) ~= ARGV[6] then
|
|
89
|
+
return -3
|
|
90
|
+
end
|
|
91
|
+
|
|
79
92
|
if object_id < 1 or object_id > max_slots then
|
|
80
93
|
return 0
|
|
81
94
|
end
|
|
@@ -103,8 +116,45 @@ redis.call('SET', key, world)
|
|
|
103
116
|
return 1
|
|
104
117
|
`;
|
|
105
118
|
|
|
119
|
+
/** Release the sim lock only while it still holds this token (KEYS[1] = lock, ARGV[1] = token). */
|
|
120
|
+
export const LUA_RELEASE_LOCK = `
|
|
121
|
+
if redis.call('GET', KEYS[1]) == ARGV[1] then
|
|
122
|
+
return redis.call('DEL', KEYS[1])
|
|
123
|
+
end
|
|
124
|
+
return 0
|
|
125
|
+
`;
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* One round trip for a tick: the world, the stored sim time and Redis' own clock (ms), so
|
|
129
|
+
* every pod measures dt against the same clock whatever its local skew.
|
|
130
|
+
* KEYS = world, sim-at. Returns {world or '', sim-at or '', now}.
|
|
131
|
+
*/
|
|
132
|
+
export const LUA_READ_WORLD = `
|
|
133
|
+
local world = redis.call('GET', KEYS[1])
|
|
134
|
+
local sim_at = redis.call('GET', KEYS[2])
|
|
135
|
+
local t = redis.call('TIME')
|
|
136
|
+
local now = string.format('%.0f', t[1] * 1000 + math.floor(t[2] / 1000))
|
|
137
|
+
return { world or '', sim_at or '', now }
|
|
138
|
+
`;
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Conditional world write: only while the lock holds the token, SET the world and sim-at
|
|
142
|
+
* together. KEYS = lock, world, sim-at; ARGV = token, world bytes, sim-at ms.
|
|
143
|
+
* Returns 1 when written, 0 when the lock was lost (nothing written).
|
|
144
|
+
*/
|
|
145
|
+
export const LUA_COMMIT_WORLD = `
|
|
146
|
+
if redis.call('GET', KEYS[1]) ~= ARGV[1] then
|
|
147
|
+
return 0
|
|
148
|
+
end
|
|
149
|
+
redis.call('SET', KEYS[2], ARGV[2])
|
|
150
|
+
redis.call('SET', KEYS[3], ARGV[3])
|
|
151
|
+
return 1
|
|
152
|
+
`;
|
|
153
|
+
|
|
106
154
|
export const REDIS_EVAL_KEYS = {
|
|
107
155
|
worldKey: REDIS_WORLD_KEY,
|
|
156
|
+
lockKey: REDIS_SIM_LOCK_KEY,
|
|
157
|
+
simAtKey: REDIS_SIM_AT_KEY,
|
|
108
158
|
worldByteLength: String(WORLD_BYTE_LENGTH),
|
|
109
159
|
slotByteLength: String(OBJECT_SLOT_BYTE_LENGTH),
|
|
110
160
|
maxSlots: String(MAX_LIVE_OBJECTS),
|
|
@@ -3,6 +3,12 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import { objectIdToSlot } from "./world-layout.js";
|
|
5
5
|
|
|
6
|
+
/** Physics steps per second; the world broadcasts every SIM_HZ / BROADCAST_HZ-th step. */
|
|
7
|
+
export const SIM_HZ = 60;
|
|
8
|
+
export const BROADCAST_HZ = 30;
|
|
9
|
+
/** Initial speed range (px/s) of a new object; collisions can raise one component to MAX_SPEED x sqrt(2). */
|
|
10
|
+
export const MIN_SPEED = 90;
|
|
11
|
+
export const MAX_SPEED = 180;
|
|
6
12
|
export const BOARD_WIDTH = 1280;
|
|
7
13
|
export const BOARD_HEIGHT = 720;
|
|
8
14
|
export const OBJECT_RADIUS = 25;
|