diff --git a/TODO.md b/TODO.md index 73da407b..592afd90 100644 --- a/TODO.md +++ b/TODO.md @@ -62,6 +62,7 @@ Conventions: - **Lock enforcement on remote command apply** — layer `locked` now syncs as a `SetLayerLockedCommand`, so both peers' edit-input paths respect a padlock; but `Engine.applyRemoteCommand` itself doesn't re-check the flag, so an op already in flight when the lock landed still applies. Decide whether remote apply should hard-block (and how to reconcile the sender's optimistic apply). *owner: engine, why: race window only — input-side checks cover the common case* - **Two engine components are read by nothing, and a third only for `depth`** — `CollisionComponent`: the shipped "Blocks movement" toggle has no runtime effect, no movement system consults it, so the player walks straight through every chest / sign / door the templates seed. `SpriteRefComponent` (only `depth` is read, by `applyActorDepth`): the placement graphic is built from the DEFINITION (`buildPlacementGraphic(def, …)` finds the `visual` entry itself), so writing the component at runtime does nothing — a runtime sprite/animation swap needs the graphic build routed through it. `CustomDataComponent` is the third and stays one BY DESIGN (the project-script escape hatch). `NpcRouteComponent` left this list when `HostileAiSystem` started walking its waypoints for a `patrol` enemy; the general `NpcMovementSystem` that walks a route with no fight attached is still unbuilt, so a peaceful NPC still stands still. The two still orphaned carry an `orphan-component-ok:` note; `check-orphan-components.mjs` fails the build on a third. *owner: engine* - **Real runtime effect systems (dialogue / inventory / audio)** — the maker host surfaces the `EventActionSystem` effects (`item-picked-up`, `flag-set`, `play-sfx`) as playtest toasts (forwarded engine widget → `EngineController` → `ApplicationWindow._showToast`); `show-text` is no longer one. The **flags store landed** (`GameSaveStateComponent` + `FlagSystem` + `StateSystem`, [`docs/concepts/game-systems.md`](docs/concepts/game-systems.md)) — `flag-set` now gates entity states for real, and the toast stays as the only visible sign a flag flipped. The in-game **dialogue text box** for `show-text` landed (`DialogueSystem` + runtime-only `DialogueStateComponent`, owned by `core`: whole-number `uiScale`, pages rasterised once, typewriter clips, tap/Enter/Space/confirm advance, the sequenced list waits for `DIALOGUE_CLOSED`). **Signs and people speak**: the `dialogue` component (`speaker?`, `lines[]`) is read on the action button by the facing probe and shown through the same box; the 13 Kokiri signs carry EN/DE texts. The **inspector rows** for it landed: "Who speaks" (an entry row) and "What it says" (a generic list-of-texts row: one entry per line, "Add a line", reorder by drag or the row's Move up / Move down, remove); a blank line stays in the data while it is typed into and the game skips it. The **`ask` action** landed (engine side): a prompt in the text box, 2-4 tappable rows above it, keyboard/controller highlight, optional cancel option, the picked list entered on the run's frame stack; the maker's **Ask card** landed too (prompt row, 2-4 answer rows each with its own nested action list one level deep and no `ask` inside, "Antwort beim Abbrechen" combo, drag and Move up/down reorder, one undo step per edit; the answer text is edited for the default language only until H5). Still placeholders: an **inventory bag** for `item-picked-up` (`InventoryComponent` + `item-def` library entities + `INVENTORY_CHANGED`, owned by the `inventory` game system), and an **audio layer** for `play-sfx`. Teleport is the one fully-real effect (engine `loadMap` + spawn override). *owner: engine + project layer* +- **Game memory panel is flags-only and a Test run only** — the panel lists declared flags and, per placement, thing-scoped ones; it does not show the inventory, removed-thing markers or the player record, and an edit is never undoable or sent to collaborators (a run's values are local runtime state, [`save-record.md`](docs/concepts/save-record.md) § Writing a value during a run). The state cards' "active now" badge (branch `feat/state-badge`) still polls every 250 ms and should read `LiveStateService` instead once both land; `placementStates` is already part of `LiveState`. *owner: maker* - **State overlays are actions-only** — `StateSystem` swaps a matched state's `actions` list and nothing else; a state carrying `visual`, `collision` or any other type validates with a warning and stays inert. Visible cost: a door teleports once its flag is set but never *looks* open, and a chest still looks closed after it gave you its item. Doing it properly means rebuilding a live entity's overlaid components through the spawn pipeline mid-frame (sprite swap, collider swap) while keeping runtime companions like `TriggerFiredComponent` alive — the first piece of engine work in this design that rebuilds a spawned entity, so it gets its own round. The "When …" authoring editor landed (flag-is / counter / has-item, all / any / not, `change-counter` action); `has-item` evaluates false until the inventory exists. *owner: engine + gjs* - **`inventory` has no bag yet** — the base system owns `item` and contributes the existing `ItemPickupSystem`, so a pickup fires and the host toasts it, but nothing holds what was picked up: no `InventoryComponent` on the session singleton, no `item-def` library entities, no `INVENTORY_CHANGED`. Lands with the first system that reads a bag. *owner: engine, why: no consumer yet — see [`docs/concepts/game-systems.md`](docs/concepts/game-systems.md) § Reach* - **`combat-action` leaves three gaps** — (a) **no real game over**: a defeated hero is full-healed and given a grace period so a playtest cannot dead-end; a retry / restart flow needs playthrough save-state that survives a scene load, which does not exist. (b) **`stats.speed` is not shipped** — its only reader is `combat-turn`'s speed-sorted `TurnOrderSystem`, and in realtime combat the movement rate is already `movement.tilesPerSec`; it lands with that system. (c) **the Game-rules body has no destructive "Remove data" row** — the switch-off `Adw.AlertDialog` landed in step 6.4 (`confirmRuleSwitchOff`: a plain alert, not a destructive one, counting what goes quiet and saying the settings stay), but the row that would actually delete the dormant data did not. Dormancy is the contract, so a row that deletes what the dialog just promised to keep needs its own decision — what it removes (component data on entities? placements that only exist for that system?), whether it is undoable, and what it does to a peer mid-session. See [`docs/concepts/game-systems.md`](docs/concepts/game-systems.md) § Reach. *owner: engine + maker* diff --git a/apps/maker-gjs/src/services/engine-event-bridge.ts b/apps/maker-gjs/src/services/engine-event-bridge.ts index f51ddf5b..a50b4f9e 100644 --- a/apps/maker-gjs/src/services/engine-event-bridge.ts +++ b/apps/maker-gjs/src/services/engine-event-bridge.ts @@ -67,6 +67,8 @@ export interface EngineEventBridgeContext { * you leave a mode you never explicitly entered the way out of. */ pointerInput(): void + /** A flag changed during a run — the shared live state re-reads. */ + flagSet(): void } /** @@ -91,7 +93,10 @@ export function wireEngineEvents(engine: EngineController, ctx: EngineEventBridg engine.on('layer-list-changed', () => ctx.refreshLayers()) engine.on('map-loaded', ({ mapId }) => ctx.mapLoaded(mapId)) engine.on('item-picked-up', ({ itemId, qty }) => ctx.showToast(qty > 1 ? `Got ${qty}× ${itemId}` : `Got ${itemId}`)) - engine.on('flag-set', ({ flag, value }) => ctx.showToast(`Flag "${flag}" = ${String(value)}`)) + engine.on('flag-set', ({ flag, value }) => { + ctx.showToast(`Flag "${flag}" = ${String(value)}`) + ctx.flagSet() + }) engine.on('play-sfx', ({ sound }) => ctx.showToast(`Play sound: ${sound}`)) engine.on('pointer-input', () => ctx.pointerInput()) } diff --git a/apps/maker-gjs/src/services/live-state.service.spec.ts b/apps/maker-gjs/src/services/live-state.service.spec.ts new file mode 100644 index 00000000..b5ca7eaf --- /dev/null +++ b/apps/maker-gjs/src/services/live-state.service.spec.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from '@gjsify/unit' + +import { type LiveState, LiveStateService } from './live-state.service.ts' + +export default async () => { + await describe('LiveStateService', async () => { + await it('reads nothing and tells nobody outside a run', async () => { + let reads = 0 + const svc = new LiveStateService(() => { + reads++ + return { flags: {}, thingFlags: {} } + }) + let calls = 0 + svc.onChanged(() => calls++) + svc.refresh() + expect(reads).toBe(0) + expect(calls).toBe(0) + expect(svc.snapshot).toBe(null) + }) + + await it('reads on start and again on every refresh while running', async () => { + let coins = 0 + const svc = new LiveStateService(() => ({ flags: { coins }, thingFlags: {} })) + const seen: (number | null)[] = [] + svc.onChanged((s) => seen.push(s ? (s.flags.coins as number) : null)) + svc.start() + coins = 3 + svc.refresh() + expect(seen).toStrictEqual([0, 3]) + expect(svc.active).toBe(true) + }) + + await it('forgets the state when the run stops, and stops reading', async () => { + let reads = 0 + const svc = new LiveStateService(() => { + reads++ + return { flags: {}, thingFlags: {} } + }) + let last: LiveState | null | undefined + svc.onChanged((s) => { + last = s + }) + svc.start() + svc.stop() + svc.refresh() + expect(last).toBe(null) + expect(reads).toBe(1) + }) + + await it('an unsubscribed listener hears nothing more', async () => { + const svc = new LiveStateService(() => ({ flags: {}, thingFlags: {} })) + let calls = 0 + const off = svc.onChanged(() => calls++) + svc.start() + off() + svc.refresh() + expect(calls).toBe(1) + }) + }) +} diff --git a/apps/maker-gjs/src/services/live-state.service.ts b/apps/maker-gjs/src/services/live-state.service.ts new file mode 100644 index 00000000..44fdcf89 --- /dev/null +++ b/apps/maker-gjs/src/services/live-state.service.ts @@ -0,0 +1,70 @@ +import type { FlagValue } from '@pixelrpg/engine' + +/** + * What a test run currently remembers, as far as the window's panels care. + * + * `placementStates` is the active state index per placement id (the + * "active now" badge of the state cards reads it); a source that does not + * report it leaves it out. + */ +export interface LiveState { + readonly flags: Readonly> + readonly thingFlags: Readonly>>> + readonly placementStates?: Readonly> +} + +/** + * The ONE place the window reads a running game's state, so every panel + * that shows it (the Game memory page, the state cards' "active now" + * badge) shares a snapshot instead of each polling the engine. + * + * It is event-driven: the owner calls {@link refresh} when something the + * run remembers changed (a flag event) and {@link start} / {@link stop} + * around a run. Outside a run it holds nothing and every call but + * {@link start} does nothing, so an editing session pays nothing for it. + */ +export class LiveStateService { + private _active = false + private _snapshot: LiveState | null = null + private readonly _listeners = new Set<(state: LiveState | null) => void>() + + constructor(private readonly _read: () => LiveState | null) {} + + /** Whether a run is on. */ + get active(): boolean { + return this._active + } + + /** The state as of the last refresh; `null` outside a run. */ + get snapshot(): LiveState | null { + return this._snapshot + } + + /** A run began (or began again): read the state and tell the listeners. */ + start(): void { + this._active = true + this._set(this._read()) + } + + /** The run ended: forget the state and tell the listeners. */ + stop(): void { + this._active = false + this._set(null) + } + + /** Something the run remembers changed. A no-op outside a run. */ + refresh(): void { + if (this._active) this._set(this._read()) + } + + /** Listen for a new snapshot (`null` once the run ends). Returns the unsubscribe. */ + onChanged(listener: (state: LiveState | null) => void): () => void { + this._listeners.add(listener) + return () => this._listeners.delete(listener) + } + + private _set(state: LiveState | null): void { + this._snapshot = state + for (const listener of [...this._listeners]) listener(state) + } +} diff --git a/apps/maker-gjs/src/test.mts b/apps/maker-gjs/src/test.mts index aabd3232..d9cae961 100644 --- a/apps/maker-gjs/src/test.mts +++ b/apps/maker-gjs/src/test.mts @@ -8,6 +8,7 @@ import instanceIdSuite from './instance-id.spec.js' import assistantPausePolicySuite from './services/assistant-pause-policy.spec.js' import atlasCameraStoreSuite from './services/atlas-camera-store.spec.js' import assistantStateServiceSuite from './services/assistant-state.service.spec.js' +import liveStateServiceSuite from './services/live-state.service.spec.js' import backOrderSuite from './services/back-order.spec.js' import brushKeysSuite from './services/brush-keys.spec.js' import coachMarksServiceSuite from './services/coach-marks.service.spec.js' @@ -91,6 +92,7 @@ run({ actionRegistrySuite, assistantPausePolicySuite, assistantStateServiceSuite, + liveStateServiceSuite, atlasCameraStoreSuite, backOrderSuite, brushKeysSuite, diff --git a/apps/maker-gjs/src/widgets/application-window.ts b/apps/maker-gjs/src/widgets/application-window.ts index a6b1d412..6a11e948 100644 --- a/apps/maker-gjs/src/widgets/application-window.ts +++ b/apps/maker-gjs/src/widgets/application-window.ts @@ -54,6 +54,7 @@ import { EngineController } from '../services/engine-controller.ts' import type { AnimationClearHost, EntityDeleteHost } from '../services/entity-deletion.ts' import { GameController } from '../services/game-controller.ts' import { isChipInTier, type LibraryChip } from '../services/library-chip.ts' +import { LiveStateService } from '../services/live-state.service.ts' import { wireEngineEvents } from '../services/engine-event-bridge.ts' import { syncEngineState } from '../services/engine-state-sync.ts' import { buildVariant } from '../services/gvariant.ts' @@ -286,6 +287,11 @@ export class ApplicationWindow extends Adw.ApplicationWindow implements EntityDe * networked human peers come from the live CollabSession awareness. */ private readonly _assistantState = new AssistantStateService() + /** What the running game remembers; the Game memory page reads it, only during a run. */ + private readonly _liveState = new LiveStateService(() => { + const snap = this._engineCtl.engine?.getRuntimeSnapshot() + return snap ? { flags: snap.flags, thingFlags: snap.thingFlags } : null + }) private _engineCtl = new EngineController( (engine) => { if (engine) this._scene_editor_view.setEngineWidget(engine, engine) @@ -634,6 +640,7 @@ export class ApplicationWindow extends Adw.ApplicationWindow implements EntityDe pointerInput: () => { if (this._collabPresenceCtl.followedPeerId) this._collabPresenceCtl.followParticipant(null) }, + flagSet: () => this._scheduleLiveRefresh(), }) this._wireStoreEvents() } @@ -644,7 +651,27 @@ export class ApplicationWindow extends Adw.ApplicationWindow implements EntityDe * and this window translates + toasts them (msgids stay literal for * extraction). */ + /** + * One refresh per burst of flag events, after the engine's own listeners + * have stored the value: an action that sets three flags redraws once, + * and a panel edit is never read back before the save record has it. + */ + private _liveRefreshQueued = false + private _scheduleLiveRefresh(): void { + if (this._liveRefreshQueued) return + this._liveRefreshQueued = true + GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => { + this._liveRefreshQueued = false + this._liveState.refresh() + return GLib.SOURCE_REMOVE + }) + } + private _wireStoreEvents(): void { + this._scene_editor_view.setLiveState(this._liveState) + this._scene_editor_view.flagWriter = (flag, value, thing) => + void this._engineCtl.engine?.setFlag(flag, value, thing ?? undefined) + this._scene_editor_view.probeSwitch = (on) => this._engineCtl.engine?.setFrameProbe(on) ?? null 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()) @@ -1161,7 +1188,11 @@ export class ApplicationWindow extends Adw.ApplicationWindow implements EntityDe const { play } = installPlaytestActions(group, { persistCurrentMap: () => this._mapPersistCtl.persistCurrentMap(), setRuntimeMode: (playing) => this._engineCtl.engine?.setRuntimeMode(playing), - setViewPlaying: (playing) => this._scene_editor_view.setPlaying(playing), + setViewPlaying: (playing) => { + this._scene_editor_view.setPlaying(playing) + if (playing) this._liveState.start() + else this._liveState.stop() + }, clearSaveState: () => this._engineCtl.engine?.clearSaveState(), applyPlayZoom: () => void this._engineCtl.engine?.applyPlayZoom(), }) diff --git a/apps/maker-gjs/src/widgets/scene-editor-view.ts b/apps/maker-gjs/src/widgets/scene-editor-view.ts index fe6c85c0..7dbd3d25 100644 --- a/apps/maker-gjs/src/widgets/scene-editor-view.ts +++ b/apps/maker-gjs/src/widgets/scene-editor-view.ts @@ -8,6 +8,8 @@ import { type EditorTool, effectiveComponentRegistry, type EntityDefinition, + type FlagValue, + findFlagUsages, type FlagKind, type FlagScope, type LayerPlane, @@ -26,6 +28,7 @@ import { CoachMarks, type CollaboratorEntry, EditorPages, + memorySections, type Engine, GdkSpriteSetResource, type GdkSpriteSheet, @@ -52,6 +55,7 @@ import { } from '@pixelrpg/gjs' import { terrainBrushKey, terrainIdOfBrushKey, tileBrushKey, tileIdOfBrushKey } from '../services/brush-keys.ts' import type { DoorInfo } from '../services/door-target-flow.ts' +import type { LiveStateService } from '../services/live-state.service.ts' import { toLayerDescriptors } from '../services/layer-descriptors.ts' import { planeTarget } from '../services/layer-draft.ts' import { loadStarterPacks } from '../services/starter-pack-catalog.ts' @@ -177,6 +181,13 @@ export class SceneEditorView extends ResponsiveEditorView { 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, scope?: FlagScope) => string | null) | null = null + /** Writes one flag into the running game; the window points it at the engine. */ + flagWriter: ((flag: string, value: FlagValue, thing: string | null) => void) | null = null + /** Turns the frame-time measurement on or off; returns the file it writes to. */ + probeSwitch: ((on: boolean) => string | null) | null = null + private _liveState: LiveStateService | null = null + private _liveOff: (() => void) | null = null + private _playing = false /** 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. */ @@ -353,13 +364,53 @@ export class SceneEditorView extends ResponsiveEditorView { */ setPlaying(playing: boolean): void { this._editor.setPlaying(playing) + // A restart re-enters with `playing` already true: keep what the + // person had open before the FIRST run, not what the run left. + if (playing === this._playing) return + this._playing = playing + this._inspector.memoryMode = playing + this._editor.memoryMode = playing if (playing) { this._inspectorBeforeRun = this.showInspector this.showInspector = false return } - if (this._inspectorBeforeRun) this.showInspector = true + this._pages.memory.clear() + this.showInspector = this._inspectorBeforeRun this._inspectorBeforeRun = false + if (this.inspectorCollapsed) this.collapseSheet() + } + + /** + * Hand the view the shared live-state service. The Game memory page is + * redrawn from its snapshot every time it changes — the service fires + * on flag events only, so there is no timer here and nothing is + * subscribed outside a run. + */ + setLiveState(service: LiveStateService): void { + this._liveOff?.() + this._liveState = service + this._pages.memory.onWrite = (flag, value, thing) => this.flagWriter?.(flag, value, thing) + this._pages.memory.onProbe = (on) => { + this._pages.memory.setProbe(on, this.probeSwitch?.(on) ?? null) + } + this._liveOff = service.onChanged(() => this._renderMemory()) + } + + private _renderMemory(): void { + const live = this._liveState?.snapshot + if (!live) return + const project = this._refProject?.resource.data + const mapData = this._mapData + const placements = (mapData?.objectPlacements ?? []).map((p) => ({ + id: p.id, + defId: p.defId, + name: resolvePlacementDefinition(p, this._entityLibrary)?.name ?? _('Object'), + tileX: p.tileX, + tileY: p.tileY, + })) + const usages = project && mapData ? findFlagUsages(project, [mapData]) : new Map() + this._pages.memory.setSections(memorySections(project?.flags ?? [], placements, usages, live)) } /** diff --git a/docs/concepts/README.md b/docs/concepts/README.md index af72229d..a3f2d384 100644 --- a/docs/concepts/README.md +++ b/docs/concepts/README.md @@ -43,7 +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. | +| [`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. Also how the Game memory panel writes a value during a run. | | [`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/save-record.md b/docs/concepts/save-record.md index 8c8143b8..8be02b8c 100644 --- a/docs/concepts/save-record.md +++ b/docs/concepts/save-record.md @@ -155,6 +155,22 @@ interface RuntimeSnapshot { `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. +## Writing a value during a run + +The maker's **Game memory** panel shows the snapshot above live and lets the person change a value. +The write is `Engine.setFlag(flag, value, thing?)` (`services/flag-write.ts`, `writeFlag`): it emits +`EngineEvent.FLAG_SET`, exactly what a `set-flag` action emits, so `FlagSystem` stays the one writer +of the record and `StateSystem` re-resolves every placement on its next frame. It refuses (returns +`false`) outside a run, for a flag the project never declared, and for a value of the wrong type for +the flag's kind; a thing-scoped flag needs the placement id as `thing`. + +It is deliberately not a `Command`: a run's flag values are local, un-persisted runtime state, not +part of the shared document, so they are neither undoable nor sent to collaborators. + +The panel updates on `FLAG_SET` only, never per frame: `LiveStateService` +(`apps/maker-gjs/src/services/live-state.service.ts`) re-reads the snapshot once per burst of flag +events and every panel that shows live state reads that one snapshot. + ## What M5 and M8 add - **M5 — the bag.** An inventory is per player: `PlayerRecord` gains `bag`, and the `has-item` @@ -224,7 +240,9 @@ they have two lifetimes. `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), +- **The write** — `services/flag-write.ts` (`writeFlag`), `engine.ts` `setFlag`; the panel is + `packages/gjs/src/widgets/editor/game-memory-page.ts` over the pure `game-memory.model.ts`. +- **Specs** — `services/flag-write.spec.ts`, `components/game-save-state.component.spec.ts` (shape, migration, resolved view), `systems/state.system.spec.ts` (two placements, two players, the snapshot). ## Related concepts diff --git a/packages/engine/src/engine.ts b/packages/engine/src/engine.ts index f3612c78..fe756920 100644 --- a/packages/engine/src/engine.ts +++ b/packages/engine/src/engine.ts @@ -38,6 +38,7 @@ import { ASSISTANT_PEER_ID, AssistantPresenceController } from './services/assis import { attachPeerEditFlash } from './services/peer-edit-flash.ts' import { placementTileCentre } from './services/placement-geometry.ts' import { optionsOpen } from './services/ask-state.ts' +import { writeFlag } from './services/flag-write.ts' import { applyRuntimeMode, isRuntimeModeActive } from './services/runtime-mode.ts' import { refreshWallOverlayFor } from './services/wall-overlay.ts' import { @@ -52,6 +53,7 @@ import { playZoom, wholeMapZoom } from './utils/play-camera.ts' import { SessionState } from './utils/session-state.ts' import { clampZoom } from './utils/zoom.ts' import { type AwarenessMessage, RemoteCursorRenderer } from './sync/index.ts' +import type { FlagValue } from './types/data/EntityDefinition.ts' import type { EntityDefinition, LayerData, LayerPlane, ObjectPlacement } from './types/data/index.ts' import { type ArrivalPickRequest, @@ -956,6 +958,21 @@ export class Engine { } } + /** + * Set one flag of the running game — what the Game memory panel calls. + * `thing` names the owning placement for a `scope: 'thing'` flag. + * + * It goes through `FLAG_SET`, so `FlagSystem` stays the record's only + * writer and the states re-resolve on the next frame. Returns `false` + * when nothing was written: no run, an undeclared flag, a value of the + * wrong kind. See {@link writeFlag}. + */ + setFlag(flag: string, value: FlagValue, thing?: string): boolean { + const scene = this.activeMapScene() + if (!scene) return false + return writeFlag(this.events, scene, scene.flags, flag, value, thing) + } + /** Current runtime-mode state on the active scene (`false` if no scene). */ isRuntimeMode(): boolean { const scene = this.activeMapScene() diff --git a/packages/engine/src/services/flag-write.spec.ts b/packages/engine/src/services/flag-write.spec.ts new file mode 100644 index 00000000..a03be1a0 --- /dev/null +++ b/packages/engine/src/services/flag-write.spec.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from '@gjsify/unit' +import { Entity, EventEmitter, Scene } from 'excalibur' +import { EntityStatesComponent } from '../components/entity-states.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 { FlagSystem } from '../systems/flag.system.ts' +import { StateSystem } from '../systems/state.system.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 { writeFlag } from './flag-write.ts' + +const DEFS: FlagData[] = [ + { id: 'coins', name: 'Coins', kind: 'number', initial: 0, scope: 'game' }, + { id: 'chest-open', name: 'Chest open', kind: 'yes-no', initial: false, scope: 'thing' }, +] + +function rig(runtime = true) { + const events = new EventEmitter() + const scene = new Scene() + if (runtime) SessionState.set(scene, new RuntimeModeComponent()) + const chest = new Entity() + chest.addComponent(new PlacementIdComponent('chest-a')) + chest.addComponent(new EntityStatesComponent([{ id: 'open', when: { flag: 'chest-open' }, components: [] }], [])) + scene.world.add(chest) + const flags = new FlagSystem(events, DEFS) + const states = new StateSystem() + for (const system of [flags, states]) system.onInitialize(scene.world, scene) + const store = () => SessionState.get(scene, GameSaveStateComponent)! + const write = (flag: string, value: boolean | number | string, thing?: string) => + writeFlag(events, scene, DEFS, flag, value, thing) + return { events, scene, chest, states, store, write } +} + +export default async () => { + await describe('writeFlag — the Game memory panel’s write', async () => { + await it('lands a game-scoped value in the world bag', async () => { + const { store, write } = rig() + expect(write('coins', 7)).toBe(true) + expect(store().world.flags.coins).toBe(7) + }) + + await it('lands a thing-scoped value in that placement’s own bag and re-resolves its state', async () => { + const { store, write, states, chest } = rig() + states.onUpdate(16) + expect(chest.get(EntityStatesComponent)?.activeStateId).toBe(null) + expect(write('chest-open', true, 'chest-a')).toBe(true) + states.onUpdate(16) + expect(store().world.things['chest-a']).toStrictEqual({ 'chest-open': true }) + expect(chest.get(EntityStatesComponent)?.activeStateId).toBe('open') + }) + + await it('is announced as FLAG_SET, like a value the game wrote itself', async () => { + const { events, write } = rig() + const seen: string[] = [] + events.on(EngineEvent.FLAG_SET, (p) => seen.push(`${p.flag}=${String(p.value)}`)) + write('coins', 3) + expect(seen).toStrictEqual(['coins=3']) + }) + + await it('refuses outside a run', async () => { + const { store, write } = rig(false) + expect(write('coins', 7)).toBe(false) + expect(store().world.flags.coins).toBe(0) + }) + + await it('refuses a flag the project never declared and a value of the wrong type', async () => { + const { store, write } = rig() + expect(write('nope', 1)).toBe(false) + expect(write('coins', 'many')).toBe(false) + expect(store().world.flags.coins).toBe(0) + }) + }) +} diff --git a/packages/engine/src/services/flag-write.ts b/packages/engine/src/services/flag-write.ts new file mode 100644 index 00000000..a60ae850 --- /dev/null +++ b/packages/engine/src/services/flag-write.ts @@ -0,0 +1,37 @@ +import type { EventEmitter, Scene } from 'excalibur' +import type { FlagValue } from '../types/data/EntityDefinition.ts' +import { type FlagData, flagValueFitsKind } from '../types/data/FlagData.ts' +import { EngineEvent, type EngineEventMap } from '../types/index.ts' +import { isRuntimeModeActive } from './runtime-mode.ts' + +/** + * Write one flag of the running game, the way a `set-flag` action does. + * + * The write is an `EngineEvent.FLAG_SET`, not a poke at the save record: + * `FlagSystem` is the one writer of that record, so a value set from the + * Game memory panel lands in the same bag, notifies the same readers and + * is announced to the same listeners as one the game itself set. + * `StateSystem` then re-resolves every placement on its next frame. + * + * Refused (returns `false`) rather than thrown, because the caller is a + * UI row that can be one frame behind the run: outside a run (there is + * no save to write to), for a flag the project never declared, and for a + * value of the wrong type for the flag's kind. + * + * Not a `Command`: a run's flag values are local, un-persisted runtime + * state, not part of the shared document (`docs/concepts/save-record.md`). + */ +export function writeFlag( + events: EventEmitter, + scene: Scene, + flagDefs: readonly FlagData[], + flag: string, + value: FlagValue, + thing?: string, +): boolean { + if (!isRuntimeModeActive(scene)) return false + const def = flagDefs.find((f) => f.id === flag) + if (!def || !flagValueFitsKind(value, def.kind)) return false + events.emit(EngineEvent.FLAG_SET, { flag, value, thing: def.scope === 'thing' ? thing : undefined }) + return true +} diff --git a/packages/engine/src/services/index.ts b/packages/engine/src/services/index.ts index 3bea41e9..5bb3ec8c 100644 --- a/packages/engine/src/services/index.ts +++ b/packages/engine/src/services/index.ts @@ -22,6 +22,7 @@ export * from './editor-view-flags' export * from './editor-view' export * from './eraser-preview' export * from './fill-preview' +export * from './flag-write' export * from './flood-fill' export * from './font-chain' export * from './font-metrics' diff --git a/packages/engine/src/test.mts b/packages/engine/src/test.mts index adcf8378..cbc54b27 100644 --- a/packages/engine/src/test.mts +++ b/packages/engine/src/test.mts @@ -106,6 +106,7 @@ import combatActionSuite from './systems/combat-action.spec.js' import askStateSuite from './services/ask-state.spec.js' import dialogueStateSuite from './services/dialogue-state.spec.js' import uiInsetSuite from './services/ui-inset.spec.js' +import flagWriteSuite from './services/flag-write.spec.js' import dialogueSpeakSuite from './systems/dialogue-speak.spec.js' import eventActionSystemSuite from './systems/event-action.system.spec.js' import hoverOverlaysSuite from './systems/hover-overlays.spec.js' @@ -230,6 +231,7 @@ run({ askStateSuite, dialogueStateSuite, uiInsetSuite, + flagWriteSuite, eventActionSystemSuite, dialogueSpeakSuite, hoverOverlaysSuite, diff --git a/packages/gjs/src/test.mts b/packages/gjs/src/test.mts index e30ea642..27dfc7fa 100644 --- a/packages/gjs/src/test.mts +++ b/packages/gjs/src/test.mts @@ -35,6 +35,7 @@ import entityComponentsEditorModelSuite from './widgets/editor/entity-components import conditionModelSuite from './widgets/editor/condition-model.spec.js' import eventActionModelSuite from './widgets/editor/event-action-model.spec.js' import flagPickerModelSuite from './widgets/editor/flag-picker.model.spec.js' +import gameMemoryModelSuite from './widgets/editor/game-memory.model.spec.js' import layerSectionsSuite from './widgets/editor/layer-sections.spec.js' import mapConnectionsModelSuite from './widgets/editor/map-connections.model.spec.js' import mapPreviewGeometrySuite from './widgets/editor/map-preview.geometry.spec.js' @@ -75,6 +76,7 @@ run({ conditionModelSuite, eventActionModelSuite, flagPickerModelSuite, + gameMemoryModelSuite, layerSectionsSuite, mapConnectionsModelSuite, mapPreviewGeometrySuite, diff --git a/packages/gjs/src/widgets/editor/chrome-stages.spec.ts b/packages/gjs/src/widgets/editor/chrome-stages.spec.ts index 6dd38793..53ae7f16 100644 --- a/packages/gjs/src/widgets/editor/chrome-stages.spec.ts +++ b/packages/gjs/src/widgets/editor/chrome-stages.spec.ts @@ -44,6 +44,12 @@ export default async () => { } }) + await it('offers the Game memory button during a run and only then', async () => { + for (const { stage, layout, playing } of everyState()) { + expect(chromeFlags(stage, layout, playing).memoryButton).toBe(playing) + } + }) + await it('never hides undo behind the overflow menu', async () => { // The bar this replaces put undo inside "⋯" below 460sp, which on // a phone made the only undo on touch two taps deep. diff --git a/packages/gjs/src/widgets/editor/chrome-stages.ts b/packages/gjs/src/widgets/editor/chrome-stages.ts index 179f8461..6d361f98 100644 --- a/packages/gjs/src/widgets/editor/chrome-stages.ts +++ b/packages/gjs/src/widgets/editor/chrome-stages.ts @@ -145,6 +145,8 @@ export interface ChromeFlags { stopButton: boolean /** ↺ Restart beside it, in both layouts: the FAB has no second verb to spare. */ restartButton: boolean + /** ⚙ Game memory in the context pill while a run is on. */ + memoryButton: boolean /** The accent frame around the canvas while a run is on — wide only (§4.6). */ runBorder: boolean /** The Play FAB. */ @@ -266,6 +268,7 @@ export function chromeFlags(stage: ChromeStage, layout: ChromeLayout, playing: b overflowButton: !phoneRun && !picking, stopButton: phoneRun, restartButton: playing, + memoryButton: playing, runBorder: !phone && playing, playFab: !phoneRun && !picking, bottomBar: phone && editing, diff --git a/packages/gjs/src/widgets/editor/editor-pages.ts b/packages/gjs/src/widgets/editor/editor-pages.ts index ffa38321..d003ee41 100644 --- a/packages/gjs/src/widgets/editor/editor-pages.ts +++ b/packages/gjs/src/widgets/editor/editor-pages.ts @@ -1,11 +1,12 @@ import type Adw from '@girs/adw-1' import { BrushPage } from './brush-page.ts' +import { GameMemoryPage } from './game-memory-page.ts' import { LayersPage } from './layers-page.ts' import { SelectedPage } from './selected-page.ts' /** - * The three `Adw.Bin`s one layout offers as homes for the editor pages. + * The four `Adw.Bin`s one layout offers as homes for the editor pages. * * `RightInspector` exposes one set, `SceneEditor`'s bottom sheet another; * only ever one of them holds the pages. @@ -14,12 +15,17 @@ export interface PageSlots { brush: Adw.Bin layers: Adw.Bin selected: Adw.Bin + /** The Game memory page's home: only shown while a test run is on. */ + memory: Adw.Bin } /** - * The editor's three pages — Brush, Layers, Selected — as ONE set of + * The editor's pages — Brush, Layers, Selected and Game memory — as ONE set of * widget instances that moves between layouts. * + * Game memory is the odd one out: it is only offered during a test run, where + * it replaces the other three (`memoryMode` on both containers). + * * The wide layout shows them in the right inspector, the phone layout in * the bottom sheet. Building a copy per layout is what makes "the layer * list is stale on phone" bugs: every host write would have to find both @@ -33,6 +39,7 @@ export class EditorPages { readonly brush = new BrushPage() readonly layers = new LayersPage() readonly selected = new SelectedPage() + readonly memory = new GameMemoryPage() private _slots: PageSlots | null = null @@ -54,11 +61,13 @@ export class EditorPages { this._slots.brush.set_child(null) this._slots.layers.set_child(null) this._slots.selected.set_child(null) + this._slots.memory.set_child(null) } this._slots = slots if (!slots) return slots.brush.set_child(this.brush) slots.layers.set_child(this.layers) slots.selected.set_child(this.selected) + slots.memory.set_child(this.memory) } } diff --git a/packages/gjs/src/widgets/editor/game-memory-page.blp b/packages/gjs/src/widgets/editor/game-memory-page.blp new file mode 100644 index 00000000..9b128e16 --- /dev/null +++ b/packages/gjs/src/widgets/editor/game-memory-page.blp @@ -0,0 +1,45 @@ +using Gtk 4.0; +using Adw 1; + +template $PixelRpgGameMemoryPage : Adw.Bin { + Gtk.Box { + orientation: vertical; + spacing: 18; + margin-top: 12; + margin-bottom: 12; + margin-start: 12; + margin-end: 12; + + // Said once, in place of the groups, so the page of a game with no + // flags reads as a fact and not as a failed load. + Gtk.Label empty_label { + visible: false; + label: _("This game has no flags yet. The ones it sets will show up here."); + wrap: true; + xalign: 0; + styles ["dim-label"] + } + + Adw.PreferencesGroup game_group { + title: _("The whole game"); + description: _("Change a value to try the game with it."); + } + + // One group per placement, built in TS: how many there are depends on the map. + Gtk.Box things_box { + orientation: vertical; + spacing: 18; + } + + Adw.PreferencesGroup { + Adw.ExpanderRow { + title: _("For experts"); + + Adw.SwitchRow probe_row { + title: _("Measure frame times"); + subtitle: _("Writes how long each frame took to a file."); + } + } + } + } +} diff --git a/packages/gjs/src/widgets/editor/game-memory-page.d.blp.ts b/packages/gjs/src/widgets/editor/game-memory-page.d.blp.ts new file mode 100644 index 00000000..9e5ea4eb --- /dev/null +++ b/packages/gjs/src/widgets/editor/game-memory-page.d.blp.ts @@ -0,0 +1,32 @@ +// GENERATED from game-memory-page.blp — do not edit. ADR 0088 says what these exports mean. +// Regenerate with `gjsify blueprint types`; `scripts/check-blueprint-sidecars.mjs` holds it. + +import type Adw from "gi://Adw?version=1"; +import type Gtk from "gi://Gtk?version=4.0"; + +/** The GtkBuilder XML this `.blp` compiles to. */ +declare const xml: string; +export default xml; + +/** The class `template $PixelRpgGameMemoryPage` defines. */ +export declare const GTypeName: "PixelRpgGameMemoryPage"; + +/** + * Every id inside the template, in source order — what `registerClass` is given. + * + * A MUTABLE tuple, and the `readonly` is missing for a reason that is not ours: `@girs` + * declares `GObject.MetaInfo['InternalChildren']` as `string[]`, so a `readonly` tuple is + * refused at the call site with TS4104 and the consumer would have to spread it — the + * boilerplate ADR 0088 exists to remove. The tuple still pins the exact ids and arity, + * which is the property that matters. `status/open-todos/blueprint.md` carries the + * upstream half. + */ +export declare const InternalChildren: ["empty_label", "game_group", "things_box", "probe_row"]; + +/** The `_`-prefixed members GJS installs for them. Merge it into the class interface. */ +export interface Children { + _empty_label: Gtk.Label; + _game_group: Adw.PreferencesGroup; + _things_box: Gtk.Box; + _probe_row: Adw.SwitchRow; +} diff --git a/packages/gjs/src/widgets/editor/game-memory-page.ts b/packages/gjs/src/widgets/editor/game-memory-page.ts new file mode 100644 index 00000000..0f041374 --- /dev/null +++ b/packages/gjs/src/widgets/editor/game-memory-page.ts @@ -0,0 +1,164 @@ +import Adw from '@girs/adw-1' +import GObject from '@girs/gobject-2.0' +import type Gtk from '@girs/gtk-4.0' +import type { FlagValue } from '@pixelrpg/engine' +import { gettext as _ } from 'gettext' +import { entryRow, spinRow, switchRow } from '../common/preference-rows.ts' +import { valueEditorKind } from './event-action-model.ts' +import { FLAG_NUMBER_RANGE, type MemoryRow, type MemorySections, memoryShape } from './game-memory.model.ts' +import Template from './game-memory-page.blp' + +/** Puts a new value into a row that is already on screen. */ +type RowUpdater = (value: FlagValue) => void + +/** + * The "Game memory" page: what the game remembers during a test run, with + * every value editable. + * + * It is a view of a snapshot and nothing else. The host feeds it the + * rows ({@link setSections}) and the values ({@link setValues}) and + * receives the person's edits through {@link onWrite}; the page never + * reads the engine and never writes a value itself, so a switch that did + * not take (the run ended a frame earlier) simply stays where the next + * snapshot puts it. + * + * Values arrive on every flag event, so they update the rows in place. + * Rebuilding a row under the finger would drop a spinner mid-drag. + */ +export class GameMemoryPage extends Adw.Bin { + declare _game_group: Adw.PreferencesGroup + declare _things_box: Gtk.Box + declare _empty_label: Gtk.Label + declare _probe_row: Adw.SwitchRow + + /** Asked to set one flag; `thing` is the owning placement for a thing-scoped one. */ + onWrite: ((flag: string, value: FlagValue, thing: string | null) => void) | null = null + /** Asked to switch the frame-time measurement. */ + onProbe: ((on: boolean) => void) | null = null + + private _shape = '' + private _gameRows: Adw.PreferencesRow[] = [] + private _thingGroups: Adw.PreferencesGroup[] = [] + private readonly _updaters = new Map() + /** True while a snapshot is being put into rows, so setting a row is not mistaken for an edit. */ + private _muted = false + + static { + GObject.registerClass( + { + GTypeName: 'PixelRpgGameMemoryPage', + Template, + InternalChildren: ['game_group', 'things_box', 'empty_label', 'probe_row'], + }, + GameMemoryPage, + ) + } + + constructor(params?: Partial) { + super(params) + this._probe_row.connect('notify::active', () => { + if (!this._muted) this.onProbe?.(this._probe_row.get_active()) + }) + } + + /** Forget everything: the run is over. */ + clear(): void { + this._shape = '' + this._clearRows() + this._game_group.set_visible(false) + this._empty_label.set_visible(false) + } + + /** + * Show these rows. A snapshot whose rows are the ones already on + * screen only updates their values. + */ + setSections(sections: MemorySections): void { + const shape = memoryShape(sections) + if (shape === this._shape) { + this._applyRows(sections) + return + } + this._shape = shape + this._clearRows() + this._game_group.set_visible(sections.game.length > 0) + this._empty_label.set_visible(sections.game.length === 0 && sections.things.length === 0) + for (const r of sections.game) this._gameRows.push(this._addRow(this._game_group, r)) + for (const thing of sections.things) { + const group = new Adw.PreferencesGroup({ + title: thing.name, + description: _('At tile %s, %s').replace('%s', String(thing.tileX)).replace('%s', String(thing.tileY)), + }) + for (const r of thing.rows) this._addRow(group, r) + this._things_box.append(group) + this._thingGroups.push(group) + } + } + + /** Reflect the frame-time switch; `path` is the file it writes to while on. */ + setProbe(on: boolean, path: string | null): void { + this._muted = true + this._probe_row.set_active(on) + this._muted = false + this._probe_row.set_tooltip_text(on && path ? path : null) + } + + /** Whether the frame-time switch is on. */ + get probeActive(): boolean { + return this._probe_row.get_active() + } + + private _applyRows(sections: MemorySections): void { + this._muted = true + try { + for (const r of [...sections.game, ...sections.things.flatMap((t) => t.rows)]) + this._updaters.get(r.key)?.(r.value) + } finally { + this._muted = false + } + } + + private _clearRows(): void { + for (const row of this._gameRows) this._game_group.remove(row) + this._gameRows = [] + for (const group of this._thingGroups) this._things_box.remove(group) + this._thingGroups = [] + this._updaters.clear() + } + + /** One row, edited the way the flag's kind asks: a switch, a number or a word. */ + private _addRow(group: Adw.PreferencesGroup, r: MemoryRow): Adw.PreferencesRow { + const write = (value: FlagValue) => { + if (!this._muted) this.onWrite?.(r.flag, value, r.thing) + } + let row: Adw.PreferencesRow + switch (valueEditorKind(r.kind, r.value)) { + case 'yes-no': { + const w = switchRow(r.name, r.value === true, write) + this._updaters.set(r.key, (v) => w.set_active(v === true)) + row = w + break + } + case 'number': { + const w = spinRow(r.name, typeof r.value === 'number' ? r.value : 0, FLAG_NUMBER_RANGE, write) + this._updaters.set(r.key, (v) => { + if (typeof v === 'number' && Math.round(w.get_value()) !== v) w.set_value(v) + }) + row = w + break + } + case 'text': { + const w = entryRow(r.name, String(r.value), write) + this._updaters.set(r.key, (v) => { + if (w.get_text() !== String(v)) w.set_text(String(v)) + }) + row = w + break + } + } + group.add(row) + return row + } +} + +GObject.type_ensure(GameMemoryPage.$gtype) diff --git a/packages/gjs/src/widgets/editor/game-memory.model.spec.ts b/packages/gjs/src/widgets/editor/game-memory.model.spec.ts new file mode 100644 index 00000000..004dc196 --- /dev/null +++ b/packages/gjs/src/widgets/editor/game-memory.model.spec.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from '@gjsify/unit' +import type { FlagData, FlagUsage } from '@pixelrpg/engine' +import { memorySections, memoryShape } from './game-memory.model.ts' + +const DEFS: FlagData[] = [ + { id: 'coins', name: 'Coins', kind: 'number', initial: 0, scope: 'game' }, + { id: 'has-key', name: 'Has the key', kind: 'yes-no', initial: false, scope: 'game' }, + { id: 'opened', name: 'Opened', kind: 'yes-no', initial: false, scope: 'thing' }, +] + +const usage = (flagId: string, placementId: string | null, entityId: string): FlagUsage => ({ + flagId, + access: 'write', + via: 'set-flag', + mapId: placementId ? 'm' : null, + placementId, + entityId, + stateIndex: null, + actionIndex: 0, +}) + +// "opened" is written by the chest's library entry, so every chest placement carries it. +const USAGES = new Map([['opened', [usage('opened', null, 'chest')]]]) + +const PLACEMENTS = [ + { id: 'p-b', defId: 'chest', name: 'Chest', tileX: 9, tileY: 2 }, + { id: 'p-a', defId: 'chest', name: 'Chest', tileX: 3, tileY: 2 }, + { id: 'p-sign', defId: 'sign', name: 'Sign', tileX: 1, tileY: 1 }, +] + +export default async () => { + await describe('game-memory.model', async () => { + await it('lists game-scoped flags with their written value, else their initial', async () => { + const { game } = memorySections(DEFS, PLACEMENTS, USAGES, { flags: { coins: 5 }, thingFlags: {} }) + expect(game.map((r) => [r.flag, r.value, r.thing])).toStrictEqual([ + ['coins', 5, null], + ['has-key', false, null], + ]) + }) + + await it('groups thing-scoped values per placement, by name, in reading order', async () => { + const { things } = memorySections(DEFS, PLACEMENTS, USAGES, { + flags: {}, + thingFlags: { 'p-a': { opened: true } }, + }) + expect(things.map((t) => [t.name, t.placementId, t.rows[0].value])).toStrictEqual([ + ['Chest', 'p-a', true], + ['Chest', 'p-b', false], + ]) + expect(things[0].rows[0].key).toBe('p-a/opened') + expect(things[0].rows[0].thing).toBe('p-a') + }) + + await it('leaves out a placement whose data names no thing-scoped flag', async () => { + const { things } = memorySections(DEFS, PLACEMENTS, USAGES, { flags: {}, thingFlags: {} }) + expect(things.some((t) => t.placementId === 'p-sign')).toBe(false) + }) + + await it('counts a usage on the placement itself, not only on its library entry', async () => { + const own = new Map([['opened', [usage('opened', 'p-sign', 'sign')]]]) + const { things } = memorySections(DEFS, PLACEMENTS, own, { flags: {}, thingFlags: {} }) + expect(things.map((t) => t.placementId)).toStrictEqual(['p-sign']) + }) + + await it('keeps the shape when only a value changes, and changes it when a row appears', async () => { + const before = memorySections(DEFS, PLACEMENTS, USAGES, { flags: { coins: 1 }, thingFlags: {} }) + const after = memorySections(DEFS, PLACEMENTS, USAGES, { + flags: { coins: 9 }, + thingFlags: { 'p-a': { opened: true } }, + }) + expect(memoryShape(after)).toBe(memoryShape(before)) + const fewer = memorySections(DEFS.slice(1), PLACEMENTS, USAGES, { flags: {}, thingFlags: {} }) + expect(memoryShape(fewer) === memoryShape(before)).toBe(false) + }) + }) +} diff --git a/packages/gjs/src/widgets/editor/game-memory.model.ts b/packages/gjs/src/widgets/editor/game-memory.model.ts new file mode 100644 index 00000000..a9a281f6 --- /dev/null +++ b/packages/gjs/src/widgets/editor/game-memory.model.ts @@ -0,0 +1,124 @@ +import type { FlagData, FlagKind, FlagUsage, FlagValue } from '@pixelrpg/engine' + +/** + * What the Game memory panel shows during a test run, as plain data. + * + * The panel lists the project's flags twice over: the ones that hold one + * value for the whole game, then — per placement — the ones each thing + * remembers for itself (`scope: 'thing'`). A thing shows under its NAME; + * its placement id is the save key and never reaches the screen. + */ + +/** The range a number flag's spinner covers, the same the action editor offers. */ +export const FLAG_NUMBER_RANGE = { min: -100000, max: 100000, step: 1 } + +/** One editable line: a flag, and whose value it is. */ +export interface MemoryRow { + /** `flag` for a game-scoped value, `placementId/flag` for a thing's. Stable across value changes. */ + key: string + flag: string + name: string + kind: FlagKind + /** The owning placement for a thing-scoped value, `null` for the whole game. */ + thing: string | null + value: FlagValue +} + +/** One placement and its own values. */ +export interface MemoryThing { + placementId: string + name: string + /** Where it stands, so two chests of one kind can be told apart. */ + tileX: number + tileY: number + rows: MemoryRow[] +} + +export interface MemorySections { + game: MemoryRow[] + things: MemoryThing[] +} + +/** A placement the panel may list; the host resolves its name. */ +export interface MemoryPlacement { + id: string + /** The library entry it instantiates; usages that sit on the entry itself count for every placement of it. */ + defId?: string + name: string + tileX: number + tileY: number +} + +/** The record's two value bags, as `RuntimeSnapshot` carries them. */ +export interface MemoryValues { + flags: Readonly> + thingFlags: Readonly>>> +} + +/** The flags a placement's own data names (its states, its actions), thing-scoped only. */ +function thingFlagsOf( + placement: MemoryPlacement, + defs: readonly FlagData[], + usages: ReadonlyMap, +): FlagData[] { + return defs.filter( + (def) => + def.scope === 'thing' && + (usages.get(def.id) ?? []).some( + (u) => u.placementId === placement.id || (u.placementId === null && u.entityId === placement.defId), + ), + ) +} + +/** + * The panel's rows for the current values. + * + * A value nobody has written yet reads as the flag's `initial`, which is + * what the game itself would read. A placement shows only when its data + * names a thing-scoped flag, so a map of fifty decorations does not + * become fifty empty groups; placements are listed in reading order + * (top to bottom, left to right) rather than in the order they were made. + */ +export function memorySections( + defs: readonly FlagData[], + placements: readonly MemoryPlacement[], + usages: ReadonlyMap, + values: MemoryValues, +): MemorySections { + const row = (def: FlagData, thing: string | null, value: FlagValue | undefined): MemoryRow => ({ + key: thing === null ? def.id : `${thing}/${def.id}`, + flag: def.id, + name: def.name, + kind: def.kind, + thing, + value: value ?? def.initial, + }) + const game = defs.filter((d) => d.scope !== 'thing').map((d) => row(d, null, values.flags[d.id])) + const things: MemoryThing[] = [] + for (const p of [...placements].sort((a, b) => a.tileY - b.tileY || a.tileX - b.tileX)) { + const own = thingFlagsOf(p, defs, usages) + if (own.length === 0) continue + things.push({ + placementId: p.id, + name: p.name, + tileX: p.tileX, + tileY: p.tileY, + rows: own.map((d) => row(d, p.id, values.thingFlags[p.id]?.[d.id])), + }) + } + return { game, things } +} + +/** + * What decides whether the panel's rows have to be rebuilt: the set of + * rows and the names they carry, never their values. A value change must + * update a row in place — rebuilding it would take the focus from the + * spinner the person is dragging. + */ +export function memoryShape(sections: MemorySections): string { + const line = (r: MemoryRow) => `${r.key}:${r.kind}:${r.name}` + return JSON.stringify([ + sections.game.map(line), + sections.things.map((t) => [t.placementId, t.name, t.tileX, t.tileY, t.rows.map(line)]), + ]) +} diff --git a/packages/gjs/src/widgets/editor/index.ts b/packages/gjs/src/widgets/editor/index.ts index 779af430..68f88227 100644 --- a/packages/gjs/src/widgets/editor/index.ts +++ b/packages/gjs/src/widgets/editor/index.ts @@ -39,6 +39,8 @@ export * from './flag-picker.model' export * from './floating-play' export * from './floating-zoom.story' export * from './floating-zoom' +export * from './game-memory-page' +export * from './game-memory.model' export * from './language-text-row' export * from './layer-row.story' export * from './layer-row' diff --git a/packages/gjs/src/widgets/editor/phone-chrome.probe.spec.ts b/packages/gjs/src/widgets/editor/phone-chrome.probe.spec.ts index da281426..a17521a3 100644 --- a/packages/gjs/src/widgets/editor/phone-chrome.probe.spec.ts +++ b/packages/gjs/src/widgets/editor/phone-chrome.probe.spec.ts @@ -125,5 +125,15 @@ export default async () => { expect(cond.sheetAllocPx).toBe(cond.floorPx) expect(cond.offenders.length).toBe(0) }) + + await it('keeps the Game memory page, every row kind and the experts group, within the floor', async () => { + const mem = probe.probeGameMemory() + console.log( + `[phone-chrome] game memory sheet min ${mem.sheetMinPx} alloc ${mem.sheetAllocPx} (floor ${mem.floorPx})\n ${mem.offenders.map((r) => `${r.name} min ${r.min}`).join('\n ')}`, + ) + expect(mem.sheetMinPx).toBeLessThanOrEqual(mem.floorPx) + expect(mem.sheetAllocPx).toBe(mem.floorPx) + expect(mem.offenders.length).toBe(0) + }) }) } diff --git a/packages/gjs/src/widgets/editor/phone-chrome.probe.ts b/packages/gjs/src/widgets/editor/phone-chrome.probe.ts index a1fb3b42..60f1d542 100644 --- a/packages/gjs/src/widgets/editor/phone-chrome.probe.ts +++ b/packages/gjs/src/widgets/editor/phone-chrome.probe.ts @@ -341,3 +341,66 @@ export function probeConditionEditor(): ConditionWidthReport { window.destroy() return result } + +/** The Game memory page at the floor: every kind of row, the longest honest names, the experts group open. */ +export function probeGameMemory(): ConditionWidthReport { + const dir = GLib.getenv('GJSIFY_LOCALE_DIR') + if (dir) { + bindtextdomain('org.pixelrpg.maker', dir) + textdomain('org.pixelrpg.maker') + } + ensureStyles() + const editor = new SceneEditor() + const floorPx = editor._ladder.width_request + const window = new Gtk.Window({ default_width: floorPx, default_height: 780, decorated: false }) + window.set_child(editor) + editor.setLayout('phone') + const pages = populate(editor) + const long = 'Coins collected in the whole village' + pages.memory.setSections({ + game: [ + { key: 'coins', flag: 'coins', name: long, kind: 'number', thing: null, value: 12 }, + { + key: 'met', + flag: 'met', + name: 'Has talked to the old fisherman by the lake', + kind: 'yes-no', + thing: null, + value: true, + }, + { + key: 'nick', + flag: 'nick', + name: 'What the hero is called', + kind: 'text', + thing: null, + value: 'Link of the Lake', + }, + ], + things: [ + { + placementId: 'p1', + name: 'Treasure chest behind the waterfall', + tileX: 12, + tileY: 34, + rows: [{ key: 'p1/open', flag: 'open', name: 'Opened already', kind: 'yes-no', thing: 'p1', value: false }], + }, + ], + }) + editor.setPlaying(true) + editor.memoryMode = true + window.present() + pumpUntil(() => editor.get_mapped() && editor._phone_bar.get_width() >= 0, 'game memory window') + editor.openSheet() + pumpUntil(() => editor._bottom_sheet.get_width() > 0, 'game memory sheet') + const offenders: WidthReport[] = [] + scan(editor._bottom_sheet, floorPx, 0, offenders) + const result = { + floorPx, + sheetMinPx: editor._bottom_sheet.measure(Gtk.Orientation.HORIZONTAL, -1)[0], + sheetAllocPx: editor._bottom_sheet.get_width(), + offenders, + } + window.destroy() + return result +} diff --git a/packages/gjs/src/widgets/editor/right-inspector.blp b/packages/gjs/src/widgets/editor/right-inspector.blp index 2099f37f..b0f21af8 100644 --- a/packages/gjs/src/widgets/editor/right-inspector.blp +++ b/packages/gjs/src/widgets/editor/right-inspector.blp @@ -40,7 +40,7 @@ template $PixelRpgRightInspector : Adw.Bin { // The page switcher sits on top, under the header — the same three-page // order the phone sheet will use, so the pages read as one set. [top] - Adw.InlineViewSwitcher { + Adw.InlineViewSwitcher switcher { stack: stack; display-mode: labels; homogeneous: false; @@ -91,6 +91,16 @@ template $PixelRpgRightInspector : Adw.Bin { child: Adw.Bin selected_slot {}; } + + // Only while a test run is on (`memoryMode`): then it is the one page. + Adw.ViewStackPage { + name: "memory"; + title: _("Game memory"); + icon-name: "preferences-other-symbolic"; + visible: false; + + child: Adw.Bin memory_slot {}; + } }; }; }; diff --git a/packages/gjs/src/widgets/editor/right-inspector.ts b/packages/gjs/src/widgets/editor/right-inspector.ts index 59a886fb..1a115f42 100644 --- a/packages/gjs/src/widgets/editor/right-inspector.ts +++ b/packages/gjs/src/widgets/editor/right-inspector.ts @@ -7,7 +7,8 @@ import Template from './right-inspector.blp' * Right-side inspector for the scene editor. * * Hosts an `Adw.ViewStack` + `Adw.InlineViewSwitcher` with three pages: - * **Brush**, **Layers**, **Selected**. It does not own their content — + * **Brush**, **Layers**, **Selected** — and a fourth, **Game memory**, + * that stands in for them during a test run. It does not own their content — * each page is an `Adw.Bin` slot the shell fills from its single * {@link EditorPages} set, which the phone sheet borrows instead when * the layout collapses. @@ -17,6 +18,10 @@ export class RightInspector extends Adw.Bin { declare _brush_slot: Adw.Bin declare _layers_slot: Adw.Bin declare _selected_slot: Adw.Bin + declare _memory_slot: Adw.Bin + declare _switcher: Adw.InlineViewSwitcher + + private _pageBeforeMemory: string | null = null private _collapsed = false @@ -25,7 +30,7 @@ export class RightInspector extends Adw.Bin { { GTypeName: 'PixelRpgRightInspector', Template, - InternalChildren: ['stack', 'brush_slot', 'layers_slot', 'selected_slot'], + InternalChildren: ['stack', 'brush_slot', 'layers_slot', 'selected_slot', 'memory_slot', 'switcher'], Properties: { 'visible-page': GObject.ParamSpec.string( 'visible-page', @@ -53,7 +58,33 @@ export class RightInspector extends Adw.Bin { /** The three bins the shell hands to `EditorPages.host` on wide layouts. */ get pageSlots(): PageSlots { - return { brush: this._brush_slot, layers: this._layers_slot, selected: this._selected_slot } + return { + brush: this._brush_slot, + layers: this._layers_slot, + selected: this._selected_slot, + memory: this._memory_slot, + } + } + + /** + * Swap the three editing pages for Game memory while a test run is on, + * and put the page the person was on back afterwards. The switcher goes + * too: one page needs no tabs. + */ + set memoryMode(on: boolean) { + if (on === (this._pageBeforeMemory !== null)) return + for (const slot of [this._brush_slot, this._layers_slot, this._selected_slot]) { + this._stack.get_page(slot).set_visible(!on) + } + this._stack.get_page(this._memory_slot).set_visible(on) + this._switcher.set_visible(!on) + if (on) { + this._pageBeforeMemory = this.visiblePage + this._stack.set_visible_child_name('memory') + } else { + this._stack.set_visible_child_name(this._pageBeforeMemory ?? 'brush') + this._pageBeforeMemory = null + } } get visiblePage(): string { diff --git a/packages/gjs/src/widgets/editor/scene-editor.blp b/packages/gjs/src/widgets/editor/scene-editor.blp index 36fb2986..62731ec7 100644 --- a/packages/gjs/src/widgets/editor/scene-editor.blp +++ b/packages/gjs/src/widgets/editor/scene-editor.blp @@ -306,6 +306,17 @@ template $PixelRpgSceneEditor : Adw.Bin { styles ["flat"] } + // Playing: the way to the Game memory page. The run hides the + // bar and the inspector, so without it nothing reaches the + // page; `action-target` is set in TS like the badge's. + Gtk.Button memory_button { + visible: false; + icon-name: "preferences-other-symbolic"; + action-name: "win.sheet-page"; + tooltip-text: _("Game memory"); + styles ["flat"] + } + Gtk.Button restart_button { visible: false; icon-name: "view-refresh-symbolic"; @@ -678,6 +689,16 @@ template $PixelRpgSceneEditor : Adw.Bin { child: Adw.Bin selected_slot_sheet {}; } + + // Only while a test run is on (`memoryMode`): then it is the one page. + Adw.ViewStackPage { + name: "memory"; + title: _("Game memory"); + icon-name: "preferences-other-symbolic"; + visible: false; + + child: Adw.Bin memory_slot_sheet {}; + } }; } }; diff --git a/packages/gjs/src/widgets/editor/scene-editor.d.blp.ts b/packages/gjs/src/widgets/editor/scene-editor.d.blp.ts index b5fb115c..88bb3819 100644 --- a/packages/gjs/src/widgets/editor/scene-editor.d.blp.ts +++ b/packages/gjs/src/widgets/editor/scene-editor.d.blp.ts @@ -45,6 +45,7 @@ export declare const InternalChildren: [ "context_pill", "roster_slot", "stop_button", + "memory_button", "restart_button", "overflow_button", "inspector_toggle", @@ -76,6 +77,7 @@ export declare const InternalChildren: [ "brush_slot_sheet", "layers_slot_sheet", "selected_slot_sheet", + "memory_slot_sheet", ]; /** The `_`-prefixed members GJS installs for them. Merge it into the class interface. */ @@ -102,6 +104,7 @@ export interface Children { _context_pill: Gtk.Box; _roster_slot: Adw.Bin; _stop_button: Gtk.Button; + _memory_button: Gtk.Button; _restart_button: Gtk.Button; _overflow_button: Gtk.MenuButton; _inspector_toggle: Gtk.ToggleButton; @@ -133,4 +136,5 @@ export interface Children { _brush_slot_sheet: Adw.Bin; _layers_slot_sheet: Adw.Bin; _selected_slot_sheet: Adw.Bin; + _memory_slot_sheet: Adw.Bin; } diff --git a/packages/gjs/src/widgets/editor/scene-editor.ts b/packages/gjs/src/widgets/editor/scene-editor.ts index 501d3575..c4385f00 100644 --- a/packages/gjs/src/widgets/editor/scene-editor.ts +++ b/packages/gjs/src/widgets/editor/scene-editor.ts @@ -37,6 +37,7 @@ export type SceneEditorLayout = 'wide' | 'phone' /** `win.sheet-page`'s target for every affordance that means "the brush". */ const BRUSH_PAGE_TARGET = GLib.Variant.new_string('brush') +const MEMORY_PAGE_TARGET = GLib.Variant.new_string('memory') /** * Typed view of the signals {@link SceneEditor} registers, layered on @@ -95,6 +96,8 @@ export class SceneEditor extends Adw.Bin { declare _roster_slot: Adw.Bin declare _stop_button: Gtk.Button declare _restart_button: Gtk.Button + declare _memory_button: Gtk.Button + declare _memory_slot_sheet: Adw.Bin declare _overflow_button: Gtk.MenuButton declare _inspector_toggle: Gtk.ToggleButton @@ -217,6 +220,7 @@ export class SceneEditor extends Adw.Bin { 'roster_slot', 'stop_button', 'restart_button', + 'memory_button', 'overflow_button', 'inspector_toggle', 'pick_banner', @@ -244,6 +248,7 @@ export class SceneEditor extends Adw.Bin { 'brush_slot_sheet', 'layers_slot_sheet', 'selected_slot_sheet', + 'memory_slot_sheet', ], Properties: { stage: GObject.ParamSpec.string( @@ -310,6 +315,7 @@ export class SceneEditor extends Adw.Bin { // target is set here. `check-blp-actions.mjs` only validates the // action NAME, which the template still carries. this._badge_button.set_action_target_value(BRUSH_PAGE_TARGET) + this._memory_button.set_action_target_value(MEMORY_PAGE_TARGET) this._phoneBadgeButton.add_css_class('flat') this._phoneBadgeButton.add_css_class('badge-phone') @@ -373,7 +379,25 @@ export class SceneEditor extends Adw.Bin { /** The three bins the shell hands to `EditorPages.host` on phone. */ get pageSlots(): PageSlots { - return { brush: this._brush_slot_sheet, layers: this._layers_slot_sheet, selected: this._selected_slot_sheet } + return { + brush: this._brush_slot_sheet, + layers: this._layers_slot_sheet, + selected: this._selected_slot_sheet, + memory: this._memory_slot_sheet, + } + } + + /** + * Swap the sheet's three editing pages for Game memory during a test + * run, and back. The switcher goes too: one page needs no tabs. + */ + set memoryMode(on: boolean) { + for (const slot of [this._brush_slot_sheet, this._layers_slot_sheet, this._selected_slot_sheet]) { + this._sheet_stack.get_page(slot).set_visible(!on) + } + this._sheet_stack.get_page(this._memory_slot_sheet).set_visible(on) + this._sheet_switcher.set_visible(!on) + if (on) this._sheet_stack.set_visible_child_name('memory') } get sheetPage(): string { @@ -742,6 +766,7 @@ export class SceneEditor extends Adw.Bin { this._phone_redo.set_visible(f.phoneRedo) this._stop_button.set_visible(f.stopButton) this._restart_button.set_visible(f.restartButton) + this._memory_button.set_visible(f.memoryButton) this._overflow_button.set_visible(f.overflowButton) this._inspector_toggle.set_visible(f.inspectorToggle) // The chip is always visible in itself (solo it is the invite diff --git a/packages/gjs/src/widgets/engine/engine.ts b/packages/gjs/src/widgets/engine/engine.ts index d04c94dc..fba8d0e8 100644 --- a/packages/gjs/src/widgets/engine/engine.ts +++ b/packages/gjs/src/widgets/engine/engine.ts @@ -25,7 +25,7 @@ import { Color, EventEmitter, type Subscription, Vector } from 'excalibur' import { SignalScope } from '../../utils/signal-scope.ts' import { type CanvasBridge, createCanvasBridge, readFramebufferPng } from './canvas-bridge.ts' import { forwardEngineEvents } from './engine-events.ts' -import { installFrameProbe } from './frame-probe.ts' +import { defaultFrameProbePath, installFrameProbe } from './frame-probe.ts' import { attachLongPress } from './long-press.ts' import { attachMultiFingerTap } from './multi-finger-tap.ts' import { attachPinchZoom } from './pinch-zoom.ts' @@ -485,6 +485,49 @@ export class Engine extends Adw.Bin { this._excalibur?.setLocalPlayerId(playerId) } + /** Forward to `Engine.setFlag` — the Game memory panel's write. */ + public setFlag(flag: string, value: boolean | number | string, thing?: string): boolean { + return this._excalibur?.setFlag(flag, value, thing) ?? false + } + + private _frameProbeStop: (() => void) | null = null + private _frameProbePath: string | null = null + + /** The file the frame probe is writing to, or `null` while it is off. */ + public get frameProbePath(): string | null { + return this._frameProbeStop ? this._frameProbePath : null + } + + /** + * Turn the frame probe on or off at run time (the Game memory panel's + * "For experts" switch). `PIXELRPG_FRAME_PROBE` still starts it at + * launch and names the file; with no variable set the file is + * {@link defaultFrameProbePath}. Returns the file now written to. + */ + public setFrameProbe(on: boolean): string | null { + if (!on) { + this._stopFrameProbe() + return null + } + if (!this._frameProbeStop) this._startFrameProbe(GLib.getenv('PIXELRPG_FRAME_PROBE') ?? defaultFrameProbePath()) + return this.frameProbePath + } + + private _startFrameProbe(path: string | null): void { + if (!this._excalibur || !path || this._frameProbeStop) return + const stop = installFrameProbe(this._excalibur.excalibur, path) + if (!stop) return + this._frameProbePath = path + this._frameProbeStop = stop + this._excaliburSubscriptions.push({ close: () => this._stopFrameProbe() }) + } + + private _stopFrameProbe(): void { + const stop = this._frameProbeStop + this._frameProbeStop = null + stop?.() + } + /** Forward to `Engine.getRuntimeSnapshot`. */ public getRuntimeSnapshot(): ReturnType { return this._excalibur?.getRuntimeSnapshot() ?? null @@ -1028,8 +1071,7 @@ export class Engine extends Adw.Bin { await engine.initialize() // Frame measurement, off unless PIXELRPG_FRAME_PROBE names a file. // After `initialize()` so the clock is running and `stats` is populated. - const stopProbe = installFrameProbe(engine.excalibur) - if (stopProbe) this._excaliburSubscriptions.push({ close: stopProbe }) + this._startFrameProbe(GLib.getenv('PIXELRPG_FRAME_PROBE')) // Apply the scratchpad backdrop colour as the engine clear // colour. With GLArea alpha compositing being unreliable on // this stack, painting the backdrop INSIDE the canvas is the diff --git a/packages/gjs/src/widgets/engine/frame-probe.ts b/packages/gjs/src/widgets/engine/frame-probe.ts index 4f63f19a..8af2fd73 100644 --- a/packages/gjs/src/widgets/engine/frame-probe.ts +++ b/packages/gjs/src/widgets/engine/frame-probe.ts @@ -73,13 +73,24 @@ const FLUSH_EVERY = 120 /** ...or every N ms, so the tail of a short run is never stuck in memory when the process is killed. */ const FLUSH_AFTER_MS = 500 +/** Where the Game memory panel's "For experts" switch writes when no environment path names a file. */ +export function defaultFrameProbePath(): string { + return GLib.build_filenamev([GLib.get_user_cache_dir(), 'pixelrpg-maker', 'frame-probe.jsonl']) +} + /** - * Start sampling into the file named by `PIXELRPG_FRAME_PROBE`, if set. - * Returns a stop function, or `null` when the probe is off (the normal case). + * Start sampling into `path` — by default the file named by + * `PIXELRPG_FRAME_PROBE`, if set. Returns a stop function, or `null` + * when the probe is off (the normal case). + * + * The explicit `path` is the switch in the Game memory panel; the + * environment variable stays the way a headless driver turns the probe + * on before the first frame. */ -export function installFrameProbe(excalibur: ExcaliburEngine): (() => void) | null { - const path = GLib.getenv('PIXELRPG_FRAME_PROBE') +export function installFrameProbe(excalibur: ExcaliburEngine, explicitPath?: string): (() => void) | null { + const path = explicitPath ?? GLib.getenv('PIXELRPG_FRAME_PROBE') if (!path) return null + GLib.mkdir_with_parents(GLib.path_get_dirname(path), 0o755) const file = Gio.File.new_for_path(path) const stream = file.append_to(Gio.FileCreateFlags.NONE, null) diff --git a/packages/translations/de.po b/packages/translations/de.po index 45b8bafc..2855cfb4 100644 --- a/packages/translations/de.po +++ b/packages/translations/de.po @@ -423,6 +423,10 @@ msgstr "Fragen: %1$s (%2$s)" msgid "At hero height" msgstr "Auf Höhe der Heldenfigur" +#, javascript-format +msgid "At tile %s, %s" +msgstr "Auf Feld %s, %s" + msgid "Author" msgstr "Autor" @@ -498,6 +502,9 @@ msgstr "Abbrechen" msgid "Cancel answer" msgstr "Antwort beim Abbrechen" +msgid "Change a value to try the game with it." +msgstr "Ändere einen Wert, um das Spiel damit auszuprobieren." + msgid "Change by" msgstr "Ändern um" @@ -909,6 +916,9 @@ msgstr "Folgt" msgid "Following %s" msgstr "Folgt %s" +msgid "For experts" +msgstr "Für Profis" + msgid "Found brushes" msgstr "Gefundene Pinsel" @@ -936,6 +946,9 @@ msgstr "Vollansicht ein" msgid "Game" msgstr "Spiel" +msgid "Game memory" +msgstr "Spielgedächtnis" + msgid "Ghost the previous + next frames behind the current one" msgstr "Vorherigen und nächsten Frame als Schatten hinter dem aktuellen zeigen" @@ -1270,6 +1283,9 @@ msgstr "Markiert, wo die Spielfigur (oder eine NPC) eine Karte betritt." msgid "Marks your cursor and your name for everyone else" msgstr "Zeigt allen anderen deinen Mauszeiger und deinen Namen" +msgid "Measure frame times" +msgstr "Bildzeiten messen" + msgid "Medium" msgstr "Mittel" @@ -1514,6 +1530,9 @@ msgstr "Noch nirgendwohin" msgid "Number" msgstr "Zahl" +msgid "Object" +msgstr "Objekt" + msgid "Offset X" msgstr "Versatz X" @@ -2226,6 +2245,9 @@ msgstr "Diese Tür führt jetzt nach „%s“" msgid "This door points at a map the project does not have." msgstr "Diese Tür zeigt auf eine Karte, die das Projekt nicht hat." +msgid "This game has no flags yet. The ones it sets will show up here." +msgstr "Dieses Spiel hat noch keine Flaggen. Die, die es setzt, erscheinen hier." + msgid "This picture could not be read." msgstr "Dieses Bild konnte nicht gelesen werden." @@ -2469,6 +2491,9 @@ msgstr "Die Wörter bleiben in deinen Spieldateien, aber niemand sieht sie, bis msgid "World" msgstr "Welt" +msgid "Writes how long each frame took to a file." +msgstr "Schreibt in eine Datei, wie lange jedes Bild gedauert hat." + #, javascript-format msgid "Writing in %s. Click to switch language." msgstr "Sprache: %s. Klicke zum Wechseln." diff --git a/packages/translations/org.pixelrpg.maker.pot b/packages/translations/org.pixelrpg.maker.pot index d2e4a51f..f5db5cdd 100644 --- a/packages/translations/org.pixelrpg.maker.pot +++ b/packages/translations/org.pixelrpg.maker.pot @@ -424,6 +424,10 @@ msgstr "" msgid "At hero height" msgstr "" +#, javascript-format +msgid "At tile %s, %s" +msgstr "" + msgid "Author" msgstr "" @@ -499,6 +503,9 @@ msgstr "" msgid "Cancel answer" msgstr "" +msgid "Change a value to try the game with it." +msgstr "" + msgid "Change by" msgstr "" @@ -910,6 +917,9 @@ msgstr "" msgid "Following %s" msgstr "" +msgid "For experts" +msgstr "" + msgid "Found brushes" msgstr "" @@ -937,6 +947,9 @@ msgstr "" msgid "Game" msgstr "" +msgid "Game memory" +msgstr "" + msgid "Ghost the previous + next frames behind the current one" msgstr "" @@ -1271,6 +1284,9 @@ msgstr "" msgid "Marks your cursor and your name for everyone else" msgstr "" +msgid "Measure frame times" +msgstr "" + msgid "Medium" msgstr "" @@ -1515,6 +1531,9 @@ msgstr "" msgid "Number" msgstr "" +msgid "Object" +msgstr "" + msgid "Offset X" msgstr "" @@ -2227,6 +2246,9 @@ msgstr "" msgid "This door points at a map the project does not have." msgstr "" +msgid "This game has no flags yet. The ones it sets will show up here." +msgstr "" + msgid "This picture could not be read." msgstr "" @@ -2470,6 +2492,9 @@ msgstr "" msgid "World" msgstr "" +msgid "Writes how long each frame took to a file." +msgstr "" + #, javascript-format msgid "Writing in %s. Click to switch language." msgstr "" diff --git a/scripts/capture-views.py b/scripts/capture-views.py index 7f571261..d97aacbd 100755 --- a/scripts/capture-views.py +++ b/scripts/capture-views.py @@ -34,6 +34,7 @@ FLAG_SHOTS = ["26-flag-picker", "26b-flag-picker-open", "26c-flag-new"] COND_SHOTS = ["27-condition-editor", "27b-change-counter"] USAGE_SHOTS = ["28-game-flags", "28b-flag-usages-open", "28c-flag-usage-opened"] +MEMORY_SHOTS = ["29-game-memory", "29b-game-memory-edited", "29c-game-memory-chest"] NEWMAP_SHOTS = ["18-new-map-dialog", "18b-new-map-created", "18c-new-map-shelf"] ap = argparse.ArgumentParser() @@ -45,7 +46,7 @@ args = ap.parse_args() CO, OUT = args.checkout, args.outdir ONLY = set(args.only.split(",")) if args.only else None -ALL_SHOTS = TIER_SHOTS + TERRAIN_SHOTS + CREDIT_SHOTS + SHELF_SHOTS + LIVE_SHOTS + GFX_SHOTS + ADDGFX_SHOTS + NEWMAP_SHOTS + DEPTH_SHOTS + NEWGAME_SHOTS + LANG_SHOTS + FLAG_SHOTS + COND_SHOTS + USAGE_SHOTS +ALL_SHOTS = TIER_SHOTS + TERRAIN_SHOTS + CREDIT_SHOTS + SHELF_SHOTS + LIVE_SHOTS + GFX_SHOTS + ADDGFX_SHOTS + NEWMAP_SHOTS + DEPTH_SHOTS + NEWGAME_SHOTS + LANG_SHOTS + FLAG_SHOTS + COND_SHOTS + USAGE_SHOTS + MEMORY_SHOTS if ONLY and ONLY - set(ALL_SHOTS): ap.error("unknown shot id(s) %s; valid: %s" % (", ".join(sorted(ONLY - set(ALL_SHOTS))), ", ".join(ALL_SHOTS))) if args.lang: @@ -781,6 +782,104 @@ def capture_conditions(tier, w, h): p.wait() +def capture_memory(tier, w, h): + # The Game memory page during a test run. PROJECT must carry a "coins" + # counter, a yes-no game flag and a thing-scoped "opened" flag on two + # chests, plus a gate whose state switches on coins >= 3. The panel is + # driven with real clicks: MEMORY_PLUS="x,y" is the Coins spin row's + # plus button on the monitor (headless-run --size WxH), MEMORY_CLICKS + # how often to press it. + lib = os.environ["HEADLESS_RUN_LIB"] + inp = os.environ.get("HOLD_INPUT", os.path.join(lib, "headless-input.js")) + + def keys(*steps): + subprocess.run(["gjs", "-m", inp, *steps], timeout=60) + time.sleep(1) + + def runtime(): + return (status() or {}).get("runtime") or {} + + def say(what): + rt = runtime() + print(what, "flags", rt.get("flags"), "thingFlags", rt.get("thingFlags"), + "dialogue", (rt.get("dialogue") or {}).get("text"), rt.get("playerTile"), rt.get("facing")) + + def face_and_press(key): + # Keyboard focus sits in the panel after a click there: take it back. + fx, fy = os.environ.get("MEMORY_FOCUS", "40,40").split(",") + keys("click", fx, fy) + keys("hold", str(key), "400") + keys("hold", "0x20", "600") + time.sleep(0.5) + say("PRESS %#x" % key) + keys("hold", "0x20", "600") + keys("hold", "0x20", "600") + + p = subprocess.Popen([BIN], env=ENV, stdout=log, stderr=log) + try: + if not wait(lambda s: s.get("mapped"), 90): + sys.exit("app never came up") + call("ResizeWindow", str(w), str(h)) + time.sleep(1.5) + call("OpenProject", PROJECT) + wait(lambda s: len(s.get("sceneIds", [])) > 0, 60) + time.sleep(2) + act("mode", "world") + act("open-scene-by-id", "kokiri-forest") + wait(lambda s: s.get("engineReady") and s.get("activeLayer"), 60) + time.sleep(2) + act("dismiss-toasts") + act("play") + time.sleep(4) + act("sheet-page", "memory") + time.sleep(1.5) + say("START") + shot(tier, "29-game-memory") + gameplay = True + def focus(): + # Keyboard focus sits in the panel after a click there: take it back. + keys("click", *os.environ.get("MEMORY_FOCUS", "40,40").split(",")) + + def press(label): + keys("hold", "0x20", "600") + time.sleep(0.5) + say(label) + for _ in range(8): # advance until the dialogue closes + if not runtime().get("dialogueOpen"): + break + keys("hold", "0x20", "300") + time.sleep(0.6) + + if gameplay: + focus() + keys("hold", "0xff53", "700") # right: stop in front of the gate + press("GATE before") + plus = os.environ.get("MEMORY_PLUS") + if plus: + x, y = plus.split(",") + for _ in range(int(os.environ.get("MEMORY_CLICKS", "3"))): + keys("click", x, y) + time.sleep(1) + say("EDITED") + shot(tier, "29b-game-memory-edited") + if gameplay: + focus() + press("GATE after") + focus() + keys("hold", "0xff51", "700") # left: walk up to the blue chest + before = runtime().get("thingFlags") + press("CHEST was %s, now" % before) + shot(tier, "29c-game-memory-chest") + act("play") + finally: + p.terminate() + try: + p.wait(10) + except subprocess.TimeoutExpired: + p.kill() + p.wait() + + for tier, w, h in TIERS: if not ONLY or ONLY & set(TIER_SHOTS): capture_tier(tier, w, h) @@ -818,3 +917,9 @@ def capture_conditions(tier, w, h): if ONLY and ONLY & set(USAGE_SHOTS): for tier, w, h in [("phone-360", 360, 720), ("wide-1920", 1920, 1200)]: capture_flag_usages(tier, w, h) + +if ONLY and ONLY & set(MEMORY_SHOTS): + # Only the tier the monitor matches: the plus button's coordinates are per size. + tiers = [("phone-360", 360, 720), ("wide-1920", 1920, 1200)] + for tier, w, h in [t for t in tiers if t[0] == os.environ.get("MEMORY_TIER", t[0])]: + capture_memory(tier, w, h)