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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions apps/maker-gjs/data/org.pixelrpg.maker.gschema.xml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,20 @@
the dialog writes here too, so the two cannot disagree.
</description>
</key>
<key name="player-id" type="s">
<default>''</default>
<summary>Who you are in a saved playthrough</summary>
<description>
The key your half of a game's save record is filed under —
where you stood, and later what you carry. Stable across
launches, which is exactly what a peer id is not: a peer id is
new every session, so a position filed under one would be lost
on reconnect. Empty means "not generated yet"; the first read
writes a random id and keeps it. A fact about the person at the
keyboard, never shared with collaborators and never part of a
project.
</description>
</key>
<key name="coach-marks-seen" type="as">
<default>[]</default>
<summary>First-run tips already shown</summary>
Expand Down
19 changes: 19 additions & 0 deletions apps/maker-gjs/src/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { CollabIdentityService } from './services/collab-identity.service.ts'
import { ControlDbusService } from './services/control-dbus.service.ts'
import { cleanupOrphanedPublishers } from './services/orphan-publisher-cleanup.ts'
import { lookupAppSettings } from './services/app-settings.ts'
import { playerIdentity } from './services/player-identity.ts'
import { CoachMarksService } from './services/coach-marks.service.ts'
import { EditorDefaultsService } from './services/editor-defaults.service.ts'
import { type PixelrpgIntent, pickPixelrpgIntent } from './services/pixelrpg-url.ts'
Expand Down Expand Up @@ -85,6 +86,21 @@ export class Application extends Adw.Application {
*/
readonly collabIdentityService = new CollabIdentityService()

/**
* Who the person at this keyboard is in a game's save record
* (GSettings `player-id`) — the key the engine files `players[id]`
* under. Read once in {@link onStartup}, because the first read is
* also the write that creates it: asking twice before the window
* exists would be two ids for one person. `undefined` until then;
* the engine falls back to its own default.
*/
private _playerId: string | undefined

/** The save-record key of the local player; `undefined` before startup. */
get playerId(): string | undefined {
return this._playerId
}

static {
GObject.registerClass(
{
Expand Down Expand Up @@ -137,6 +153,8 @@ export class Application extends Adw.Application {
this.editorDefaultsService.init(settings)
this.coachMarksService.init(settings)
this.collabIdentityService.init(settings)
// Not a service: one value, generated on first read and then fixed.
this._playerId = playerIdentity(settings)
this.initControlInterface()
// Opt-in @gjsify/devtools control plane (`org.gjsify.Devtools`) — the
// standard interface `gjsify debug` (MCP) + a `gdbus` Screenshot speak,
Expand Down Expand Up @@ -324,6 +342,7 @@ export class Application extends Adw.Application {
this.editorDefaultsService,
this.collabIdentityService,
this.coachMarksService,
this._playerId,
)

active_window.present()
Expand Down
5 changes: 5 additions & 0 deletions apps/maker-gjs/src/services/flags-edit.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ export default async () => {
expect(newFlag([], 'Mood', 'text').initial).toBe('')
})

await it('takes the scope it is given, so a per-thing flag stays per-thing', async () => {
expect(newFlag([], 'Chest open', 'yes-no', 'thing').scope).toBe('thing')
expect(newFlag([], 'Chest open', 'yes-no').scope).toBe('game')
})

await it('never reuses an id of the list, even for the same name', async () => {
const a = newFlag([], 'Key')
const b = newFlag([a], 'Key')
Expand Down
16 changes: 13 additions & 3 deletions apps/maker-gjs/src/services/flags-edit.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
type FlagData,
type FlagKind,
type FlagScope,
type FlagUsage,
defaultFlagInitial,
findFlagUsages,
Expand All @@ -26,9 +27,18 @@ export type FlagRemoveResult =
| { removed: false; reason: 'unknown' }
| { removed: false; reason: 'in-use'; usage: FlagUsage[] }

/** A flag called `name` with the kind's default start value and a free id. */
export function newFlag(list: readonly FlagData[], name: string, kind: FlagKind = 'yes-no'): FlagData {
return { id: newFlagId(list, name), name: name.trim(), kind, initial: defaultFlagInitial(kind), scope: 'game' }
/**
* A flag called `name` with the kind's default start value and a free id.
* `scope` says whose memory it is: one value for the game, or one per
* placed thing — see `docs/concepts/save-record.md`.
*/
export function newFlag(
list: readonly FlagData[],
name: string,
kind: FlagKind = 'yes-no',
scope: FlagScope = 'game',
): FlagData {
return { id: newFlagId(list, name), name: name.trim(), kind, initial: defaultFlagInitial(kind), scope }
}

/** Where `flagId` is referenced, across the library and every loaded map. */
Expand Down
47 changes: 47 additions & 0 deletions apps/maker-gjs/src/services/player-identity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import GLib from '@girs/glib-2.0'
import type Gio from '@girs/gio-2.0'

/**
* Who this installation is in a saved playthrough (GSettings key
* `player-id`) — the key the engine files `players[id]` under.
*
* Generated once and kept, because a save is only worth keeping if the
* person it belongs to can be found again: an id that changed per launch
* would orphan every position it ever wrote. That is also why the peer
* id of a shared session cannot serve here — `generatePeerId()` is new
* every session by design. See `docs/concepts/save-record.md`.
*
* A fact about the person at the keyboard, like the view tier and the
* collaborator colour: it follows them across projects, is never written
* into a project, and is never sent to collaborators.
*
* Unlike `collab-name` and `collab-colour`, the default is *stored
* rather than derived*: there is nothing in the system to derive a save
* key from, and a value that cannot be recomputed must be written down
* the first time it exists. Falls back to a session-only id with a
* warning when the schema is unavailable, so an unpackaged build still
* plays — its save simply does not outlive the run, which is already
* true of every playtest.
*/
export function playerIdentity(settings: Gio.Settings | null): string {
if (!settings) {
console.warn('[playerIdentity] GSettings schema not found — this run gets a throwaway player id')
return generatePlayerId()
}
const stored = settings.get_string('player-id')
if (stored && stored.length > 0) return stored
const fresh = generatePlayerId()
settings.set_string('player-id', fresh)
return fresh
}

/**
* A new save key: `player-` plus a UUID.
*
* A UUID rather than the shorter random token `generatePeerId()` builds,
* because two people whose records are merged into one world must not
* collide, and a merge has no referee to break a tie with.
*/
export function generatePlayerId(): string {
return `player-${GLib.uuid_string_random()}`
}
8 changes: 8 additions & 0 deletions apps/maker-gjs/src/services/project-store.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1298,6 +1298,14 @@ export default async () => {
expect(store.pruneUnusedPickerFlags()).toStrictEqual([])
})

await it('createFlag stores the scope the picker asked for', async () => {
const { store, data } = makeStore(makeProjectData({ flags: [] }))
const perThing = store.createFlag('Chest open', 'yes-no', 'thing')
const perGame = store.createFlag('Has the map')
expect(data.flags?.find((f) => f.id === perThing)?.scope).toBe('thing')
expect(data.flags?.find((f) => f.id === perGame)?.scope).toBe('game')
})

await it('applies remote flag ops without re-broadcasting', async () => {
const { store, data } = makeStore()
const session = makeSession()
Expand Down
13 changes: 7 additions & 6 deletions apps/maker-gjs/src/services/project-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
FLAG_UPSERT_KIND,
type FlagData,
type FlagKind,
type FlagScope,
findFlagUsages,
type CreditEntry,
effectiveComponentRegistry,
Expand Down Expand Up @@ -329,29 +330,29 @@ export class ProjectStore {
appearances: RefOption[]
languages: ProjectLanguages
flags: FlagOption[]
createFlag: (name: string, kind?: FlagKind) => string | null
createFlag: (name: string, kind?: FlagKind, scope?: FlagScope) => string | null
} {
const resource = this.resource
return {
...buildRefOptions(resource?.data?.maps, resource?.spriteSets, undefined, this.flags()),
languages: this.languages(),
createFlag: (name, kind) => this.createFlag(name, kind),
createFlag: (name, kind, scope) => this.createFlag(name, kind, scope),
}
}

/** Told after {@link createFlag} made a flag (the window shows a toast). */
onFlagCreated: ((flag: FlagData) => void) | null = null

/**
* The picker's "New…": make a yes/no flag called `name` and return its
* id (`null` for an empty name). No Undo toast: the action that asked
* The picker's "New…": make a flag called `name` of `kind` and `scope`
* and return its id (`null` for an empty name). No Undo toast: the action that asked
* for it uses the flag at once, and a used flag cannot be removed. The
* flag is remembered so {@link pruneUnusedPickerFlags} can take it back
* when an undo leaves nothing using it.
*/
createFlag(name: string, kind: FlagKind = 'yes-no'): string | null {
createFlag(name: string, kind: FlagKind = 'yes-no', scope: FlagScope = 'game'): string | null {
if (!name.trim()) return null
const made = this.upsertFlag(newFlag(this.flags(), name, kind))
const made = this.upsertFlag(newFlag(this.flags(), name, kind, scope))
if (!made) return null
if (!made.previous) this._pickerFlags.add(made.flag.id)
this.onFlagCreated?.(made.flag)
Expand Down
12 changes: 11 additions & 1 deletion apps/maker-gjs/src/widgets/application-window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,9 @@ export class ApplicationWindow extends Adw.ApplicationWindow implements EntityDe
const engine = new Engine()
// A test language chosen before the engine existed still applies.
engine.setPlayLocale(this._testLocale)
// Who a test run saves as. Fixed for the window's lifetime, so
// unlike the locale it never has to be re-applied later.
engine.setLocalPlayerId(this._playerId)
return engine
},
)
Expand Down Expand Up @@ -564,6 +567,13 @@ export class ApplicationWindow extends Adw.ApplicationWindow implements EntityDe
private readonly _editorDefaults: EditorDefaultsService,
private readonly _collabIdentity: CollabIdentityService,
private readonly _coachMarks: CoachMarksService,
/**
* Who the person here is in a game's save record
* (`players[playerId]`) — supplied by the application, which read it
* from GSettings. `undefined` leaves the engine on its own default.
* See `docs/concepts/save-record.md`.
*/
private readonly _playerId?: string,
) {
super({ application })
this._installActions()
Expand Down Expand Up @@ -635,7 +645,7 @@ export class ApplicationWindow extends Adw.ApplicationWindow implements EntityDe
* extraction).
*/
private _wireStoreEvents(): void {
this._scene_editor_view.flagCreator = (name, kind) => this._projectStore.createFlag(name, kind)
this._scene_editor_view.flagCreator = (name, kind, scope) => this._projectStore.createFlag(name, kind, scope)
this._projectStore.onFlagCreated = (flag) => this._showToast(_('Added flag “%s”').replace('%s', flag.name))
this._projectStore.on('flags-changed', () => this._scene_editor_view.refreshFlagOptions())
this._projectStore.on('notice', (notice) => this._showToast(this._noticeText(notice)))
Expand Down
5 changes: 3 additions & 2 deletions apps/maker-gjs/src/widgets/scene-editor-view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
effectiveComponentRegistry,
type EntityDefinition,
type FlagKind,
type FlagScope,
type LayerPlane,
makeTileStamp,
type MapData,
Expand Down Expand Up @@ -175,7 +176,7 @@ export class SceneEditorView extends ResponsiveEditorView {
private _mapData: MapData | null = null
private _refProject: LoadedProject | null = null
/** Makes a flag for the action pickers' "New…"; the window points it at the ProjectStore. */
flagCreator: ((name: string, kind?: FlagKind) => string | null) | null = null
flagCreator: ((name: string, kind?: FlagKind, scope?: FlagScope) => string | null) | null = null
/** The project's entity library, for resolving a placement to its definition. */
private _entityLibrary: readonly EntityDefinition[] = []
/** Sprite sheets behind the placement sprites, keyed by sprite-set id. */
Expand Down Expand Up @@ -1035,7 +1036,7 @@ export class SceneEditorView extends ResponsiveEditorView {
const data = project.resource.data
this._pages.selected.setRefOptions({
...buildRefOptions(data?.maps, project.resource.spriteSets, data?.languages, data?.flags),
createFlag: (name, kind) => this.flagCreator?.(name, kind) ?? null,
createFlag: (name, kind, scope) => this.flagCreator?.(name, kind, scope) ?? null,
})
}

Expand Down
1 change: 1 addition & 0 deletions docs/concepts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ Ordered by dependency — read top-to-bottom for the cleanest mental sequence. E
| [`entity-and-appearance-model.md`](entity-and-appearance-model.md) | **The target content model** — explicit `components[]` on entity definitions (replaces `ObjectKind`-switch + properties union), component registry with schema-generated inspectors, templates as the RPG-Maker-style authoring surface, declarative states, **Appearance** (sheet + animations) as a shared asset layer. Folds the Cast "Characters"/"Sprite sheets" split in; where the built-in code editor attaches. |
| [`game-systems.md`](game-systems.md) | **What a project is made of** — `GameSystemSpec`: the switchable bundle of components, templates and ECS systems a user turns on ("my game has fighting"), distinct from an ECS `System`. Component ownership (exactly one owner, machine-checked), the effective registry, dormant-vs-unknown, the `__project/systems.set` channel, the Game-rules page, and the flag store + conditional states the base layer ships. |
| [`action-sequencer.md`](action-sequencer.md) | **A list that can pause** — the run as a stack of frames on the triggering entity (`ActionRunComponent`), the control lock on the session singleton (`ControlLockComponent`) that takes input intent without stopping the world, re-trigger guards, scene unload, what each peer runs, and the save's "at rest" definition. |
| [`save-record.md`](save-record.md) | **What a playthrough remembers** — the `world` / `players` split of the save record: game-scoped flag values, thing-scoped values keyed by placement id (so two chests are two memories under one flag), removed-thing markers, per-player position. Where the player id comes from, how `scope: thing` resolves into the view `evaluateCondition` reads, and what the bag and the save file add later. |
| [`collaboration-and-multiplayer.md`](collaboration-and-multiplayer.md) | **Multi-peer sync** — Op-Log with Host-Sequencer (Player 1) for both collaborative editing and networked multiplayer. Single mechanism, two op vocabularies. Solo edits work locally; collab requires a host. |
| [`ai-collaborator.md`](ai-collaborator.md) | **In-process AI as live peer** — virtual collaborator on the shared op-log + awareness (cursor, presence, follow), driven via D-Bus/MCP, relayed to remote peers. |

Expand Down
5 changes: 5 additions & 0 deletions docs/concepts/collaboration-and-multiplayer.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,8 @@ type GameOp =

Note the symmetry with editor ops: every op references stable IDs, carries enough state for application, and is host-validated before broadcast.

`playerId` here is the save record's player key — a stable per-device id, never a peer id, which is fresh per session. `object.removed` lands in `world.removedThings` and a `set-flag` on a thing in `world.things[placementId]`; both are the host's to write. See [`save-record.md`](save-record.md).

The host **runs the simulation** locally. Non-host peers send `input.frame` ops; the host runs its physics + game systems and produces the `player.moved` / `object.removed` / `item.granted` ops as the **broadcast result**.

For non-host peers, "playing the game" is essentially watching a stream of ops + sending input ops back. Their local engine applies the broadcasts to mirror the host's state.
Expand Down Expand Up @@ -263,6 +265,8 @@ SpriteData.tileProperties // shared (via __project/spriteset.update.chunk

// game — replicated via game op-log (host-authoritative; future)
TileTransformComponent (player) // host derives + broadcasts via player.moved
GameSaveStateComponent.world // host-authoritative (flags, things, removedThings)
GameSaveStateComponent.players[] // the peer playing that player writes; host validates
PlayerHealthComponent (future) // host-authoritative
InventoryComponent (future) // host-authoritative

Expand Down Expand Up @@ -385,6 +389,7 @@ Most of the shared work lands *implicitly* as we land the earlier object-system
- [`editor-architecture.md`](editor-architecture.md) — the operation-oriented mutation API + `Command` interface defined there **IS** the editor op vocabulary. Phase 5 (Undo) implicitly designs the editor op-log for us. Phase 0 constraints in this doc fold back into editor-architecture's migration phases.
- [`runtime-modes.md`](runtime-modes.md) — Live Run and Test Run share a single peer's simulation; they're not multiplayer-aware. Full Run with multiplayer is where the game op-log machinery activates. The mode markers themselves are local-only — `EditorMode` / `RuntimeMode` / `SpawnOverride` never replicate.
- [`object-system.md`](object-system.md) — stable identifiers (`ObjectPlacement.id`, `EntityDefinition.id`) are what editor op payloads are keyed on. The transport-compatibility constraint covered in Phase 0 means future schema changes must preserve "stable keys in array-shaped collections, no circular refs, JSON-serialisable everywhere".
- [`save-record.md`](save-record.md) — the state behind the game op vocabulary: `world` (host-authoritative: flags, thing flag values, removed things) and `players[playerId]` (position, written by the peer playing it). The split is what makes "who may write this" a question with an answer; phase 6 replicates it.

## Open questions

Expand Down
2 changes: 1 addition & 1 deletion docs/concepts/entity-and-appearance-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ interface EntityState {
}
```

A door (closed/open), a day/night NPC, a quest-stage marker. State evaluation is `StateSystem` (`packages/engine/src/systems/state.system.ts`) reading the flag store `FlagSystem` folds `FLAG_SET` into (`GameSaveStateComponent` on the session singleton).
A door (closed/open), a day/night NPC, a quest-stage marker. State evaluation is `StateSystem` (`packages/engine/src/systems/state.system.ts`) reading the save record `FlagSystem` folds `FLAG_SET` into (`GameSaveStateComponent` on the session singleton). A `scope: 'thing'` flag resolves per placement, so two chests sharing one flag remember separately — see [`save-record.md`](save-record.md).

The condition vocabulary is a small typed union (`flag-is`, `counter`, `has-item`, one level of `all` / `any` / `not`), with `{ flag, equals? }` kept as shorthand for `flag-is` — see [`game-systems.md`](game-systems.md). An expression DSL nobody validates is still refused. Any other `when` is a validation warning and never matches, so a project from a newer editor still opens.

Expand Down
Loading
Loading