diff --git a/apps/maker-gjs/data/org.pixelrpg.maker.gschema.xml b/apps/maker-gjs/data/org.pixelrpg.maker.gschema.xml index c44bb410..0df2e899 100644 --- a/apps/maker-gjs/data/org.pixelrpg.maker.gschema.xml +++ b/apps/maker-gjs/data/org.pixelrpg.maker.gschema.xml @@ -82,6 +82,20 @@ the dialog writes here too, so the two cannot disagree. + + '' + Who you are in a saved playthrough + + The key your half of a game's save record is filed under — + where you stood, and later what you carry. Stable across + launches, which is exactly what a peer id is not: a peer id is + new every session, so a position filed under one would be lost + on reconnect. Empty means "not generated yet"; the first read + writes a random id and keeps it. A fact about the person at the + keyboard, never shared with collaborators and never part of a + project. + + [] First-run tips already shown diff --git a/apps/maker-gjs/src/application.ts b/apps/maker-gjs/src/application.ts index 09bc2fdf..4f8f7da2 100644 --- a/apps/maker-gjs/src/application.ts +++ b/apps/maker-gjs/src/application.ts @@ -12,6 +12,7 @@ import { CollabIdentityService } from './services/collab-identity.service.ts' import { ControlDbusService } from './services/control-dbus.service.ts' import { cleanupOrphanedPublishers } from './services/orphan-publisher-cleanup.ts' import { lookupAppSettings } from './services/app-settings.ts' +import { playerIdentity } from './services/player-identity.ts' import { CoachMarksService } from './services/coach-marks.service.ts' import { EditorDefaultsService } from './services/editor-defaults.service.ts' import { type PixelrpgIntent, pickPixelrpgIntent } from './services/pixelrpg-url.ts' @@ -85,6 +86,21 @@ export class Application extends Adw.Application { */ readonly collabIdentityService = new CollabIdentityService() + /** + * Who the person at this keyboard is in a game's save record + * (GSettings `player-id`) — the key the engine files `players[id]` + * under. Read once in {@link onStartup}, because the first read is + * also the write that creates it: asking twice before the window + * exists would be two ids for one person. `undefined` until then; + * the engine falls back to its own default. + */ + private _playerId: string | undefined + + /** The save-record key of the local player; `undefined` before startup. */ + get playerId(): string | undefined { + return this._playerId + } + static { GObject.registerClass( { @@ -137,6 +153,8 @@ export class Application extends Adw.Application { this.editorDefaultsService.init(settings) this.coachMarksService.init(settings) this.collabIdentityService.init(settings) + // Not a service: one value, generated on first read and then fixed. + this._playerId = playerIdentity(settings) this.initControlInterface() // Opt-in @gjsify/devtools control plane (`org.gjsify.Devtools`) — the // standard interface `gjsify debug` (MCP) + a `gdbus` Screenshot speak, @@ -324,6 +342,7 @@ export class Application extends Adw.Application { this.editorDefaultsService, this.collabIdentityService, this.coachMarksService, + this._playerId, ) active_window.present() diff --git a/apps/maker-gjs/src/services/flags-edit.spec.ts b/apps/maker-gjs/src/services/flags-edit.spec.ts index ae3f1791..278b5729 100644 --- a/apps/maker-gjs/src/services/flags-edit.spec.ts +++ b/apps/maker-gjs/src/services/flags-edit.spec.ts @@ -12,6 +12,11 @@ export default async () => { expect(newFlag([], 'Mood', 'text').initial).toBe('') }) + await it('takes the scope it is given, so a per-thing flag stays per-thing', async () => { + expect(newFlag([], 'Chest open', 'yes-no', 'thing').scope).toBe('thing') + expect(newFlag([], 'Chest open', 'yes-no').scope).toBe('game') + }) + await it('never reuses an id of the list, even for the same name', async () => { const a = newFlag([], 'Key') const b = newFlag([a], 'Key') diff --git a/apps/maker-gjs/src/services/flags-edit.ts b/apps/maker-gjs/src/services/flags-edit.ts index bfa013ac..b7387b9e 100644 --- a/apps/maker-gjs/src/services/flags-edit.ts +++ b/apps/maker-gjs/src/services/flags-edit.ts @@ -1,6 +1,7 @@ import { type FlagData, type FlagKind, + type FlagScope, type FlagUsage, defaultFlagInitial, findFlagUsages, @@ -26,9 +27,18 @@ export type FlagRemoveResult = | { removed: false; reason: 'unknown' } | { removed: false; reason: 'in-use'; usage: FlagUsage[] } -/** A flag called `name` with the kind's default start value and a free id. */ -export function newFlag(list: readonly FlagData[], name: string, kind: FlagKind = 'yes-no'): FlagData { - return { id: newFlagId(list, name), name: name.trim(), kind, initial: defaultFlagInitial(kind), scope: 'game' } +/** + * A flag called `name` with the kind's default start value and a free id. + * `scope` says whose memory it is: one value for the game, or one per + * placed thing — see `docs/concepts/save-record.md`. + */ +export function newFlag( + list: readonly FlagData[], + name: string, + kind: FlagKind = 'yes-no', + scope: FlagScope = 'game', +): FlagData { + return { id: newFlagId(list, name), name: name.trim(), kind, initial: defaultFlagInitial(kind), scope } } /** Where `flagId` is referenced, across the library and every loaded map. */ diff --git a/apps/maker-gjs/src/services/player-identity.ts b/apps/maker-gjs/src/services/player-identity.ts new file mode 100644 index 00000000..a0b161cb --- /dev/null +++ b/apps/maker-gjs/src/services/player-identity.ts @@ -0,0 +1,47 @@ +import GLib from '@girs/glib-2.0' +import type Gio from '@girs/gio-2.0' + +/** + * Who this installation is in a saved playthrough (GSettings key + * `player-id`) — the key the engine files `players[id]` under. + * + * Generated once and kept, because a save is only worth keeping if the + * person it belongs to can be found again: an id that changed per launch + * would orphan every position it ever wrote. That is also why the peer + * id of a shared session cannot serve here — `generatePeerId()` is new + * every session by design. See `docs/concepts/save-record.md`. + * + * A fact about the person at the keyboard, like the view tier and the + * collaborator colour: it follows them across projects, is never written + * into a project, and is never sent to collaborators. + * + * Unlike `collab-name` and `collab-colour`, the default is *stored + * rather than derived*: there is nothing in the system to derive a save + * key from, and a value that cannot be recomputed must be written down + * the first time it exists. Falls back to a session-only id with a + * warning when the schema is unavailable, so an unpackaged build still + * plays — its save simply does not outlive the run, which is already + * true of every playtest. + */ +export function playerIdentity(settings: Gio.Settings | null): string { + if (!settings) { + console.warn('[playerIdentity] GSettings schema not found — this run gets a throwaway player id') + return generatePlayerId() + } + const stored = settings.get_string('player-id') + if (stored && stored.length > 0) return stored + const fresh = generatePlayerId() + settings.set_string('player-id', fresh) + return fresh +} + +/** + * A new save key: `player-` plus a UUID. + * + * A UUID rather than the shorter random token `generatePeerId()` builds, + * because two people whose records are merged into one world must not + * collide, and a merge has no referee to break a tie with. + */ +export function generatePlayerId(): string { + return `player-${GLib.uuid_string_random()}` +} diff --git a/apps/maker-gjs/src/services/project-store.spec.ts b/apps/maker-gjs/src/services/project-store.spec.ts index 3dee6fd1..ff421e6f 100644 --- a/apps/maker-gjs/src/services/project-store.spec.ts +++ b/apps/maker-gjs/src/services/project-store.spec.ts @@ -1298,6 +1298,14 @@ export default async () => { expect(store.pruneUnusedPickerFlags()).toStrictEqual([]) }) + await it('createFlag stores the scope the picker asked for', async () => { + const { store, data } = makeStore(makeProjectData({ flags: [] })) + const perThing = store.createFlag('Chest open', 'yes-no', 'thing') + const perGame = store.createFlag('Has the map') + expect(data.flags?.find((f) => f.id === perThing)?.scope).toBe('thing') + expect(data.flags?.find((f) => f.id === perGame)?.scope).toBe('game') + }) + await it('applies remote flag ops without re-broadcasting', async () => { const { store, data } = makeStore() const session = makeSession() diff --git a/apps/maker-gjs/src/services/project-store.ts b/apps/maker-gjs/src/services/project-store.ts index 46932e1b..ecadbefe 100644 --- a/apps/maker-gjs/src/services/project-store.ts +++ b/apps/maker-gjs/src/services/project-store.ts @@ -25,6 +25,7 @@ import { FLAG_UPSERT_KIND, type FlagData, type FlagKind, + type FlagScope, findFlagUsages, type CreditEntry, effectiveComponentRegistry, @@ -329,13 +330,13 @@ export class ProjectStore { appearances: RefOption[] languages: ProjectLanguages flags: FlagOption[] - createFlag: (name: string, kind?: FlagKind) => string | null + createFlag: (name: string, kind?: FlagKind, scope?: FlagScope) => string | null } { const resource = this.resource return { ...buildRefOptions(resource?.data?.maps, resource?.spriteSets, undefined, this.flags()), languages: this.languages(), - createFlag: (name, kind) => this.createFlag(name, kind), + createFlag: (name, kind, scope) => this.createFlag(name, kind, scope), } } @@ -343,15 +344,15 @@ export class ProjectStore { onFlagCreated: ((flag: FlagData) => void) | null = null /** - * The picker's "New…": make a yes/no flag called `name` and return its - * id (`null` for an empty name). No Undo toast: the action that asked + * The picker's "New…": make a flag called `name` of `kind` and `scope` + * and return its id (`null` for an empty name). No Undo toast: the action that asked * for it uses the flag at once, and a used flag cannot be removed. The * flag is remembered so {@link pruneUnusedPickerFlags} can take it back * when an undo leaves nothing using it. */ - createFlag(name: string, kind: FlagKind = 'yes-no'): string | null { + createFlag(name: string, kind: FlagKind = 'yes-no', scope: FlagScope = 'game'): string | null { if (!name.trim()) return null - const made = this.upsertFlag(newFlag(this.flags(), name, kind)) + const made = this.upsertFlag(newFlag(this.flags(), name, kind, scope)) if (!made) return null if (!made.previous) this._pickerFlags.add(made.flag.id) this.onFlagCreated?.(made.flag) diff --git a/apps/maker-gjs/src/widgets/application-window.ts b/apps/maker-gjs/src/widgets/application-window.ts index 247b96f5..a6b1d412 100644 --- a/apps/maker-gjs/src/widgets/application-window.ts +++ b/apps/maker-gjs/src/widgets/application-window.ts @@ -295,6 +295,9 @@ export class ApplicationWindow extends Adw.ApplicationWindow implements EntityDe const engine = new Engine() // A test language chosen before the engine existed still applies. engine.setPlayLocale(this._testLocale) + // Who a test run saves as. Fixed for the window's lifetime, so + // unlike the locale it never has to be re-applied later. + engine.setLocalPlayerId(this._playerId) return engine }, ) @@ -564,6 +567,13 @@ export class ApplicationWindow extends Adw.ApplicationWindow implements EntityDe private readonly _editorDefaults: EditorDefaultsService, private readonly _collabIdentity: CollabIdentityService, private readonly _coachMarks: CoachMarksService, + /** + * Who the person here is in a game's save record + * (`players[playerId]`) — supplied by the application, which read it + * from GSettings. `undefined` leaves the engine on its own default. + * See `docs/concepts/save-record.md`. + */ + private readonly _playerId?: string, ) { super({ application }) this._installActions() @@ -635,7 +645,7 @@ export class ApplicationWindow extends Adw.ApplicationWindow implements EntityDe * extraction). */ private _wireStoreEvents(): void { - this._scene_editor_view.flagCreator = (name, kind) => this._projectStore.createFlag(name, kind) + this._scene_editor_view.flagCreator = (name, kind, scope) => this._projectStore.createFlag(name, kind, scope) this._projectStore.onFlagCreated = (flag) => this._showToast(_('Added flag “%s”').replace('%s', flag.name)) this._projectStore.on('flags-changed', () => this._scene_editor_view.refreshFlagOptions()) this._projectStore.on('notice', (notice) => this._showToast(this._noticeText(notice))) diff --git a/apps/maker-gjs/src/widgets/scene-editor-view.ts b/apps/maker-gjs/src/widgets/scene-editor-view.ts index ddde38c4..fe6c85c0 100644 --- a/apps/maker-gjs/src/widgets/scene-editor-view.ts +++ b/apps/maker-gjs/src/widgets/scene-editor-view.ts @@ -9,6 +9,7 @@ import { effectiveComponentRegistry, type EntityDefinition, type FlagKind, + type FlagScope, type LayerPlane, makeTileStamp, type MapData, @@ -175,7 +176,7 @@ export class SceneEditorView extends ResponsiveEditorView { private _mapData: MapData | null = null private _refProject: LoadedProject | null = null /** Makes a flag for the action pickers' "New…"; the window points it at the ProjectStore. */ - flagCreator: ((name: string, kind?: FlagKind) => string | null) | null = null + flagCreator: ((name: string, kind?: FlagKind, scope?: FlagScope) => string | null) | null = null /** The project's entity library, for resolving a placement to its definition. */ private _entityLibrary: readonly EntityDefinition[] = [] /** Sprite sheets behind the placement sprites, keyed by sprite-set id. */ @@ -1035,7 +1036,7 @@ export class SceneEditorView extends ResponsiveEditorView { const data = project.resource.data this._pages.selected.setRefOptions({ ...buildRefOptions(data?.maps, project.resource.spriteSets, data?.languages, data?.flags), - createFlag: (name, kind) => this.flagCreator?.(name, kind) ?? null, + createFlag: (name, kind, scope) => this.flagCreator?.(name, kind, scope) ?? null, }) } diff --git a/docs/concepts/README.md b/docs/concepts/README.md index 7fe81341..af72229d 100644 --- a/docs/concepts/README.md +++ b/docs/concepts/README.md @@ -43,6 +43,7 @@ Ordered by dependency — read top-to-bottom for the cleanest mental sequence. E | [`entity-and-appearance-model.md`](entity-and-appearance-model.md) | **The target content model** — explicit `components[]` on entity definitions (replaces `ObjectKind`-switch + properties union), component registry with schema-generated inspectors, templates as the RPG-Maker-style authoring surface, declarative states, **Appearance** (sheet + animations) as a shared asset layer. Folds the Cast "Characters"/"Sprite sheets" split in; where the built-in code editor attaches. | | [`game-systems.md`](game-systems.md) | **What a project is made of** — `GameSystemSpec`: the switchable bundle of components, templates and ECS systems a user turns on ("my game has fighting"), distinct from an ECS `System`. Component ownership (exactly one owner, machine-checked), the effective registry, dormant-vs-unknown, the `__project/systems.set` channel, the Game-rules page, and the flag store + conditional states the base layer ships. | | [`action-sequencer.md`](action-sequencer.md) | **A list that can pause** — the run as a stack of frames on the triggering entity (`ActionRunComponent`), the control lock on the session singleton (`ControlLockComponent`) that takes input intent without stopping the world, re-trigger guards, scene unload, what each peer runs, and the save's "at rest" definition. | +| [`save-record.md`](save-record.md) | **What a playthrough remembers** — the `world` / `players` split of the save record: game-scoped flag values, thing-scoped values keyed by placement id (so two chests are two memories under one flag), removed-thing markers, per-player position. Where the player id comes from, how `scope: thing` resolves into the view `evaluateCondition` reads, and what the bag and the save file add later. | | [`collaboration-and-multiplayer.md`](collaboration-and-multiplayer.md) | **Multi-peer sync** — Op-Log with Host-Sequencer (Player 1) for both collaborative editing and networked multiplayer. Single mechanism, two op vocabularies. Solo edits work locally; collab requires a host. | | [`ai-collaborator.md`](ai-collaborator.md) | **In-process AI as live peer** — virtual collaborator on the shared op-log + awareness (cursor, presence, follow), driven via D-Bus/MCP, relayed to remote peers. | diff --git a/docs/concepts/collaboration-and-multiplayer.md b/docs/concepts/collaboration-and-multiplayer.md index 70a0d0de..ebcf8de9 100644 --- a/docs/concepts/collaboration-and-multiplayer.md +++ b/docs/concepts/collaboration-and-multiplayer.md @@ -234,6 +234,8 @@ type GameOp = Note the symmetry with editor ops: every op references stable IDs, carries enough state for application, and is host-validated before broadcast. +`playerId` here is the save record's player key — a stable per-device id, never a peer id, which is fresh per session. `object.removed` lands in `world.removedThings` and a `set-flag` on a thing in `world.things[placementId]`; both are the host's to write. See [`save-record.md`](save-record.md). + The host **runs the simulation** locally. Non-host peers send `input.frame` ops; the host runs its physics + game systems and produces the `player.moved` / `object.removed` / `item.granted` ops as the **broadcast result**. For non-host peers, "playing the game" is essentially watching a stream of ops + sending input ops back. Their local engine applies the broadcasts to mirror the host's state. @@ -263,6 +265,8 @@ SpriteData.tileProperties // shared (via __project/spriteset.update.chunk // game — replicated via game op-log (host-authoritative; future) TileTransformComponent (player) // host derives + broadcasts via player.moved +GameSaveStateComponent.world // host-authoritative (flags, things, removedThings) +GameSaveStateComponent.players[] // the peer playing that player writes; host validates PlayerHealthComponent (future) // host-authoritative InventoryComponent (future) // host-authoritative @@ -385,6 +389,7 @@ Most of the shared work lands *implicitly* as we land the earlier object-system - [`editor-architecture.md`](editor-architecture.md) — the operation-oriented mutation API + `Command` interface defined there **IS** the editor op vocabulary. Phase 5 (Undo) implicitly designs the editor op-log for us. Phase 0 constraints in this doc fold back into editor-architecture's migration phases. - [`runtime-modes.md`](runtime-modes.md) — Live Run and Test Run share a single peer's simulation; they're not multiplayer-aware. Full Run with multiplayer is where the game op-log machinery activates. The mode markers themselves are local-only — `EditorMode` / `RuntimeMode` / `SpawnOverride` never replicate. - [`object-system.md`](object-system.md) — stable identifiers (`ObjectPlacement.id`, `EntityDefinition.id`) are what editor op payloads are keyed on. The transport-compatibility constraint covered in Phase 0 means future schema changes must preserve "stable keys in array-shaped collections, no circular refs, JSON-serialisable everywhere". +- [`save-record.md`](save-record.md) — the state behind the game op vocabulary: `world` (host-authoritative: flags, thing flag values, removed things) and `players[playerId]` (position, written by the peer playing it). The split is what makes "who may write this" a question with an answer; phase 6 replicates it. ## Open questions diff --git a/docs/concepts/entity-and-appearance-model.md b/docs/concepts/entity-and-appearance-model.md index e17eb7a4..af1df974 100644 --- a/docs/concepts/entity-and-appearance-model.md +++ b/docs/concepts/entity-and-appearance-model.md @@ -133,7 +133,7 @@ interface EntityState { } ``` -A door (closed/open), a day/night NPC, a quest-stage marker. State evaluation is `StateSystem` (`packages/engine/src/systems/state.system.ts`) reading the flag store `FlagSystem` folds `FLAG_SET` into (`GameSaveStateComponent` on the session singleton). +A door (closed/open), a day/night NPC, a quest-stage marker. State evaluation is `StateSystem` (`packages/engine/src/systems/state.system.ts`) reading the save record `FlagSystem` folds `FLAG_SET` into (`GameSaveStateComponent` on the session singleton). A `scope: 'thing'` flag resolves per placement, so two chests sharing one flag remember separately — see [`save-record.md`](save-record.md). The condition vocabulary is a small typed union (`flag-is`, `counter`, `has-item`, one level of `all` / `any` / `not`), with `{ flag, equals? }` kept as shorthand for `flag-is` — see [`game-systems.md`](game-systems.md). An expression DSL nobody validates is still refused. Any other `when` is a validation warning and never matches, so a project from a newer editor still opens. diff --git a/docs/concepts/game-systems.md b/docs/concepts/game-systems.md index 81972d8f..e3f64308 100644 --- a/docs/concepts/game-systems.md +++ b/docs/concepts/game-systems.md @@ -112,8 +112,8 @@ The model is built in `apps/maker-gjs/src/services/game-rules-model.ts` (pure, u The base layer's payload this round is the thing that makes the simple view able to build a real game: a key sets a flag, a locked door opens only when that flag is set. -- **Flags are project data** (`GameProjectData.flags`: `id`, `name`, `kind`, `initial`, `scope`); every `set-flag` and `when` names the flag's **id**. A playthrough starts from each flag's `initial`. `scope: 'thing'` is stored but behaves like `'game'` until the world/player/thing split. Old projects migrate on load (`format/migrate-flags.ts`); removing a flag a door, chest or state still names is refused. `findFlagUsages` (`format/flag-usages.ts`) lists every read and write per flag; Game › Flags shows that list, one row per place, each a link to the thing. -- **`GameSaveStateComponent`** (session singleton) holds `flags`. `FlagSystem` folds `FLAG_SET` into it — the event `EventActionSystem` has emitted since the action list shipped, heard by nobody until now. +- **Flags are project data** (`GameProjectData.flags`: `id`, `name`, `kind`, `initial`, `scope`); every `set-flag` and `when` names the flag's **id**. A playthrough starts from each flag's `initial`. `scope: 'game'` is one memory for the whole game; `scope: 'thing'` is one memory per placement, so two chests sharing the flag "Chest is open" remember separately — see [`save-record.md`](save-record.md). Old projects migrate on load (`format/migrate-flags.ts`); removing a flag a door, chest or state still names is refused. `findFlagUsages` (`format/flag-usages.ts`) lists every read and write per flag; Game › Flags shows that list, one row per place, each a link to the thing. +- **`GameSaveStateComponent`** (session singleton) holds the save record: `world` (game-scoped flag values, thing-scoped values by placement id, removed things) and `players[playerId]`. `FlagSystem` folds `FLAG_SET` into it, routed by the flag's scope — the event `EventActionSystem` has emitted since the action list shipped, heard by nobody until the store existed. See [`save-record.md`](save-record.md). - **`EntityStatesComponent`** is attached by the spawn pipeline when a definition declares `states`, carrying the authored states plus the entity's base actions. - **`StateSystem`** resolves the first matching state each tick and swaps the entity's action list, so `EventActionSystem` runs the new body unchanged. Per-tick and idempotent rather than event-driven: it covers entities spawned after a flag was set, needs no ordering agreement with `FlagSystem`, and cannot miss an event. Gated on `RuntimeModeComponent` — the editor always shows the base composition. diff --git a/docs/concepts/save-record.md b/docs/concepts/save-record.md new file mode 100644 index 00000000..8c8143b8 --- /dev/null +++ b/docs/concepts/save-record.md @@ -0,0 +1,252 @@ +# The Save Record — world, players, things + +> Status: tracked in the [phase tracker](#phase-tracker) — the single source of truth for what's landed vs planned. + +A playthrough remembers three different kinds of thing, and before this design it remembered them +in one flat bag. `GameSaveStateComponent.flags` was `Record`: "the door is +unlocked" and "this chest is open" lived side by side, keyed only by the flag's id. That works +until the second chest. + +Two chests both set the flag "Chest is open". In one bag they are the same memory: opening the +first opens the second. The author's repair is to declare one flag per chest — `chest-open-1`, +`chest-open-2`, … — which is a global name for a local fact, and it does not scale past the first +dungeon. `FlagData.scope` has carried `'thing'` since flags became project data precisely so this +could be fixed without a file-format change; until now the runtime treated `'thing'` exactly like +`'game'`. + +The second thing the flat bag cannot hold is a **second player**. Collaboration and multiplayer +(see [`collaboration-and-multiplayer.md`](collaboration-and-multiplayer.md)) put more than one hero +in one world. "The gate is open" is one fact for everyone; "where I am standing" is one fact per +person. A single `Record` has no place to say which. + +This document decides the shape that separates them. + +## The record + +```ts +interface GameSaveRecord { + schemaVersion: number + world: WorldRecord + players: Record +} + +interface WorldRecord { + /** Game-scoped flag values, by flag id. One memory for everyone. */ + flags: Record + /** Thing-scoped flag values: placement id → flag id → value. */ + things: Record> + /** Placement ids the world no longer shows (a chest taken, a rock smashed). */ + removedThings: string[] +} + +interface PlayerRecord { + /** The map this player is on; `null` before the first spawn. */ + mapId: string | null + tileX: number | null + tileY: number | null + facing: string | null +} +``` + +Three deliberate properties: + +- **`world` is one thing, `players` is many.** Every fact that belongs to the game rather than to a + person is in `world`, keyed by nothing but itself. Every fact that belongs to a person is under + that person's id. There is no third place, and nothing is duplicated between them. +- **Thing-scoped values are keyed by `ObjectPlacement.id`,** the stable per-placement id the + `PlacementIdComponent` carries. Two chests built from the same library definition are two keys in + `world.things`, so one flag id — "Chest is open" — is enough for the whole game. This is the + workspace's stable-identifier rule (`AGENTS.md` § Transport-ready primitives) applied to save + state: Excalibur's runtime `Entity.id` is never a save or wire key. +- **A thing's values are in `world`, not in a player's record.** Whether a chest is open is a fact + about the world; two players walking into the same room must see the same chest. The alternative + (per-player thing state, so each player opens their own copy) is a game-design choice some games + want, and it would be a per-flag property rather than a different record — out of scope here, and + nothing in this shape forecloses it. + +### `schemaVersion` + +`schemaVersion` is on the record because the record is what a save file will contain (M8), and a +save written by one build is read by another. It is `1` today. A reader that finds a higher number +reads what it understands and leaves the rest untouched, the same discipline `GameProjectData` +already follows for a component type from a newer build: reduced behaviour, never an error, never a +rewrite that loses the part it did not understand. + +## Who writes what + +| Field | Writer | Through | +|---|---|---| +| `world.flags` | `FlagSystem` | `FLAG_SET` without a `thing` | +| `world.things[placementId][flagId]` | `FlagSystem` | `FLAG_SET` carrying `thing` | +| `world.removedThings` | — (M6; the field exists and is read) | — | +| `players[id].mapId/tileX/tileY/facing` | `PlayerSystem` | its own tile-change pass | + +**The host owns `world`.** In a session with peers, the host is the only peer that writes +`world.flags` and `world.things`; other peers receive the result. That is the host-authoritative +rule the game op vocabulary already states for `object.removed` and `item.granted`, and the split +is what makes it expressible: before it, a peer writing its own position and a peer writing a world +flag were the same write to the same bag. A player's own record is written by the peer that plays +that player and broadcast as `player.moved`; the host validates it. + +None of that replication is wired yet — phase 6 of the collab plan. What lands here is the shape it +needs, and the single writer per field that makes "who is allowed to write this" a question with an +answer. + +## How `scope: thing` resolves + +The flag's **definition** says which memory a reference means; the **placement** says which copy. + +1. `set-flag` runs inside an action list, and an action list is attached to the entity whose trigger + fired (`ActionRunComponent`, see [`action-sequencer.md`](action-sequencer.md)). `EventActionSystem` + reads that entity's `PlacementIdComponent` and puts it on the event: `FLAG_SET` and + `COUNTER_CHANGED` carry an optional `thing`. +2. `FlagSystem` looks the flag up in the project's flag list. `scope: 'game'` → `world.flags`. + `scope: 'thing'` **with** a `thing` id → `world.things[thing]`. `scope: 'thing'` with no `thing` + id (a run on an entity that is not a placement) falls back to `world.flags`, which is what the + build did for every thing-scoped flag until now: a write with no owner is better in the world + than dropped. +3. `StateSystem` resolves per entity. For each entity it builds the **view** that entity sees — + `world.flags` with that placement's `world.things` entry layered on top, and each thing-scoped + flag the placement has never written falling back to the flag's `initial` — and hands the view to + `evaluateCondition`. + +`evaluateCondition` stays pure and stays ignorant: it takes `ConditionState` and reads +`state.flags`. It does not know about placements, scopes or the ECS, which is what keeps it usable +from the editor (the condition summary, "Used in") with no engine running. + +The cost of the layering is one small record per entity per tick, and it is paid only by entities +that have states. The alternative — handing `evaluateCondition` a resolver callback — was rejected: +it makes a pure total function depend on something that can throw. + +## Migration + +The old shape is `{ flags: Record }` — no `world`, no `players`, no +`schemaVersion`. `migrateSaveRecord` reads it into `world.flags` verbatim and adds the empty +`things`, `removedThings` and `players`. Nothing is dropped and nothing is renamed, so the +migration is lossless and idempotent (a record that already has `schemaVersion` is returned +unchanged), the same contract `format/migrate-flags.ts` holds for the flag-name → flag-id bridge. + +There is no save file yet, so today the migration has exactly one real caller: a `runtime` snapshot +or an in-memory record built by an older build in the same process. It ships with the shape rather +than after it, because the first thing M8 does is read a file some build wrote. + +One behaviour change is not a migration and is named instead: a project whose flag is declared +`scope: 'thing'` used to get one global value and now gets one value per placement. That is the bug +this round fixes. A project that relied on the old behaviour — one flag, one value, several things +— declares the flag `scope: 'game'`, which is what it always meant. + +## The runtime snapshot + +`Engine.getRuntimeSnapshot()` feeds the D-Bus `GetStatus` `runtime` field a playtest driver reads. +It keeps `flags` as the flat game-scoped bag it always was, so every existing driver and spec reads +unchanged, and gains the rest of the record: + +```ts +interface RuntimeSnapshot { + flags: Record // === save.world.flags + thingFlags: Record> + removedThings: string[] + players: Record + playerTile: { x: number; y: number } | null // the local player, as before + // … dialogue, ask, input, facing as before +} +``` + +`playerTile` stays: it is read off the live actor, it is what every playtest asserts on, and it is +the local player. `players` is the record, which is the thing a second player will appear in. + +## What M5 and M8 add + +- **M5 — the bag.** An inventory is per player: `PlayerRecord` gains `bag`, and the `has-item` + condition (stored, editable, always `false` today) starts reading it through the same resolved + view, so `give-item` becomes a write to the acting player's record rather than to the world. Live + hit points join it there (`StatsRuntimeComponent` is the per-actor live block today and states the + same not-persisted rule). +- **M8 — saving at rest.** The record is what gets written. "At rest" is already defined by the + action sequencer: no blocking run is active, so `frames` and `pending` never reach the file and + the step vocabulary stays out of the save format. `schemaVersion` is what makes a file a file + rather than a dump, and `world`/`players` is what makes "continue on another machine" and "a + second player joins a saved world" the same read. + +Neither is built here. The fields they need are named above and absent from the type until their +system ships: a field nothing writes is a field that drifts. + +## Phase tracker + +| # | Scope | Status | +|---|---|---| +| 1 | `GameSaveRecord` on the session singleton — `world.flags` + `world.things` + `players`, `schemaVersion`, lossless migration from the flat bag | **landed** | +| 2 | `scope: 'thing'` resolves per placement id — `FLAG_SET`/`COUNTER_CHANGED` carry `thing`, `StateSystem` layers the view | **landed** | +| 3 | `scope` selectable in the editor's new-flag dialog | **landed** | +| 4 | Player id from the host (`player-id`, GSettings), `players[id]` written by `PlayerSystem` | **landed** (one local player) | +| 5 | `world.removedThings` written — a taken chest stays taken | planned (M6) | +| 6 | `PlayerRecord.bag` + `has-item` reading it; live hit points in the record | planned (M5) | +| 7 | Saving the record at rest, and reading a file a newer build wrote | planned (M8) | +| 8 | Host-authoritative replication of `world`; `player.moved` for each player's record | planned (collab phase 6) | + +## The player id + +A player's record is keyed by an id that must be **stable across runs** — the whole point of +`players[id]` is that the same person comes back to the same position — and must **not** be a peer +id: `generatePeerId()` in `session-service.ts` is fresh per session, so keying on it would file +every run under a new player. + +The id is therefore a fact about the device, supplied by the **host** and not invented by the +engine, exactly as the play locale is: `Engine.setLocalPlayerId` → `ProjectLoaderHost.localPlayerId()` +→ `MapSceneOptions.localPlayerId` → `GameSystemRuntimeContext.localPlayerId`. The engine's default +is the literal `'local'` (`LOCAL_PLAYER_ID`), so a host that supplies nothing — the browser host, a +headless spec — still gets a valid record with one player in it. + +The GJS maker supplies it from a new GSettings key, `player-id`, defaulting to the empty string and +filled with a generated UUID the first time it is read (`playerIdentity()` in +`apps/maker-gjs/src/services/player-identity.ts`). Empty-default-then-write is the pattern +`collab-name` and `collab-colour` already use and for the same reason: a value written at install +time freezes a fact about a machine into the settings of a user who never chose it. + +It is deliberately **not** the collaboration display name. The name is what others see and is +changed freely; the player id is what the save is keyed on and must never change. Two keys because +they have two lifetimes. + +## Where this is implemented + +- **The record** — `packages/engine/src/components/game-save-state.component.ts`: + `GameSaveRecord`, `WorldRecord`, `PlayerRecord`, `SAVE_RECORD_VERSION`, `LOCAL_PLAYER_ID`, + `emptySaveRecord`, `initialFlagValues`, `migrateSaveRecord`, `resolvedFlagView`. +- **The writers** — `systems/flag.system.ts` (world + thing flag values, routed by the flag's + scope), `systems/player.system.ts` (the local player's map, tile and facing). +- **The reader** — `systems/state.system.ts` builds one resolved view per entity and hands it to the + pure `evaluateCondition` (`types/data/Condition.ts`). +- **The owning placement** — `systems/event-action.system.ts` reads `PlacementIdComponent` off the + entity the run is attached to and puts it on `FLAG_SET` / `COUNTER_CHANGED` + (`types/engine-events.ts`). +- **The player id** — `engine.ts` (`setLocalPlayerId`), `engine/project-loader.ts`, + `scenes/map.scene.ts`, `game-systems/game-system-spec.ts`, + `apps/maker-gjs/src/services/player-identity.ts`, `apps/maker-gjs/data/org.pixelrpg.maker.gschema.xml`. +- **The snapshot** — `engine.ts` `RuntimeSnapshot` + `getRuntimeSnapshot`, surfaced on D-Bus + `GetStatus` by `apps/maker-gjs/src/widgets/application-window.ts`. +- **Specs** — `components/game-save-state.component.spec.ts` (shape, migration, resolved view), + `systems/state.system.spec.ts` (two placements, two players, the snapshot). + +## Related concepts + +- [`game-systems.md`](game-systems.md) — the flag store and conditional states the base layer ships; + `FlagData.scope` is declared there as project data. +- [`action-sequencer.md`](action-sequencer.md) — the run the `set-flag` step lives in, and the "at + rest" definition M8 saves against. +- [`collaboration-and-multiplayer.md`](collaboration-and-multiplayer.md) — who owns `world`, and the + `player.moved` / `object.removed` ops the record is the state behind. +- [`object-system.md`](object-system.md) — `ObjectPlacement.id`, the key `world.things` is built on. + +## Open questions + +- **Per-player thing state.** Some games want each player to open their own copy of a chest. That is + a third scope rather than a different record (`scope: 'thing-per-player'` → + `players[id].things[placementId]`). Nothing here forecloses it; nothing asks for it yet. +- **Pruning.** `world.things` grows one entry per placement that was ever written, and + `removedThings` one per thing taken. Both are bounded by the number of placements in the project, + so a save is small; a project with tens of thousands of placements would want the defaults + stripped on write. Defer until a save file exists to measure. +- **A thing that is deleted from the project** leaves an orphan entry in `world.things` keyed by a + placement id no map holds. Harmless (nothing reads it) and lossless (an undo that puts the + placement back finds its memory intact), which is why it is not pruned on load. Revisit with the + save file. diff --git a/packages/engine/src/components/game-save-state.component.spec.ts b/packages/engine/src/components/game-save-state.component.spec.ts new file mode 100644 index 00000000..3acfcecf --- /dev/null +++ b/packages/engine/src/components/game-save-state.component.spec.ts @@ -0,0 +1,218 @@ +import { describe, expect, it } from '@gjsify/unit' +import type { FlagData } from '../types/data/FlagData.ts' +import { + GameSaveStateComponent, + LOCAL_PLAYER_ID, + SAVE_RECORD_VERSION, + emptyPlayerRecord, + emptySaveRecord, + initialSaveRecord, + migrateSaveRecord, + resolvedFlagView, + saveSnapshot, +} from './game-save-state.component.ts' + +/** A door everyone shares, and a chest each placement remembers for itself. */ +const FLAGS: FlagData[] = [ + { id: 'gate-open', name: 'Gate open', kind: 'yes-no', initial: false, scope: 'game' }, + { id: 'chest-open', name: 'Chest open', kind: 'yes-no', initial: false, scope: 'thing' }, + { id: 'coins', name: 'Coins', kind: 'number', initial: 0, scope: 'game' }, +] + +export default async () => { + await describe('save record — one world, many players', async () => { + await it('starts every declared flag from its initial value, in the world', async () => { + const record = initialSaveRecord(FLAGS) + expect(record.schemaVersion).toBe(SAVE_RECORD_VERSION) + expect(record.world.flags).toStrictEqual({ 'gate-open': false, 'chest-open': false, coins: 0 }) + expect(record.world.things).toStrictEqual({}) + expect(record.world.removedThings).toStrictEqual([]) + expect(record.players).toStrictEqual({}) + }) + + await it('gives two players separate positions in one world', async () => { + // The whole point of the split: "the gate is open" is one fact for + // the game, "where I am standing" is one fact per person. + const store = new GameSaveStateComponent(initialSaveRecord(FLAGS)) + store.world.flags['gate-open'] = true + + const ana = store.playerRecord('player-ana') + ana.mapId = 'kokiri-forest' + ana.tileX = 4 + ana.tileY = 7 + ana.facing = 'down' + + const bo = store.playerRecord('player-bo') + bo.mapId = 'tree-house' + bo.tileX = 1 + bo.tileY = 2 + bo.facing = 'up' + + expect(store.players['player-ana']).toStrictEqual({ + mapId: 'kokiri-forest', + tileX: 4, + tileY: 7, + facing: 'down', + }) + expect(store.players['player-bo']).toStrictEqual({ mapId: 'tree-house', tileX: 1, tileY: 2, facing: 'up' }) + // One world flag, read the same by both. + expect(store.flags['gate-open']).toBe(true) + }) + + await it('creates a player record on first ask and keeps handing back the same one', async () => { + const store = new GameSaveStateComponent(initialSaveRecord(FLAGS)) + const first = store.playerRecord('player-ana') + expect(first).toStrictEqual(emptyPlayerRecord()) + first.tileX = 9 + expect(store.playerRecord('player-ana').tileX).toBe(9) + expect(Object.keys(store.players)).toStrictEqual(['player-ana']) + }) + }) + + await describe('thing-scoped values resolve per placement', async () => { + await it('reads two placements of one flag independently', async () => { + const record = initialSaveRecord(FLAGS) + record.world.things['chest-a'] = { 'chest-open': true } + + // Opening one chest leaves the other shut — the bug this scope exists for. + expect(resolvedFlagView(record.world, 'chest-a')['chest-open']).toBe(true) + expect(resolvedFlagView(record.world, 'chest-b')['chest-open']).toBe(false) + // And the game-scoped flags stay visible through both views. + expect(resolvedFlagView(record.world, 'chest-a')['gate-open']).toBe(false) + }) + + await it('falls back to the world for an entity that is not a placement', async () => { + const record = initialSaveRecord(FLAGS) + record.world.flags['chest-open'] = true + expect(resolvedFlagView(record.world, null)['chest-open']).toBe(true) + }) + + await it('leaves the world’s own bag untouched when it layers a placement on top', async () => { + const record = initialSaveRecord(FLAGS) + record.world.things['chest-a'] = { 'chest-open': true } + resolvedFlagView(record.world, 'chest-a') + expect(record.world.flags['chest-open']).toBe(false) + }) + + await it('remembers which things the world no longer shows', async () => { + const record = initialSaveRecord(FLAGS) + record.world.removedThings.push('pot-3') + expect(migrateSaveRecord(JSON.parse(JSON.stringify(record))).world.removedThings).toStrictEqual(['pot-3']) + }) + }) + + await describe('migration', async () => { + await it('reads the old flat flag bag as the world’s flags', async () => { + const migrated = migrateSaveRecord({ 'gate-open': true, coins: 7 }) + // The legacy shape is the bag itself under `flags`, so a bare bag + // is not a record — it migrates to an empty one rather than + // guessing. The real legacy shape is covered below. + expect(migrated.world.flags).toStrictEqual({}) + + const fromLegacy = migrateSaveRecord({ flags: { 'gate-open': true, coins: 7 } }) + expect(fromLegacy.schemaVersion).toBe(SAVE_RECORD_VERSION) + expect(fromLegacy.world.flags).toStrictEqual({ 'gate-open': true, coins: 7 }) + expect(fromLegacy.world.things).toStrictEqual({}) + expect(fromLegacy.players).toStrictEqual({}) + }) + + await it('is lossless and idempotent', async () => { + const record = initialSaveRecord(FLAGS) + record.world.flags['gate-open'] = true + record.world.things['chest-a'] = { 'chest-open': true } + record.world.removedThings.push('pot-3') + record.players['player-ana'] = { mapId: 'kokiri-forest', tileX: 4, tileY: 7, facing: 'down' } + + const once = migrateSaveRecord(JSON.parse(JSON.stringify(record))) + expect(once).toStrictEqual(record) + expect(migrateSaveRecord(once)).toStrictEqual(record) + }) + + await it('keeps a newer build’s version rather than writing it down', async () => { + // Forward compatibility: an older reader reads what it understands + // and does not relabel the record as its own. + expect(migrateSaveRecord({ schemaVersion: 99, world: { flags: { a: 1 } } }).schemaVersion).toBe(99) + }) + + await it('drops nothing it understands and invents nothing it does not', async () => { + const migrated = migrateSaveRecord({ + schemaVersion: 1, + world: { + flags: { a: true, bad: { nested: 1 } }, + things: { 'chest-a': { b: 2, worse: [] } }, + removedThings: ['x', 5], + }, + players: { ana: { mapId: 'm', tileX: 1, tileY: 'two', extra: 'ignored' } }, + }) + expect(migrated.world.flags).toStrictEqual({ a: true }) + expect(migrated.world.things['chest-a']).toStrictEqual({ b: 2 }) + expect(migrated.world.removedThings).toStrictEqual(['x']) + expect(migrated.players.ana).toStrictEqual({ mapId: 'm', tileX: 1, tileY: null, facing: null }) + }) + + await it('reads junk as an empty record rather than throwing', async () => { + for (const junk of [null, undefined, 42, 'nope', []]) { + expect(migrateSaveRecord(junk)).toStrictEqual(emptySaveRecord()) + } + }) + + await it('prefers the new world over a flat bag carried alongside it', async () => { + const migrated = migrateSaveRecord({ flags: { a: 1 }, world: { flags: { a: 2, b: 3 } } }) + expect(migrated.world.flags).toStrictEqual({ a: 2, b: 3 }) + }) + + await it('runs every record a component is built from through the migration', async () => { + expect(new GameSaveStateComponent({ a: true }).flags).toStrictEqual({}) + expect(new GameSaveStateComponent().record).toStrictEqual(emptySaveRecord()) + const store = new GameSaveStateComponent(migrateSaveRecord({ flags: { a: true } })) + expect(store.flags).toStrictEqual({ a: true }) + }) + }) + + await describe('runtime snapshot shape', async () => { + await it('reports the whole record, flat flags first', async () => { + const record = initialSaveRecord(FLAGS) + record.world.flags['gate-open'] = true + record.world.things['chest-a'] = { 'chest-open': true } + record.world.removedThings.push('pot-3') + record.players['player-ana'] = { mapId: 'kokiri-forest', tileX: 4, tileY: 7, facing: 'down' } + + expect(saveSnapshot(record, 'player-ana')).toStrictEqual({ + flags: { 'gate-open': true, 'chest-open': false, coins: 0 }, + thingFlags: { 'chest-a': { 'chest-open': true } }, + removedThings: ['pot-3'], + players: { 'player-ana': { mapId: 'kokiri-forest', tileX: 4, tileY: 7, facing: 'down' } }, + localPlayerId: 'player-ana', + }) + }) + + await it('copies all the way down, so two reads can be compared', async () => { + // A driver holds one snapshot and diffs it against the next; handing + // out the live record would make every comparison pass. + const record = initialSaveRecord(FLAGS) + record.world.things['chest-a'] = { 'chest-open': false } + record.players['player-ana'] = { mapId: 'm', tileX: 0, tileY: 0, facing: 'down' } + const before = saveSnapshot(record, 'player-ana') + + record.world.flags['gate-open'] = true + record.world.things['chest-a']['chest-open'] = true + record.world.removedThings.push('pot-3') + record.players['player-ana'].tileX = 5 + + expect(before.flags['gate-open']).toBe(false) + expect(before.thingFlags['chest-a']['chest-open']).toBe(false) + expect(before.removedThings).toStrictEqual([]) + expect(before.players['player-ana'].tileX).toBe(0) + }) + + await it('reads a missing record as an empty one', async () => { + expect(saveSnapshot(null, LOCAL_PLAYER_ID)).toStrictEqual({ + flags: {}, + thingFlags: {}, + removedThings: [], + players: {}, + localPlayerId: LOCAL_PLAYER_ID, + }) + }) + }) +} diff --git a/packages/engine/src/components/game-save-state.component.ts b/packages/engine/src/components/game-save-state.component.ts index 727055f2..4f7bd24a 100644 --- a/packages/engine/src/components/game-save-state.component.ts +++ b/packages/engine/src/components/game-save-state.component.ts @@ -2,41 +2,272 @@ import { Component } from 'excalibur' import type { FlagValue } from '../types/data/EntityDefinition.ts' import type { FlagData } from '../types/data/FlagData.ts' +/** + * The record's shape version. Bumped when a reader would need to know + * which build wrote it; `1` is the world/player split itself. + */ +export const SAVE_RECORD_VERSION = 1 + +/** + * The player id a host that supplies none gets. One local player is + * still a player: the browser host and every headless spec land here, + * and a record with one key is the same shape as a record with four. + */ +export const LOCAL_PLAYER_ID = 'local' + +/** Game-scoped flag values, by flag id: one memory for everyone. */ +export type FlagValues = Record + +/** + * What belongs to the game rather than to a person — and therefore what + * the host owns in a session with peers (see + * `docs/concepts/collaboration-and-multiplayer.md`). + */ +export interface WorldRecord { + /** `scope: 'game'` flag values, by flag id. */ + flags: FlagValues + /** + * `scope: 'thing'` flag values: placement id → flag id → value. Keyed + * by `ObjectPlacement.id` (the {@link PlacementIdComponent} id), so + * two chests built from one definition are two memories under one + * flag — which is the whole point of the scope. + */ + things: Record + /** Placement ids the world no longer shows (a chest taken, a rock smashed). */ + removedThings: string[] +} + +/** + * What belongs to one person. Position today; the bag and live hit + * points join it when their systems ship (M5) — a field nothing writes + * is a field that drifts, so they are absent until then. + */ +export interface PlayerRecord { + /** The map this player is on; `null` before the first spawn. */ + mapId: string | null + tileX: number | null + tileY: number | null + facing: string | null +} + +/** + * The playthrough's save record: one world, many players. + * + * Design: `docs/concepts/save-record.md`. + */ +export interface GameSaveRecord { + schemaVersion: number + world: WorldRecord + players: Record +} + +/** A player record before that player has ever spawned. */ +export function emptyPlayerRecord(): PlayerRecord { + return { mapId: null, tileX: null, tileY: null, facing: null } +} + +/** A record with nothing remembered yet. */ +export function emptySaveRecord(): GameSaveRecord { + return { schemaVersion: SAVE_RECORD_VERSION, world: { flags: {}, things: {}, removedThings: [] }, players: {} } +} + /** * The value of every declared flag at the start of a playthrough, by id. - * `scope: 'thing'` is stored but behaves like `'game'` here until the - * world/player/thing split of the "Remember" stage lands. + * + * Thing-scoped flags are listed here too: the value is what a placement + * that has never written falls back to, which is what + * {@link resolvedFlagView} layers under a placement's own entry. */ -export function initialFlagValues(flags: readonly FlagData[] | undefined): Record { - const out: Record = {} +export function initialFlagValues(flags: readonly FlagData[] | undefined): FlagValues { + const out: FlagValues = {} for (const flag of flags ?? []) out[flag.id] = flag.initial return out } +/** A fresh record for a project whose flags are `flags`. */ +export function initialSaveRecord(flags: readonly FlagData[] | undefined): GameSaveRecord { + const record = emptySaveRecord() + record.world.flags = initialFlagValues(flags) + return record +} + +/** + * The old flat shape: `{ flags: Record }` — no + * `world`, no `players`, no `schemaVersion`. + */ +interface LegacySaveRecord { + flags?: unknown +} + +/** + * Read any record this or an older build wrote into the current shape. + * + * Lossless and idempotent, the contract `format/migrate-flags.ts` holds + * for the flag-name → flag-id bridge: a flat bag becomes `world.flags` + * verbatim, a record that already has `schemaVersion` is returned with + * only its missing containers filled in. Nothing is dropped and nothing + * is renamed, so a reader never has to decide whether a value it does + * not recognise was a flag. + */ +export function migrateSaveRecord(value: unknown): GameSaveRecord { + if (value == null || typeof value !== 'object' || Array.isArray(value)) return emptySaveRecord() + const raw = value as Partial & LegacySaveRecord + const out = emptySaveRecord() + // A newer build's record keeps its version: a reader reads what it + // understands and leaves the rest alone rather than rewriting it down. + if (typeof raw.schemaVersion === 'number') out.schemaVersion = raw.schemaVersion + // The flat bag and the new `world.flags` are the same values under two + // names; a record carrying both prefers `world`, which is the one this + // build writes. + out.world.flags = { ...flagValuesOf(raw.flags), ...flagValuesOf(raw.world?.flags) } + const things = raw.world?.things + if (things != null && typeof things === 'object' && !Array.isArray(things)) { + for (const [placementId, values] of Object.entries(things as Record)) { + out.world.things[placementId] = flagValuesOf(values) + } + } + if (Array.isArray(raw.world?.removedThings)) { + out.world.removedThings = raw.world.removedThings.filter((id): id is string => typeof id === 'string') + } + const players = raw.players + if (players != null && typeof players === 'object' && !Array.isArray(players)) { + for (const [playerId, record] of Object.entries(players as Record)) { + out.players[playerId] = playerRecordOf(record) + } + } + return out +} + +function flagValuesOf(value: unknown): FlagValues { + if (value == null || typeof value !== 'object' || Array.isArray(value)) return {} + const out: FlagValues = {} + for (const [key, v] of Object.entries(value as Record)) { + const t = typeof v + if (t === 'boolean' || t === 'string' || (t === 'number' && Number.isFinite(v))) out[key] = v as FlagValue + } + return out +} + +function playerRecordOf(value: unknown): PlayerRecord { + const out = emptyPlayerRecord() + if (value == null || typeof value !== 'object' || Array.isArray(value)) return out + const raw = value as Record + if (typeof raw.mapId === 'string') out.mapId = raw.mapId + if (typeof raw.tileX === 'number' && Number.isFinite(raw.tileX)) out.tileX = raw.tileX + if (typeof raw.tileY === 'number' && Number.isFinite(raw.tileY)) out.tileY = raw.tileY + if (typeof raw.facing === 'string') out.facing = raw.facing + return out +} + +/** + * What one placement sees: the world's game-scoped values with that + * placement's thing-scoped values layered on top. + * + * This is the view `StateSystem` hands the pure `evaluateCondition`, and + * the reason that function stays ignorant of placements, scopes and the + * ECS — it reads `state.flags` and nothing else, which is what keeps it + * usable from the editor with no engine running. + * + * `placementId` `null` (an entity that is not a placement) yields the + * world's values unlayered: a thing-scoped flag read with no owner falls + * back to the shared value, which is what every build did before the + * split. + */ +export function resolvedFlagView(world: WorldRecord, placementId: string | null): Readonly { + const own = placementId == null ? undefined : world.things[placementId] + if (!own) return world.flags + return { ...world.flags, ...own } +} + +/** + * The save half of a runtime snapshot: what a playtest driver reads back + * over D-Bus `GetStatus` → `runtime`. + * + * Deliberately a copy all the way down. A driver holds a snapshot across + * frames and compares it with the next one; handing out the live record + * would make both reads the same object and every comparison pass. + * + * `flags` keeps the flat game-scoped shape every existing driver reads, + * and the rest of the record sits beside it rather than inside it — see + * `docs/concepts/save-record.md`. + */ +export interface SaveSnapshot { + flags: FlagValues + thingFlags: Record + removedThings: string[] + players: Record + localPlayerId: string +} + +/** Read {@link GameSaveRecord} out as a {@link SaveSnapshot}; `null` reads as empty. */ +export function saveSnapshot(record: GameSaveRecord | undefined | null, localPlayerId: string): SaveSnapshot { + const source = record ?? emptySaveRecord() + return { + flags: { ...source.world.flags }, + thingFlags: Object.fromEntries(Object.entries(source.world.things).map(([id, values]) => [id, { ...values }])), + removedThings: [...source.world.removedThings], + players: Object.fromEntries(Object.entries(source.players).map(([id, player]) => [id, { ...player }])), + localPlayerId, + } +} + /** * The playthrough's save state, on the session singleton. * - * Its first (and today only) occupant is the **flag store**: the - * key/value bag `set-flag` actions write and `EntityState.when` - * conditions read. That pairing is the point — `FLAG_SET` - * (`types/engine-events.ts`) has been emitted since the action list - * shipped and heard by nobody; {@link FlagSystem} folds it in here and - * {@link StateSystem} reads it back out, which is what makes the - * key-and-door loop buildable without code. + * It holds the **save record**: `world` — the flag values `set-flag` + * actions write and `EntityState.when` conditions read, the per-placement + * values a `scope: 'thing'` flag resolves to, and the things the world no + * longer shows — plus `players[playerId]`, where each person's position + * lives. The split is what lets "the gate is open" be one fact for + * everyone while "where I am standing" is one fact per person, and what + * makes "who may write this" a question with an answer once peers join. * - * Runtime state, deliberately not persisted: a playtest starts with an - * empty bag. Save/load of a playthrough (and what ↺ Restart resets) is a - * separate question — see TODO.md. + * Runtime state, deliberately not persisted: a playtest starts from the + * project's `initial` values. Writing the record to disk is a separate + * round — see `docs/concepts/save-record.md`. * - * Live hit points, the inventory bag and the clock join it here as their + * Live hit points and the inventory bag join `players[id]` as their * owning game systems ship; see `docs/concepts/game-systems.md`. */ export class GameSaveStateComponent extends Component { + public readonly record: GameSaveRecord + /** - * Keys are flag ids (`GameProjectData.flags`). A fresh playthrough - * starts from {@link initialFlagValues}, not from an empty bag. + * Built from a record (normally {@link initialSaveRecord}), or empty. + * Anything a previous build may have written goes through + * {@link migrateSaveRecord} first, so the component never holds a + * half-shaped record. */ - constructor(public flags: Record = {}) { + constructor(record?: GameSaveRecord | FlagValues) { super() + this.record = record === undefined ? emptySaveRecord() : migrateSaveRecord(record) + } + + /** The world half: everyone's memory. */ + public get world(): WorldRecord { + return this.record.world + } + + /** Every player's record, by player id. */ + public get players(): Record { + return this.record.players + } + + /** + * Game-scoped flag values. Kept as `flags` because that is what the + * runtime snapshot, the playtest drivers and the condition docs have + * always called this bag; it is `record.world.flags`, not a copy. + */ + public get flags(): FlagValues { + return this.record.world.flags + } + + /** `players[playerId]`, created empty on first ask. */ + public playerRecord(playerId: string): PlayerRecord { + const existing = this.record.players[playerId] + if (existing) return existing + const fresh = emptyPlayerRecord() + this.record.players[playerId] = fresh + return fresh } } diff --git a/packages/engine/src/engine.ts b/packages/engine/src/engine.ts index ed8a2113..f3612c78 100644 --- a/packages/engine/src/engine.ts +++ b/packages/engine/src/engine.ts @@ -5,7 +5,10 @@ import { type EditorViewFlags, DialogueStateComponent, GameSaveStateComponent, - initialFlagValues, + initialSaveRecord, + LOCAL_PLAYER_ID, + saveSnapshot, + type SaveSnapshot, InputSourceComponent, AskStateComponent, PlayerActorComponent, @@ -68,9 +71,17 @@ export type { PointerTileEvent, PointerWorldEvent } from './engine/pointer-obser /** Empty border per side, as a fraction of the view, that {@link Engine.frameMap} leaves around the map. */ const FRAME_MARGIN = 0.1 -/** What a playtest driver can read back from the running game. */ -export interface RuntimeSnapshot { - flags: Record +/** + * What a playtest driver can read back from the running game. + * + * The save record's half of it is {@link SaveSnapshot} — `flags` (flat + * and game-scoped, the shape every existing driver reads), the + * thing-scoped values beside it, the removed things, and each player's + * record. The rest is live frame state: where the hero stands right now, + * what the text box says, what the input source publishes. + */ +export interface RuntimeSnapshot extends SaveSnapshot { + /** The LOCAL player's tile, read off the live actor. */ playerTile: { x: number; y: number } | null /** The open question: option count, highlighted row, rows visible and live. */ /** The hero's facing direction. */ @@ -203,6 +214,7 @@ export class Engine { setStatus: (status) => this.setStatus(status), isRuntimeMode: () => this.isRuntimeMode(), playLocale: () => this._playLocale, + localPlayerId: () => this._localPlayerId, }) this.session = new EditorSession(activeScene, this.events) this.viewMode = new ViewModeController(this.excalibur, activeScene, this.events) @@ -791,6 +803,35 @@ export class Engine { this.activeMapScene()?.setLocale(locale) } + /** + * Who the person at this keyboard is, in the save record. Session + * state, defaulting to {@link LOCAL_PLAYER_ID}. + */ + private _localPlayerId: string = LOCAL_PLAYER_ID + + /** + * Name the local player — the key their half of the save record is + * filed under (`players[id]`). + * + * Supplied by the host, because only the host knows who is sitting + * there: the GJS maker reads a stable id out of GSettings, the + * browser host has none and keeps the default. It must NOT be a peer + * id — a peer id is new every session, and a position filed under it + * would be lost on reconnect. See `docs/concepts/save-record.md`. + * + * Takes effect for maps entered afterwards; the record already + * written under the old id is left alone rather than renamed, which + * keeps the operation lossless. + */ + setLocalPlayerId(playerId: string | undefined): void { + this._localPlayerId = playerId && playerId.length > 0 ? playerId : LOCAL_PLAYER_ID + } + + /** The key the local player's record is filed under. */ + get localPlayerId(): string { + return this._localPlayerId + } + /** * Frame the active map the way a fresh run should open: the largest * whole-pixel zoom that still shows a roomful of tiles. @@ -841,7 +882,7 @@ export class Engine { clearSaveState(): void { const scene = this.activeMapScene() if (!scene) return - SessionState.set(scene, new GameSaveStateComponent(initialFlagValues(scene.flags))) + SessionState.set(scene, new GameSaveStateComponent(initialSaveRecord(scene.flags))) } /** @@ -876,8 +917,13 @@ export class Engine { } /** - * Read-back of the running game for a playtest driver: the flag store - * and the player's tile. `null` without an active map scene. + * Read-back of the running game for a playtest driver: the save + * record and the player's tile. `null` without an active map scene. + * + * `flags` stays the flat game-scoped bag every existing driver reads; + * the rest of the record — thing-scoped values, removed things, each + * player's position — sits beside it. See + * `docs/concepts/save-record.md`. */ getRuntimeSnapshot(): RuntimeSnapshot | null { const scene = this.activeMapScene() @@ -891,7 +937,7 @@ export class Engine { const box = SessionState.get(scene, DialogueStateComponent) const src = SessionState.get(scene, InputSourceComponent) return { - flags: { ...(save?.flags ?? {}) }, + ...saveSnapshot(save?.record, this._localPlayerId), playerTile: player ? { x: Math.floor(player.pos.x / tw), y: Math.floor(player.pos.y / th) } : null, facing: player?.get(PlayerActorComponent)?.facing ?? null, dialogueOpen: box != null, diff --git a/packages/engine/src/engine/project-loader.ts b/packages/engine/src/engine/project-loader.ts index 2deb14be..5163c325 100644 --- a/packages/engine/src/engine/project-loader.ts +++ b/packages/engine/src/engine/project-loader.ts @@ -46,6 +46,12 @@ export interface ProjectLoaderHost { isRuntimeMode(): boolean /** The language a test run shows text in; `undefined` = the project default. */ playLocale(): string | undefined + /** + * The key the local player's half of the save record is filed under. + * A stable per-installation id the host supplies, never a peer id — + * see `docs/concepts/save-record.md`. + */ + localPlayerId(): string } /** @@ -244,6 +250,7 @@ export class ProjectLoader { languages: projectData?.languages, flags: projectData?.flags, locale: this.host.playLocale(), + localPlayerId: this.host.localPlayerId(), playerCharacter, playerSpriteSet, gameSystems: effectiveGameSystems(projectData), diff --git a/packages/engine/src/game-systems/game-system-spec.ts b/packages/engine/src/game-systems/game-system-spec.ts index bb2e2bee..566052cd 100644 --- a/packages/engine/src/game-systems/game-system-spec.ts +++ b/packages/engine/src/game-systems/game-system-spec.ts @@ -64,6 +64,12 @@ export interface GameSystemRuntimeContext { readonly languages?: ProjectLanguages /** Language the running game shows text in; absent = project default. */ readonly locale?: string + /** + * The key the local player's half of the save record is filed under + * (`players[id]`) — a stable per-installation id from the host, never + * a peer id. See `docs/concepts/save-record.md`. + */ + readonly localPlayerId: string /** The resolved player definition, when the project names one. */ readonly playerCharacter?: CharacterDefinition /** The player's sprite set, when it resolved. */ diff --git a/packages/engine/src/game-systems/specs/core.ts b/packages/engine/src/game-systems/specs/core.ts index f24fbed0..a9982a95 100644 --- a/packages/engine/src/game-systems/specs/core.ts +++ b/packages/engine/src/game-systems/specs/core.ts @@ -72,6 +72,7 @@ export const coreGameSystem: GameSystemSpec = { ctx.playerSpriteSet, ctx.entityLibrary, ctx.componentRegistry, + ctx.localPlayerId, ), new DepthSortSystem(ctx.mapResource), new TriggerSystem(ctx.events), diff --git a/packages/engine/src/scenes/map.scene.ts b/packages/engine/src/scenes/map.scene.ts index 1e339ddb..34f4df78 100644 --- a/packages/engine/src/scenes/map.scene.ts +++ b/packages/engine/src/scenes/map.scene.ts @@ -1,5 +1,5 @@ import { Actor, type EventEmitter, Logger, Scene } from 'excalibur' -import { EditorModeComponent, PlacementIdComponent } from '../components/index.ts' +import { EditorModeComponent, LOCAL_PLAYER_ID, PlacementIdComponent } from '../components/index.ts' import type { ComponentSpecRegistry } from '../entity/component-spec.ts' import { resolvePlacementDefinition } from '../entity/data-access.ts' import { BUILT_IN_COMPONENT_SPECS } from '../entity/registry.ts' @@ -42,6 +42,13 @@ export interface MapSceneOptions { flags?: readonly FlagData[] /** Language the game shows text in; absent = project default (seam for the language picker). */ locale?: string + /** + * The key the local player's half of the save record is filed under + * (`players[id]`). Supplied by the host; absent falls back to + * `LOCAL_PLAYER_ID`. Never a peer id — see + * `docs/concepts/save-record.md`. + */ + localPlayerId?: string /** The resolved player definition, when the project names one. */ playerCharacter?: CharacterDefinition /** The player's sprite set, when it resolved. */ @@ -129,6 +136,7 @@ export class MapScene extends Scene { languages: options.languages, flags: this.flags, locale: options.locale, + localPlayerId: options.localPlayerId ?? LOCAL_PLAYER_ID, playerCharacter: options.playerCharacter, playerSpriteSet: options.playerSpriteSet, } diff --git a/packages/engine/src/systems/event-action.system.ts b/packages/engine/src/systems/event-action.system.ts index a78284d4..2be9ba01 100644 --- a/packages/engine/src/systems/event-action.system.ts +++ b/packages/engine/src/systems/event-action.system.ts @@ -12,6 +12,7 @@ import { ActionRunComponent, type ActionRunCause } from '../components/action-ru import { ControlLockComponent } from '../components/control-lock.component.ts' import { DialogueComponent } from '../components/dialogue.component.ts' import { EventActionsComponent } from '../components/event-actions.component.ts' +import { PlacementIdComponent } from '../components/placement-id.component.ts' import type { ActionData, AskOption } from '../types/data/ActionData.ts' import { effectiveLanguages, type ProjectLanguages, resolveText } from '../types/data/LocalizedText.ts' import { EngineEvent, type EngineEventMap } from '../types/index.ts' @@ -213,7 +214,7 @@ export class EventActionSystem extends System { run.frames.pop() continue } - const outcome = this.step(run, frame.actions[frame.cursor++]) + const outcome = this.step(run, frame.actions[frame.cursor++], entity.get(PlacementIdComponent)?.id) switch (outcome.kind) { case 'done': break @@ -242,8 +243,17 @@ export class EventActionSystem extends System { } } - /** Run one step. Protected so a spec can supply steps no authored type produces yet. */ - protected step(run: ActionRunComponent, action: ActionData): StepOutcome { + /** + * Run one step. Protected so a spec can supply steps no authored type + * produces yet. + * + * `thing` is the stable placement id of the entity this run is + * attached to, when it is a placement — the owner a `scope: 'thing'` + * flag write is filed under (`docs/concepts/save-record.md`). The + * sequencer reads it off the entity rather than off the run so a run + * cannot outlive the truth: the entity is what `advance` already has. + */ + protected step(run: ActionRunComponent, action: ActionData, thing?: string): StepOutcome { switch (action.type) { case 'show-text': { const fallback = effectiveLanguages(this.languages).default @@ -283,10 +293,10 @@ export class EventActionSystem extends System { this.events.emit(EngineEvent.ITEM_PICKED_UP, { itemId: action.itemId, qty: action.qty ?? 1 }) return DONE case 'set-flag': - this.events.emit(EngineEvent.FLAG_SET, { flag: action.flag, value: action.value }) + this.events.emit(EngineEvent.FLAG_SET, { flag: action.flag, value: action.value, thing }) return DONE case 'change-counter': - this.events.emit(EngineEvent.COUNTER_CHANGED, { flag: action.flag, amount: action.amount }) + this.events.emit(EngineEvent.COUNTER_CHANGED, { flag: action.flag, amount: action.amount, thing }) return DONE case 'play-sfx': this.events.emit(EngineEvent.PLAY_SFX_REQUESTED, { sound: action.sound }) diff --git a/packages/engine/src/systems/flag.system.ts b/packages/engine/src/systems/flag.system.ts index d1150330..3575b169 100644 --- a/packages/engine/src/systems/flag.system.ts +++ b/packages/engine/src/systems/flag.system.ts @@ -1,12 +1,12 @@ import { type EventEmitter, type Scene, System, SystemType, type World } from 'excalibur' -import { GameSaveStateComponent, initialFlagValues } from '../components/game-save-state.component.ts' +import { type FlagValues, GameSaveStateComponent, initialSaveRecord } from '../components/game-save-state.component.ts' import type { FlagData } from '../types/data/FlagData.ts' import { EngineEvent, type EngineEventMap } from '../types/index.ts' import { SessionState } from '../utils/session-state.ts' import { SubscriptionScope } from '../utils/subscription-scope.ts' /** - * Folds `set-flag` actions into the playthrough's flag store. + * Folds `set-flag` actions into the playthrough's save record. * * `FLAG_SET` has been emitted by `EventActionSystem` since the action * list shipped and heard by nothing — the write side of a store that did @@ -14,6 +14,13 @@ import { SubscriptionScope } from '../utils/subscription-scope.ts' * {@link GameSaveStateComponent} is on the session singleton and records * every flag into it. {@link StateSystem} is the reader. * + * **Scope decides where a value lands.** A `scope: 'game'` flag is one + * memory for the whole game (`world.flags`); a `scope: 'thing'` flag is + * one memory per placement (`world.things[placementId]`), so two chests + * sharing the flag "Chest is open" remember separately. The owning + * placement rides on the event as `thing`. Design: + * `docs/concepts/save-record.md`. + * * Stateless (the scene is captured in the subscription closure) and * mode-gated upstream: `TriggerSystem` only emits `TRIGGER_FIRED` in * runtime mode, so nothing reaches this while editing. @@ -33,17 +40,19 @@ export class FlagSystem extends System { public onInitialize(world: World, scene: Scene): void { if (super.onInitialize) super.onInitialize(world, scene) - // Create the store up front so every reader finds a bag rather than - // having to distinguish "no flags yet" from "no store at all". + // Create the store up front so every reader finds a record rather + // than having to distinguish "no flags yet" from "no store at all". if (!SessionState.get(scene, GameSaveStateComponent)) { - SessionState.set(scene, new GameSaveStateComponent(initialFlagValues(this.flagDefs))) + SessionState.set(scene, new GameSaveStateComponent(initialSaveRecord(this.flagDefs))) } this.subscriptions.add( - this.events.on(EngineEvent.FLAG_SET, ({ flag, value }) => { + this.events.on(EngineEvent.FLAG_SET, ({ flag, value, thing }) => { const store = SessionState.get(scene, GameSaveStateComponent) - if (!store || store.flags[flag] === value) return - store.flags[flag] = value + if (!store) return + const bag = this.bagFor(store, flag, thing) + if (bag[flag] === value) return + bag[flag] = value // Workspace rule: a write to a session-singleton component is // followed by an explicit notify — Excalibur observes no fields. SessionState.notifyMutation(scene, store) @@ -51,18 +60,50 @@ export class FlagSystem extends System { ) this.subscriptions.add( - this.events.on(EngineEvent.COUNTER_CHANGED, ({ flag, amount }) => { + this.events.on(EngineEvent.COUNTER_CHANGED, ({ flag, amount, thing }) => { const store = SessionState.get(scene, GameSaveStateComponent) if (!store) return - const current = store.flags[flag] + const bag = this.bagFor(store, flag, thing) + const current = bag[flag] ?? this.initialOf(flag) const next = (typeof current === 'number' ? current : 0) + amount // Re-announce the total as a plain flag write: the store, the toast - // and the playtest read-back all already follow FLAG_SET. - this.events.emit(EngineEvent.FLAG_SET, { flag, value: next }) + // and the playtest read-back all already follow FLAG_SET. The + // owner rides along so the total lands in the same bag the + // counter was read from. + this.events.emit(EngineEvent.FLAG_SET, { flag, value: next, thing }) }), ) } + /** + * Where a write to `flag` belongs: the world's shared bag, or the + * owning placement's own. + * + * A thing-scoped flag written by a run that is not on a placement + * (a scripted or spec-supplied step) falls back to the world — a write + * with no owner is better shared than dropped, and it is exactly what + * the build did for every thing-scoped flag before the split. + */ + private bagFor(store: GameSaveStateComponent, flag: string, thing: string | undefined): FlagValues { + if (thing === undefined || this.scopeOf(flag) !== 'thing') return store.world.flags + const own = store.world.things[thing] + if (own) return own + const fresh: FlagValues = {} + store.world.things[thing] = fresh + return fresh + } + + /** The declared scope of `flag`; an undeclared flag is game-scoped. */ + private scopeOf(flag: string): FlagData['scope'] { + return this.flagDefs.find((f) => f.id === flag)?.scope ?? 'game' + } + + /** What a placement that has never written this flag counts from. */ + private initialOf(flag: string): number | undefined { + const initial = this.flagDefs.find((f) => f.id === flag)?.initial + return typeof initial === 'number' ? initial : undefined + } + public dispose(): void { this.subscriptions.closeAll() } diff --git a/packages/engine/src/systems/player.system.ts b/packages/engine/src/systems/player.system.ts index 200d63b2..689d2d16 100644 --- a/packages/engine/src/systems/player.system.ts +++ b/packages/engine/src/systems/player.system.ts @@ -12,6 +12,8 @@ import { type World, } from 'excalibur' import { + GameSaveStateComponent, + LOCAL_PLAYER_ID, PlayerActorComponent, PlayerComponent, PlayerSessionComponent, @@ -91,6 +93,13 @@ export class PlayerSystem extends System { private readonly playerSpriteSet?: SpriteSetResource, private readonly entityLibrary: readonly EntityDefinition[] = [], private readonly componentRegistry?: ComponentSpecRegistry, + /** + * Whose half of the save record this scene's hero writes to — + * `players[localPlayerId]`. One scene drives one person; a second + * person's position arrives through the session, not through this + * system. See `docs/concepts/save-record.md`. + */ + private readonly localPlayerId: string = LOCAL_PLAYER_ID, ) { super() } @@ -409,6 +418,7 @@ export class PlayerSystem extends System { const previous = prevX !== null && prevY !== null ? { tileX: prevX, tileY: prevY } : null session.lastTileX = tileX session.lastTileY = tileY + this.rememberPosition(tileX, tileY, pc.facing) this.events.emit(EngineEvent.PLAYER_TILE_CHANGED, { tileX, tileY, previous, facing: pc.facing }) } @@ -421,4 +431,27 @@ export class PlayerSystem extends System { session.actionWasHeld = false } } + + /** + * Write where this player stands into their half of the save record. + * + * Only on tile-boundary crossings (the caller's branch), because a + * tile is the resolution a save has: writing every frame would be the + * same record a hundred times a second. The first crossing after a + * spawn has `previous === null`, so the starting tile is recorded too. + */ + private rememberPosition(tileX: number, tileY: number, facing: Facing): void { + const scene = this.scene + if (!scene) return + const save = SessionState.get(scene, GameSaveStateComponent) + if (!save) return + const record = save.playerRecord(this.localPlayerId) + record.mapId = this.mapResource.mapData?.id ?? null + record.tileX = tileX + record.tileY = tileY + record.facing = facing + // Workspace rule: Excalibur observes no fields, so a write to a + // session-singleton component is followed by an explicit notify. + SessionState.notifyMutation(scene, save) + } } diff --git a/packages/engine/src/systems/state.system.spec.ts b/packages/engine/src/systems/state.system.spec.ts index 624032f3..608aae0c 100644 --- a/packages/engine/src/systems/state.system.spec.ts +++ b/packages/engine/src/systems/state.system.spec.ts @@ -3,9 +3,11 @@ import { Entity, EventEmitter, Scene } from 'excalibur' import { EntityStatesComponent } from '../components/entity-states.component.ts' import { EventActionsComponent } from '../components/event-actions.component.ts' import { GameSaveStateComponent } from '../components/game-save-state.component.ts' +import { PlacementIdComponent } from '../components/placement-id.component.ts' import { RuntimeModeComponent } from '../components/runtime-mode.component.ts' import type { ActionData } from '../types/data/ActionData.ts' import type { EntityState } from '../types/data/EntityDefinition.ts' +import type { FlagData } from '../types/data/FlagData.ts' import { EngineEvent, type EngineEventMap } from '../types/index.ts' import { SessionState } from '../utils/session-state.ts' import { EventActionSystem } from './event-action.system.ts' @@ -55,6 +57,58 @@ const openState: EntityState = { components: [{ type: 'actions', actions: [OPEN] }], } +const TAKE_LID_OFF: ActionData = { id: 'c1', type: 'set-flag', flag: 'chest-open', value: true } +const EMPTY: ActionData = { id: 'c2', type: 'show-text', text: 'Empty' } +const COIN_FOUND: ActionData = { id: 'c3', type: 'set-flag', flag: 'found-a-chest', value: true } + +/** + * Two chests built from one definition, sharing one `scope: 'thing'` + * flag — the case the scope exists for. Touching a shut chest sets + * "Chest is open" and gives a coin; touching an open one says it is + * empty. If the flag were one value for the game, the second chest + * would be empty before anyone touched it. + */ +function chestRig() { + const events = new EventEmitter() + const scene = new Scene() + SessionState.set(scene, new RuntimeModeComponent()) + + const base = [TAKE_LID_OFF, COIN_FOUND] + const states: EntityState[] = [ + { id: 'open', when: { flag: 'chest-open' }, components: [{ type: 'actions', actions: [EMPTY] }] }, + ] + const chests = new Map() + for (const id of ['chest-a', 'chest-b']) { + const chest = new Entity() + chest.addComponent(new PlacementIdComponent(id)) + chest.addComponent(new EventActionsComponent(base.slice())) + chest.addComponent(new EntityStatesComponent(states, base)) + scene.world.add(chest) + chests.set(id, chest) + } + + const flagDefs: FlagData[] = [ + { id: 'chest-open', name: 'Chest open', kind: 'yes-no', initial: false, scope: 'thing' }, + { id: 'found-a-chest', name: 'Found a chest', kind: 'yes-no', initial: false, scope: 'game' }, + ] + const flags = new FlagSystem(events, flagDefs) + const stateSystem = new StateSystem() + const actions = new EventActionSystem(events) + for (const system of [flags, stateSystem, actions]) system.onInitialize(scene.world, scene) + + const seen: string[] = [] + events.on(EngineEvent.SHOW_TEXT_REQUESTED, (p) => { + seen.push(`text:${p.text}`) + events.emit(EngineEvent.DIALOGUE_CLOSED, {}) + }) + + const touch = (id: string) => events.emit(EngineEvent.TRIGGER_FIRED, { entityId: chests.get(id)!.id, by: 'touch' }) + const tick = () => stateSystem.onUpdate(16) + const store = () => SessionState.get(scene, GameSaveStateComponent)! + const stateOf = (id: string) => chests.get(id)!.get(EntityStatesComponent)?.activeStateId ?? null + return { events, scene, seen, touch, tick, store, stateOf } +} + export default async () => { await describe('flag store + entity states — the key and the door', async () => { await it('runs the base actions before the flag is set', async () => { @@ -206,4 +260,47 @@ export default async () => { expect(door.get(EntityStatesComponent)?.activeStateId).toBe('open') }) }) + + await describe('this chest is open — one flag, one memory per placement', async () => { + await it('opens only the chest that was touched', async () => { + const { touch, tick, store, stateOf } = chestRig() + touch('chest-a') + tick() + expect(store().world.things).toStrictEqual({ 'chest-a': { 'chest-open': true } }) + expect(stateOf('chest-a')).toBe('open') + expect(stateOf('chest-b')).toBe(null) + }) + + await it('leaves the shared bag alone, so a second chest still starts shut', async () => { + const { touch, tick, store } = chestRig() + touch('chest-a') + tick() + // The whole bug: a thing-scoped write that landed in `world.flags` + // would read back `true` for every chest in the game. + expect(store().flags['chest-open']).toBe(false) + }) + + await it('runs each chest’s own body: the first gives, the second gives, the first is empty', async () => { + const { touch, tick, seen, store } = chestRig() + touch('chest-a') + tick() + touch('chest-b') + tick() + touch('chest-a') + expect(seen).toStrictEqual(['text:Empty']) + expect(store().world.things).toStrictEqual({ + 'chest-a': { 'chest-open': true }, + 'chest-b': { 'chest-open': true }, + }) + }) + + await it('still writes a game-scoped flag from a placement to the world', async () => { + // Scope decides the bag, not where the action ran: a chest that + // sets "Found a chest" sets it for the playthrough. + const { touch, store } = chestRig() + touch('chest-a') + expect(store().flags['found-a-chest']).toBe(true) + expect(store().world.things['chest-a']).toStrictEqual({ 'chest-open': true }) + }) + }) } diff --git a/packages/engine/src/systems/state.system.ts b/packages/engine/src/systems/state.system.ts index 602ea16d..17986c7c 100644 --- a/packages/engine/src/systems/state.system.ts +++ b/packages/engine/src/systems/state.system.ts @@ -1,15 +1,18 @@ import { type Entity, type Query, type Scene, System, SystemType, type World } from 'excalibur' import { EntityStatesComponent } from '../components/entity-states.component.ts' import { EventActionsComponent } from '../components/event-actions.component.ts' -import { GameSaveStateComponent } from '../components/game-save-state.component.ts' +import { GameSaveStateComponent, resolvedFlagView, type WorldRecord } from '../components/game-save-state.component.ts' +import { PlacementIdComponent } from '../components/placement-id.component.ts' import { RuntimeModeComponent } from '../components/runtime-mode.component.ts' import type { ActionData } from '../types/data/ActionData.ts' import { evaluateCondition } from '../types/data/Condition.ts' -import type { FlagValue } from '../types/data/EntityDefinition.ts' import { SessionState } from '../utils/session-state.ts' type StatesQuery = Query +/** What a scene with no save record yet resolves against: every flag at its `initial`. */ +const EMPTY_WORLD: WorldRecord = { flags: {}, things: {}, removedThings: [] } + /** * Resolves each entity's active {@link EntityState} against the flag * store and applies its overlay — the runtime half of the no-code @@ -53,15 +56,20 @@ export class StateSystem extends System { if (!scene || !this.statesQuery) return if (!SessionState.get(scene, RuntimeModeComponent)) return - const flags = SessionState.get(scene, GameSaveStateComponent)?.flags ?? {} - for (const entity of this.statesQuery.entities) this.resolve(entity, flags) + const world = SessionState.get(scene, GameSaveStateComponent)?.world ?? EMPTY_WORLD + for (const entity of this.statesQuery.entities) this.resolve(entity, world) } /** Apply the first matching state (or the base) to one entity. */ - private resolve(entity: Entity, flags: Readonly>): void { + private resolve(entity: Entity, world: WorldRecord): void { const states = entity.get(EntityStatesComponent) if (!states) return + // The view this entity sees: the world's shared values with its own + // placement's thing-scoped values layered on top. Built per entity + // because `scope: 'thing'` means "one memory per placement" — two + // chests reading one flag read two different values. + const flags = resolvedFlagView(world, entity.get(PlacementIdComponent)?.id ?? null) const match = states.states.find((state) => evaluateCondition(state.when, { flags })) ?? null const nextId = match?.id ?? null if (states.resolvedOnce && states.activeStateId === nextId) return diff --git a/packages/engine/src/test.mts b/packages/engine/src/test.mts index f42b7355..adcf8378 100644 --- a/packages/engine/src/test.mts +++ b/packages/engine/src/test.mts @@ -26,6 +26,7 @@ import paintTileCommandSuite from './commands/paint-tile.command.spec.js' import footprintSuite from './commands/footprint.spec.js' import registrySuite from './commands/registry.spec.js' import tilemapPlaneSuite from './components/tilemap-plane.spec.js' +import gameSaveStateSuite from './components/game-save-state.component.spec.js' import actionsSpecSuite from './entity/specs/actions.spec.js' import conditionSuite from './types/data/condition.spec.js' import entityConvertSuite from './entity/convert.spec.js' @@ -150,6 +151,7 @@ run({ layerContentCommandSuite, layerOrderCommandSuite, tilemapPlaneSuite, + gameSaveStateSuite, objectPlacementCommandSuite, entityRegistrySuite, gameSystemsRegistrySuite, diff --git a/packages/engine/src/types/data/FlagData.ts b/packages/engine/src/types/data/FlagData.ts index a924e1ad..cbdb8050 100644 --- a/packages/engine/src/types/data/FlagData.ts +++ b/packages/engine/src/types/data/FlagData.ts @@ -5,9 +5,11 @@ export const FLAG_KINDS = ['yes-no', 'number', 'text'] as const export type FlagKind = (typeof FLAG_KINDS)[number] /** - * Whose memory a flag lives in. `'thing'` is stored and synced but the - * runtime treats it like `'game'` until the world/player/thing split of - * the "Remember" stage lands — see `docs/concepts/game-systems.md`. + * Whose memory a flag lives in. `'game'` is one value for the whole + * playthrough ("the gate is open"); `'thing'` is one value per placement + * ("this chest is open"), resolved against the placement's stable id, so + * two chests from one definition remember separately under one flag. + * See `docs/concepts/save-record.md`. */ export const FLAG_SCOPES = ['game', 'thing'] as const export type FlagScope = (typeof FLAG_SCOPES)[number] diff --git a/packages/engine/src/types/engine-events.ts b/packages/engine/src/types/engine-events.ts index 15bd6a2b..284cd67c 100644 --- a/packages/engine/src/types/engine-events.ts +++ b/packages/engine/src/types/engine-events.ts @@ -282,15 +282,22 @@ export interface EngineEventMap { [EngineEvent.ASK_ANSWERED]: { optionId: string } /** * Emitted by `EventActionSystem` for a `set-flag` action — the write - * side of the (future) game-flags store that gates entity states. + * side of the game-flags store that gates entity states. + * + * `thing` is the stable `ObjectPlacement.id` of the placement whose + * action list ran the step, when there is one. A `scope: 'thing'` flag + * is stored under it, so two chests sharing one flag remember + * separately; a `scope: 'game'` flag ignores it. See + * `docs/concepts/save-record.md`. */ - [EngineEvent.FLAG_SET]: { flag: string; value: boolean | number | string } + [EngineEvent.FLAG_SET]: { flag: string; value: boolean | number | string; thing?: string } /** * Emitted by `EventActionSystem` for a `change-counter` action: add * `amount` (negative subtracts) to a number flag. `FlagSystem` folds it - * and then announces the new total as `FLAG_SET`. + * and then announces the new total as `FLAG_SET`. `thing` carries the + * owning placement, exactly as for {@link EngineEvent.FLAG_SET}. */ - [EngineEvent.COUNTER_CHANGED]: { flag: string; amount: number } + [EngineEvent.COUNTER_CHANGED]: { flag: string; amount: number; thing?: string } /** Emitted by `EventActionSystem` for a `play-sfx` action. */ [EngineEvent.PLAY_SFX_REQUESTED]: { sound: string } /** diff --git a/packages/gjs/src/widgets/editor/component-inspector.ts b/packages/gjs/src/widgets/editor/component-inspector.ts index b35edfea..3f72fdd2 100644 --- a/packages/gjs/src/widgets/editor/component-inspector.ts +++ b/packages/gjs/src/widgets/editor/component-inspector.ts @@ -9,6 +9,7 @@ import { type FieldDescriptor, type FieldOption, type FlagKind, + type FlagScope, isLocalizedText, type LocalizedText, type ProjectLanguages, @@ -42,7 +43,7 @@ export interface ComponentRefOptions { * invisible to the options' JSON comparison, which is fine — the host * passes the same one every time. */ - createFlag?: (name: string, kind?: FlagKind) => string | null + createFlag?: (name: string, kind?: FlagKind, scope?: FlagScope) => string | null } /** The four directions a `facing` field can hold; labels are msgids. */ diff --git a/packages/gjs/src/widgets/editor/flag-picker-row.ts b/packages/gjs/src/widgets/editor/flag-picker-row.ts index 51a2ada5..41f763b7 100644 --- a/packages/gjs/src/widgets/editor/flag-picker-row.ts +++ b/packages/gjs/src/widgets/editor/flag-picker-row.ts @@ -8,9 +8,9 @@ import { promptNewFlag } from './new-flag-dialog.ts' /** * The flag picker row both the action list and the condition editor use: - * the project's flags by name, "New…" last. Picking "New…" asks for a name - * and kind, creates the flag through the host and picks it; the value - * handed to `onPick` is always the flag's id, never its name. + * the project's flags by name, "New…" last. Picking "New…" asks for a name, + * a kind and a scope, creates the flag through the host and picks it; the + * value handed to `onPick` is always the flag's id, never its name. * * `onlyKind` narrows the list (and fixes the kind a new flag gets); the * currently held flag stays listed so a row never silently changes it. @@ -70,6 +70,6 @@ async function createFlagFor( // A name that is already a flag picks that flag: two flags of one name would read as one. const id = existingFlagId(chosen.name, flags) ?? - (cleanNewFlagName(chosen.name, flags) ? create(chosen.name, chosen.kind) : null) + (cleanNewFlagName(chosen.name, flags) ? create(chosen.name, chosen.kind, chosen.scope) : null) if (id) onCreated(id) } diff --git a/packages/gjs/src/widgets/editor/new-flag-dialog.ts b/packages/gjs/src/widgets/editor/new-flag-dialog.ts index ab098a86..996ea930 100644 --- a/packages/gjs/src/widgets/editor/new-flag-dialog.ts +++ b/packages/gjs/src/widgets/editor/new-flag-dialog.ts @@ -1,12 +1,14 @@ import Adw from '@girs/adw-1' import Gtk from '@girs/gtk-4.0' -import { FLAG_KINDS, type FlagKind } from '@pixelrpg/engine' +import { FLAG_KINDS, FLAG_SCOPES, type FlagKind, type FlagScope } from '@pixelrpg/engine' import { gettext as _ } from 'gettext' +import { comboRow } from '../common/preference-rows.ts' -/** What the dialog hands back: the name typed and the kind picked. */ +/** What the dialog hands back: the name typed, the kind picked and whose memory it is. */ export interface NewFlagChoice { name: string kind: FlagKind + scope: FlagScope } /** The kind labels, in {@link FLAG_KINDS} order; a function so they follow the locale. */ @@ -19,9 +21,54 @@ function kindLabels(): Record { } /** - * Ask for a new flag's name and kind over `parent`. Create stays off - * while the name is empty and Enter in the entry activates it; the kind - * starts on yes/no, the common case. Resolves `null` on cancel. + * The scope labels, in {@link FLAG_SCOPES} order. Worded as the question + * an author actually has — "is this one fact, or one per thing?" — rather + * than as the word the save record uses, because "scope" is a programmer's + * name for it. See `docs/concepts/save-record.md`. + */ +function scopeLabels(): Record { + return { + game: _('The whole game'), + thing: _('Each thing on its own'), + } +} + +/** + * The scope choice as one radio row per answer rather than a dropdown. + * The dialog is as narrow as the phone window, and a `ComboRow` there + * ellipsises its value to "Das ganze S…" — the one thing it exists to + * say. Two rows also show both answers at once, which is the point: the + * difference only becomes visible when you can compare them. + */ +function scopeGroupFor( + scope: FlagScope, + labels: Record, + onPick: (s: FlagScope) => void, +): Adw.PreferencesGroup { + const group = new Adw.PreferencesGroup({ + title: _('Remembered by'), + description: _('“Each thing on its own” gives every chest, door or pot its own answer.'), + }) + let first: Gtk.CheckButton | null = null + for (const candidate of FLAG_SCOPES) { + const check = new Gtk.CheckButton({ active: candidate === scope }) + if (first) check.set_group(first) + else first = check + const row = new Adw.ActionRow({ title: labels[candidate], activatableWidget: check }) + row.add_prefix(check) + check.connect('toggled', () => { + if (check.get_active()) onPick(candidate) + }) + group.add(row) + } + return group +} + +/** + * Ask for a new flag's name, kind and scope over `parent`. Create stays + * off while the name is empty and Enter in the entry activates it; the + * kind starts on yes/no and the scope on the whole game, the common + * cases. Resolves `null` on cancel. */ export function promptNewFlag(parent: Gtk.Widget, fixedKind?: FlagKind): Promise { return new Promise((resolve) => { @@ -29,11 +76,34 @@ export function promptNewFlag(parent: Gtk.Widget, fixedKind?: FlagKind): Promise placeholderText: _('Name, like “Has the key”'), activatesDefault: true, }) - const labels = kindLabels() - const kinds = new Gtk.DropDown({ model: Gtk.StringList.new(FLAG_KINDS.map((k) => labels[k])) }) + const kindText = kindLabels() + const scopeText = scopeLabels() + let kind: FlagKind = fixedKind ?? 'yes-no' + let scope: FlagScope = 'game' + const box = new Gtk.Box({ orientation: Gtk.Orientation.VERTICAL, spacing: 12 }) box.append(entry) - if (!fixedKind) box.append(kinds) + + if (!fixedKind) { + const kindGroup = new Adw.PreferencesGroup() + kindGroup.add( + comboRow( + _('Holds'), + FLAG_KINDS.map((k) => ({ value: k, label: kindText[k] })), + kind, + (value) => { + kind = value as FlagKind + }, + ), + ) + box.append(kindGroup) + } + + box.append( + scopeGroupFor(scope, scopeText, (picked) => { + scope = picked + }), + ) const dialog = new Adw.AlertDialog({ heading: _('New flag'), @@ -49,11 +119,7 @@ export function promptNewFlag(parent: Gtk.Widget, fixedKind?: FlagKind): Promise entry.connect('changed', () => dialog.set_response_enabled('create', entry.get_text().trim() !== '')) dialog.connect('response', (_d: Adw.AlertDialog, response: string) => { const name = entry.get_text().trim() - resolve( - response === 'create' && name - ? { name, kind: fixedKind ?? FLAG_KINDS[kinds.get_selected()] ?? 'yes-no' } - : null, - ) + resolve(response === 'create' && name ? { name, kind, scope } : null) }) dialog.present(parent) entry.grab_focus() diff --git a/packages/gjs/src/widgets/engine/engine.ts b/packages/gjs/src/widgets/engine/engine.ts index 7d0efb50..d04c94dc 100644 --- a/packages/gjs/src/widgets/engine/engine.ts +++ b/packages/gjs/src/widgets/engine/engine.ts @@ -476,6 +476,15 @@ export class Engine extends Adw.Bin { this._excalibur?.setPlayLocale(locale) } + /** Kept here for the same reason as {@link _playLocale}: the engine is created lazily. */ + private _localPlayerId: string | undefined + + /** Forward to `Engine.setLocalPlayerId` — who the person here is in the save record. */ + public setLocalPlayerId(playerId: string | undefined): void { + this._localPlayerId = playerId + this._excalibur?.setLocalPlayerId(playerId) + } + /** Forward to `Engine.getRuntimeSnapshot`. */ public getRuntimeSnapshot(): ReturnType { return this._excalibur?.getRuntimeSnapshot() ?? null @@ -1013,6 +1022,7 @@ export class Engine extends Adw.Bin { this._excaliburSubscriptions.push(...forwardEngineEvents(engine, this)) this._excalibur = engine engine.setPlayLocale(this._playLocale) + engine.setLocalPlayerId(this._localPlayerId) engine.setViewportInset(this._viewportInset) this._pushUiInset() await engine.initialize() diff --git a/packages/translations/de.po b/packages/translations/de.po index 9eb730c0..45b8bafc 100644 --- a/packages/translations/de.po +++ b/packages/translations/de.po @@ -793,6 +793,9 @@ msgstr "Duplizieren" msgid "Duplicate map" msgstr "Karte duplizieren" +msgid "Each thing on its own" +msgstr "Jedes Ding für sich" + msgid "Edit" msgstr "Bearbeiten" @@ -1031,6 +1034,9 @@ msgstr "Heldenfiguren" msgid "History" msgstr "Verlauf" +msgid "Holds" +msgstr "Enthält" + msgid "How you appear to the people you build a game with" msgstr "Wie du für die Leute erscheinst, mit denen du ein Spiel baust" @@ -1360,7 +1366,7 @@ msgid "New thing" msgstr "Neues Ding" msgid "New…" -msgstr "…" +msgstr "Neu…" msgid "No actions yet" msgstr "Noch keine Aktionen" @@ -1774,6 +1780,9 @@ msgstr "Wiederholen" msgid "Redo (Ctrl+Shift+Z)" msgstr "Wiederholen (Strg+Umschalt+Z)" +msgid "Remembered by" +msgstr "Gemerkt von" + msgid "Remove" msgstr "Entfernen" @@ -2177,6 +2186,9 @@ msgstr "Die Sprachen, in denen die Wörter deines Spiels geschrieben sind." msgid "The map the hero wakes up on." msgstr "Die Karte, auf der die Heldenfigur aufwacht." +msgid "The whole game" +msgstr "Das ganze Spiel" + msgid "Then" msgstr "Danach" @@ -2562,6 +2574,9 @@ msgstr[1] "„%s“ wird noch an %d Stellen benutzt. Siehe Spiel › Flaggen." msgid "“%s” will be removed from the project. Characters using it lose their look until reassigned. This cannot be undone." msgstr "„%s“ wird aus dem Projekt entfernt. Figuren, die es verwenden, verlieren ihr Aussehen, bis ihnen ein neues zugewiesen wird. Das lässt sich nicht rückgängig machen." +msgid "“Each thing on its own” gives every chest, door or pot its own answer." +msgstr "„Jedes Ding für sich“ gibt jeder Truhe, Tür und Vase eine eigene Antwort." + msgid "…" msgstr "…" diff --git a/packages/translations/org.pixelrpg.maker.pot b/packages/translations/org.pixelrpg.maker.pot index 5d59451c..d2e4a51f 100644 --- a/packages/translations/org.pixelrpg.maker.pot +++ b/packages/translations/org.pixelrpg.maker.pot @@ -794,6 +794,9 @@ msgstr "" msgid "Duplicate map" msgstr "" +msgid "Each thing on its own" +msgstr "" + msgid "Edit" msgstr "" @@ -1032,6 +1035,9 @@ msgstr "" msgid "History" msgstr "" +msgid "Holds" +msgstr "" + msgid "How you appear to the people you build a game with" msgstr "" @@ -1775,6 +1781,9 @@ msgstr "" msgid "Redo (Ctrl+Shift+Z)" msgstr "" +msgid "Remembered by" +msgstr "" + msgid "Remove" msgstr "" @@ -2178,6 +2187,9 @@ msgstr "" msgid "The map the hero wakes up on." msgstr "" +msgid "The whole game" +msgstr "" + msgid "Then" msgstr "" @@ -2563,6 +2575,9 @@ msgstr[1] "" msgid "“%s” will be removed from the project. Characters using it lose their look until reassigned. This cannot be undone." msgstr "" +msgid "“Each thing on its own” gives every chest, door or pot its own answer." +msgstr "" + msgid "…" msgstr ""