diff --git a/TODO.md b/TODO.md index e25875b1..73da407b 100644 --- a/TODO.md +++ b/TODO.md @@ -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* diff --git a/apps/maker-gjs/src/services/project-store.spec.ts b/apps/maker-gjs/src/services/project-store.spec.ts index 8fb0abff..8d37f228 100644 --- a/apps/maker-gjs/src/services/project-store.spec.ts +++ b/apps/maker-gjs/src/services/project-store.spec.ts @@ -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() diff --git a/apps/maker-gjs/src/services/project-store.ts b/apps/maker-gjs/src/services/project-store.ts index 6366acdc..862014f5 100644 --- a/apps/maker-gjs/src/services/project-store.ts +++ b/apps/maker-gjs/src/services/project-store.ts @@ -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() + + /** + * 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 diff --git a/apps/maker-gjs/src/widgets/application-window.ts b/apps/maker-gjs/src/widgets/application-window.ts index 315c0d90..3a0393d2 100644 --- a/apps/maker-gjs/src/widgets/application-window.ts +++ b/apps/maker-gjs/src/widgets/application-window.ts @@ -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 diff --git a/docs/concepts/entity-and-appearance-model.md b/docs/concepts/entity-and-appearance-model.md index 8c7db409..e17eb7a4 100644 --- a/docs/concepts/entity-and-appearance-model.md +++ b/docs/concepts/entity-and-appearance-model.md @@ -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. @@ -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. diff --git a/docs/concepts/game-systems.md b/docs/concepts/game-systems.md index e8278260..1d914b4b 100644 --- a/docs/concepts/game-systems.md +++ b/docs/concepts/game-systems.md @@ -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. diff --git a/packages/engine/src/entity/specs/actions.spec.ts b/packages/engine/src/entity/specs/actions.spec.ts index 11b0f3f0..0f2b9abc 100644 --- a/packages/engine/src/entity/specs/actions.spec.ts +++ b/packages/engine/src/entity/specs/actions.spec.ts @@ -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) }) @@ -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) }) }) diff --git a/packages/engine/src/entity/validate.ts b/packages/engine/src/entity/validate.ts index 3eff6554..2640431f 100644 --- a/packages/engine/src/entity/validate.ts +++ b/packages/engine/src/entity/validate.ts @@ -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' @@ -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', ) } diff --git a/packages/engine/src/format/migrate-flags.ts b/packages/engine/src/format/migrate-flags.ts index 9bf74aa6..a5dbce15 100644 --- a/packages/engine/src/format/migrate-flags.ts +++ b/packages/engine/src/format/migrate-flags.ts @@ -27,6 +27,7 @@ function visitActions(actions: unknown, visit: (ref: FlagRef) => void): void { for (const raw of actions as ActionData[]) { if (raw == null || typeof raw !== 'object') continue if (raw.type === 'set-flag') visit({ role: 'set', holder: raw, value: raw.value }) + else if (raw.type === 'change-counter') visit({ role: 'set', holder: raw, value: raw.amount }) else if (raw.type === 'ask' && Array.isArray(raw.options)) { for (const option of raw.options) visitActions(option?.actions, visit) } @@ -43,15 +44,29 @@ export function visitComponentFlagRefs( } } +/** Every flag a condition reads: the shorthand, each typed leaf, and the leaves inside all / any / not. */ +function visitConditionFlagRefs(when: unknown, visit: (ref: FlagRef) => void): void { + if (when == null || typeof when !== 'object') return + const c = when as { type?: unknown; of?: unknown; flag?: unknown; equals?: FlagValue; value?: unknown } + if (c.type === 'all' || c.type === 'any') { + if (Array.isArray(c.of)) for (const leaf of c.of) visitConditionFlagRefs(leaf, visit) + return + } + if (c.type === 'not') { + visitConditionFlagRefs(c.of, visit) + return + } + if (typeof c.flag !== 'string') return + const value = c.type === 'counter' ? (c.value as FlagValue) : c.equals + visit({ role: 'when', holder: when as { flag: string }, value }) +} + /** Every flag reference in one definition: its own actions and each state's condition + overlay. */ export function visitDefinitionFlagRefs(def: EntityDefinition | undefined, visit: (ref: FlagRef) => void): void { if (!def) return visitComponentFlagRefs(def.components, visit) for (const state of def.states ?? []) { - const when = state.when as { flag?: unknown; equals?: FlagValue } | undefined - if (when && typeof when === 'object' && typeof when.flag === 'string') { - visit({ role: 'when', holder: when as { flag: string }, value: when.equals }) - } + visitConditionFlagRefs(state.when, visit) visitComponentFlagRefs(state.components, visit) } } diff --git a/packages/engine/src/systems/event-action.system.spec.ts b/packages/engine/src/systems/event-action.system.spec.ts index 4b7a7a3a..362667bc 100644 --- a/packages/engine/src/systems/event-action.system.spec.ts +++ b/packages/engine/src/systems/event-action.system.spec.ts @@ -43,6 +43,18 @@ export default async () => { expect(seen).toStrictEqual(['text:hi', 'item:potionx2', 'flag:opened=true', 'sfx:chime', 'tp:dungeon']) }) + await it('maps change-counter onto COUNTER_CHANGED with its signed amount', async () => { + const { events, entity, seen } = setup([ + { id: '1', type: 'change-counter', flag: 'coins', amount: 2 }, + { id: '2', type: 'change-counter', flag: 'coins', amount: -1 }, + ]) + const changes: string[] = [] + events.on(EngineEvent.COUNTER_CHANGED, (p) => changes.push(`${p.flag}${p.amount > 0 ? '+' : ''}${p.amount}`)) + events.emit(EngineEvent.TRIGGER_FIRED, { entityId: entity.id, by: 'action-button' }) + expect(changes).toStrictEqual(['coins+2', 'coins-1']) + expect(seen.length).toBe(0) + }) + await it('defaults give-item qty to 1', async () => { const { events, entity, seen } = setup([{ id: '1', type: 'give-item', itemId: 'key' }]) events.emit(EngineEvent.TRIGGER_FIRED, { entityId: entity.id, by: 'action-button' }) diff --git a/packages/engine/src/systems/event-action.system.ts b/packages/engine/src/systems/event-action.system.ts index be600d93..a78284d4 100644 --- a/packages/engine/src/systems/event-action.system.ts +++ b/packages/engine/src/systems/event-action.system.ts @@ -285,6 +285,9 @@ export class EventActionSystem extends System { case 'set-flag': this.events.emit(EngineEvent.FLAG_SET, { flag: action.flag, value: action.value }) return DONE + case 'change-counter': + this.events.emit(EngineEvent.COUNTER_CHANGED, { flag: action.flag, amount: action.amount }) + return DONE case 'play-sfx': this.events.emit(EngineEvent.PLAY_SFX_REQUESTED, { sound: action.sound }) return DONE diff --git a/packages/engine/src/systems/flag.system.ts b/packages/engine/src/systems/flag.system.ts index 0191c12b..d1150330 100644 --- a/packages/engine/src/systems/flag.system.ts +++ b/packages/engine/src/systems/flag.system.ts @@ -49,6 +49,18 @@ export class FlagSystem extends System { SessionState.notifyMutation(scene, store) }), ) + + this.subscriptions.add( + this.events.on(EngineEvent.COUNTER_CHANGED, ({ flag, amount }) => { + const store = SessionState.get(scene, GameSaveStateComponent) + if (!store) return + const current = store.flags[flag] + const next = (typeof current === 'number' ? current : 0) + amount + // Re-announce the total as a plain flag write: the store, the toast + // and the playtest read-back all already follow FLAG_SET. + this.events.emit(EngineEvent.FLAG_SET, { flag, value: next }) + }), + ) } public dispose(): void { diff --git a/packages/engine/src/systems/state.system.spec.ts b/packages/engine/src/systems/state.system.spec.ts index b064a304..624032f3 100644 --- a/packages/engine/src/systems/state.system.spec.ts +++ b/packages/engine/src/systems/state.system.spec.ts @@ -106,6 +106,27 @@ export default async () => { expect(seen).toStrictEqual(['text:Locked', 'tp:inside']) }) + await it('adds to a counter flag and flips a comparing state at the threshold', async () => { + const { events, interact, tick, seen, scene } = rig([ + { + id: 'open', + when: { type: 'counter', flag: 'coins', op: '≥', value: 3 }, + components: [{ type: 'actions', actions: [OPEN] }], + }, + ]) + for (let i = 0; i < 2; i++) events.emit(EngineEvent.COUNTER_CHANGED, { flag: 'coins', amount: 1 }) + tick() + interact() + events.emit(EngineEvent.COUNTER_CHANGED, { flag: 'coins', amount: 1 }) + tick() + interact() + events.emit(EngineEvent.COUNTER_CHANGED, { flag: 'coins', amount: -2 }) + tick() + interact() + expect(SessionState.get(scene, GameSaveStateComponent)?.flags.coins).toBe(1) + expect(seen).toStrictEqual(['text:Locked', 'tp:inside', 'text:Locked']) + }) + await it('takes the first matching state', async () => { const { events, interact, tick, seen } = rig([ { id: 'first', when: { flag: 'f' }, components: [{ type: 'actions', actions: [OPEN] }] }, diff --git a/packages/engine/src/systems/state.system.ts b/packages/engine/src/systems/state.system.ts index 487e1aa4..602ea16d 100644 --- a/packages/engine/src/systems/state.system.ts +++ b/packages/engine/src/systems/state.system.ts @@ -4,7 +4,8 @@ import { EventActionsComponent } from '../components/event-actions.component.ts' import { GameSaveStateComponent } from '../components/game-save-state.component.ts' import { RuntimeModeComponent } from '../components/runtime-mode.component.ts' import type { ActionData } from '../types/data/ActionData.ts' -import { type FlagValue, stateConditionHolds } from '../types/data/EntityDefinition.ts' +import { evaluateCondition } from '../types/data/Condition.ts' +import type { FlagValue } from '../types/data/EntityDefinition.ts' import { SessionState } from '../utils/session-state.ts' type StatesQuery = Query @@ -61,7 +62,7 @@ export class StateSystem extends System { const states = entity.get(EntityStatesComponent) if (!states) return - const match = states.states.find((state) => stateConditionHolds(state.when, flags)) ?? null + const match = states.states.find((state) => evaluateCondition(state.when, { flags })) ?? null const nextId = match?.id ?? null if (states.resolvedOnce && states.activeStateId === nextId) return diff --git a/packages/engine/src/test.mts b/packages/engine/src/test.mts index 9c7bc7c9..108c5bfa 100644 --- a/packages/engine/src/test.mts +++ b/packages/engine/src/test.mts @@ -27,6 +27,7 @@ import footprintSuite from './commands/footprint.spec.js' import registrySuite from './commands/registry.spec.js' import tilemapPlaneSuite from './components/tilemap-plane.spec.js' import actionsSpecSuite from './entity/specs/actions.spec.js' +import conditionSuite from './types/data/condition.spec.js' import entityConvertSuite from './entity/convert.spec.js' import entityDataAccessSuite from './entity/data-access.spec.js' import entityDisclosureSuite from './entity/disclosure.spec.js' @@ -152,6 +153,7 @@ run({ entityRegistrySuite, gameSystemsRegistrySuite, actionsSpecSuite, + conditionSuite, entityValidateSuite, entityConvertSuite, entityDataAccessSuite, diff --git a/packages/engine/src/types/data/ActionData.ts b/packages/engine/src/types/data/ActionData.ts index f2271e00..652e6966 100644 --- a/packages/engine/src/types/data/ActionData.ts +++ b/packages/engine/src/types/data/ActionData.ts @@ -17,6 +17,7 @@ export type ActionData = | { id: string; type: 'teleport'; targetMapId: string; targetTileX: number; targetTileY: number; facing?: string } | { id: string; type: 'give-item'; itemId: string; qty?: number } | { id: string; type: 'set-flag'; flag: string; value: boolean | number | string } + | { id: string; type: 'change-counter'; flag: string; amount: number } | { id: string; type: 'play-sfx'; sound: string } | { id: string; type: 'wait'; ms: number } | { @@ -45,6 +46,7 @@ export const ACTION_TYPES: readonly ActionData['type'][] = [ 'teleport', 'give-item', 'set-flag', + 'change-counter', 'play-sfx', 'wait', 'ask', @@ -67,6 +69,8 @@ export function isActionData(value: unknown): value is ActionData { typeof a.flag === 'string' && (typeof a.value === 'boolean' || typeof a.value === 'number' || typeof a.value === 'string') ) + case 'change-counter': + return typeof a.flag === 'string' && typeof a.amount === 'number' && Number.isFinite(a.amount) case 'play-sfx': return typeof a.sound === 'string' case 'wait': diff --git a/packages/engine/src/types/data/Condition.ts b/packages/engine/src/types/data/Condition.ts new file mode 100644 index 00000000..edffb2c6 --- /dev/null +++ b/packages/engine/src/types/data/Condition.ts @@ -0,0 +1,187 @@ +import { type FlagValue, isFlagValue } from './EntityDefinition.ts' + +/** + * What a state asks of the game before it switches on: a typed union, + * not an expression language. Leaves compare one thing; `all` / `any` / + * `not` combine leaves, one level deep (a group holds leaves, never + * another group), which keeps the editor a list of rows and the data + * easy to validate. + */ + +/** The six ways a counter can be compared. */ +export const COUNTER_OPERATORS = ['=', '≠', '<', '≤', '>', '≥'] as const +export type CounterOperator = (typeof COUNTER_OPERATORS)[number] + +/** + * The first condition shape ever stored: one flag against one value, + * `equals` defaulting to `true`. Projects hold it as is; it reads as a + * `flag-is` leaf, so nothing about the author's data is rewritten. + */ +export interface StateCondition { + /** Flag id in `GameSaveStateComponent.flags`. */ + flag: string + /** Value the flag must hold. Absent = `true`. */ + equals?: FlagValue +} + +/** A yes/no or text flag holds exactly this value (`equals` absent = `true`). */ +export interface FlagIsCondition { + type: 'flag-is' + flag: string + equals?: FlagValue +} + +/** A number flag compares to a number. */ +export interface CounterCondition { + type: 'counter' + flag: string + op: CounterOperator + value: number +} + +/** + * The hero carries an item. Stored and editable, but items have no runtime + * yet, so it never holds. + */ +export interface HasItemCondition { + type: 'has-item' + itemId: string +} + +/** One comparison: a typed leaf, or the original flag shorthand. */ +export type ConditionLeaf = FlagIsCondition | CounterCondition | HasItemCondition | StateCondition + +/** Several leaves combined. `not` negates exactly one. */ +export type ConditionGroup = + | { type: 'all'; of: ConditionLeaf[] } + | { type: 'any'; of: ConditionLeaf[] } + | { type: 'not'; of: ConditionLeaf } + +export type Condition = ConditionLeaf | ConditionGroup + +/** What a condition reads. Items join here once the game has them. */ +export interface ConditionState { + flags: Readonly> +} + +function hasOnlyKeys(v: Record, keys: readonly string[]): boolean { + return Object.keys(v).every((k) => keys.includes(k)) +} + +function isRecord(value: unknown): value is Record { + return value != null && typeof value === 'object' && !Array.isArray(value) +} + +function isFlagId(value: unknown): value is string { + return typeof value === 'string' && value.length > 0 +} + +/** The original `{ flag, equals }` shorthand. */ +export function isStateCondition(value: unknown): value is StateCondition { + if (!isRecord(value)) return false + if (!isFlagId(value.flag)) return false + if (value.equals !== undefined && !isFlagValue(value.equals)) return false + // An unknown sibling key means a richer vocabulary this build does not + // know; matching on half a condition would be worse than not matching. + return hasOnlyKeys(value, ['flag', 'equals']) +} + +export function isConditionLeaf(value: unknown): value is ConditionLeaf { + if (!isRecord(value)) return false + switch (value.type) { + case undefined: + return isStateCondition(value) + case 'flag-is': + return ( + isFlagId(value.flag) && + (value.equals === undefined || isFlagValue(value.equals)) && + hasOnlyKeys(value, ['type', 'flag', 'equals']) + ) + case 'counter': + return ( + isFlagId(value.flag) && + typeof value.op === 'string' && + (COUNTER_OPERATORS as readonly string[]).includes(value.op) && + typeof value.value === 'number' && + Number.isFinite(value.value) && + hasOnlyKeys(value, ['type', 'flag', 'op', 'value']) + ) + case 'has-item': + return isFlagId(value.itemId) && hasOnlyKeys(value, ['type', 'itemId']) + default: + return false + } +} + +/** Type guard for every supported condition shape; anything else is "not understood". */ +export function isCondition(value: unknown): value is Condition { + if (!isRecord(value)) return false + if (value.type === 'all' || value.type === 'any') { + return Array.isArray(value.of) && value.of.every(isConditionLeaf) && hasOnlyKeys(value, ['type', 'of']) + } + if (value.type === 'not') return isConditionLeaf(value.of) && hasOnlyKeys(value, ['type', 'of']) + return isConditionLeaf(value) +} + +function compare(actual: number, op: CounterOperator, expected: number): boolean { + switch (op) { + case '=': + return actual === expected + case '≠': + return actual !== expected + case '<': + return actual < expected + case '≤': + return actual <= expected + case '>': + return actual > expected + case '≥': + return actual >= expected + } +} + +function leafHolds(leaf: ConditionLeaf, state: ConditionState): boolean { + const l = leaf as unknown as Record + switch (l.type) { + case 'has-item': + return false + case 'counter': { + const actual = state.flags[(leaf as CounterCondition).flag] + if (typeof actual !== 'number') return false + return compare(actual, (leaf as CounterCondition).op, (leaf as CounterCondition).value) + } + default: { + const { flag, equals } = leaf as StateCondition + return state.flags[flag] === (equals ?? true) + } + } +} + +/** + * Does `condition` hold? Pure and total: a flag nobody has set, a number + * compared with a word, and a shape this build does not know all answer + * `false`. An unknown shape is `false` even under `not`, so a state written + * by a newer editor stays off rather than flipping on. + */ +export function evaluateCondition(condition: unknown, state: ConditionState): boolean { + if (!isCondition(condition)) return false + const c = condition as Record + switch (c.type) { + case 'all': + return (c.of as ConditionLeaf[]).every((leaf) => leafHolds(leaf, state)) + case 'any': + return (c.of as ConditionLeaf[]).some((leaf) => leafHolds(leaf, state)) + case 'not': + return !leafHolds(c.of as ConditionLeaf, state) + default: + return leafHolds(condition as ConditionLeaf, state) + } +} + +/** Every flag id a condition reads, in order, with the leaf that names it. */ +export function conditionLeaves(condition: Condition): ConditionLeaf[] { + const c = condition as unknown as Record + if (c.type === 'all' || c.type === 'any') return [...(c.of as ConditionLeaf[])] + if (c.type === 'not') return [c.of as ConditionLeaf] + return [condition as ConditionLeaf] +} diff --git a/packages/engine/src/types/data/EntityDefinition.ts b/packages/engine/src/types/data/EntityDefinition.ts index d8224dff..13cedf00 100644 --- a/packages/engine/src/types/data/EntityDefinition.ts +++ b/packages/engine/src/types/data/EntityDefinition.ts @@ -23,27 +23,11 @@ */ export type ComponentData = { type: string } & Record +import type { Condition } from './Condition.ts' + /** A value a game flag can hold. Deliberately JSON-primitive only. */ export type FlagValue = boolean | number | string -/** - * The activation condition of an {@link EntityState}: **exactly one flat - * equality** against the flag store, `equals` defaulting to `true`. - * - * One shape, on purpose. The alternative — an expression DSL — is a - * second language nobody validates, which the concept refuses; the same - * one-flat-equality discipline governs conditional inspector rows. A - * `when` of any other shape is reported as a validation warning and never - * matches, so a project written by a newer editor still opens and still - * behaves predictably here. - */ -export interface StateCondition { - /** Flag key in `GameSaveStateComponent.flags`. */ - flag: string - /** Value the flag must hold. Absent = `true`. */ - equals?: FlagValue -} - /** * A conditional overlay of components — the no-code behaviour tier * (RPG-Maker event pages, modernised). When `when` matches, the state's @@ -64,7 +48,7 @@ export interface EntityState { * Activation condition. First matching state wins; absent = a * manually/scripted-switched state, never auto-activated. */ - when?: StateCondition + when?: Condition /** Components overlaid on the base when this state is active. */ components: ComponentData[] } @@ -75,32 +59,6 @@ export function isFlagValue(value: unknown): value is FlagValue { return t === 'boolean' || t === 'string' || (t === 'number' && Number.isFinite(value)) } -/** - * Type guard for the ONE supported {@link StateCondition} shape. Used by - * both the validator (which warns on anything else) and `StateSystem` - * (which never matches anything else), so "reported" and "inert" can't - * drift apart. - */ -export function isStateCondition(value: unknown): value is StateCondition { - if (value == null || typeof value !== 'object' || Array.isArray(value)) return false - const v = value as Record - if (typeof v.flag !== 'string' || v.flag.length === 0) return false - if (v.equals !== undefined && !isFlagValue(v.equals)) return false - // Exactly one shape: an unknown sibling key means a richer vocabulary - // this build does not implement, and silently ignoring it would make - // the state match on half a condition. - return Object.keys(v).every((k) => k === 'flag' || k === 'equals') -} - -/** - * Does `condition` hold against a flag bag? `equals` defaults to `true`, - * and an unsupported condition shape never matches. - */ -export function stateConditionHolds(condition: unknown, flags: Readonly>): boolean { - if (!isStateCondition(condition)) return false - return flags[condition.flag] === (condition.equals ?? true) -} - /** * A reusable, named, project-level definition: a list of components * (+ optional conditional states). Lives in diff --git a/packages/engine/src/types/data/condition.spec.ts b/packages/engine/src/types/data/condition.spec.ts new file mode 100644 index 00000000..07806f77 --- /dev/null +++ b/packages/engine/src/types/data/condition.spec.ts @@ -0,0 +1,112 @@ +import { describe, expect, it } from '@gjsify/unit' +import { COUNTER_OPERATORS, type CounterOperator, evaluateCondition, isCondition } from './Condition.ts' + +const flags = { key: true, coins: 3, name: 'Ada', off: false } +const state = { flags } + +const COMPARE: { op: CounterOperator; value: number; actual: number; holds: boolean }[] = [] +for (const [op, rows] of Object.entries({ + '=': [ + [3, 3, true], + [2, 3, false], + ], + '≠': [ + [2, 3, true], + [3, 3, false], + ], + '<': [ + [2, 3, true], + [3, 3, false], + ], + '≤': [ + [3, 3, true], + [4, 3, false], + ], + '>': [ + [4, 3, true], + [3, 3, false], + ], + '≥': [ + [3, 3, true], + [2, 3, false], + ], +}) as [CounterOperator, [number, number, boolean][]][]) { + for (const [actual, value, holds] of rows) COMPARE.push({ op, actual, value, holds }) +} + +export default async () => { + await describe('evaluateCondition', async () => { + await it('knows every operator', async () => { + expect(new Set(COMPARE.map((c) => c.op)).size).toBe(COUNTER_OPERATORS.length) + }) + + for (const row of COMPARE) { + await it(`counter ${row.actual} ${row.op} ${row.value} is ${row.holds}`, async () => { + const cond = { type: 'counter', flag: 'n', op: row.op, value: row.value } + expect(evaluateCondition(cond, { flags: { n: row.actual } })).toBe(row.holds) + }) + } + + await it('reads the shorthand as flag-is, equals defaulting to true', async () => { + expect(evaluateCondition({ flag: 'key' }, state)).toBe(true) + expect(evaluateCondition({ flag: 'off' }, state)).toBe(false) + expect(evaluateCondition({ flag: 'name', equals: 'Ada' }, state)).toBe(true) + expect(evaluateCondition({ flag: 'coins', equals: 3 }, state)).toBe(true) + }) + + await it('flag-is behaves like the shorthand', async () => { + expect(evaluateCondition({ type: 'flag-is', flag: 'key' }, state)).toBe(true) + expect(evaluateCondition({ type: 'flag-is', flag: 'key', equals: false }, state)).toBe(false) + expect(evaluateCondition({ type: 'flag-is', flag: 'off', equals: false }, state)).toBe(true) + }) + + await it('is false for a missing flag and never throws', async () => { + expect(evaluateCondition({ type: 'flag-is', flag: 'nope' }, state)).toBe(false) + expect(evaluateCondition({ type: 'counter', flag: 'nope', op: '≥', value: 0 }, state)).toBe(false) + expect(evaluateCondition({ type: 'counter', flag: 'nope', op: '<', value: 5 }, state)).toBe(false) + }) + + await it('is false when the flag kind does not match', async () => { + expect(evaluateCondition({ type: 'counter', flag: 'name', op: '≥', value: 0 }, state)).toBe(false) + expect(evaluateCondition({ type: 'counter', flag: 'key', op: '=', value: 1 }, state)).toBe(false) + expect(evaluateCondition({ type: 'flag-is', flag: 'coins', equals: true }, state)).toBe(false) + }) + + await it('has-item holds nothing until items exist', async () => { + expect(evaluateCondition({ type: 'has-item', itemId: 'sword' }, state)).toBe(false) + }) + + await it('combines leaves with all / any / not', async () => { + const yes = { type: 'flag-is', flag: 'key' } + const no = { type: 'flag-is', flag: 'off' } + expect(evaluateCondition({ type: 'all', of: [yes, yes] }, state)).toBe(true) + expect(evaluateCondition({ type: 'all', of: [yes, no] }, state)).toBe(false) + expect(evaluateCondition({ type: 'any', of: [no, yes] }, state)).toBe(true) + expect(evaluateCondition({ type: 'any', of: [no, no] }, state)).toBe(false) + expect(evaluateCondition({ type: 'not', of: no }, state)).toBe(true) + expect(evaluateCondition({ type: 'not', of: yes }, state)).toBe(false) + }) + + await it('allows one nesting level only', async () => { + const leaf = { type: 'flag-is', flag: 'key' } + expect(isCondition({ type: 'all', of: [leaf] })).toBe(true) + expect(isCondition({ type: 'all', of: [{ type: 'any', of: [leaf] }] })).toBe(false) + expect(isCondition({ type: 'not', of: { type: 'not', of: leaf } })).toBe(false) + expect(evaluateCondition({ type: 'not', of: { type: 'not', of: leaf } }, state)).toBe(false) + }) + + await it('never matches a shape it does not know, even under not', async () => { + expect(evaluateCondition({ type: 'moon-phase' }, state)).toBe(false) + expect(evaluateCondition({ flag: 'key', extra: 1 }, state)).toBe(false) + expect(evaluateCondition({ type: 'not', of: { type: 'moon-phase' } }, state)).toBe(false) + expect(evaluateCondition(undefined, state)).toBe(false) + expect(evaluateCondition(null, state)).toBe(false) + expect(evaluateCondition('key', state)).toBe(false) + }) + + await it('rejects a counter with a bad operator or a non-finite value', async () => { + expect(isCondition({ type: 'counter', flag: 'n', op: '~', value: 1 })).toBe(false) + expect(isCondition({ type: 'counter', flag: 'n', op: '=', value: Number.NaN })).toBe(false) + }) + }) +} diff --git a/packages/engine/src/types/data/index.ts b/packages/engine/src/types/data/index.ts index 6204818a..6ec5e960 100644 --- a/packages/engine/src/types/data/index.ts +++ b/packages/engine/src/types/data/index.ts @@ -5,6 +5,7 @@ export * from './AnimationStrategy' export * from './CharacterAnimationRole' export * from './CharacterDefinition' export * from './ColliderShape' +export * from './Condition' export * from './CreditEntry' export * from './EditorMetadata' export * from './ElevationStepData' diff --git a/packages/engine/src/types/engine-events.ts b/packages/engine/src/types/engine-events.ts index 96d5dfc2..15bd6a2b 100644 --- a/packages/engine/src/types/engine-events.ts +++ b/packages/engine/src/types/engine-events.ts @@ -44,6 +44,7 @@ export enum EngineEvent { ASK_REQUESTED = 'ask-requested', ASK_ANSWERED = 'ask-answered', FLAG_SET = 'flag-set', + COUNTER_CHANGED = 'counter-changed', PLAY_SFX_REQUESTED = 'play-sfx-requested', POINTER_TAP = 'pointer-tap', POINTER_LONG_PRESS = 'pointer-long-press', @@ -284,6 +285,12 @@ export interface EngineEventMap { * side of the (future) game-flags store that gates entity states. */ [EngineEvent.FLAG_SET]: { flag: string; value: boolean | number | string } + /** + * Emitted by `EventActionSystem` for a `change-counter` action: add + * `amount` (negative subtracts) to a number flag. `FlagSystem` folds it + * and then announces the new total as `FLAG_SET`. + */ + [EngineEvent.COUNTER_CHANGED]: { flag: string; amount: number } /** Emitted by `EventActionSystem` for a `play-sfx` action. */ [EngineEvent.PLAY_SFX_REQUESTED]: { sound: string } /** diff --git a/packages/gjs/src/test.mts b/packages/gjs/src/test.mts index 90bd90e8..e30ea642 100644 --- a/packages/gjs/src/test.mts +++ b/packages/gjs/src/test.mts @@ -32,6 +32,7 @@ import textListModelSuite from './widgets/editor/text-list.model.spec.js' import depthGlyphGeometrySuite from './widgets/editor/depth-glyph.geometry.spec.js' import doorTargetModelSuite from './widgets/editor/door-target.model.spec.js' import entityComponentsEditorModelSuite from './widgets/editor/entity-components-editor.model.spec.js' +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 layerSectionsSuite from './widgets/editor/layer-sections.spec.js' @@ -71,6 +72,7 @@ run({ depthGlyphGeometrySuite, doorTargetModelSuite, entityComponentsEditorModelSuite, + conditionModelSuite, eventActionModelSuite, flagPickerModelSuite, layerSectionsSuite, diff --git a/packages/gjs/src/widgets/editor/condition-editor.ts b/packages/gjs/src/widgets/editor/condition-editor.ts new file mode 100644 index 00000000..de6f07ce --- /dev/null +++ b/packages/gjs/src/widgets/editor/condition-editor.ts @@ -0,0 +1,222 @@ +import Adw from '@girs/adw-1' +import GLib from '@girs/glib-2.0' +import GObject from '@girs/gobject-2.0' +import Gtk from '@girs/gtk-4.0' +import { COUNTER_OPERATORS, type Condition, type ConditionLeaf, type CounterOperator } from '@pixelrpg/engine' +import { gettext as _ } from 'gettext' +import { comboRow, entryRow, type RowOption, spinRow, switchRow } from '../common/preference-rows.ts' +import { + addLeaf, + CONDITION_KINDS, + type ConditionFlag, + type ConditionKind, + changeConditionKind, + conditionKindOf, + conditionSummary, + defaultLeaf, + LEAF_KINDS, + leafForFlag, + leafKindOf, + leavesOf, + removeLeaf, + replaceLeaf, + takesManyLeaves, + usesItems, +} from './condition-model.ts' +import { conditionKindLabel, conditionText } from './condition-summary.ts' +import type { ComponentRefOptions } from './component-inspector.ts' +import { flagPickerRow } from './flag-picker-row.ts' + +const COUNTER_RANGE = { min: -100000, max: 100000, step: 1 } + +/** + * Typed view of the signals {@link ConditionEditor} registers, layered on + * the parent's own so inherited signals keep their argument lists. + */ +export interface ConditionEditorSignals extends Adw.PreferencesGroup.SignalSignatures { + 'condition-changed': (conditionJson: string) => void +} + +/** + * Friendly editor for one state's `when`: a "kind" row (a flag, a number, + * an item, or `all` / `any` / `not` over leaves — one level, a group never + * holds a group), then the rows of each leaf. The flag picker is the same + * one the action list uses; the operator is a dropdown and the value widget + * follows the flag's kind (switch / number / word). The group description + * reads the whole condition back as a sentence. Every edit emits + * `condition-changed` with the whole condition as JSON. + */ +export class ConditionEditor extends Adw.PreferencesGroup { + private _condition: Condition + private _refOptions: ComponentRefOptions = {} + private _rows: Gtk.Widget[] = [] + private _silent = false + + static { + GObject.registerClass( + { + GTypeName: 'PixelRpgConditionEditor', + Signals: { + 'condition-changed': { param_types: [GObject.TYPE_STRING] }, + }, + }, + ConditionEditor, + ) + } + + declare connect: GObject.SignalMethods['connect'] + declare connect_after: GObject.SignalMethods['connect_after'] + declare emit: GObject.SignalMethods['emit'] + + constructor() { + super({ title: _('When') }) + this._condition = defaultLeaf('flag-is') + this._rebuild() + } + + /** Populate from a stored condition; data that is no condition starts over as a blank flag row. */ + setCondition(condition: unknown): void { + this._condition = conditionKindOf(condition) ? (condition as Condition) : defaultLeaf('flag-is') + this._rebuild() + } + + setRefOptions(options: ComponentRefOptions): void { + if (JSON.stringify(options) === JSON.stringify(this._refOptions)) return + this._refOptions = options + this._rebuild() + } + + private get _flags(): ConditionFlag[] { + return (this._refOptions.flags ?? []).map((f) => ({ value: f.value, label: f.label, kind: f.kind })) + } + + private _flagKind(id: string): ConditionFlag['kind'] { + return this._flags.find((f) => f.value === id)?.kind + } + + private _set(next: Condition, rebuild: boolean): void { + this._condition = next + if (!this._silent) this.emit('condition-changed', JSON.stringify(next)) + if (rebuild) { + // Not inside the signal whose row this rebuild would destroy. + GLib.idle_add(GLib.PRIORITY_DEFAULT, () => { + this._rebuild() + return GLib.SOURCE_REMOVE + }) + } else this._refreshSummary() + } + + private _refreshSummary(): void { + this.set_description(conditionSummary(this._condition, this._flags, conditionText())) + } + + private _rebuild(): void { + for (const row of this._rows) this.remove(row) + this._rows = [] + this._refreshSummary() + const kind = conditionKindOf(this._condition) ?? 'flag-is' + this._add(this._kindRow(kind)) + const many = takesManyLeaves(kind) + const grouped = kind === 'all' || kind === 'any' || kind === 'not' + leavesOf(this._condition).forEach((leaf, index) => { + for (const row of this._leafRows(leaf, index, grouped, many)) this._add(row) + }) + if (many) this._add(this._addLeafRow()) + if (usesItems(this._condition)) this._add(this._itemsWarning()) + } + + private _add(row: Gtk.Widget): void { + this.add(row) + this._rows.push(row) + } + + private _kindRow(kind: ConditionKind): Adw.ComboRow { + const options: RowOption[] = CONDITION_KINDS.map((k) => ({ value: k, label: conditionKindLabel(k) })) + return comboRow(_('Kind'), options, kind, (value) => { + if (value === kind) return + this._set(changeConditionKind(this._condition, value as ConditionKind, this._flags), true) + }) + } + + /** The rows of one leaf; inside a group each leaf also picks its own shape and may be removed. */ + private _leafRows(leaf: ConditionLeaf, index: number, grouped: boolean, removable: boolean): Gtk.Widget[] { + const rows: Gtk.Widget[] = [] + const kind = leafKindOf(leaf) + const put = (next: ConditionLeaf, rebuild: boolean) => this._set(replaceLeaf(this._condition, index, next), rebuild) + if (grouped) { + const options: RowOption[] = LEAF_KINDS.map((k) => ({ value: k, label: conditionKindLabel(k) })) + const row = comboRow(_('Condition'), options, kind, (value) => { + if (value === kind) return + const flag = 'flag' in leaf ? leaf.flag : '' + const made = defaultLeaf(value as 'flag-is' | 'counter' | 'has-item', flag, this._flagKind(flag)) + put(made, true) + }) + if (removable && leavesOf(this._condition).length > 1) { + const remove = new Gtk.Button({ + iconName: 'user-trash-symbolic', + tooltipText: _('Remove condition'), + cssClasses: ['flat'], + valign: Gtk.Align.CENTER, + }) + remove.connect('clicked', () => this._set(removeLeaf(this._condition, index), true)) + row.add_suffix(remove) + } + rows.push(row) + } + if (kind === 'has-item') { + rows.push( + entryRow(_('Item id'), (leaf as { itemId: string }).itemId, (v) => put({ type: 'has-item', itemId: v }, false)), + ) + return rows + } + const flagId = (leaf as { flag: string }).flag + rows.push( + flagPickerRow(this._refOptions, flagId, undefined, (id) => { + put(leafForFlag(leaf, id, this._flagKind(id)), true) + }), + ) + if ('type' in leaf && leaf.type === 'counter') { + const counter = leaf + const ops: RowOption[] = COUNTER_OPERATORS.map((op) => ({ value: op, label: op })) + rows.push( + comboRow(_('Compare'), ops, counter.op, (v) => put({ ...counter, op: v as CounterOperator }, false)), + spinRow(_('Number'), counter.value, COUNTER_RANGE, (n) => put({ ...counter, value: n }, false)), + ) + return rows + } + const equals = (leaf as { equals?: boolean | string }).equals ?? true + if (this._flagKind(flagId) === 'text' || typeof equals === 'string') { + rows.push( + entryRow(_('Is'), String(equals === true ? '' : equals), (v) => + put({ type: 'flag-is', flag: flagId, equals: v }, false), + ), + ) + } else { + rows.push( + switchRow(_('Is yes'), equals !== false, (on) => put({ type: 'flag-is', flag: flagId, equals: on }, false)), + ) + } + return rows + } + + private _addLeafRow(): Adw.ButtonRow { + const row = new Adw.ButtonRow({ title: _('Add condition'), startIconName: 'list-add-symbolic' }) + row.connect('activated', () => { + const flag = this._flags[0] + this._set(addLeaf(this._condition, defaultLeaf('flag-is', flag?.value ?? '', flag?.kind)), true) + }) + return row + } + + private _itemsWarning(): Adw.ActionRow { + const row = new Adw.ActionRow({ + title: _('Items arrive later'), + subtitle: _('The game has no items yet, so a condition with an item never holds.'), + subtitleLines: 0, + }) + row.add_prefix(new Gtk.Image({ iconName: 'dialog-warning-symbolic' })) + return row + } +} + +GObject.type_ensure(ConditionEditor.$gtype) diff --git a/packages/gjs/src/widgets/editor/condition-model.spec.ts b/packages/gjs/src/widgets/editor/condition-model.spec.ts new file mode 100644 index 00000000..e653fd35 --- /dev/null +++ b/packages/gjs/src/widgets/editor/condition-model.spec.ts @@ -0,0 +1,127 @@ +import { describe, expect, it } from '@gjsify/unit' + +import type { Condition } from '@pixelrpg/engine' +import { + addLeaf, + changeConditionKind, + type ConditionFlag, + conditionKindOf, + conditionSummary, + defaultLeaf, + leafForFlag, + leafKindForFlag, + leavesOf, + removeLeaf, + replaceLeaf, + usesItems, +} from './condition-model.ts' + +const FLAGS: ConditionFlag[] = [ + { value: 'coins', label: 'Coins', kind: 'number' }, + { value: 'key', label: 'Has Key', kind: 'yes-no' }, + { value: 'mood', label: 'Mood', kind: 'text' }, +] + +export default async () => { + await describe('condition-model', async () => { + await it('reads the shorthand as a flag-is row and rejects non-conditions', async () => { + expect(conditionKindOf({ flag: 'key' })).toBe('flag-is') + expect(conditionKindOf({ type: 'counter', flag: 'coins', op: '≥', value: 3 })).toBe('counter') + expect(conditionKindOf({ type: 'not', of: { flag: 'key' } })).toBe('not') + expect(conditionKindOf({ type: 'any', of: [{ type: 'all', of: [] }] })).toBe(null) + expect(conditionKindOf('nope')).toBe(null) + }) + + await it('picks the leaf shape by the flag kind', async () => { + expect(leafKindForFlag('number')).toBe('counter') + expect(leafKindForFlag('yes-no')).toBe('flag-is') + expect(leafKindForFlag('text')).toBe('flag-is') + expect(leafKindForFlag(undefined)).toBe('flag-is') + }) + + await it('reshapes a leaf when its flag changes kind', async () => { + const counter = defaultLeaf('counter', 'coins') + expect(leafForFlag(counter, 'key', 'yes-no')).toStrictEqual({ type: 'flag-is', flag: 'key', equals: true }) + expect(leafForFlag(counter, 'mood', 'text')).toStrictEqual({ type: 'flag-is', flag: 'mood', equals: '' }) + const key = { type: 'flag-is', flag: 'key', equals: false } as const + expect(leafForFlag(key, 'coins', 'number')).toStrictEqual({ type: 'counter', flag: 'coins', op: '≥', value: 1 }) + expect(leafForFlag(key, 'other', 'yes-no')).toStrictEqual({ type: 'flag-is', flag: 'other', equals: false }) + const kept = { type: 'counter', flag: 'coins', op: '<', value: 7 } as const + expect(leafForFlag(kept, 'gems', 'number')).toStrictEqual({ type: 'counter', flag: 'gems', op: '<', value: 7 }) + }) + + await it('changes the top shape and keeps what it can', async () => { + const leaf = { type: 'counter', flag: 'coins', op: '>', value: 2 } as const + expect(changeConditionKind(leaf, 'all', FLAGS)).toStrictEqual({ type: 'all', of: [leaf] }) + expect(changeConditionKind({ type: 'all', of: [leaf, { flag: 'key' }] }, 'not', FLAGS)).toStrictEqual({ + type: 'not', + of: leaf, + }) + expect(changeConditionKind({ type: 'any', of: [{ flag: 'key' }, leaf] }, 'all', FLAGS)).toStrictEqual({ + type: 'all', + of: [{ flag: 'key' }, leaf], + }) + expect(changeConditionKind({ type: 'any', of: [leaf] }, 'counter', FLAGS)).toStrictEqual(leaf) + expect(changeConditionKind(undefined, 'flag-is', FLAGS)).toStrictEqual({ + type: 'flag-is', + flag: 'coins', + equals: true, + }) + expect(changeConditionKind(leaf, 'has-item', FLAGS)).toStrictEqual({ type: 'has-item', itemId: '' }) + }) + + await it('edits a group one level deep and never empties it', async () => { + const group: Condition = { type: 'all', of: [{ flag: 'key' }] } + const added = addLeaf(group, defaultLeaf('counter', 'coins')) + expect(added).toStrictEqual({ type: 'all', of: [{ flag: 'key' }, defaultLeaf('counter', 'coins')] }) + expect(removeLeaf(added, 0)).toStrictEqual({ type: 'all', of: [defaultLeaf('counter', 'coins')] }) + expect(removeLeaf(group, 0)).toStrictEqual(group) + expect(replaceLeaf(added, 1, { flag: 'mood', equals: 'x' })).toStrictEqual({ + type: 'all', + of: [{ flag: 'key' }, { flag: 'mood', equals: 'x' }], + }) + expect(replaceLeaf({ type: 'not', of: { flag: 'key' } }, 0, { flag: 'mood' })).toStrictEqual({ + type: 'not', + of: { flag: 'mood' }, + }) + expect(addLeaf({ type: 'not', of: { flag: 'key' } }, { flag: 'mood' })).toStrictEqual({ + type: 'not', + of: { flag: 'key' }, + }) + }) + + await it('says the condition the way a child would', async () => { + expect(conditionSummary({ type: 'counter', flag: 'coins', op: '≥', value: 3 }, FLAGS)).toBe('Coins ≥ 3') + expect(conditionSummary({ type: 'flag-is', flag: 'key' }, FLAGS)).toBe('Has Key is Yes') + expect(conditionSummary({ flag: 'key', equals: false }, FLAGS)).toBe('Has Key is No') + expect(conditionSummary({ flag: 'mood', equals: 'happy' }, FLAGS)).toBe('Mood is “happy”') + expect( + conditionSummary( + { type: 'all', of: [{ flag: 'key' }, { type: 'counter', flag: 'coins', op: '≠', value: 0 }] }, + FLAGS, + ), + ).toBe('Has Key is Yes and Coins ≠ 0') + expect(conditionSummary({ type: 'any', of: [{ flag: 'key' }, { flag: 'mood', equals: 'a' }] }, FLAGS)).toBe( + 'Has Key is Yes or Mood is “a”', + ) + expect(conditionSummary({ type: 'not', of: { flag: 'key' } }, FLAGS)).toBe('Not: Has Key is Yes') + expect(conditionSummary({ flag: 'gone' }, FLAGS)).toBe('… is Yes') + expect(conditionSummary({ type: 'has-item', itemId: 'sword' }, FLAGS)).toBe('Has item sword') + }) + + await it('flags items so the editor can warn', async () => { + expect(usesItems({ type: 'has-item', itemId: 'a' })).toBe(true) + expect(usesItems({ type: 'any', of: [{ flag: 'key' }, { type: 'has-item', itemId: 'a' }] })).toBe(true) + expect(usesItems({ flag: 'key' })).toBe(false) + }) + + await it('treats a leaf with no flag picked yet as a leaf, not a group', async () => { + const blank = defaultLeaf('flag-is') + expect(leavesOf(blank)).toStrictEqual([blank]) + expect(conditionSummary(blank, FLAGS)).toBe('… is Yes') + const counter = defaultLeaf('counter') + expect(leavesOf(counter)).toStrictEqual([counter]) + expect(typeof conditionSummary({ type: 'all', of: [blank, counter] }, FLAGS)).toBe('string') + }) + }) +} diff --git a/packages/gjs/src/widgets/editor/condition-model.ts b/packages/gjs/src/widgets/editor/condition-model.ts new file mode 100644 index 00000000..cbeab058 --- /dev/null +++ b/packages/gjs/src/widgets/editor/condition-model.ts @@ -0,0 +1,219 @@ +import { + type Condition, + type ConditionLeaf, + type CounterOperator, + type FlagKind, + type FlagValue, + isCondition, + isConditionLeaf, +} from '@pixelrpg/engine' + +/** + * GTK-free logic of the condition editor: which shape a row is, how a + * flag's kind picks the shape, the one-level group edits and the + * child-readable summary. Like the action model it holds no gettext — the + * sentences come in as a {@link ConditionText} from the widget side + * (`condition-summary.ts`); {@link ENGLISH_CONDITION_TEXT} is what specs + * and a caller without translations get. + */ + +/** What the top row of a condition editor can be. */ +export type ConditionKind = 'flag-is' | 'counter' | 'has-item' | 'all' | 'any' | 'not' + +export const CONDITION_KINDS: readonly ConditionKind[] = ['flag-is', 'counter', 'has-item', 'all', 'any', 'not'] + +/** The kinds a group's rows can be; a group never holds a group. */ +export const LEAF_KINDS: readonly ConditionKind[] = ['flag-is', 'counter', 'has-item'] + +type LeafKind = 'flag-is' | 'counter' | 'has-item' + +/** The sentences a condition summary is made of; the widget side translates each. */ +export interface ConditionText { + /** A flag that is switched on or off: "Has Key is Yes". */ + flagIsYesNo(flag: string, on: boolean): string + /** A flag that holds a word: "Mood is “happy”". */ + flagIsText(flag: string, value: string): string + /** A number flag against a number: "Coins ≥ 3". */ + counter(flag: string, op: CounterOperator, value: number): string + hasItem(item: string): string + all(parts: string[]): string + any(parts: string[]): string + not(part: string): string + /** What stands in for a flag or item nobody picked yet. */ + noFlag: string +} + +export const ENGLISH_CONDITION_TEXT: ConditionText = { + flagIsYesNo: (flag, on) => `${flag} is ${on ? 'Yes' : 'No'}`, + flagIsText: (flag, value) => `${flag} is “${value}”`, + counter: (flag, op, value) => `${flag} ${op} ${value}`, + hasItem: (item) => `Has item ${item}`, + all: (parts) => parts.join(' and '), + any: (parts) => parts.join(' or '), + not: (part) => `Not: ${part}`, + noFlag: '…', +} + +/** A flag as the picker knows it. */ +export interface ConditionFlag { + value: string + label: string + kind?: FlagKind +} + +/** The shape one leaf has; the `{ flag, equals }` shorthand reads as `flag-is`. */ +export function leafKindOf(leaf: ConditionLeaf): LeafKind { + return 'type' in leaf ? leaf.type : 'flag-is' +} + +/** The shape the editor shows for a stored condition; `null` for data that is no condition. */ +export function conditionKindOf(condition: unknown): ConditionKind | null { + if (!isCondition(condition)) return null + if (isConditionLeaf(condition)) return leafKindOf(condition) + return condition.type +} + +/** The leaf shape a flag of this kind is compared with; a flag nobody picked reads as yes/no. */ +export function leafKindForFlag(kind: FlagKind | undefined): 'flag-is' | 'counter' { + return kind === 'number' ? 'counter' : 'flag-is' +} + +function defaultEquals(kind: FlagKind | undefined): FlagValue { + return kind === 'text' ? '' : true +} + +/** A fresh leaf of `kind`, already fitting `flag` where it has one. */ +export function defaultLeaf(kind: LeafKind, flag = '', flagKind?: FlagKind): ConditionLeaf { + switch (kind) { + case 'counter': + return { type: 'counter', flag, op: '≥', value: 1 } + case 'has-item': + return { type: 'has-item', itemId: '' } + default: + return { type: 'flag-is', flag, equals: defaultEquals(flagKind) } + } +} + +/** + * The leaf after its flag changed: a number flag becomes a counter, any + * other a flag-is, and a value that cannot fit the new kind is reset. + * Keeps the operator and number when the leaf stays a counter. + */ +export function leafForFlag(leaf: ConditionLeaf, flag: string, flagKind: FlagKind | undefined): ConditionLeaf { + if (leafKindOf(leaf) === 'has-item') return leaf + if (leafKindForFlag(flagKind) === 'counter') { + return 'type' in leaf && leaf.type === 'counter' ? { ...leaf, flag } : defaultLeaf('counter', flag) + } + const equals = 'equals' in leaf ? leaf.equals : undefined + const fits = flagKind === 'text' ? typeof equals === 'string' : typeof equals === 'boolean' + return { type: 'flag-is', flag, equals: fits && equals !== undefined ? equals : defaultEquals(flagKind) } +} + +/** + * Whether the editor shows this as a group. Decided by `type` alone: a leaf + * still being filled in (no flag picked yet) is not a valid condition for the + * engine, but it is a leaf here, never a group. + */ +function isGroup(condition: Condition): condition is Exclude { + return 'type' in condition && (condition.type === 'all' || condition.type === 'any' || condition.type === 'not') +} + +/** The leaves a condition holds, in order (a leaf is its own single leaf). */ +export function leavesOf(condition: Condition): ConditionLeaf[] { + if (!isGroup(condition)) return [condition] + return Array.isArray(condition.of) ? [...condition.of] : [condition.of] +} + +function pickFlag(flags: readonly ConditionFlag[]): string { + return flags[0]?.value ?? '' +} + +/** + * The condition after the top row changed shape. A leaf wrapped in a group + * keeps its leaf; a group turned into a leaf keeps its first one; `all` ↔ + * `any` keeps every leaf; `not` keeps the first. + */ +export function changeConditionKind( + condition: Condition | undefined, + kind: ConditionKind, + flags: readonly ConditionFlag[] = [], +): Condition { + const leaves = condition ? leavesOf(condition) : [] + const first = leaves[0] + const fresh = () => { + const flag = pickFlag(flags) + return defaultLeaf('flag-is', flag, flags[0]?.kind) + } + switch (kind) { + case 'all': + case 'any': + return { type: kind, of: leaves.length > 0 ? leaves : [fresh()] } + case 'not': + return { type: 'not', of: first ?? fresh() } + default: { + if (first && leafKindOf(first) === kind) return first + if (kind === 'has-item') return defaultLeaf('has-item') + const flag = first && 'flag' in first ? first.flag : pickFlag(flags) + const flagKind = flags.find((f) => f.value === flag)?.kind + return defaultLeaf(kind, flag, flagKind) + } + } +} + +/** A group with the leaf at `index` swapped; a bare leaf or `not` is replaced outright. */ +export function replaceLeaf(condition: Condition, index: number, leaf: ConditionLeaf): Condition { + if (!isGroup(condition)) return leaf + if (condition.type === 'not') return { type: 'not', of: leaf } + const of = [...condition.of] + of[index] = leaf + return { type: condition.type, of } +} + +/** A group with one more leaf; anything but `all` / `any` is returned as is. */ +export function addLeaf(condition: Condition, leaf: ConditionLeaf): Condition { + if (!isGroup(condition) || condition.type === 'not') return condition + return { type: condition.type, of: [...condition.of, leaf] } +} + +/** A group without the leaf at `index`; the last leaf stays (an empty group would never mean anything). */ +export function removeLeaf(condition: Condition, index: number): Condition { + if (!isGroup(condition) || condition.type === 'not') return condition + if (condition.of.length <= 1) return condition + return { type: condition.type, of: condition.of.filter((_, i) => i !== index) } +} + +/** Whether the top row is a group that takes more than one leaf. */ +export function takesManyLeaves(kind: ConditionKind): boolean { + return kind === 'all' || kind === 'any' +} + +/** Whether a condition mentions an item; items have no runtime yet, so the editor warns. */ +export function usesItems(condition: Condition): boolean { + return leavesOf(condition).some((l) => leafKindOf(l) === 'has-item') +} + +/** One leaf as a sentence a child can read. */ +export function leafSummary( + leaf: ConditionLeaf, + flags: readonly ConditionFlag[], + text: ConditionText = ENGLISH_CONDITION_TEXT, +): string { + if ('type' in leaf && leaf.type === 'has-item') return text.hasItem(leaf.itemId || text.noFlag) + const id = (leaf as { flag: string }).flag + const name = id ? (flags.find((f) => f.value === id)?.label ?? text.noFlag) : text.noFlag + if ('type' in leaf && leaf.type === 'counter') return text.counter(name, leaf.op, leaf.value) + const equals = (leaf as { equals?: FlagValue }).equals ?? true + return typeof equals === 'string' ? text.flagIsText(name, equals) : text.flagIsYesNo(name, equals !== false) +} + +/** The whole condition as one sentence; an absent condition is the caller's to word. */ +export function conditionSummary( + condition: Condition, + flags: readonly ConditionFlag[], + text: ConditionText = ENGLISH_CONDITION_TEXT, +): string { + if (!isGroup(condition)) return leafSummary(condition, flags, text) + if (condition.type === 'not') return text.not(leafSummary(condition.of, flags, text)) + const parts = condition.of.map((l) => leafSummary(l, flags, text)) + return condition.type === 'all' ? text.all(parts) : text.any(parts) +} diff --git a/packages/gjs/src/widgets/editor/condition-summary.ts b/packages/gjs/src/widgets/editor/condition-summary.ts new file mode 100644 index 00000000..8a8bb0d5 --- /dev/null +++ b/packages/gjs/src/widgets/editor/condition-summary.ts @@ -0,0 +1,42 @@ +import { gettext as _ } from 'gettext' +import type { ConditionKind, ConditionText } from './condition-model.ts' + +/** Fill `%1$s`, `%2$s`, … so a translation may reorder what it shows. */ +function fill(template: string, ...args: Array): string { + return template.replace(/%(\d+)\$s/g, (_m, n: string) => String(args[Number(n) - 1] ?? '')) +} + +/** + * The sentences of a condition summary, translated. Each msgid is a + * literal `_()` call so `xgettext` finds it; a placeholder is `%N$s`. + */ +export function conditionText(): ConditionText { + return { + flagIsYesNo: (flag, on) => fill(on ? _('%1$s is Yes') : _('%1$s is No'), flag), + flagIsText: (flag, value) => fill(_('%1$s is “%2$s”'), flag, value), + counter: (flag, op, value) => fill(_('%1$s %2$s %3$s'), flag, op, value), + hasItem: (item) => fill(_('Has item %1$s'), item), + all: (parts) => parts.join(_(' and ')), + any: (parts) => parts.join(_(' or ')), + not: (part) => fill(_('Not: %1$s'), part), + noFlag: _('…'), + } +} + +/** The label of a condition shape in the "Kind" dropdown. */ +export function conditionKindLabel(kind: ConditionKind): string { + switch (kind) { + case 'flag-is': + return _('A flag is') + case 'counter': + return _('A number compares') + case 'has-item': + return _('Has an item') + case 'all': + return _('All of these') + case 'any': + return _('Any of these') + case 'not': + return _('None of this') + } +} diff --git a/packages/gjs/src/widgets/editor/entity-components-editor.ts b/packages/gjs/src/widgets/editor/entity-components-editor.ts index 8ecf5e9e..4275ba8b 100644 --- a/packages/gjs/src/widgets/editor/entity-components-editor.ts +++ b/packages/gjs/src/widgets/editor/entity-components-editor.ts @@ -23,6 +23,7 @@ import { type DormantComponentFacts, dormantComponentFacts, } from './entity-components-editor.model.ts' +import { ConditionEditor } from './condition-editor.ts' import { EventActionListEditor } from './event-action-list-editor.ts' /** A per-component editor widget in the stack — the generic inspector or a bespoke one. */ @@ -209,6 +210,7 @@ export class EntityComponentsEditor extends Adw.Bin { setRefOptions(options: ComponentRefOptions): void { this._refOptions = options for (const editor of this._componentEditors()) editor.setRefOptions(options) + for (const child of this._rendered) if (child instanceof ConditionEditor) child.setRefOptions(options) } /** Populate from an entity definition (no `entity-changed` echo). */ @@ -245,6 +247,7 @@ export class EntityComponentsEditor extends Adw.Bin { this._box.insert_child_after(child, this._lastRenderedOrNull()) this._rendered.push(child) } + this._renderStateConditions() this._refreshMoreRow() this._refreshAddRow() this._silent = false @@ -337,6 +340,31 @@ export class EntityComponentsEditor extends Adw.Bin { this._moreGroup.set_visible(count > 0) } + /** + * One "When" editor per state: the condition that switches the state on. + * Absent `when` (a manually switched state) has no row — nothing to edit. + */ + private _renderStateConditions(): void { + ;(this._states ?? []).forEach((state, index) => { + if (state.when === undefined) return + const editor = new ConditionEditor() + editor.set_title(_('When “%s”').replace('%s', state.id)) + editor.setRefOptions(this._refOptions) + editor.setCondition(state.when) + editor.connect('condition-changed', (_w: ConditionEditor, json: string) => { + if (!this._states) return + try { + this._states = this._states.map((st, i) => (i === index ? { ...st, when: JSON.parse(json) } : st)) + } catch { + return + } + this._emitChange() + }) + this._box.insert_child_after(editor, this._lastRenderedOrNull()) + this._rendered.push(editor) + }) + } + private _lastRenderedOrNull(): Gtk.Widget | null { return this._rendered.length > 0 ? this._rendered[this._rendered.length - 1] : null } diff --git a/packages/gjs/src/widgets/editor/event-action-list-editor.ts b/packages/gjs/src/widgets/editor/event-action-list-editor.ts index ab099cd3..9eb2f877 100644 --- a/packages/gjs/src/widgets/editor/event-action-list-editor.ts +++ b/packages/gjs/src/widgets/editor/event-action-list-editor.ts @@ -10,15 +10,9 @@ import { comboRow, entryRow, type RowOption, spinRow, switchRow } from '../commo import { localizedEntryRow } from './language-text-row.ts' import { TextLanguageState } from './text-language.model.ts' import type { ComponentRefOptions } from './component-inspector.ts' -import { - cleanNewFlagName, - existingFlagId, - flagDisplayName, - flagPickerOptions, - isNewFlagChoice, -} from './flag-picker.model.ts' +import { flagDisplayName } from './flag-picker.model.ts' import { actionLabel, summaryText } from './event-action-summary.ts' -import { promptNewFlag } from './new-flag-dialog.ts' +import { flagPickerRow } from './flag-picker-row.ts' import { ACTION_ICONS, type AskAction, @@ -430,6 +424,11 @@ export class EventActionListEditor extends Adw.PreferencesGroup { ] case 'set-flag': return [this._flagRow(list, index, afterEdit), this._flagValueRow(action.flag, action.value, patch)] + case 'change-counter': + return [ + this._flagRow(list, index, afterEdit, 'number'), + spinRow(_('Change by'), action.amount, FLAG_NUMBER_RANGE, (n) => patch({ amount: n })), + ] case 'play-sfx': return [entryRow(_('Sound'), action.sound, (v) => patch({ sound: v }))] case 'wait': @@ -546,61 +545,36 @@ export class EventActionListEditor extends Adw.PreferencesGroup { } /** - * The flag picker: the project's flags by name, "New…" last. Picking - * "New…" asks for a name and kind, creates the flag through the host and - * selects it; the stored value is always the flag's id, never its name. - * A flag of another kind swaps the value editor and the value with it. + * The flag picker (see {@link flagPickerRow}). A flag of another kind + * swaps the value editor and the value with it. */ - private _flagRow(list: ActionData[], index: number, afterEdit: () => void): Adw.ComboRow { - const held = () => list[index] as Extract - const current = held().flag - const flags = this._refOptions.flags ?? [] - const options = flagPickerOptions(flags, current, { - none: _('(None)'), - create: _('New…'), - missing: _('Missing flag'), - }) + private _flagRow(list: ActionData[], index: number, afterEdit: () => void, onlyKind?: FlagKind): Adw.ComboRow { + const held = () => list[index] as Extract // Store a pick; true when the value editor has to change with it. const store = (id: string): boolean => { const kind = this._flagKind(id) - if (!kind) { + const action = held() + if (!kind || action.type !== 'set-flag') { this._patch(list, index, { flag: id }) return false } - const before = valueEditorKind(this._flagKind(held().flag), held().value) - this._patch(list, index, { flag: id, value: flagValueForKind(held().value, kind) }) + const before = valueEditorKind(this._flagKind(action.flag), action.value) + this._patch(list, index, { flag: id, value: flagValueForKind(action.value, kind) }) return kind !== before } - let settled = current - let reverting = false - const row = comboRow(_('Flag'), options, current, (value) => { - if (reverting) return - if (!isNewFlagChoice(value)) { - settled = value - if (store(value)) { - // Not inside the signal that this rebuild would destroy the row of. - GLib.idle_add(GLib.PRIORITY_DEFAULT, () => { - this._commit() - return GLib.SOURCE_REMOVE - }) - } else afterEdit() - return - } - // Hand the row back to what it held while the name is asked for. - reverting = true - row.set_selected( - Math.max( - 0, - options.findIndex((o) => o.value === settled), - ), - ) - reverting = false - void this._createFlagFor(row, flags, (id) => { - settled = id - store(id) - }) + return flagPickerRow(this._refOptions, held().flag, onlyKind, (id, created) => { + const rebuild = store(id) + if (created) { + // The host re-sends the options with the new flag; this rebuild shows it selected. + this._commit() + } else if (rebuild) { + // Not inside the signal that this rebuild would destroy the row of. + GLib.idle_add(GLib.PRIORITY_DEFAULT, () => { + this._commit() + return GLib.SOURCE_REMOVE + }) + } else afterEdit() }) - return row } /** The value of a `set-flag`, edited the way the flag's kind asks: a switch, a number or a word. */ @@ -619,26 +593,6 @@ export class EventActionListEditor extends Adw.PreferencesGroup { } } - private async _createFlagFor( - row: Adw.ComboRow, - flags: ReadonlyArray<{ value: string; label: string }>, - onCreated: (flagId: string) => void, - ): Promise { - const create = this._refOptions.createFlag - if (!create) return - const chosen = await promptNewFlag(row) - if (!chosen) return - // A name that is already a flag picks that flag: two flags of one name would read as one. - const id = - existingFlagId(chosen.name, flags) ?? - (cleanNewFlagName(chosen.name, flags) ? create(chosen.name, chosen.kind) : null) - if (id) { - onCreated(id) - // The host re-sends the options with the new flag; this rebuild shows it selected. - this._commit() - } - } - private _flagKind(id: string): FlagKind | undefined { return this._refOptions.flags?.find((f) => f.value === id)?.kind } diff --git a/packages/gjs/src/widgets/editor/event-action-model.ts b/packages/gjs/src/widgets/editor/event-action-model.ts index f7c7ec9a..45fd45e6 100644 --- a/packages/gjs/src/widgets/editor/event-action-model.ts +++ b/packages/gjs/src/widgets/editor/event-action-model.ts @@ -33,6 +33,8 @@ export interface SummaryText { setFlagYesNo(flag: string, on: boolean): string /** A flag that holds a number or a word. */ setFlagValue(flag: string, value: string): string + /** A number flag that goes up or down by an amount (`amount` is never 0 here). */ + changeCounter(flag: string, amount: number): string playSound(sound: string): string wait(ms: number): string ask(prompt: string, answers: number): string @@ -44,6 +46,7 @@ export const ENGLISH_SUMMARY: SummaryText = { giveItem: (qty, item) => `Give ${qty}× ${item}`, setFlagYesNo: (flag, on) => `Set “${flag}” to ${on ? 'yes' : 'no'}`, setFlagValue: (flag, value) => `Set “${flag}” to ${value}`, + changeCounter: (flag, amount) => `Change “${flag}” by ${amount > 0 ? '+' : ''}${amount}`, playSound: (sound) => `Play sound: ${sound}`, wait: (ms) => `Wait ${ms} ms`, ask: (prompt, answers) => `Ask: ${prompt} (${answers})`, @@ -55,6 +58,7 @@ export const ACTION_ICONS: Record = { teleport: 'go-jump-symbolic', 'give-item': 'package-x-generic-symbolic', 'set-flag': 'object-select-symbolic', + 'change-counter': 'list-add-symbolic', 'play-sfx': 'audio-volume-high-symbolic', wait: 'alarm-symbolic', ask: 'dialog-question-symbolic', @@ -71,6 +75,8 @@ export function defaultAction(type: ActionData['type'], id: string, firstMapId: return { id, type, itemId: '', qty: 1 } case 'set-flag': return { id, type, flag: '', value: true } + case 'change-counter': + return { id, type, flag: '', amount: 1 } case 'play-sfx': return { id, type, sound: '' } case 'wait': @@ -114,6 +120,8 @@ export function actionSummary( const flag = a.flag ? flagLabel(a.flag) : '…' return typeof a.value === 'boolean' ? text.setFlagYesNo(flag, a.value) : text.setFlagValue(flag, String(a.value)) } + case 'change-counter': + return text.changeCounter(a.flag ? flagLabel(a.flag) : '…', a.amount) case 'play-sfx': return text.playSound(a.sound || '…') case 'wait': diff --git a/packages/gjs/src/widgets/editor/event-action-summary.ts b/packages/gjs/src/widgets/editor/event-action-summary.ts index d1da55fe..226d1952 100644 --- a/packages/gjs/src/widgets/editor/event-action-summary.ts +++ b/packages/gjs/src/widgets/editor/event-action-summary.ts @@ -18,6 +18,8 @@ export function summaryText(): SummaryText { giveItem: (qty, item) => fill(_('Give %1$s× %2$s'), qty, item), setFlagYesNo: (flag, on) => fill(on ? _('Set “%1$s” to yes') : _('Set “%1$s” to no'), flag), setFlagValue: (flag, value) => fill(_('Set “%1$s” to %2$s'), flag, value), + changeCounter: (flag, amount) => + fill(amount < 0 ? _('Change “%1$s” by %2$s') : _('Change “%1$s” by +%2$s'), flag, amount), playSound: (sound) => fill(_('Play sound: %1$s'), sound), wait: (ms) => fill(_('Wait %1$s ms'), ms), ask: (prompt, answers) => fill(_('Ask: %1$s (%2$s)'), prompt, answers), @@ -35,6 +37,8 @@ export function actionLabel(type: ActionData['type']): string { return _('Give item') case 'set-flag': return _('Set flag') + case 'change-counter': + return _('Change counter') case 'play-sfx': return _('Play sound') case 'wait': diff --git a/packages/gjs/src/widgets/editor/flag-picker-row.ts b/packages/gjs/src/widgets/editor/flag-picker-row.ts new file mode 100644 index 00000000..51a2ada5 --- /dev/null +++ b/packages/gjs/src/widgets/editor/flag-picker-row.ts @@ -0,0 +1,75 @@ +import type Adw from '@girs/adw-1' +import type { FlagKind } from '@pixelrpg/engine' +import { gettext as _ } from 'gettext' +import { comboRow } from '../common/preference-rows.ts' +import type { ComponentRefOptions } from './component-inspector.ts' +import { cleanNewFlagName, existingFlagId, flagPickerOptions, isNewFlagChoice } from './flag-picker.model.ts' +import { promptNewFlag } from './new-flag-dialog.ts' + +/** + * The flag picker row both the action list and the condition editor use: + * the project's flags by name, "New…" last. Picking "New…" asks for a name + * and kind, creates the flag through the host and picks it; the value + * handed to `onPick` is always the flag's id, never its name. + * + * `onlyKind` narrows the list (and fixes the kind a new flag gets); the + * currently held flag stays listed so a row never silently changes it. + * `onPick(id, created)` runs for a pick from the list (`created` false) and + * for a flag made through "New…" (`created` true) — the latter is when the + * host is about to re-send the options, so the caller rebuilds then. + */ +export function flagPickerRow( + refOptions: ComponentRefOptions, + current: string, + onlyKind: FlagKind | undefined, + onPick: (flagId: string, created: boolean) => void, +): Adw.ComboRow { + const flags = (refOptions.flags ?? []).filter((f) => !onlyKind || f.kind === onlyKind || f.value === current) + const options = flagPickerOptions(flags, current, { + none: _('(None)'), + create: _('New…'), + missing: _('Missing flag'), + }) + let settled = current + let reverting = false + const row = comboRow(_('Flag'), options, current, (value) => { + if (reverting) return + if (!isNewFlagChoice(value)) { + settled = value + onPick(value, false) + return + } + // Hand the row back to what it held while the name is asked for. + reverting = true + row.set_selected( + Math.max( + 0, + options.findIndex((o) => o.value === settled), + ), + ) + reverting = false + void createFlagFor(row, refOptions, flags, onlyKind, (id) => { + settled = id + onPick(id, true) + }) + }) + return row +} + +async function createFlagFor( + row: Adw.ComboRow, + refOptions: ComponentRefOptions, + flags: ReadonlyArray<{ value: string; label: string }>, + onlyKind: FlagKind | undefined, + onCreated: (flagId: string) => void, +): Promise { + const create = refOptions.createFlag + if (!create) return + const chosen = await promptNewFlag(row, onlyKind) + if (!chosen) return + // A name that is already a flag picks that flag: two flags of one name would read as one. + const id = + existingFlagId(chosen.name, flags) ?? + (cleanNewFlagName(chosen.name, flags) ? create(chosen.name, chosen.kind) : null) + if (id) onCreated(id) +} diff --git a/packages/gjs/src/widgets/editor/index.ts b/packages/gjs/src/widgets/editor/index.ts index 4c1cc82f..d2e562bd 100644 --- a/packages/gjs/src/widgets/editor/index.ts +++ b/packages/gjs/src/widgets/editor/index.ts @@ -17,6 +17,9 @@ export * from './brush-page' export * from './chrome-stages' export * from './component-inspector.model' export * from './component-inspector' +export * from './condition-editor' +export * from './condition-model' +export * from './condition-summary' export * from './depth-glyph.geometry' export * from './depth-glyph.probe' export * from './depth-glyph.story' @@ -31,6 +34,7 @@ export * from './event-action-list-editor.story' export * from './event-action-list-editor' export * from './event-action-model' export * from './event-action-summary' +export * from './flag-picker-row' export * from './flag-picker.model' export * from './floating-play' export * from './floating-zoom.story' diff --git a/packages/gjs/src/widgets/editor/new-flag-dialog.ts b/packages/gjs/src/widgets/editor/new-flag-dialog.ts index d28e3d3c..ab098a86 100644 --- a/packages/gjs/src/widgets/editor/new-flag-dialog.ts +++ b/packages/gjs/src/widgets/editor/new-flag-dialog.ts @@ -23,7 +23,7 @@ function kindLabels(): Record { * while the name is empty and Enter in the entry activates it; the kind * starts on yes/no, the common case. Resolves `null` on cancel. */ -export function promptNewFlag(parent: Gtk.Widget): Promise { +export function promptNewFlag(parent: Gtk.Widget, fixedKind?: FlagKind): Promise { return new Promise((resolve) => { const entry = new Gtk.Entry({ placeholderText: _('Name, like “Has the key”'), @@ -33,7 +33,7 @@ export function promptNewFlag(parent: Gtk.Widget): Promise const kinds = new Gtk.DropDown({ model: Gtk.StringList.new(FLAG_KINDS.map((k) => labels[k])) }) const box = new Gtk.Box({ orientation: Gtk.Orientation.VERTICAL, spacing: 12 }) box.append(entry) - box.append(kinds) + if (!fixedKind) box.append(kinds) const dialog = new Adw.AlertDialog({ heading: _('New flag'), @@ -49,7 +49,11 @@ export function promptNewFlag(parent: Gtk.Widget): Promise entry.connect('changed', () => dialog.set_response_enabled('create', entry.get_text().trim() !== '')) dialog.connect('response', (_d: Adw.AlertDialog, response: string) => { const name = entry.get_text().trim() - resolve(response === 'create' && name ? { name, kind: FLAG_KINDS[kinds.get_selected()] ?? 'yes-no' } : null) + resolve( + response === 'create' && name + ? { name, kind: fixedKind ?? FLAG_KINDS[kinds.get_selected()] ?? 'yes-no' } + : null, + ) }) dialog.present(parent) entry.grab_focus() 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 57c005b5..da281426 100644 --- a/packages/gjs/src/widgets/editor/phone-chrome.probe.spec.ts +++ b/packages/gjs/src/widgets/editor/phone-chrome.probe.spec.ts @@ -115,5 +115,15 @@ export default async () => { } expect(Math.abs(pills.contextSolo - CONTEXT_PILL_PX.solo)).toBeLessThanOrEqual(EXACT_PX) }) + + await it('keeps a selected gate with a condition and a counter action within the floor', async () => { + const cond = probe.probeConditionEditor() + console.log( + `[phone-chrome] sheet with a gate min ${cond.sheetMinPx} alloc ${cond.sheetAllocPx} (floor ${cond.floorPx})\n ${cond.offenders.map((r) => `${r.name} min ${r.min}`).join('\n ')}`, + ) + expect(cond.sheetMinPx).toBeLessThanOrEqual(cond.floorPx) + expect(cond.sheetAllocPx).toBe(cond.floorPx) + expect(cond.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 d4ac4b34..a1fb3b42 100644 --- a/packages/gjs/src/widgets/editor/phone-chrome.probe.ts +++ b/packages/gjs/src/widgets/editor/phone-chrome.probe.ts @@ -2,12 +2,16 @@ import Adw from '@girs/adw-1' import Gdk from '@girs/gdk-4.0' import type Graphene from '@girs/graphene-1.0' import Gtk from '@girs/gtk-4.0' +import { effectiveComponentRegistry } from '@pixelrpg/engine' +import GLib from '@girs/glib-2.0' +import { bindtextdomain, textdomain } from 'gettext' import packageStyle from '../../index.css' import type { ChromeStage } from './chrome-stages.ts' import { EditorPages } from './editor-pages.ts' import { pumpUntil, solidPaintable, solidPaintableRect } from './pixel-probe.ts' +import { RecentTiles } from './recent-tiles.ts' import { RECENT_TILES_MAX } from './recent-tiles.geometry.ts' import { SceneEditor } from './scene-editor.ts' import type { TileDescriptor } from './tile-palette.ts' @@ -259,3 +263,81 @@ export function probePillWidths(): PillWidths { window.destroy() return { editing, contextSolo } } + +/** What the sheet asks of a 360 px window once the Selected page holds a gate with a condition and a counter action. */ +export interface ConditionWidthReport { + floorPx: number + sheetMinPx: number + sheetAllocPx: number + /** Every descendant whose own minimum exceeds `floorPx`, outermost first. */ + offenders: WidthReport[] +} + +function scan(widget: Gtk.Widget, floorPx: number, depth: number, out: WidthReport[]): void { + // Unseen pages cost nothing; a scroller pans; the recent strip drops swatches that do not fit. + if (!widget.get_mapped() || widget instanceof RecentTiles) return + const r = report( + `${' '.repeat(depth)}${widget.constructor.name}${widget.get_name() && widget.get_name() !== widget.constructor.name ? `#${widget.get_name()}` : ''}`, + widget, + ) + if (r.min > floorPx) { + const chain: string[] = [] + for (let a = widget.get_parent(); a; a = a.get_parent()) chain.push(a.constructor.name) + out.push({ ...r, name: `${r.name.trim()} < ${chain.slice(0, 8).join(' < ')} visible=${widget.get_mapped()}` }) + } + if (widget instanceof Gtk.ScrolledWindow) return + for (let c = widget.get_first_child(); c; c = c.get_next_sibling()) scan(c, floorPx, depth + 1, out) +} + +/** Longest honest content: a counter flag with a long name, a counter action, a state condition. */ +export function probeConditionEditor(): 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) + pages.selected.setComponentRegistry(effectiveComponentRegistry({} as never)) + pages.selected.setRefOptions({ + flags: [{ value: 'coins', label: 'Coins collected in the whole village', kind: 'number' }], + } as never) + pages.selected.setPlacement({ + placementId: 'p-gate', + defId: null, + kind: 'Gate', + tileX: 3, + tileY: 4, + layerName: 'Objects', + paintable: null, + baseComponentTypes: [], + doorTarget: null, + definition: { + id: 'gate', + name: 'Gate', + components: [ + { type: 'trigger', on: 'walk-onto' }, + { type: 'actions', actions: [{ id: 'a1', type: 'change-counter', flag: 'coins', amount: 1 }] }, + ], + states: [{ id: 'open', when: { type: 'counter', flag: 'coins', op: '≥', value: 3 } }, { id: 'shut' }], + }, + } as never) + editor.setPlacementSelected('Gate') + window.present() + pumpUntil(() => editor.get_mapped() && editor._phone_bar.get_width() > 0, 'condition sheet window') + 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/scene-editor.blp b/packages/gjs/src/widgets/editor/scene-editor.blp index 9f52f1ee..36fb2986 100644 --- a/packages/gjs/src/widgets/editor/scene-editor.blp +++ b/packages/gjs/src/widgets/editor/scene-editor.blp @@ -556,7 +556,7 @@ template $PixelRpgSceneEditor : Adw.Bin { // than wrapped: at 360 px the buttons have the right of // way, and a two-line name would grow the docked bar. Gtk.Inscription selection_label { - min-chars: 4; + min-chars: 0; nat-chars: 8; xalign: 0.0; hexpand: true; diff --git a/packages/translations/de.po b/packages/translations/de.po index 8b0847c0..ec2be4aa 100644 --- a/packages/translations/de.po +++ b/packages/translations/de.po @@ -17,6 +17,28 @@ msgstr "" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" +msgid " and " +msgstr " und " + +msgid " or " +msgstr " oder " + +#, javascript-format +msgid "%1$s %2$s %3$s" +msgstr "%1$s %2$s %3$s" + +#, javascript-format +msgid "%1$s is No" +msgstr "%1$s ist Nein" + +#, javascript-format +msgid "%1$s is Yes" +msgstr "%1$s ist Ja" + +#, javascript-format +msgid "%1$s is “%2$s”" +msgstr "%1$s ist „%2$s“" + #, javascript-format msgid "%1$s → %2$s" msgstr "%1$s → %2$s" @@ -185,6 +207,9 @@ msgstr "Eine Tür führt ins Leere" msgid "A door the player opens to travel to another map." msgstr "Eine Tür, durch die man auf eine andere Karte gelangt." +msgid "A flag is" +msgstr "Ein Merker ist" + msgid "A flag is something the game remembers. Give it a name and say what it holds." msgstr "Eine Flagge ist etwas, das sich das Spiel merkt. Gib ihr einen Namen und sag, was sie speichert." @@ -197,6 +222,9 @@ msgstr "Eine Karte" msgid "A number" msgstr "Eine Zahl" +msgid "A number compares" +msgstr "Eine Zahl wird verglichen" + msgid "A pad that moves the player to another map / tile." msgstr "Ein Feld, das die Spielfigur auf eine andere Karte oder Kachel bringt." @@ -291,6 +319,9 @@ msgstr "Fähigkeit hinzufügen" msgid "Add an answer" msgstr "Antwort hinzufügen" +msgid "Add condition" +msgstr "Bedingung hinzufügen" + msgid "Add custom animation…" msgstr "Eigene Animation hinzufügen …" @@ -330,6 +361,9 @@ msgstr "Alle" msgid "All layers on this map" msgstr "Alle Ebenen dieser Karte" +msgid "All of these" +msgstr "Alle davon" + msgid "Also counts as this" msgstr "Zählt auch als dieser" @@ -361,6 +395,9 @@ msgstr "Antwort %d" msgid "Answer text" msgstr "Text der Antwort" +msgid "Any of these" +msgstr "Eine davon" + msgid "Appearance" msgstr "Erscheinungsbild" @@ -452,6 +489,20 @@ msgstr "Abbrechen" msgid "Cancel answer" msgstr "Antwort beim Abbrechen" +msgid "Change by" +msgstr "Ändern um" + +msgid "Change counter" +msgstr "Zähler ändern" + +#, javascript-format +msgid "Change “%1$s” by %2$s" +msgstr "Ändere „%1$s“ um %2$s" + +#, javascript-format +msgid "Change “%1$s” by +%2$s" +msgstr "Ändere „%1$s“ um +%2$s" + #. The host's detail header takes its title from here — also when the #. pane is not attached yet, so a roster that arrives during #. construction still names the header. @@ -532,9 +583,15 @@ msgstr "Spalten" msgid "Comes from %s" msgstr "Kommt von %s" +msgid "Compare" +msgstr "Vergleich" + msgid "Component options" msgstr "Komponentenoptionen" +msgid "Condition" +msgstr "Bedingung" + msgid "Connecting…" msgstr "Verbindung wird hergestellt …" @@ -905,9 +962,16 @@ msgstr "Boden" msgid "Ground brushes" msgstr "Boden-Pinsel" +msgid "Has an item" +msgstr "Hat einen Gegenstand" + msgid "Has collision" msgstr "Hat Kollision" +#, javascript-format +msgid "Has item %1$s" +msgstr "Hat Gegenstand %1$s" + msgid "Hatch every tile the hero cannot walk through" msgstr "Jede Kachel schraffieren, durch die die Heldenfigur nicht laufen kann" @@ -1011,12 +1075,21 @@ msgstr "Einladungslink kopiert." msgid "Invite someone to this project" msgstr "Jemanden zu diesem Projekt einladen" +msgid "Is" +msgstr "Ist" + +msgid "Is yes" +msgstr "Ist Ja" + msgid "Item" msgstr "Gegenstand" msgid "Item id" msgstr "Gegenstands-ID" +msgid "Items arrive later" +msgstr "Gegenstände kommen später" + #, javascript-format msgid "Its settings are kept, and work again once “%s” is on" msgstr "Die Einstellungen bleiben erhalten und wirken wieder, sobald „%s“ eingeschaltet ist" @@ -1255,7 +1328,7 @@ msgid "New thing" msgstr "Neues Ding" msgid "New…" -msgstr "Neu …" +msgstr "…" msgid "No actions yet" msgstr "Noch keine Aktionen" @@ -1341,6 +1414,9 @@ msgstr "Keine" msgid "None (passive)" msgstr "Keine (passiv)" +msgid "None of this" +msgstr "Nichts davon" + msgid "None yet" msgstr "Noch keine" @@ -1359,6 +1435,10 @@ msgstr "Wird nicht in deinem Spiel gespeichert." msgid "Not used by any map" msgstr "Von keiner Karte verwendet" +#, javascript-format +msgid "Not: %1$s" +msgstr "Nicht: %1$s" + msgid "Nothing found. Tiles drawn on a solid background cannot be told apart this way — use New brush… instead." msgstr "Nichts gefunden. Kacheln auf einfarbigem Hintergrund lassen sich so nicht unterscheiden — verwende stattdessen „Neuer Pinsel …“." @@ -1387,6 +1467,9 @@ msgstr "Tippe jetzt auf die Kachel, die dieses Teil verwenden soll." msgid "Nowhere yet" msgstr "Noch nirgendwohin" +msgid "Number" +msgstr "Zahl" + msgid "Offset X" msgstr "Versatz X" @@ -1654,6 +1737,9 @@ msgstr "Antwort entfernen" msgid "Remove component" msgstr "Komponente entfernen" +msgid "Remove condition" +msgstr "Bedingung entfernen" + msgid "Remove from credits" msgstr "Aus den Mitwirkenden entfernen" @@ -2003,6 +2089,9 @@ msgstr "Diese Antwort wird gewählt, wenn du zurückgehst." msgid "The character the player moves around." msgstr "Die Figur, die die Spielerin oder der Spieler steuert." +msgid "The game has no items yet, so a condition with an item never holds." +msgstr "Das Spiel hat noch keine Gegenstände, deshalb trifft eine Bedingung mit einem Gegenstand nie zu." + #, javascript-format msgid "The game now starts on “%s”" msgstr "Das Spiel beginnt jetzt auf „%s“" @@ -2256,6 +2345,13 @@ msgstr "Was gesagt wird" msgid "What the tile grid is set to when you open a map" msgstr "Wie das Kachelraster beim Öffnen einer Karte eingestellt ist" +msgid "When" +msgstr "Wenn" + +#, javascript-format +msgid "When “%s”" +msgstr "Wenn „%s“" + msgid "Where is it?" msgstr "Wo ist es?" @@ -2382,6 +2478,9 @@ msgstr "„%s“ wird noch an %d Stelle(n) verwendet (Figuren oder Karten). Lös msgid "“%s” will be removed from the project. Characters using it lose their look until reassigned. This cannot be undone." msgstr "„%s“ wird aus dem Projekt entfernt. Figuren, die es verwenden, verlieren ihr Aussehen, bis ihnen ein neues zugewiesen wird. Das lässt sich nicht rückgängig machen." +msgid "…" +msgstr "…" + #, javascript-format msgid "→ %s" msgstr "→ %s" diff --git a/packages/translations/org.pixelrpg.maker.pot b/packages/translations/org.pixelrpg.maker.pot index f2462564..14434183 100644 --- a/packages/translations/org.pixelrpg.maker.pot +++ b/packages/translations/org.pixelrpg.maker.pot @@ -18,6 +18,28 @@ msgstr "" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n" +msgid " and " +msgstr "" + +msgid " or " +msgstr "" + +#, javascript-format +msgid "%1$s %2$s %3$s" +msgstr "" + +#, javascript-format +msgid "%1$s is No" +msgstr "" + +#, javascript-format +msgid "%1$s is Yes" +msgstr "" + +#, javascript-format +msgid "%1$s is “%2$s”" +msgstr "" + #, javascript-format msgid "%1$s → %2$s" msgstr "" @@ -186,6 +208,9 @@ msgstr "" msgid "A door the player opens to travel to another map." msgstr "" +msgid "A flag is" +msgstr "" + msgid "A flag is something the game remembers. Give it a name and say what it holds." msgstr "" @@ -198,6 +223,9 @@ msgstr "" msgid "A number" msgstr "" +msgid "A number compares" +msgstr "" + msgid "A pad that moves the player to another map / tile." msgstr "" @@ -292,6 +320,9 @@ msgstr "" msgid "Add an answer" msgstr "" +msgid "Add condition" +msgstr "" + msgid "Add custom animation…" msgstr "" @@ -331,6 +362,9 @@ msgstr "" msgid "All layers on this map" msgstr "" +msgid "All of these" +msgstr "" + msgid "Also counts as this" msgstr "" @@ -362,6 +396,9 @@ msgstr "" msgid "Answer text" msgstr "" +msgid "Any of these" +msgstr "" + msgid "Appearance" msgstr "" @@ -453,6 +490,20 @@ msgstr "" msgid "Cancel answer" msgstr "" +msgid "Change by" +msgstr "" + +msgid "Change counter" +msgstr "" + +#, javascript-format +msgid "Change “%1$s” by %2$s" +msgstr "" + +#, javascript-format +msgid "Change “%1$s” by +%2$s" +msgstr "" + #. The host's detail header takes its title from here — also when the #. pane is not attached yet, so a roster that arrives during #. construction still names the header. @@ -533,9 +584,15 @@ msgstr "" msgid "Comes from %s" msgstr "" +msgid "Compare" +msgstr "" + msgid "Component options" msgstr "" +msgid "Condition" +msgstr "" + msgid "Connecting…" msgstr "" @@ -906,9 +963,16 @@ msgstr "" msgid "Ground brushes" msgstr "" +msgid "Has an item" +msgstr "" + msgid "Has collision" msgstr "" +#, javascript-format +msgid "Has item %1$s" +msgstr "" + msgid "Hatch every tile the hero cannot walk through" msgstr "" @@ -1012,12 +1076,21 @@ msgstr "" msgid "Invite someone to this project" msgstr "" +msgid "Is" +msgstr "" + +msgid "Is yes" +msgstr "" + msgid "Item" msgstr "" msgid "Item id" msgstr "" +msgid "Items arrive later" +msgstr "" + #, javascript-format msgid "Its settings are kept, and work again once “%s” is on" msgstr "" @@ -1342,6 +1415,9 @@ msgstr "" msgid "None (passive)" msgstr "" +msgid "None of this" +msgstr "" + msgid "None yet" msgstr "" @@ -1360,6 +1436,10 @@ msgstr "" msgid "Not used by any map" msgstr "" +#, javascript-format +msgid "Not: %1$s" +msgstr "" + msgid "Nothing found. Tiles drawn on a solid background cannot be told apart this way — use New brush… instead." msgstr "" @@ -1388,6 +1468,9 @@ msgstr "" msgid "Nowhere yet" msgstr "" +msgid "Number" +msgstr "" + msgid "Offset X" msgstr "" @@ -1655,6 +1738,9 @@ msgstr "" msgid "Remove component" msgstr "" +msgid "Remove condition" +msgstr "" + msgid "Remove from credits" msgstr "" @@ -2004,6 +2090,9 @@ msgstr "" msgid "The character the player moves around." msgstr "" +msgid "The game has no items yet, so a condition with an item never holds." +msgstr "" + #, javascript-format msgid "The game now starts on “%s”" msgstr "" @@ -2257,6 +2346,13 @@ msgstr "" msgid "What the tile grid is set to when you open a map" msgstr "" +msgid "When" +msgstr "" + +#, javascript-format +msgid "When “%s”" +msgstr "" + msgid "Where is it?" msgstr "" @@ -2383,6 +2479,9 @@ msgstr "" msgid "“%s” will be removed from the project. Characters using it lose their look until reassigned. This cannot be undone." msgstr "" +msgid "…" +msgstr "" + #, javascript-format msgid "→ %s" msgstr "" diff --git a/scripts/capture-views.py b/scripts/capture-views.py index acd3eea2..c0a6ec10 100755 --- a/scripts/capture-views.py +++ b/scripts/capture-views.py @@ -32,6 +32,7 @@ NEWGAME_SHOTS = ["20-new-game-opened", "21-new-game-painted", "22-coach-brush", "23-coach-play", "24-second-new-game"] LANG_SHOTS = ["25-game-languages", "25b-inspector-language-toggle"] FLAG_SHOTS = ["26-flag-picker", "26b-flag-picker-open", "26c-flag-new"] +COND_SHOTS = ["27-condition-editor", "27b-change-counter"] NEWMAP_SHOTS = ["18-new-map-dialog", "18b-new-map-created", "18c-new-map-shelf"] ap = argparse.ArgumentParser() @@ -43,7 +44,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 +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 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: @@ -685,6 +686,62 @@ def capture_flags(tier, w, h): p.wait() +def runtime_flags(): + s = status() + return ((s or {}).get("runtime") or {}).get("flags") + + +def capture_conditions(tier, w, h): + # A "Coins >= 3" state on p-gate and a "change Coins by +1" action on + # p-purse (both need a project that carries them: see COND_PROJECT in + # the README of the PR). The play-test starts the game four times: each + # start adds 1 to Coins, and the gate's state flips once Coins reaches 3. + 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") + for placement, name in (("p-gate", "27-condition-editor"), ("p-purse", "27b-change-counter")): + act("select-placement", placement) + act("sheet-page", "selected") + time.sleep(1.5) + if tier == "phone-360" and os.environ.get("HOLD_INPUT"): + # drag the sheet up so the condition editor shows (a local input helper with a drag step); + # run on a monitor the size of the window (headless-run --size WxH) + subprocess.run(["gjs", "-m", os.environ["HOLD_INPUT"], "drag", str(w // 2), os.environ.get("HANDLE_Y", "418"), "0"], timeout=60) + time.sleep(1) + subprocess.run(["gjs", "-m", os.environ["HOLD_INPUT"], "scroll", str(w // 2), "500", "12"], timeout=60) + time.sleep(1.5) + shot(tier, name) + if tier == "wide-1920" and not args.lang: + act("play") + time.sleep(4) + lib = os.environ["HEADLESS_RUN_LIB"] + print("START", runtime_flags(), (status() or {}).get("runtime", {}).get("playerTile")) + for key, label, ms in tuple((0xff52 if d == "up" else 0xff54, d, 700) for d in ("up", "down", "up", "down", "up", "up")): + subprocess.run(["gjs", "-m", os.environ.get("HOLD_INPUT", os.path.join(lib, "headless-input.js")), "hold", str(key), str(ms)], timeout=30) + time.sleep(1) + rt = (status() or {}).get("runtime") or {} + print("STEP", label, rt.get("playerTile"), rt.get("flags")) + 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) @@ -711,6 +768,10 @@ def capture_flags(tier, w, h): for tier, w, h in [("phone-360", 360, 720), ("wide-1920", 1920, 1200)]: capture_flags(tier, w, h) +if ONLY and ONLY & set(COND_SHOTS): + for tier, w, h in [("phone-360", 360, 720), ("wide-1920", 1920, 1200)]: + capture_conditions(tier, w, h) + if ONLY and ONLY & set(LANG_SHOTS): for tier, w, h in [("phone-360", 360, 720), ("wide-1920", 1920, 1200)]: capture_languages(tier, w, h)