Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .changeset/netcode-events-across-saves.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
"@typeonce/ritmo-netcode": minor
---

**`session.events` confirms the ticks a save makes final.** A save (the match's start, `resync()`, a page seated again after it loaded again, a hidden page back under `"resync-on-return"`) is the host's world as it ran, guesses of other seats' input included. Until now every peer, the host too, withdrew the ticks it had run before the save but not confirmed yet, and never confirmed them: their events were gone without a word. Under rollback that is up to `maxRollback` ticks on every page at each save: a page that reloads mid-match lets the others run on guesses of its seat until it is back, so a lap, a checkpoint, or a sound of that stretch never reached any page. The page the save seated was not affected: it confirms every tick from the save on, as before.

- The host confirms every tick it ran before its save.
- The save carries the inputs each of its last ticks ran with on the host. Every other peer confirms the ticks it ran with the same inputs, from a tick both confirmed; what `predicted()` handed out of them stands.
- The ticks before the save that a peer ran otherwise, confirmed otherwise (it had an input the host's world never got), or did not run at all, are reported by `lost()` with the new reason `"save"`, and what was predicted of them is withdrawn. A page the save seats for its first match (one that loaded again) is told nothing of the ticks before it: the save's world holds them.
- Fixed: a peer ahead of the host can confirm the save's own tick and the `inputDelay` ticks after it; `lost()` reported one tick fewer when a resync ran them again with other events.

The sync message carries the inputs (protocol version 6, with this release's other session changes): every page of a match runs this release.

**Breaking (types only):** `EventsLost["reason"]` is `"unread" | "resync" | "save"`. A `switch` over it adds a case; ticks reported `"save"` are ones whose events this peer cannot tell, like `"resync"`:

```ts
const lost = hits.lost()
if (lost !== undefined && lost.reason !== "unread") {
// "resync" or "save": the match ran ticks lost.from to lost.to otherwise than this page acted on
}
```
2 changes: 1 addition & 1 deletion .changeset/netcode-one-message-per-frame.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

Over 120 ms with 60 ms of jitter and 5% loss, on pages at 60 Hz that sometimes run two or three steps in a frame: 2 peers went from 139 messages and 62 KiB a second to 97 and 16 to 23 KiB; 8 peers from 728 and 290 KiB to 387 and 73 to 103 KiB (the lower figure for input held 20 frames, the higher for input that changes nearly every frame).

**Breaking: every page of a match must run this version.** The session protocol changed (version 5): a peer on 0.26 or older ends with `ProtocolMismatch`.
**Breaking: every page of a match must run this version.** The session protocol changed (version 6): a peer on 0.26 or older ends with `ProtocolMismatch`.

**Breaking: the function `session.update(...)` returns takes the loop's two arguments.** Passed to `FixedLoop.start` as it is, nothing changes. Called from the game's own `update`, pass them through, so the session knows the frame's last step:

Expand Down
8 changes: 6 additions & 2 deletions integration/netcode/match.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ export interface Peer {
readonly heard: Array<Netcode.EventRecord<HitValue>>
/** Hits on screen as a flash: started when predicted, taken down when withdrawn, by tick. */
readonly flashes: Map<number, Array<HitValue>>
/** Ticks before a resync's save that this peer ran on a guess the host's world did not share: their hits are not known here. */
readonly lost: Array<Netcode.EventsLost>
}

type HitValue = { readonly seat: number; readonly shot: number }
Expand Down Expand Up @@ -55,7 +57,7 @@ export const match = (options: MatchOptions): readonly [Peer, Peer] => {
const shared = { simulate, seats: seats.value, seat, links: [links.value[seat]!], hostClock, step }
const session = options.mode === "rollback" ? Netcode.rollback(runtime, shared) : Netcode.lockstep(runtime, shared)
if (!session.ok) return fail("session", session.error)
return { runtime, screen, session: session.value, recorded: new Map(), heard: [], flashes: new Map() }
return { runtime, screen, session: session.value, recorded: new Map(), heard: [], flashes: new Map(), lost: [] }
}
const peers = [peer(0), peer(1)] as const
// The host's effects read the simulation's hits through the session: one reader each.
Expand All @@ -76,7 +78,9 @@ export const match = (options: MatchOptions): readonly [Peer, Peer] => {
for (const { tick } of reader.withdrawn()) flashes.delete(tick)
for (const { tick, value } of reader.predicted()) flashes.set(tick, [...flashes.get(tick) ?? [], value])
const lost = reader.lost()
if (lost !== undefined) fail(`seat ${seat} lost hits`, lost)
// A save can make final ticks this peer ran otherwise than the host: said, never silent. Nothing else is lost.
if (lost !== undefined && lost.reason === "save") peers[seat]!.lost.push(lost)
else if (lost !== undefined) fail(`seat ${seat} lost hits`, lost)
}
if (!hostClock.adjust(stepMS).ok) fail("clock", frame)
}
Expand Down
3 changes: 3 additions & 0 deletions integration/netcode/test/netcode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ describe("two peers play the shooter over a slow, reordering network", () => {
expect(status.verified).toBeGreaterThan(400)
}
expect(world(peers[0].runtime)).toBe(world(peers[1].runtime))
// The host's saves are its world: it confirms every tick it ran. The other seat may not tell a few ticks before each save, and says so.
expect(peers[0].lost).toEqual([])
for (const lost of peers[1].lost) expect(lost.to - lost.from).toBeLessThanOrEqual(8)
})
})

Expand Down
7 changes: 4 additions & 3 deletions packages/netcode/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,14 @@ const hits = session.events(Hit) // an event of the runtime's schema; one reader
for (const { tick } of hits.withdrawn()) particles.cancel(tick) // a rollback undid this tick's hits
for (const { tick, value } of hits.predicted()) particles.burst(tick, value.at) // may still be undone
for (const { value } of hits.confirmed()) sounds.play(value.kind) // exactly once per hit
const lost = hits.lost() // EventsLost: a reader that stopped reading, or a resync that replaced confirmed ticks; never silent
const lost = hits.lost() // EventsLost: a reader that stopped reading, a resync that replaced confirmed ticks, or ticks a save made final that this peer did not run as the host did; never silent
```

- `confirmed()` hands out each event once, when its tick can no longer run again within the epoch. A lockstep session confirms every tick it runs. A peer ahead of seat 0 can confirm a tick or two that seat 0's next save makes idle: when the resync runs them again with other events, `lost()` reports them with `reason: "resync"`, and the new run is not handed out again.
- `predicted()` hands out events of ticks that may still be rolled back. A tick a rollback runs again keeps what was handed out when it publishes the same events (plain data, compared by value); otherwise it is withdrawn and its new events are predicted again.
- `withdrawn()` names those ticks, so the host cancels what it started. A resync withdraws every predicted tick. A tick waiting to be withdrawn is held back from `predicted()` until `withdrawn()` named it, so a cancel never undoes the new run.
- A reader that does not call `confirmed()` for more than `Netcode.eventWindow` ticks loses the oldest: `lost()` reports them as `EventsLost` with `reason: "unread"`. One report per call, a `"resync"` one first.
- A save (the match's start, a resync, a seat seated again after a reload or a hidden tab) makes every tick before it final as the host's world went through it, guesses included. Each peer confirms the ticks it ran with the same inputs as the host (the save carries them), and the host confirms every tick it ran. The ticks before the save that a peer ran otherwise, or did not run, are reported by `lost()` with `reason: "save"`, and what was predicted of them is withdrawn. A page the save seats for its first match (one that loaded again) is told nothing of the ticks before it: the save's world holds them. From the save's tick on, every peer confirms each tick once.
- `withdrawn()` names those ticks, so the host cancels what it started. A save withdraws every predicted tick from its own tick on, which runs again. A tick waiting to be withdrawn is held back from `predicted()` until `withdrawn()` named it, so a cancel never undoes the new run.
- A reader that does not call `confirmed()` for more than `Netcode.eventWindow` ticks loses the oldest: `lost()` reports them as `EventsLost` with `reason: "unread"`. One report per call: a `"resync"` one first, then `"save"`, then `"unread"`.

When checksums differ, `advance` fails with `Desynced` until `resync()`. With `keepSnapshots: true` it carries this peer's save of that tick; `Desync.compare(mine, theirs)` from [`@typeonce/ritmo-devtools`](https://github.com/typeonce-dev/ritmo/blob/main/packages/devtools/README.md) lists what differs.

Expand Down
2 changes: 1 addition & 1 deletion packages/netcode/dtslint/Netcode.tst.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ describe("session.events", () => {
expect(hits.lost()).type.toBe<Netcode.EventsLost | undefined>()
const lost = hits.lost()
if (lost !== undefined) {
expect(lost.reason).type.toBe<"unread" | "resync">()
expect(lost.reason).type.toBe<"unread" | "resync" | "save">()
// @ts-expect-error and '"rollback"' have no overlap
if (lost.reason === "rollback") throw new Error("not a reason")
}
Expand Down
25 changes: 19 additions & 6 deletions packages/netcode/src/Netcode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -430,8 +430,15 @@ export interface EventsLost {
* ticks that the host's save makes idle). The new run's events are not
* handed out; undo or ignore what the old ones started if it matters
* (a score sent to a server).
* - `"save"`: a save made these ticks final, and this peer cannot tell
* their events as the match ran them: it ran them on a guess of another
* seat's input that the host's world did not share (the host saves its
* world as it ran, guesses included), or it confirmed them and the
* host's world went through them otherwise. What `predicted()` handed
* out of them is withdrawn. The ticks this peer ran as the host did are
* confirmed, and the host's own runs always are.
*/
readonly reason: "unread" | "resync"
readonly reason: "unread" | "resync" | "save"
}

/** How many confirmed ticks of events a reader of `session.events(...)` that stopped reading keeps; older ones are {@link EventsLost}. */
Expand All @@ -450,15 +457,21 @@ export const eventWindow: number = EventsInternal.window
* rollback runs again keeps what `predicted()` handed out when it publishes
* the same events (plain data compared by value; a class instance or a map
* counts as changed); otherwise it is withdrawn, and its new events are
* predicted again. A resync withdraws every predicted tick. A reader sees
* the ticks run from when it was made.
* predicted again. A save (the match's start, a resync, a page seated
* again) makes every tick before it final: the ticks this peer ran as the
* host's world did are confirmed, the others reported through `lost()`,
* and every predicted tick from the save on is withdrawn and runs again.
* Ticks before the save that this peer never ran are in the save's world,
* and no reader is told their events. A reader sees the ticks run from when
* it was made.
*/
export interface EventStreams<Value> {
/**
* Events of ticks that will not run again, each handed out once: a
* rolled-back tick is handed out only as it finally ran. A lockstep
* session confirms every tick it runs. Final within one epoch: a resync
* can replace ticks it handed out, which `lost()` reports.
* can replace ticks it handed out, which `lost()` reports. A save confirms
* the ticks before it that this peer ran as the host did.
*/
readonly confirmed: () => ReadonlyArray<EventRecord<Value>>
/**
Expand All @@ -475,8 +488,8 @@ export interface EventStreams<Value> {
readonly withdrawn: () => ReadonlyArray<Withdrawn>
/**
* Confirmed events lost since the previous report: `undefined` when none.
* One report per call: when both reasons are pending, a `"resync"` one
* comes first and the `"unread"` one on the next call.
* One report per call: when several reasons are pending, a `"resync"` one
* comes first, then `"save"`, then `"unread"`, one on each call.
*/
readonly lost: () => EventsLost | undefined
}
Expand Down
48 changes: 38 additions & 10 deletions packages/netcode/src/internal/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@
* out for them; a tick that runs again with other events is reported
* through `lost()` with the reason `"resync"`, and its new run is not
* handed out as confirmed a second time.
*
* A save makes every tick before it final, as the host's world went through
* it, though this peer may have run the last of them only on a guess. The
* session tells the ledger how far this peer's runs were the host's
* (`save`): those ticks are handed out as confirmed; the ones after, up to
* the save, are reported through `lost()` with the reason `"save"`, whether
* this peer ran them otherwise, confirmed them otherwise, or never ran them.
*/
import * as Inspector from "@typeonce/ritmo/Inspector"
import * as System from "@typeonce/ritmo/System"
Expand All @@ -39,8 +46,8 @@ interface Reader {
readonly delivered: Map<number, ReadonlyArray<unknown>>
/** Ticks a rewind undid after `predicted()` handed out their records, not read yet. */
readonly withdrawn: Set<number>
/** Confirmed events dropped unread, and confirmed ticks a resync ran again with other events: reported apart. */
readonly lost: { unread: Range | undefined; resync: Range | undefined }
/** Confirmed events dropped unread, confirmed ticks a resync ran again with other events, and ticks a save made final that this peer did not run as the host did: reported apart. */
readonly lost: { unread: Range | undefined; resync: Range | undefined; save: Range | undefined }
}

interface Range {
Expand All @@ -57,8 +64,15 @@ export interface Ledger {
readonly rewind: (from: number) => void
/** After a rollback ran again: withdraws what readers saw of ticks that did not run again. */
readonly resolve: () => void
/** Every unsettled tick is gone: a resync. Withdraws everything predicted. */
readonly reset: () => void
/**
* A save at tick `at`, restored: every tick before it is final. This
* peer's runs before `final` were the host's: their records are handed out
* as confirmed. The ticks from `final` up to `at` are lost (`"save"`):
* this peer ran them otherwise, confirmed them otherwise, or never ran
* them. Every unsettled tick from `at` on is gone, and what was predicted
* of it withdrawn.
*/
readonly save: (at: number, final: number) => void
/** Every tick before `settled` will not run again: hands its records to the readers' confirmed queues once. */
readonly settle: (previous: number, settled: number) => void
/** A new reader, from tick `from` on. */
Expand All @@ -71,7 +85,7 @@ export interface LedgerHost {
readonly inspect: (inspector: unknown) => unknown
/** The ticks before this one are settled. */
readonly settled: () => number
/** How many ticks before `settled()` a resync can run again: the idle ticks after a save. */
/** How many ticks before `settled()` a resync can run again: the save's tick and the idle ones after it. */
readonly resyncReach: number
}

Expand Down Expand Up @@ -160,9 +174,23 @@ export const make = (host: LedgerHost, descriptor: { readonly name: string }): L
resolve: () => {
for (const reader of readers) for (const tick of reader.delivered.keys()) if (!log.has(tick)) withdraw(reader, tick)
},
reset: () => {
save: (at, final) => {
const before = [...log.keys()].filter((tick) => tick < at).sort(byTick)
for (const reader of readers) {
// Not as the host's world went through them: run otherwise, confirmed otherwise, or not run here at all.
const from = Math.max(final, reader.from)
if (from < at) lose(reader, "save", from, at)
for (const tick of before) {
if (tick < reader.from) continue
if (tick < final) {
// Run as the host ran it: what `predicted()` handed out of it stands.
for (const value of log.get(tick)!) reader.confirmed.push({ tick, value })
reader.delivered.delete(tick)
} else if (reader.delivered.has(tick)) withdraw(reader, tick)
}
for (const tick of reader.delivered.keys()) withdraw(reader, tick)
}
log.clear()
for (const reader of readers) for (const tick of reader.delivered.keys()) withdraw(reader, tick)
},
settle: (previous, settled) => {
const ticks = [...log.keys()].filter((tick) => tick < settled).sort(byTick)
Expand Down Expand Up @@ -200,7 +228,7 @@ export const make = (host: LedgerHost, descriptor: { readonly name: string }): L
for (const tick of handedOut.keys()) if (tick < settled - host.resyncReach) handedOut.delete(tick)
},
reader: (from) => {
const reader: Reader = { from, confirmed: [], delivered: new Map(), withdrawn: new Set(), lost: { unread: undefined, resync: undefined } }
const reader: Reader = { from, confirmed: [], delivered: new Map(), withdrawn: new Set(), lost: { unread: undefined, resync: undefined, save: undefined } }
readers.push(reader)
return {
confirmed: () => {
Expand All @@ -226,8 +254,8 @@ export const make = (host: LedgerHost, descriptor: { readonly name: string }): L
return ticks
},
lost: (): EventsLost | undefined => {
// One report per call, a resync's first: it replaced events the host may have acted on.
const reason = reader.lost.resync !== undefined ? "resync" : "unread"
// One report per call, a resync's first: it replaced events the host may have acted on; then a save's.
const reason = reader.lost.resync !== undefined ? "resync" : reader.lost.save !== undefined ? "save" : "unread"
const lost = reader.lost[reason]
if (lost === undefined) return undefined
reader.lost[reason] = undefined
Expand Down
Loading