@henols/c64-re-tools 2.5.0 → 2.5.1-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -202,7 +202,7 @@ The folder `--out` gets these files:
202
202
  - `image.bin`: all 64 KiB of RAM at the entry. This RAM includes the RAM under the ROMs and the I/O area. A segment can be in the RAM under the I/O area at `$d000`-`$dfff`.
203
203
  - `image.json`: the entry, the segments, the vectors and the stages. `writtenBy` of a segment tells the last stage that wrote into it.
204
204
  - One PRG for each segment.
205
- - `entry_state.json`: the registers, `$00` and `$01`, pages 0 to 3, the VIC, SID and CIA registers, and the vectors. `cia` gives the CIA timer latches and interrupt masks. `differsFromReset` lists the bytes that are not as a clean C64 has them at READY. A rebuild must make these bytes the same, because the program can read them.
205
+ - `entry_state.json`: the registers, `$00` and `$01`, pages 0 to 3, the VIC, SID and CIA registers, the colour RAM, and the vectors. `io.colour` holds the 1000 colours at $d800. `cia` gives the CIA timer latches and interrupt masks. `differsFromReset` lists the bytes that are not as a clean C64 has them at READY. A rebuild must make these bytes the same, because the program can read them.
206
206
 
207
207
  A segment is a block that a stage wrote, also a small block. These blocks are not segments:
208
208
 
@@ -260,6 +260,7 @@ Traps:
260
260
  5. Make sure that the result is the program. The code at the entry must not be the unpacker again. A segment can be data that a loader or a cracktro left, for example intro graphics. Keep it until other evidence shows that the program does not use it. Then capture again with `--exclude` for that range.
261
261
  - Exclude each range of a cracktro that the program does not read. A rebuild has no cracktro. Also exclude a picture, an intro or a credit screen of a crack.
262
262
  - Do not exclude the start screen of the program, also when the program does not read it. An example is the loading picture of the publisher. Record it as the start screen in the project knowledge. The loader of the rebuild shows it.
263
+ - When the start screen is only in an earlier stage of the loading, capture that stage too, while it shows the screen. Do not exclude the memory of the screen in that capture. Put it into the project knowledge in a space of its own, for example `bank1`. The capture holds the VIC-II registers and the colour RAM, so the start screen needs nothing more.
263
264
  - Do not exclude other unused bytes, for example leftovers of the development or an old copy of a routine. A rebuild keeps them.
264
265
  - Keep a crack change that the program reads, for example a credit text in the game. Record it as a `crack` switch in the project knowledge.
265
266
  6. Put `<out>/image.json` into the project knowledge. The knowledge keeps the segments, the entry, the entry state and the stages. After that, you do not need the files in `<out>`.
@@ -15,8 +15,10 @@ type Registers = Awaited<ReturnType<ViceSessionClient["registersGet"]>>;
15
15
 
16
16
  const MAX_READ = 4096;
17
17
 
18
- /** The I/O areas of the entry state, read without side effects. */
19
- export const IO_AREAS = { vic: [0xd000, 0x2f], sid: [0xd400, 0x1d], cia1: [0xdc00, 0x10], cia2: [0xdd00, 0x10] } as const;
18
+ /** The I/O areas of the entry state, read without side effects. The colour RAM is the colours of the screen: a start screen of a captured stage uses them. */
19
+ export const IO_AREAS = { vic: [0xd000, 0x2f], sid: [0xd400, 0x1d], cia1: [0xdc00, 0x10], cia2: [0xdd00, 0x10], colour: [0xd800, 1000] } as const;
20
+ /** The I/O areas of chips: what differsFrom compares. The colour RAM is the content of the screen, not the state of the machine. */
21
+ const CHIP_AREAS = ["vic", "sid", "cia1", "cia2"] as const;
20
22
 
21
23
  /** What no register read of a CIA gives. */
22
24
  export interface CiaHidden {
@@ -49,6 +51,8 @@ export async function machineState(client: ViceSessionClient): Promise<MachineSt
49
51
  const pages = await readRam(client, 0x0000, 0x400);
50
52
  const io = {} as Record<keyof typeof IO_AREAS, Buffer>;
51
53
  for (const [name, [address, size]] of Object.entries(IO_AREAS)) io[name as keyof typeof IO_AREAS] = Buffer.from((await client.ioRead(address, size)).data, "hex");
54
+ // The colour RAM has 4 bits: a read gives other bits above them.
55
+ io.colour = Buffer.from(io.colour.map((value) => value & 0x0f));
52
56
  const [cia1, cia2] = (await client.cia("both")).chips.map(({ latchA, latchB, interruptMask }) => ({ latchA, latchB, interruptMask }));
53
57
  const romVectors = Buffer.from((await client.memoryRead({ address: 0xfffa, size: 6, space: "c64", view: "cpu" })).data, "hex");
54
58
  return { port, pages, io, cia: { cia1: cia1!, cia2: cia2! }, romVectors };
@@ -79,7 +83,7 @@ export function differsFrom(state: MachineState, clean: MachineState): Array<{ a
79
83
  const compare = (base: number, entry: Buffer, reset: Buffer) => entry.forEach((value, offset) => value !== reset[offset] && differs.push({ address: formatC64Address(base + offset), entry: value, reset: reset[offset]! }));
80
84
  compare(0x0000, state.port, clean.port);
81
85
  compare(0x0002, state.pages.subarray(2), clean.pages.subarray(2));
82
- for (const [name, [address]] of Object.entries(IO_AREAS)) compare(address, state.io[name as keyof typeof IO_AREAS], clean.io[name as keyof typeof IO_AREAS]);
86
+ for (const name of CHIP_AREAS) compare(IO_AREAS[name][0], state.io[name], clean.io[name]);
83
87
  return differs;
84
88
  }
85
89
 
@@ -131,6 +131,10 @@ export interface ReleaseRow {
131
131
  * crack, that the loader of the generated source shows before the entry.
132
132
  * A text screen has a charset, a bitmap screen has a bitmap. The colour RAM
133
133
  * comes from 1000 bytes at `colours` or is one `colour`; a hires bitmap has none.
134
+ * Without `stage`, the bytes are in the program at the entry. With `stage`,
135
+ * they are in the memory of that space (a captured stage of the loading, for
136
+ * example), and `call` is a routine of the stage that the start screen calls.
137
+ * `colourRam` takes the colours from the colour RAM of the capture of the stage.
134
138
  */
135
139
  export interface StartScreenRow {
136
140
  space: Space;
@@ -142,6 +146,9 @@ export interface StartScreenRow {
142
146
  colour?: number;
143
147
  border: number;
144
148
  background: number;
149
+ stage?: Space;
150
+ call?: number;
151
+ colourRam?: true;
145
152
  comment?: string;
146
153
  origin: Extract<Origin, "user" | "llm">;
147
154
  revision: string;
@@ -197,7 +204,7 @@ export const SWITCH_COLUMNS = "space, name, kind, default_value, releases, comme
197
204
  export const RELEASE_COLUMNS = "space, label, file, sha256, base, comment, origin, valid_from_revision";
198
205
  export const MACRO_COLUMNS = "space, name, params, body, comment, origin, valid_from_revision";
199
206
  export const MACRO_USE_COLUMNS = "space, start_address, end_address, macro, args, origin, valid_from_revision";
200
- export const START_SCREEN_COLUMNS = "space, mode, screen, bitmap, charset, colours, colour, border, background, comment, origin, valid_from_revision";
207
+ export const START_SCREEN_COLUMNS = "space, mode, screen, bitmap, charset, colours, colour, border, background, stage, call_address, colour_ram, comment, origin, valid_from_revision";
201
208
 
202
209
  export function toSymbol(row: Raw): SymbolRow {
203
210
  return { space: row.space as Space, address: row.address as number, name: row.name as string, kind: row.kind as SymbolKind, origin: row.origin as Origin, revision: row.valid_from_revision as string };
@@ -318,6 +325,9 @@ export function toStartScreen(row: Raw): StartScreenRow {
318
325
  revision: row.valid_from_revision as string,
319
326
  };
320
327
  for (const key of ["bitmap", "charset", "colours", "colour"] as const) if (row[key] !== null && row[key] !== undefined) value[key] = row[key] as number;
328
+ if (row.stage !== null && row.stage !== undefined) value.stage = row.stage as Space;
329
+ if (row.call_address !== null && row.call_address !== undefined) value.call = row.call_address as number;
330
+ if (row.colour_ram === 1) value.colourRam = true;
321
331
  if (row.comment !== null && row.comment !== undefined) value.comment = row.comment as string;
322
332
  return value;
323
333
  }
@@ -81,6 +81,8 @@ export const START_SCREEN_MODES = ["text", "hires", "multicolour"] as const;
81
81
  export type StartScreenMode = (typeof START_SCREEN_MODES)[number];
82
82
  /** The switch of the start screen in the generated source: no symbol, switch or release can have this name. */
83
83
  export const START_SCREEN_SWITCH = "START_SCREEN";
84
+ /** The switch of the leftovers in the generated source (bytes that nothing uses): no symbol, switch or release can have this name. */
85
+ export const LEFTOVERS_SWITCH = "LEFTOVERS";
84
86
  /** A macro name and a macro parameter. The body names a parameter with a dot in front: .dst. */
85
87
  export const MACRO_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,31}$/;
86
88
  export const MACRO_PARAM = /^[a-z_][a-z0-9_]{0,31}$/;
@@ -98,9 +100,12 @@ export const MEMORY_ROW = 64;
98
100
  /** Files that c64-source writes itself: no module can have these names. */
99
101
  export const GENERATED_FILES = ["main.asm", "loader.asm", "switches.asm", "config.asm", "constants.asm", "macros.asm", "start_screen.asm"] as const;
100
102
 
103
+ /** The file of a range of leftovers in the generated source: leftover_xxxx.asm. */
104
+ export const LEFTOVER_FILE = /^leftover_[0-9a-f]{4}\.asm$/;
105
+
101
106
  /** True for a generated file name in any letter case: the file systems of macOS and Windows ignore case. */
102
107
  export function isGeneratedFile(file: string): boolean {
103
- return (GENERATED_FILES as readonly string[]).includes(file.toLowerCase());
108
+ return (GENERATED_FILES as readonly string[]).includes(file.toLowerCase()) || LEFTOVER_FILE.test(file.toLowerCase());
104
109
  }
105
110
 
106
111
  /**
@@ -314,14 +319,19 @@ function createSchema(db: DatabaseSync): void {
314
319
  colour INTEGER CHECK (colour BETWEEN 0 AND 15),
315
320
  border INTEGER NOT NULL CHECK (border BETWEEN 0 AND 15),
316
321
  background INTEGER NOT NULL CHECK (background BETWEEN 0 AND 15),
322
+ stage TEXT CHECK (stage IS NULL OR (stage <> 'c64' AND (${SPACE_CHECK.replaceAll("space", "stage")}))),
323
+ call_address INTEGER CHECK (call_address BETWEEN 0 AND 65535),
324
+ colour_ram INTEGER CHECK (colour_ram = 1),
317
325
  comment TEXT CHECK (comment IS NULL OR length(comment) > 0),
318
326
  origin TEXT NOT NULL CHECK (origin IN ('user', 'llm')),
319
327
  valid_from_revision TEXT NOT NULL REFERENCES revisions (id),
320
328
  valid_to_revision TEXT REFERENCES revisions (id),
329
+ CHECK (call_address IS NULL OR stage IS NOT NULL),
330
+ CHECK (colour_ram IS NULL OR (stage IS NOT NULL AND colours IS NULL AND colour IS NULL AND mode <> 'hires')),
321
331
  CHECK ((mode = 'text') = (charset IS NOT NULL)),
322
332
  CHECK ((mode = 'text') = (bitmap IS NULL)),
323
333
  CHECK (colours IS NULL OR colour IS NULL),
324
- CHECK ((mode = 'hires') = (colours IS NULL AND colour IS NULL))
334
+ CHECK ((mode = 'hires') = (colours IS NULL AND colour IS NULL AND colour_ram IS NULL))
325
335
  );
326
336
  CREATE INDEX start_screens_space ON start_screens (space);
327
337
  CREATE TABLE macro_uses (
@@ -389,7 +399,7 @@ function createSchema(db: DatabaseSync): void {
389
399
  }
390
400
 
391
401
  /** The version of the index this build makes. An index with another version is emptied and made again. */
392
- export const INDEX_VERSION = 10;
402
+ export const INDEX_VERSION = 12;
393
403
 
394
404
  function indexVersion(db: DatabaseSync): number | undefined {
395
405
  const hasMeta = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'meta'").get();
@@ -0,0 +1,64 @@
1
+ // The start screen of a captured stage, from the entry state of its capture:
2
+ // the VIC-II registers and the VIC bank give the mode and the addresses, and
3
+ // the colour RAM of the capture gives the colours. Thus the start screen of a
4
+ // stage needs no address from the user.
5
+
6
+ import { Refusal } from "../errors.ts";
7
+ import type { StartScreenMode } from "./schema.ts";
8
+
9
+ /** The fields of a start screen that the capture of a stage gives. */
10
+ export interface StageScreen {
11
+ mode: StartScreenMode;
12
+ screen: number;
13
+ bitmap?: number;
14
+ charset?: number;
15
+ border: number;
16
+ background: number;
17
+ /** The colours are the colour RAM of the capture: not for hires. */
18
+ colourRam?: true;
19
+ }
20
+
21
+ /** The bytes of an I/O area of an entry state: io.<name>.bytes as hex, when the capture has them. */
22
+ function ioBytes(state: Record<string, unknown> | undefined, name: string): Buffer | undefined {
23
+ const io = state?.io as Record<string, { bytes?: unknown }> | undefined;
24
+ const bytes = io?.[name]?.bytes;
25
+ return typeof bytes === "string" && /^([0-9a-f]{2})+$/i.test(bytes) ? Buffer.from(bytes, "hex") : undefined;
26
+ }
27
+
28
+ /** The colour RAM of the capture of a stage: 1000 colours from $d800, or undefined when the capture has none. */
29
+ export function capturedColourRam(state: Record<string, unknown> | undefined): Uint8Array | undefined {
30
+ const bytes = ioBytes(state, "colour");
31
+ return bytes === undefined || bytes.length !== 1000 ? undefined : Uint8Array.from(bytes, (value) => value & 0x0f);
32
+ }
33
+
34
+ /**
35
+ * The start screen that the capture of a stage shows: its mode, its screen,
36
+ * its bitmap or charset, its colours and the colour RAM. Refuses by name when
37
+ * the capture does not show a start screen that the loader can show.
38
+ */
39
+ export function startScreenOfStage(state: Record<string, unknown> | undefined, stage: string): StageScreen {
40
+ const again = `Capture the stage again while it shows the screen, and put the capture into the project knowledge with image --space ${stage}.`;
41
+ const vic = ioBytes(state, "vic");
42
+ const cia2 = ioBytes(state, "cia2");
43
+ if (state === undefined || vic === undefined || vic.length < 0x2f || cia2 === undefined) throw new Refusal("not-found", `The program in ${stage} has no entry state with the VIC-II and CIA 2. ${again}`);
44
+ const [d011, d016, d018] = [vic[0x11]!, vic[0x16]!, vic[0x18]!];
45
+ if ((d011 & 0x10) === 0) throw new Refusal("invalid-input", `The capture in ${stage} has the display off ($d011 = $${d011.toString(16).padStart(2, "0")}). ${again}`);
46
+ if ((d011 & 0x40) !== 0) throw new Refusal("invalid-input", `The capture in ${stage} shows a screen in the extended colour mode, which a start screen does not have.`);
47
+ const bitmap = (d011 & 0x20) !== 0;
48
+ const multicolour = (d016 & 0x10) !== 0;
49
+ if (!bitmap && multicolour) throw new Refusal("invalid-input", `The capture in ${stage} shows a multicolour text screen, which a start screen does not have.`);
50
+ const bank = (3 - (cia2[0]! & 0x03)) << 14;
51
+ const mode: StartScreenMode = bitmap ? (multicolour ? "multicolour" : "hires") : "text";
52
+ const screen = bank + ((d018 >> 4) & 0x0f) * 0x400;
53
+ const colourRam = mode === "hires" ? undefined : capturedColourRam(state);
54
+ if (mode !== "hires" && colourRam === undefined) throw new Refusal("not-found", `The capture in ${stage} has no colour RAM: it is from an older version. ${again}`);
55
+ return {
56
+ mode,
57
+ screen,
58
+ ...(bitmap ? { bitmap: bank + ((d018 >> 3) & 1) * 0x2000 } : { charset: bank + ((d018 >> 1) & 7) * 0x800 }),
59
+ border: vic[0x20]! & 0x0f,
60
+ background: vic[0x21]! & 0x0f,
61
+ ...(colourRam === undefined ? {} : { colourRam: true as const }),
62
+ };
63
+ }
64
+
@@ -200,6 +200,9 @@ export const TABLES: readonly TableSpec[] = [
200
200
  field("colour", "colour", "integer", true),
201
201
  field("border", "border", "integer"),
202
202
  field("background", "background", "integer"),
203
+ field("stage", "stage", "text", true),
204
+ field("call", "call_address", "address", true),
205
+ field("colourRam", "colour_ram", "integer", true),
203
206
  field("comment", "comment", "text", true),
204
207
  origin,
205
208
  ],
@@ -78,7 +78,7 @@ import {
78
78
  type SwitchRow,
79
79
  type SymbolRow,
80
80
  } from "./read.ts";
81
- import { CODE_REGION_TYPES, COMMENT_PLACEMENTS, EVIDENCE_KINDS, MAX_ELEMENT, MODULE_FILE, DEFAULT_SPACE, GENERATED_FILES, isGeneratedFile, isSemantic, MACRO_NAME, MACRO_PARAM, OFF_KINDS, RELEASE_DEFINE, RELEASE_LABEL, START_SCREEN_MODES, START_SCREEN_SWITCH, SWITCH_KINDS, SWITCH_NAME, NO_ELEMENT_TYPES, OPERAND_SELECTS, POINTER_KIND, REFERENCE_KINDS, REGION_TYPES, SYMBOL_KINDS, type CommentPlacement, type EvidenceKind, type OperandSelect, type Origin, type ReferenceKind, type RegionType, type Space, type StartScreenMode, type SwitchKind, type SymbolKind } from "./schema.ts";
81
+ import { CODE_REGION_TYPES, COMMENT_PLACEMENTS, EVIDENCE_KINDS, MAX_ELEMENT, MODULE_FILE, DEFAULT_SPACE, GENERATED_FILES, isGeneratedFile, isSemantic, MACRO_NAME, MACRO_PARAM, OFF_KINDS, RELEASE_DEFINE, RELEASE_LABEL, LEFTOVERS_SWITCH, START_SCREEN_MODES, START_SCREEN_SWITCH, SWITCH_KINDS, SWITCH_NAME, NO_ELEMENT_TYPES, OPERAND_SELECTS, POINTER_KIND, REFERENCE_KINDS, REGION_TYPES, SYMBOL_KINDS, type CommentPlacement, type EvidenceKind, type OperandSelect, type Origin, type ReferenceKind, type RegionType, type Space, type StartScreenMode, type SwitchKind, type SymbolKind } from "./schema.ts";
82
82
  import { newRevisionId, rowId, sqlName } from "./text.ts";
83
83
 
84
84
  /** What a change rests on: a coverage run, a test or another project file with its SHA-256, or a note. */
@@ -287,8 +287,8 @@ export class Change {
287
287
 
288
288
  insertStartScreen(row: Omit<StartScreenRow, "revision">): void {
289
289
  this.#db
290
- .prepare("INSERT INTO start_screens (id, space, mode, screen, bitmap, charset, colours, colour, border, background, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
291
- .run(this.#rowId(), row.space, row.mode, row.screen, row.bitmap ?? null, row.charset ?? null, row.colours ?? null, row.colour ?? null, row.border, row.background, row.comment ?? null, row.origin, this.id());
290
+ .prepare("INSERT INTO start_screens (id, space, mode, screen, bitmap, charset, colours, colour, border, background, stage, call_address, colour_ram, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
291
+ .run(this.#rowId(), row.space, row.mode, row.screen, row.bitmap ?? null, row.charset ?? null, row.colours ?? null, row.colour ?? null, row.border, row.background, row.stage ?? null, row.call ?? null, row.colourRam === true ? 1 : null, row.comment ?? null, row.origin, this.id());
292
292
  }
293
293
 
294
294
  insertMacro(row: Omit<MacroRow, "revision">): void {
@@ -445,6 +445,7 @@ function renameStep(db: DatabaseSync, change: Change, origin: Origin, request: S
445
445
  }
446
446
  if (switchNamed(db, request.name, space) !== undefined) throw new Refusal("conflict", `${request.name} is the name of a switch. Give the symbol another name.`);
447
447
  if (request.name === START_SCREEN_SWITCH) throw new Refusal("conflict", `${START_SCREEN_SWITCH} is the switch of the start screen in the generated source. Give the symbol another name.`);
448
+ if (request.name === LEFTOVERS_SWITCH) throw new Refusal("conflict", `${LEFTOVERS_SWITCH} is the switch of the leftovers in the generated source. Give the symbol another name.`);
448
449
  const release = request.name.startsWith(RELEASE_DEFINE) ? releaseLabeled(db, request.name.slice(RELEASE_DEFINE.length), space) : undefined;
449
450
  if (release !== undefined) throw new Refusal("conflict", `${request.name} builds the release ${release.label}. Give the symbol another name.`);
450
451
  if (existing !== undefined) change.close("symbols", "space = ? AND address = ?", space, request.address);
@@ -959,6 +960,7 @@ function checkSwitch(request: SwitchRequest): void {
959
960
  checkSwitchName(request.name);
960
961
  if (request.name.startsWith(RELEASE_DEFINE)) throw new Refusal("invalid-input", `A switch name does not start with ${RELEASE_DEFINE}: the build of a release defines ${RELEASE_DEFINE}<label>.`);
961
962
  if (request.name === START_SCREEN_SWITCH) throw new Refusal("invalid-input", `${START_SCREEN_SWITCH} is the switch of the start screen in the generated source. Give the switch another name.`);
963
+ if (request.name === LEFTOVERS_SWITCH) throw new Refusal("invalid-input", `${LEFTOVERS_SWITCH} is the switch of the leftovers in the generated source. Give the switch another name.`);
962
964
  checkOneOf(SWITCH_KINDS, request.kind, "kind");
963
965
  if (request.default !== undefined && request.default !== 0 && request.default !== 1) throw new Refusal("invalid-input", "default must be 0 or 1.");
964
966
  if (OFF_KINDS.includes(request.kind) && request.default === 1) {
@@ -1064,7 +1066,7 @@ function unreleaseStep(db: DatabaseSync, change: Change, _origin: Origin, reques
1064
1066
  return { current: null };
1065
1067
  }
1066
1068
 
1067
- type StartScreenRequest = InSpace & { mode: StartScreenMode; screen: number; bitmap?: number; charset?: number; colours?: number; colour?: number; border: number; background: number; comment?: string };
1069
+ type StartScreenRequest = InSpace & { mode: StartScreenMode; screen: number; bitmap?: number; charset?: number; colours?: number; colour?: number; border: number; background: number; stage?: Space; call?: number; colourRam?: boolean; comment?: string };
1068
1070
 
1069
1071
  /**
1070
1072
  * The rules of the VIC-II for a start screen: the screen at a 1K step, the
@@ -1075,7 +1077,15 @@ type StartScreenRequest = InSpace & { mode: StartScreenMode; screen: number; bit
1075
1077
  */
1076
1078
  function checkStartScreen(request: StartScreenRequest): void {
1077
1079
  checkSpace(request);
1078
- if (spaceOf(request) !== DEFAULT_SPACE) throw new Refusal("invalid-input", "A start screen is only in the space c64.");
1080
+ if (spaceOf(request) !== DEFAULT_SPACE) throw new Refusal("invalid-input", "A start screen is only in the space c64. Give the space of its bytes with --stage.");
1081
+ if (request.stage !== undefined) {
1082
+ checkSpace({ space: request.stage });
1083
+ if (request.stage === DEFAULT_SPACE) throw new Refusal("invalid-input", "--stage is another space than c64: the space of a captured stage that holds the bytes of the start screen. Without --stage, the bytes are in the program.");
1084
+ }
1085
+ if (request.call !== undefined) {
1086
+ if (request.stage === undefined) throw new Refusal("invalid-input", "--call is a routine of the stage: give --stage too.");
1087
+ checkAddress(request.call, "call");
1088
+ }
1079
1089
  checkOneOf(START_SCREEN_MODES, request.mode, "mode");
1080
1090
  checkAddress(request.screen, "screen");
1081
1091
  for (const key of ["bitmap", "charset", "colours"] as const) if (request[key] !== undefined) checkAddress(request[key], key);
@@ -1089,7 +1099,11 @@ function checkStartScreen(request: StartScreenRequest): void {
1089
1099
  throw new Refusal("invalid-input", `A ${request.mode} start screen has a bitmap and no charset. Give --bitmap.`);
1090
1100
  }
1091
1101
  if (request.colours !== undefined && request.colour !== undefined) throw new Refusal("invalid-input", "Give the colour RAM as --colours or as --colour, not both.");
1092
- const colourRam = request.colours !== undefined || request.colour !== undefined;
1102
+ if (request.colourRam === true) {
1103
+ if (request.stage === undefined) throw new Refusal("invalid-input", "The colour RAM of a capture is only for a start screen of a stage: give --stage.");
1104
+ if (request.colours !== undefined || request.colour !== undefined) throw new Refusal("invalid-input", "The colours come from the colour RAM of the capture: do not give --colours or --colour too.");
1105
+ }
1106
+ const colourRam = request.colours !== undefined || request.colour !== undefined || request.colourRam === true;
1093
1107
  if (request.mode === "hires" && colourRam) throw new Refusal("invalid-input", "A hires bitmap does not use the colour RAM. Remove --colours and --colour.");
1094
1108
  if (request.mode !== "hires" && !colourRam) throw new Refusal("invalid-input", `A ${request.mode} start screen uses the colour RAM. Give --colours with the address of its 1000 bytes, or --colour with one colour.`);
1095
1109
  const step = (value: number, size: number, what: string) => {
@@ -1118,8 +1132,26 @@ function checkStartScreen(request: StartScreenRequest): void {
1118
1132
  checkCommentText(request.comment, "A start screen comment");
1119
1133
  }
1120
1134
 
1135
+ /** The bytes of a start screen of a stage, and its call, must be in the program of that space. */
1136
+ function checkStage(db: DatabaseSync, request: StartScreenRequest): void {
1137
+ if (request.stage === undefined) return;
1138
+ const byteAt = programBytes(db, request.stage);
1139
+ if (byteAt(request.screen) === undefined && db.prepare("SELECT 1 FROM current_memory WHERE space = ? LIMIT 1").get(request.stage) === undefined) {
1140
+ throw new Refusal("not-found", `The knowledge has no program in ${request.stage}. Capture the stage while it shows the start screen, and put the capture into the project knowledge with image --space ${request.stage}. Then record the start screen again.`);
1141
+ }
1142
+ const inStage = (range: AddressRange) => {
1143
+ for (let address = range.start; address <= range.end; address++) if (byteAt(address) === undefined) return false;
1144
+ return true;
1145
+ };
1146
+ for (const { what, range } of startScreenRanges(request)) {
1147
+ if (!inStage(range)) throw new Refusal("invalid-input", `The ${what} at ${formatC64Address(range.start)}-${formatC64Address(range.end)} is not in the program in ${request.stage}. Capture the stage again, and do not exclude the memory of the start screen.`);
1148
+ }
1149
+ if (request.call !== undefined && !inStage({ start: request.call, end: request.call })) throw new Refusal("invalid-input", `The call ${formatC64Address(request.call)} is not in the program in ${request.stage}.`);
1150
+ }
1151
+
1121
1152
  function startScreenStep(db: DatabaseSync, change: Change, origin: Origin, request: StartScreenRequest): Step<StartScreenRow, StartScreenRow> {
1122
1153
  const space = spaceOf(request);
1154
+ checkStage(db, request);
1123
1155
  const existing = currentStartScreen(db, space);
1124
1156
  const comment = request.comment === undefined ? existing?.comment : request.comment.trim();
1125
1157
  const row: Omit<StartScreenRow, "revision"> = {
@@ -1132,6 +1164,9 @@ function startScreenStep(db: DatabaseSync, change: Change, origin: Origin, reque
1132
1164
  ...(request.colour === undefined ? {} : { colour: request.colour }),
1133
1165
  border: request.border,
1134
1166
  background: request.background,
1167
+ ...(request.stage === undefined ? {} : { stage: request.stage }),
1168
+ ...(request.call === undefined ? {} : { call: request.call }),
1169
+ ...(request.colourRam === true ? { colourRam: true as const } : {}),
1135
1170
  ...(comment === undefined ? {} : { comment }),
1136
1171
  origin: origin as StartScreenRow["origin"],
1137
1172
  };
@@ -1605,7 +1640,7 @@ const KEYS = {
1605
1640
  columns: START_SCREEN_COLUMNS,
1606
1641
  map: toStartScreen,
1607
1642
  key: (row: StartScreenRow) =>
1608
- `${row.space}|${row.mode}|${row.screen}|${row.bitmap ?? ""}|${row.charset ?? ""}|${row.colours ?? ""}|${row.colour ?? ""}|${row.border}|${row.background}|${row.comment ?? ""}|${row.origin}`,
1643
+ `${row.space}|${row.mode}|${row.screen}|${row.bitmap ?? ""}|${row.charset ?? ""}|${row.colours ?? ""}|${row.colour ?? ""}|${row.border}|${row.background}|${row.stage ?? ""}|${row.call ?? ""}|${row.colourRam === true ? 1 : ""}|${row.comment ?? ""}|${row.origin}`,
1609
1644
  },
1610
1645
  macros: { columns: MACRO_COLUMNS, map: toMacro, key: (row: MacroRow) => `${row.space}|${row.name}|${listText(row.params)}|${row.body}|${row.comment ?? ""}|${row.origin}` },
1611
1646
  macro_uses: { columns: MACRO_USE_COLUMNS, map: toMacroUse, key: (row: MacroUseRow) => `${row.space}|${row.start}|${row.end}|${row.macro}|${listText(row.args)}|${row.origin}` },