Import cartridge .sav files with verified structure, checksums and clock (Closes #44)

Savegames → Import backup now reads an English Crystal .sav (from an
emulator, a cartridge dump or the 3DS Virtual Console's sav.dat) and
converts it into a native save after a preview.

- world/cartridge-save.ts: picks the copy TryLoadSaveFile would load
  (check values and checksums of the main copy, else the backup), reads
  the saved WRAM block, the numbered boxes, mail backups, Hall of Fame and
  Battle Tower by PRET labels (SRAM, SAVE_BLOCK in the profile, checked by
  check:reference with the SAV constants), engine flags via EngineFlags,
  scenes via MapScenes, and the map's objects and masks.
- Clock: an emulator MBC3 footer plus the time since it was written,
  FixDays/FixTime with wStart*, mapped to the minute and weekday offsets;
  without one, the device's time and the saved wCurDay. Day countdowns
  move with the day difference.
- Refused with the reason: unported maps, the Bug-Catching Contest, a
  Battle Tower challenge, characters outside the naming screen.
- Names keep <PK>/<MN> as ᴾᴷ/ᴹᴺ (one character, one tile); trainer names
  accept the naming screen's alphabet; boxed Eggs validate; native states
  up to 256 kB load (a full PC exceeded 64 kB).
- Tests: the committed debug saves, layout offsets against the symbols,
  backup fallback, clock footers, day counters, refusals, slot session
  and the Savegames flow in Chromium and WebKit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
kawaandClaude Opus 5.5 committed 2026-10-17 12:03:01 +02:00
1 parent 87b05b45f4
commit 592ca43a40
20 files changed
+1821 -40

No files matched your search

+80 -4
View File
@@ -15,6 +15,21 @@ export interface SlotRuntime extends GameRuntime {
reset(): void;
summary(): SlotSummary;
inspectState(state: Uint8Array): { summary: SlotSummary; schema: number };
/** A cartridge .sav as a native state; throws with the player-facing
* reason when it cannot be imported. */
convertCartridge(file: Uint8Array): {
state: Uint8Array;
copy: "main" | "backup";
clock: "rtc" | "device";
notes: string[];
};
}
/** How a cartridge save was converted (see game/world/cartridge-save). */
export interface CartridgeImport {
copy: "main" | "backup";
clock: "rtc" | "device";
notes: string[];
}
export interface SlotEntry {
@@ -37,6 +52,8 @@ export type ImportPreview =
/** Slots of the same trainer (name and ID), newest first;
* `identical` when the slot's newest record holds the same game. */
conflicts: { slot: SaveSlot; identical: boolean }[];
/** Present when the file was a cartridge save. */
cartridge?: CartridgeImport;
}
| {
ok: false;
@@ -326,12 +343,71 @@ export class SlotSession {
identity,
};
}
return {
ok: true,
record,
...inspected,
conflicts: await this.conflicts(record, inspected.summary),
};
}
/** Checks a cartridge save (.sav) the same way: converted to a native
* save on this game's clock, then loaded into a separate world. The
* file's modification time stands for when it was saved. */
async previewCartridge(
file: Uint8Array,
modified: Date,
): Promise<ImportPreview> {
if (!this.romHash)
throw new Error("Load your ROM before importing a backup.");
const savedAt = Number.isFinite(modified.getTime())
? modified.toISOString()
: new Date().toISOString();
let converted: ReturnType<SlotRuntime["convertCartridge"]>;
try {
converted = this.runtime.convertCartridge(file);
} catch (error) {
return {
ok: false,
reason: error instanceof Error ? error.message : String(error),
identity: { savedAt },
};
}
const { state, ...cartridge } = converted;
const record: SaveRecord = {
version: 1,
romHash: this.romHash,
coreId: this.runtime.id,
savedAt,
state,
};
let inspected: ReturnType<SlotRuntime["inspectState"]>;
try {
inspected = this.runtime.inspectState(record.state);
} catch (error) {
return {
ok: false,
reason: `The converted game did not pass the port's checks: ${error instanceof Error ? error.message : String(error)}`,
identity: { savedAt },
};
}
return {
ok: true,
record,
...inspected,
conflicts: await this.conflicts(record, inspected.summary),
cartridge,
};
}
/** Slots of the same trainer as an import, newest first. */
private async conflicts(record: SaveRecord, summary: SlotSummary) {
const conflicts = [];
for (const listed of await this.store.list(this.romHash)) {
for (const listed of await this.store.list(this.romHash!)) {
const slot = await this.withSummary(listed);
if (
slot.summary?.player !== inspected.summary.player ||
slot.summary.playerId !== inspected.summary.playerId
slot.summary?.player !== summary.player ||
slot.summary.playerId !== summary.playerId
)
continue;
const newest = (await this.store.records(slot.id))[0]?.record.state;
@@ -343,7 +419,7 @@ export class SlotSession {
newest.every((byte, index) => byte === record.state[index]),
});
}
return { ok: true, record, ...inspected, conflicts };
return conflicts;
}
/** Imports a previewed backup into a new slot, or over a slot (whose