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
2 changes: 1 addition & 1 deletion TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +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*
- **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. Also open: the "Only when …" authoring row (the condition is editable today only through the raw `states` JSON). *owner: engine + gjs*
- **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*
- **Per-player input sources (gamepad / remote / AI)** — movement + input shipped: `InputSystem` polls the keyboard into the session-singleton's `InputSourceComponent` (intent vector), `PlayerSystem` consumes it and emits `player-tile-changed` / `player-action-pressed`. Remaining: the source-descriptor variant on per-player entities (see `docs/concepts/collaboration-and-multiplayer.md` § 5) once split-screen / remote players arrive. *owner: engine*
Expand Down
9 changes: 9 additions & 0 deletions apps/maker-gjs/src/services/project-store.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1283,6 +1283,15 @@ export default async () => {
expect(store.removeFlag('has-key')).toStrictEqual({ removed: false, reason: 'unknown' })
})

await it('pruneUnusedPickerFlags removes a "New…" flag nothing names, keeps a used or hand-made one', async () => {
const { store, data } = makeStore(makeProjectData({ flags: [key] }))
const id = store.createFlag('Coins', 'number')
expect(data.flags?.map((f) => f.id)).toStrictEqual(['has-key', id])
expect(store.pruneUnusedPickerFlags()).toStrictEqual([id])
expect(data.flags).toStrictEqual([key])
expect(store.pruneUnusedPickerFlags()).toStrictEqual([])
})

await it('applies remote flag ops without re-broadcasting', async () => {
const { store, data } = makeStore()
const session = makeSession()
Expand Down
29 changes: 28 additions & 1 deletion apps/maker-gjs/src/services/project-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -345,16 +345,43 @@ export class ProjectStore {
/**
* The picker's "New…": make a yes/no flag called `name` and return its
* id (`null` for an empty name). No Undo toast: the action that asked
* for it uses the flag at once, and a used flag cannot be removed.
* for it uses the flag at once, and a used flag cannot be removed. The
* flag is remembered so {@link pruneUnusedPickerFlags} can take it back
* when an undo leaves nothing using it.
*/
createFlag(name: string, kind: FlagKind = 'yes-no'): string | null {
if (!name.trim()) return null
const made = this.upsertFlag(newFlag(this.flags(), name, kind))
if (!made) return null
if (!made.previous) this._pickerFlags.add(made.flag.id)
this.onFlagCreated?.(made.flag)
return made.flag.id
}

/** Flags the picker's "New…" made and that have not been removed since. */
private readonly _pickerFlags = new Set<string>()

/**
* Undoing the step that first used a flag made by "New…" must not leave
* the flag behind in the project list: remove every such flag nothing
* names any more. Used flags stay (`removeFlag` refuses them). Returns
* the removed ids.
*/
pruneUnusedPickerFlags(): string[] {
const removed: string[] = []
for (const id of [...this._pickerFlags]) {
if (!this.flags().some((f) => f.id === id)) {
this._pickerFlags.delete(id)
continue
}
if (this.removeFlag(id).removed) {
this._pickerFlags.delete(id)
removed.push(id)
}
}
return removed
}

/**
* Replace-or-append an entity in `entityLibrary`: persist + broadcast
* a `__project/entity.upsert` + notify. The single write path for
Expand Down
2 changes: 2 additions & 0 deletions apps/maker-gjs/src/widgets/application-window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,8 @@ export class ApplicationWindow extends Adw.ApplicationWindow implements EntityDe
setHistoryEnabled: (canUndo, canRedo) => {
this._actions?.undo.set_enabled(canUndo)
this._actions?.redo.set_enabled(canRedo)
// An undo may have taken back the only use of a flag "New…" just made.
if (canRedo) this._projectStore.pruneUnusedPickerFlags()
},
adoptPickedTile: (globalTileId, terrainId) => {
// A cell a brush drew hands back the brush, not the edge piece
Expand Down
6 changes: 3 additions & 3 deletions docs/concepts/entity-and-appearance-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,14 +128,14 @@ RPG Maker's most-loved feature is event *pages*: same object, different appearan
```ts
interface EntityState {
id: string // 'open', 'night', 'quest-done'
when?: StateCondition // { flag, equals? } — first matching state wins; no `when` = manual/scripted switch
when?: Condition // { flag, equals? } shorthand or a typed condition — first matching state wins; no `when` = manual/scripted switch
components: ComponentData[] // overlays base components, wholesale-replace PER TYPE (same override discipline as placements)
}
```

A door (closed/open), a day/night NPC, a quest-stage marker. State evaluation is `StateSystem` (`packages/engine/src/systems/state.system.ts`) reading the flag store `FlagSystem` folds `FLAG_SET` into (`GameSaveStateComponent` on the session singleton).

The condition vocabulary is **exactly one shape**, `{ flag: string; equals?: boolean | number | string }` with `equals` defaulting to `true` — the same one-flat-equality discipline the conditional-row design uses. An expression DSL nobody validates is refused. Any other `when` is a validation warning and never matches, so a project from a newer editor still opens.
The condition vocabulary is a small typed union (`flag-is`, `counter`, `has-item`, one level of `all` / `any` / `not`), with `{ flag, equals? }` kept as shorthand for `flag-is` — see [`game-systems.md`](game-systems.md). An expression DSL nobody validates is still refused. Any other `when` is a validation warning and never matches, so a project from a newer editor still opens.

**Actions only, so far.** `StateSystem` swaps the entity's `actions` list, which is what makes the key-and-door loop work end to end; a state carrying any other component type validates with a warning and is inert at runtime. The visible cost is real: a door teleports once the flag is set but never *looks* open, and a chest still looks closed after it gave you its item. Applying a `visual` / `collision` overlay means rebuilding a live entity mid-frame while keeping its runtime companions alive — its own piece of work, see [`game-systems.md`](game-systems.md) and TODO.md.

Expand Down Expand Up @@ -215,7 +215,7 @@ Unchanged in principle, restated for the new shapes: entity definitions, appeara

## Open questions

1. ~~**Condition vocabulary for states**~~ — **decided**: exactly one shape, `{ flag, equals? }`, `equals` defaulting to `true`. Not an expression DSL — a second language nobody validates. Richer conditions (a time-of-day condition beside the flag one) arrive with the system that has a clock to read.
1. ~~**Condition vocabulary for states**~~ — **decided**: a small typed union (flag-is, counter, has-item, all/any/not on one level) with `{ flag, equals? }` as shorthand. Not an expression DSL — a second language nobody validates. A time-of-day condition arrives with the system that has a clock to read.
2. **Multiple appearances per entity** (paperdoll/equipment) — `Visual` stays single; the union leaves room for a `layers` variant later.
3. **Script sandboxing** — TS in-process vs sandboxed; decide at Phase E (object-system.md carries the same question).
4. **Definition variants** (`extends`, Unity-prefab-variant style: "guard" extends "villager") — deliberately **not** in v1; single-level prototype→instance (definition→placement) must prove insufficient first.
Expand Down
2 changes: 1 addition & 1 deletion docs/concepts/game-systems.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ The base layer's payload this round is the thing that makes the simple view able
- **`EntityStatesComponent`** is attached by the spawn pipeline when a definition declares `states`, carrying the authored states plus the entity's base actions.
- **`StateSystem`** resolves the first matching state each tick and swaps the entity's action list, so `EventActionSystem` runs the new body unchanged. Per-tick and idempotent rather than event-driven: it covers entities spawned after a flag was set, needs no ordering agreement with `FlagSystem`, and cannot miss an event. Gated on `RuntimeModeComponent` — the editor always shows the base composition.

**One condition shape**, `{ flag, equals? }` with `equals` defaulting to `true` (`StateCondition`, `types/data/EntityDefinition.ts`). An expression DSL nobody validates is refused. Any other `when` is a validation *warning* and never matches, so a project from a newer editor opens with reduced behaviour instead of an error.
**A small typed condition union** (`types/data/Condition.ts`), read by one pure `evaluateCondition(condition, flags)` that `StateSystem` and the editor both use: `flag-is` (yes-no or text flag equals a value), `counter` (number flag compared with `=`, `≠`, `<`, `≤`, `>`, `≥`), `has-item` (stored and editable, always false until items exist; the editor warns), and the groups `all`, `any`, `not`, which hold leaves only — one level of nesting, no tree. The old `{ flag, equals? }` stays valid and is read as `flag-is`; nothing rewrites author data. A missing flag, a kind mismatch or any other shape evaluates false and never throws, so a project from a newer editor opens with reduced behaviour instead of an error. The `change-counter` action adds an amount (negative subtracts) to a number flag through `COUNTER_CHANGED` → `FlagSystem`, which re-emits `FLAG_SET` with the total. The first matching state still wins.

**Actions only, this round.** A state overlaying any other component type validates with a warning and stays inert. The cost is visible in the first hour and is named rather than hidden: a door teleports once you have the key but never *looks* open, and a chest still looks closed after it gave you its item. Applying a `visual` or `collision` overlay means rebuilding a live entity's sprite and collider mid-frame while keeping its runtime companions (`TriggerFiredComponent`) alive — the first piece of engine work in this design that rebuilds a spawned entity, and it deserves its own round.

Expand Down
4 changes: 4 additions & 0 deletions packages/engine/src/entity/specs/actions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ export default async () => {
expect(isActionData({ id: '2', type: 'teleport', targetMapId: 'm', targetTileX: 1, targetTileY: 2 })).toBe(true)
expect(isActionData({ id: '3', type: 'give-item', itemId: 'potion' })).toBe(true)
expect(isActionData({ id: '4', type: 'set-flag', flag: 'f', value: true })).toBe(true)
expect(isActionData({ id: '7', type: 'change-counter', flag: 'coins', amount: 1 })).toBe(true)
expect(isActionData({ id: '8', type: 'change-counter', flag: 'coins', amount: -2 })).toBe(true)
expect(isActionData({ id: '5', type: 'play-sfx', sound: 's' })).toBe(true)
expect(isActionData({ id: '6', type: 'wait', ms: 100 })).toBe(true)
})
Expand All @@ -21,6 +23,8 @@ export default async () => {
expect(isActionData({ id: '2', type: 'teleport', targetMapId: 'm' })).toBe(false) // missing coords
expect(isActionData({ type: 'show-text', text: 'x' })).toBe(false) // missing id
expect(isActionData({ id: '3', type: 'nope' })).toBe(false) // unknown type
expect(isActionData({ id: '9', type: 'change-counter', flag: 'coins' })).toBe(false) // missing amount
expect(isActionData({ id: '9', type: 'change-counter', flag: 'coins', amount: Number.NaN })).toBe(false)
expect(isActionData(null)).toBe(false)
})
})
Expand Down
6 changes: 3 additions & 3 deletions packages/engine/src/entity/validate.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { ComponentData, EntityDefinition, EntityState } from '../types/data/index.ts'
import { isStateCondition } from '../types/data/EntityDefinition.ts'
import { isCondition } from '../types/data/Condition.ts'
import { isLocalizedText } from '../types/data/LocalizedText.ts'
import type { ComponentSpec, ComponentSpecRegistry, FieldDescriptor } from './component-spec.ts'
import { BUILT_IN_COMPONENT_SPECS } from './registry.ts'
Expand Down Expand Up @@ -204,10 +204,10 @@ export function validateEntityDefinitionDetailed(
* newer editor unopenable.
*/
function validateStateCondition(def: EntityDefinition, state: EntityState, result: EntityValidationResult): void {
if (state.when === undefined || isStateCondition(state.when)) return
if (state.when === undefined || isCondition(state.when)) return
result.warnings.push(
`Entity "${def.id}" state "${state.id}" has a condition this editor does not understand — ` +
'only "when a flag is set" works here, so the state will never activate',
'it can compare flags and counters, group them with all / any / not (one level), so the state will never activate',
)
}

Expand Down
Loading
Loading