{"version":3,"file":"simReconciler.cjs","sources":["../../src/predict/simReconciler.ts"],"sourcesContent":["/**\n * SimReconciler — server-reconciled rollback for the entity (or entities) your\n * inputs control, when their authoritative truth isn't a single flat scalar list.\n *\n * The general counterpart to {@link Reconciler}. Both run the SAME rollback loop\n * (shared via {@link RollbackController}); where `Reconciler` mirrors a declared\n * `fields` list off ONE authoritative schema instance, `SimReconciler`\n * orchestrates that loop over whatever your inputs affect:\n *   - **composite scalar state** — several schema instances stepped together by a\n *     shared plain-math sim (e.g. `{ paddle, puck }`: your paddle by input, the puck\n *     it bounces, reconciled as one), or\n *   - **opaque engine state** — a physics solver whose truth (contacts, velocities,\n *     sub-bodies) is far more than a handful of numbers.\n *\n * AUTO-BOUND ENTRIES — the composite-scalar case is declarative: put the DECODED\n * schema instances themselves in `world` and the controller derives everything\n * from their schema metadata:\n *   - each bound entry is replaced IN PLACE by a plain scratch **mirror** seeded\n *     from the instance's scalar fields — `step` mutates the mirror, never the\n *     decoded tree;\n *   - reconcile re-copies every bound field from the instance on EVERY ack\n *     (unconditional pull — replay has mutated the mirror since the last adopt,\n *     so even an unchanged field must be re-seeded or replay double-applies);\n *   - numeric bound fields become render-pose fields keyed `\"<part>.<field>\"`\n *     (`\"paddle.x\"`, `\"puck.vx\"`), smoothed + interpolated like any pose field;\n *     non-numeric scalars (strings, booleans) are adopted verbatim but not posed.\n *     The owning `Predict` also registers each bound (instance, numeric field)\n *     into `predict.value(instance, field)`, so bound entities render through the\n *     same read idiom as remotes.\n *\n * Detection is by decode identity, top-level `world` entries only (deliberately\n * shallow): an entry with a decoder-assigned refId is part of the replicated tree,\n * i.e. a truth source — bound. A locally-constructed schema instance (no refId)\n * throws (pass the decoded one, or a plain object for scratch). Anything else —\n * engine handles, plain literals — is opaque and untouched; to keep a decoded\n * instance opaque on purpose, nest it below a plain wrapper.\n *\n * Bound sources are PINNED at construction: a server-side ref swap\n * (`state.puck = new Puck()`) is not followed — recreate the controller if your\n * server replaces instances (in-place mutation is the norm).\n *\n * For opaque state, `adopt` / `pose` remain what they always were, and compose\n * with bound entries: bound triples adopt FIRST, then your `adopt` covers the\n * rest (it may derive from just-adopted mirrors); a custom `pose` contributes\n * fields in addition to the bound parts' auto fields (its keys win on collision).\n * At least one restore path is required — zero bound entries and no `adopt`\n * throws at construction.\n *\n * > **Tradeoff:** adopt reseeds SCALARS (bound fields + whatever your `adopt`\n * > copies) and replay reproduces the rest. Engine-INTERNAL non-scalar state\n * > (contact caches, sleeping islands, solver accumulators) is NOT rolled back\n * > across reconcile. Both shipped consumers (composite scalars; a physics-engine\n * > shooter reseeding position+velocity) are well-served by this; an engine that\n * > depends on internal state surviving reconcile would need a per-tick snapshot\n * > ring, which this controller intentionally does not carry.\n *\n * Smooth error correction operates on the RENDER POSE (auto-derived from bound\n * numeric fields, and/or returned by {@link SimReconcilerOptions.pose}): a\n * misprediction is absorbed into a per-pose-field visual offset that decays to 0\n * over a few frames, so corrections never pop. For non-lerp poses (3D\n * quaternions) pass {@link SimReconcilerOptions.interpolate} — the default is a\n * per-field numeric lerp (translation/scalar only).\n *\n * Fixed-timestep, same shape as `Reconciler`, and a pure OBSERVER: you mutate + send\n * through the input handle directly; `predict.tick(now)` returns how many fixed steps\n * are due and drives reconcile + decay; the controller subscribes to the handle's\n * `onSend` and runs `step` for each input right as you send it. Render reads\n * ({@link value}/{@link pose}) interpolate between the two latest steps so motion stays\n * smooth above the step rate.\n *\n * The lifecycle, keyed to network acks the app never sees directly:\n *\n *     your render frame:\n *                                          ┌─ new ack? ─▶ adopt (bound pulls + adopt())  adopt server truth\n *       n = predict.tick(now) ─────────────┤             step(ctx, world, cmd) × pend    replay, isReplay=true\n *                                          │             refresh pose (once)\n *                                          └─ always ──▶ error decay\n *       n × (input.data = …; input.send()) ─▶            step(ctx, world, cmd)           live, isReplay=false (on send)\n *       draw(predict.value(player, \"x\"))   ◀── pure read: interpolate + smooth\n *\n * Composite-scalar example (no engine — the common case):\n *\n *     const input = room.input({ type: MoveInput, mode: \"reliable\" });\n *     const me = predict.sim({\n *         input,\n *         world: {\n *             paddle: player,                                      // decoded schema ⇒ auto-bound\n *             puck:   room.state.puck,                             // ⇒ auto-bound (x, y, vx, vy)\n *         },\n *         step: (ctx, w, cmd) => stepWorld(w, cmd, ctx.dt),        // SHARED with the server\n *         smoothMs: 65,\n *     });\n *     const n = predict.tick(now);                                 // fixed steps due this frame\n *     for (let i = 0; i < n; i++) { stage(input.data); input.send(); } // mutate + send via handle\n *     draw(predict.value(player, \"x\"), predict.value(room.state.puck, \"x\")); // one read idiom\n *     aim(me.world.paddle);                                        // raw predicted state for logic\n *\n * Engine-backed example (a physics solver — opaque world, explicit adopt/pose):\n *\n *     const me = predict.sim({\n *         input,\n *         world: { world, body },                                  // the engine handle\n *         step:  (ctx, w, cmd) => { applyInput(w.body, cmd); w.world.step(); }, // dt = ctx.dt\n *         adopt: (w) => { w.body.setTranslation({ x: self.x, y: self.y }, true); },\n *         pose:  (w) => { const t = w.body.translation(); return { x: t.x, y: t.y }; },\n *     });\n */\n\nimport type { Schema } from \"@colyseus/schema\";\nimport { RollbackController, type RollbackOptions, type StepContext } from \"./rollback.ts\";\nimport { refIdOf, metadataOf, scalarFieldsOf } from \"../core/schema-reflect.ts\";\n\n// -----------------------------------------------------------------------------\n// Compile-time sugar for auto-bound worlds. Runtime detection is refId-based;\n// these types mirror it structurally (`Schema`'s class surface — assign/restore/\n// setDirty — is distinctive enough that engine handles can't false-match, and\n// the fluent API's instance type is `{fields} & Schema`, so both authoring\n// styles are covered).\n// -----------------------------------------------------------------------------\n\n/** Keys of T whose decoded value is a plain scalar (the mirror's field set). */\ntype ScalarKeys<T> = {\n    [K in keyof T]-?: NonNullable<T[K]> extends number | string | boolean ? K : never;\n}[keyof T] & string;\n\n/** The plain scratch mirror a bound schema instance materializes into. */\nexport type ScalarsOf<T> = Pick<T, ScalarKeys<T>>;\n\n/** Keys of T whose decoded value is a number (the pose/smoothing subset). */\ntype NumericKeys<T> = {\n    [K in keyof T]-?: NonNullable<T[K]> extends number ? K : never;\n}[keyof T] & string;\n\n/**\n * The world shape `step` / `adopt` / `pose` receive and {@link SimReconciler.world}\n * returns: decoded schema entries are replaced by their plain scalar mirrors;\n * opaque entries pass through unchanged.\n */\nexport type Materialize<E> = {\n    [K in keyof E]: E[K] extends Schema ? ScalarsOf<E[K]> : E[K];\n};\n\n/** Auto-derived pose keys for the bound entries of a world: `\"<part>.<field>\"`\n *  per numeric scalar field (`\"paddle.x\"`, `\"puck.vx\"`). */\nexport type BoundPoseKeys<E> = {\n    [K in keyof E & string]: E[K] extends Schema ? `${K}.${NumericKeys<E[K]>}` : never;\n}[keyof E & string];\n\n/** One auto-bound world entry, resolved at construction: the pinned decoded\n *  source, its in-world mirror, and the field sets derived from schema metadata\n *  (`fields` = every scalar, the adopt set; `numeric` ⊆ `fields`, the pose set;\n *  `poseKeys` parallel to `numeric`). */\ninterface BindingTriple {\n    source: Record<string, any>;\n    mirror: Record<string, any>;\n    fields: readonly string[];\n    numeric: readonly string[];\n    poseKeys: readonly string[];\n}\n\nexport interface SimReconcilerOptions<I, P extends Record<string, number>, E> extends RollbackOptions<I> {\n    /**\n     * Your world handle — whatever your callbacks need to reach the simulated\n     * state. Entries that are DECODED schema instances (`{ paddle: player,\n     * puck: state.puck }`) are auto-bound: replaced in place by plain scalar\n     * mirrors that the controller seeds, re-adopts on every ack, and poses (see\n     * the file header). Everything else — an engine handle (`{ world, body }`),\n     * plain scratch literals — is opaque and untouched. Stored once and passed\n     * to every callback; never swapped (no snapshot ring to thread a fresh root\n     * through). Capture bound parts via `me.world` AFTER construction (the\n     * mirror replaces the instance on this very object).\n     */\n    world: E;\n    /**\n     * Deterministic input-application step, SHARED with the server. Apply `command`\n     * to `world` and advance it by `ctx.dt` (the engine's internal timestep MUST\n     * equal `ctx.dt` for replay to reproduce the server). One-shot concerns go\n     * through `ctx.memo` (freeze a value replay can't re-derive) and\n     * `ctx.predict` (optimistic events — live steps only, replay-safe).\n     *\n     * Parameter order matches `Reconciler`'s `step(ctx, state, command)`:\n     * context, the thing you mutate, the input — `world ≈ state`.\n     *\n     * `command` is the buffered wire input the handle recorded at `send()`\n     * (`input.at(seq)`) — the round-tripped value the server decodes, read the same\n     * way on the live catch-up step and on rollback replay, so lossy wire fields\n     * replay identically.\n     */\n    step: (ctx: StepContext, world: Materialize<E>, command: I) => void;\n    /**\n     * Adopt the server's authoritative truth into `world`'s OPAQUE entries: seed\n     * them from the authoritative scalars on your schema instance(s). Called on\n     * every server ack, BEFORE the unacked inputs are replayed on top — and AFTER\n     * the bound entries' auto-adopt, so it may derive from just-adopted mirrors\n     * (e.g. reseed an engine body from a bound part). The whole patch is decoded\n     * before the ack is processed, so reading several instances in one `adopt`\n     * adopts them all from the same server tick.\n     *\n     * Optional when bound entries cover the world; REQUIRED when nothing is\n     * bound (there'd be no restore point — construction throws).\n     */\n    adopt?: (world: Materialize<E>) => void;\n    /**\n     * Read `world`'s OPAQUE entries into a render pose — a record of numbers\n     * (e.g. `{ x, y }` or `{ x, y, z, qx, qy, qz, qw }`). Called after every\n     * step/reconcile; smoothing and interpolation operate on these fields IN\n     * ADDITION to the bound entries' auto-derived `\"<part>.<field>\"` fields\n     * (custom keys win on collision). May return a reused object — the\n     * controller copies the numbers out synchronously. The field set is taken\n     * from the first call and assumed stable. Optional — bound-only worlds\n     * need no pose callback at all.\n     */\n    pose?: (world: Materialize<E>) => P;\n    /**\n     * Custom pose interpolation `a → b` by `t ∈ [0,1]`. Required for poses that\n     * don't lerp componentwise (quaternions → slerp + renormalize). Default is a\n     * per-field numeric lerp. `a`/`b` may be reused scratch — don't retain them.\n     */\n    interpolate?: (a: P, b: P, t: number) => P;\n}\n\nexport class SimReconciler<I = any, P extends Record<string, number> = any, E = any> extends RollbackController<I> {\n    /** Your world handle — set once at construction (bound entries already\n     *  materialized into mirrors), passed to every callback, never swapped. */\n    private readonly worldHandle: Materialize<E>;\n\n    /** Auto-bound entries (decoded schema instances found in `world`),\n     *  resolved once at construction. Empty for fully-opaque worlds. */\n    private readonly bindings: BindingTriple[] = [];\n\n    /** Current step's RAW pose, refreshed after every step: bound\n     *  `\"<part>.<field>\"` fields read off the mirrors + the custom `pose`\n     *  callback's fields (written after — custom wins on key collision). */\n    private readonly curPose: Record<string, number> = {};\n    /** Pose field names (bound keys ∪ custom keys), captured on the first\n     *  {@link refreshPose}. */\n    private poseFields: readonly string[] = [];\n    /** The custom `pose` callback's own field names (first-call snapshot). */\n    private customFields: readonly string[] = [];\n    private fieldsReady = false;\n\n    /** Reused scratch for {@link pose}: smoothed prev/cur endpoints + memo. */\n    private readonly poseA: Record<string, number> = {};\n    private readonly poseB: Record<string, number> = {};\n    private readonly renderPose: Record<string, number> = {};\n    /** Set whenever the pose endpoints/alpha change; {@link pose} recomputes once. */\n    private poseDirty = true;\n\n    private readonly step: (ctx: StepContext, world: Materialize<E>, command: I) => void;\n    private readonly adopt?: (world: Materialize<E>) => void;\n    /** The `pose` option callback, stored under a distinct name so it doesn't\n     *  shadow the public {@link pose} method. */\n    private readonly readPose?: (world: Materialize<E>) => P;\n    private readonly interpolate?: (a: P, b: P, t: number) => P;\n\n    constructor(opts: SimReconcilerOptions<I, P, E>) {\n        super(opts);\n\n        // Scan the world for decoded schema instances (top-level entries only —\n        // deliberately shallow) and materialize each into a plain mirror IN\n        // PLACE, so `step` and the app (via `me.world`) see the same object.\n        const world = opts.world as Record<string, any>;\n        for (const part of Object.keys(world)) {\n            const src = world[part];\n            if (src === null || typeof src !== \"object\") continue;\n            if (refIdOf(src) === undefined) {\n                if (metadataOf(src) !== undefined) {\n                    throw new Error(\n                        `predict.sim(): world.${part} is a schema instance that hasn't been ` +\n                        \"decoded (no refId). Pass the decoded instance from room.state (e.g. \" +\n                        \"inside onAdd), or a plain object for opaque scratch.\",\n                    );\n                }\n                continue;   // opaque entry (engine handle, scratch literal)\n            }\n            const { fields, numeric } = scalarFieldsOf(src);\n            if (fields.length === 0) {\n                throw new Error(\n                    `predict.sim(): world.${part} is a decoded ref with no scalar fields ` +\n                    \"to bind. Binding a whole COLLECTION isn't supported (yet) — spread \" +\n                    \"its children into world parts (one entry per entity, fixed at \" +\n                    \"construction). Nest a scalar-less instance below a plain wrapper \" +\n                    \"if you meant it as an opaque handle.\",\n                );\n            }\n            const mirror: Record<string, any> = {};\n            for (const f of fields) mirror[f] = src[f];\n            world[part] = mirror;\n            const poseKeys = numeric.map((f) => `${part}.${f}`);\n            this.bindings.push({ source: src, mirror, fields, numeric, poseKeys });\n        }\n        if (this.bindings.length === 0 && opts.adopt === undefined) {\n            throw new Error(\n                \"predict.sim(): no restore point — world has no schema-bound entries \" +\n                \"and no adopt() was provided. Put decoded schema instances in world \" +\n                \"(auto-bound), or provide adopt().\",\n            );\n        }\n\n        this.worldHandle = opts.world as unknown as Materialize<E>;\n        this.step = opts.step;\n        this.adopt = opts.adopt;\n        this.readPose = opts.pose;\n        this.interpolate = opts.interpolate;\n        // Seed pose from the world's current state.\n        this.refreshPose();\n        for (const f of this.poseFields) { this.prev[f] = this.curPose[f]; this.error[f] = 0; }\n    }\n\n    /** Read the world pose into {@link curPose}: bound fields off the mirrors,\n     *  then the custom `pose` callback's fields (custom wins on collision).\n     *  Captures the pose field set once, on the first call. */\n    private refreshPose(): void {\n        const cur = this.curPose;\n        for (const b of this.bindings) {\n            const { mirror, numeric, poseKeys } = b;\n            for (let i = 0; i < numeric.length; i++) cur[poseKeys[i]] = mirror[numeric[i]] as number;\n        }\n        if (this.readPose !== undefined) {\n            const pose = this.readPose(this.worldHandle) as Record<string, number>;\n            if (!this.fieldsReady) this.customFields = Object.keys(pose);\n            for (const f of this.customFields) cur[f] = pose[f];\n        }\n        if (!this.fieldsReady) {\n            const keys: string[] = [];\n            for (const b of this.bindings) for (const k of b.poseKeys) keys.push(k);\n            for (const f of this.customFields) if (!keys.includes(f)) keys.push(f);\n            this.poseFields = keys;\n            this.fieldsReady = true;\n        }\n        this.poseDirty = true;\n    }\n\n    /** Your world handle (passed to every callback). Bound entries read as their\n     *  plain mirrors — capture parts from HERE (post-construction), not from the\n     *  literal you passed in. Always current — inputs are stepped eagerly as you\n     *  `send()` them (the reconciler observes the handle). */\n    get world(): Materialize<E> { return this.worldHandle; }\n\n    /** @internal Bound (instance, numeric field, pose key) registrations for the\n     *  owning Predict's `value()` overlay — one entry per bound world part. */\n    get boundRegistrations(): ReadonlyArray<{ source: object; fields: readonly string[]; poseKeys: readonly string[] }> {\n        return this.bindings.map((b) => ({ source: b.source, fields: b.numeric, poseKeys: b.poseKeys }));\n    }\n\n    /**\n     * Rendered value for one pose field — bound fields by their dotted key\n     * (`\"paddle.x\"`), custom pose fields by their own name: the predicted pose\n     * interpolated between the previous and current fixed step by\n     * {@link renderAlpha}, plus the decaying correction offset. When a custom\n     * {@link SimReconcilerOptions.interpolate} is set, reads it off the\n     * interpolated {@link pose}. For bound entities prefer the room-wide idiom\n     * `predict.value(instance, field)` — same value, no handle threading.\n     */\n    value(field: BoundPoseKeys<E> | (keyof P & string)): number {\n        this.noteRenderRead();\n        if (this.interpolate) return (this.pose() as Record<string, number>)[field];\n        const c = this.curPose[field] + (this.error[field] ?? 0);\n        const p = this.prev[field] ?? c;\n        return p + (c - p) * this.renderAlpha();\n    }\n\n    /**\n     * The full interpolated + smooth-corrected render pose (bound `\"part.field\"`\n     * keys included). Use this (not repeated {@link value} calls) when a custom\n     * `interpolate` is set — it's computed once per frame and memoized. The\n     * returned record is REUSED — read it synchronously.\n     */\n    pose(): P {\n        this.noteRenderRead();\n        if (!this.poseDirty) return this.renderPose as unknown as P;\n        const t = this.renderAlpha();\n        const a = this.poseA, b = this.poseB;\n        for (const f of this.poseFields) { a[f] = this.prev[f] ?? this.curPose[f]; b[f] = this.curPose[f] + (this.error[f] ?? 0); }\n        if (this.interpolate) {\n            const out = this.interpolate(a as P, b as P, t) as Record<string, number>;\n            for (const f of this.poseFields) this.renderPose[f] = out[f];\n        } else {\n            for (const f of this.poseFields) this.renderPose[f] = a[f] + (b[f] - a[f]) * t;\n        }\n        this.poseDirty = false;\n        return this.renderPose as unknown as P;\n    }\n\n    // --- RollbackController hooks ----------------------------------------------\n\n    protected smoothedFields(): readonly string[] { return this.poseFields; }\n    protected readCurrent(field: string): number { return this.curPose[field]; }\n    protected applyStep(input: I): void { this.step(this.stepCtx, this.worldHandle, input); }\n\n    /** Bound triples pull first — every bound field, unconditionally (replay has\n     *  mutated the mirrors since the last adopt, so even a server-unchanged field\n     *  must be re-seeded or the next replay double-applies inputs on top of a\n     *  stale predicted value). The user `adopt` then covers the opaque rest. */\n    protected adoptTruth(): void {\n        for (const b of this.bindings) {\n            const { source, mirror, fields } = b;\n            for (let i = 0; i < fields.length; i++) mirror[fields[i]] = source[fields[i]];\n        }\n        this.adopt?.(this.worldHandle);\n    }\n\n    protected refreshRender(): void { this.refreshPose(); }\n    protected markDirty(): void { this.poseDirty = true; }\n\n    protected snapshotPrev(): void {\n        for (const f of this.poseFields) this.prev[f] = this.curPose[f] + this.error[f];\n    }\n\n    protected reseedState(): void {\n        this.adoptTruth();\n        this.refreshPose();\n        for (const f of this.poseFields) { this.prev[f] = this.curPose[f]; this.error[f] = 0; }\n    }\n}\n"],"names":["RollbackController","refIdOf","metadataOf","scalarFieldsOf"],"mappings":";;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GG;AAmHG,MAAO,aAAwE,SAAQA,2BAAqB,CAAA;AAkC9G,IAAA,WAAA,CAAY,IAAmC,EAAA;QAC3C,KAAK,CAAC,IAAI,CAAC;AA9Bf;AACoE;QACnD,IAAA,CAAA,QAAQ,GAAoB,EAAE;AAE/C;;AAEwE;QACvD,IAAA,CAAA,OAAO,GAA2B,EAAE;AACrD;AAC2B;QACnB,IAAA,CAAA,UAAU,GAAsB,EAAE;;QAElC,IAAA,CAAA,YAAY,GAAsB,EAAE;QACpC,IAAA,CAAA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