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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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*
Expand Down
7 changes: 6 additions & 1 deletion apps/maker-gjs/src/services/engine-event-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

/**
Expand All @@ -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())
}
60 changes: 60 additions & 0 deletions apps/maker-gjs/src/services/live-state.service.spec.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
}
70 changes: 70 additions & 0 deletions apps/maker-gjs/src/services/live-state.service.ts
Original file line number Diff line number Diff line change
@@ -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<Record<string, FlagValue>>
readonly thingFlags: Readonly<Record<string, Readonly<Record<string, FlagValue>>>>
readonly placementStates?: Readonly<Record<string, number>>
}

/**
* 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)
}
}
2 changes: 2 additions & 0 deletions apps/maker-gjs/src/test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -91,6 +92,7 @@ run({
actionRegistrySuite,
assistantPausePolicySuite,
assistantStateServiceSuite,
liveStateServiceSuite,
atlasCameraStoreSuite,
backOrderSuite,
brushKeysSuite,
Expand Down
33 changes: 32 additions & 1 deletion apps/maker-gjs/src/widgets/application-window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()
}
Expand All @@ -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())
Expand Down Expand Up @@ -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(),
})
Expand Down
Loading
Loading