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

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.
@@ -10,6 +10,8 @@
10
10
  // copier, and the copier writes only pages $0002-$03ff. With a start
11
11
  // screen in the knowledge, the copier shows it after the copies and waits for
12
12
  // a key or a fire button: the code is start-screen.asm, the same for each program.
13
+ // The loader loads the segments without the leftovers: the ranges of the
14
+ // source that nothing uses are not in loader.prg.
13
15
 
14
16
  import { readFileSync } from "node:fs";
15
17
  import { fileURLToPath } from "node:url";
@@ -105,6 +107,8 @@ export interface PackedBlock {
105
107
  }
106
108
 
107
109
  export interface LoaderPlan {
110
+ /** The ranges that the loader puts in place: the segments without the leftovers. */
111
+ loaded: AddressRange[];
108
112
  blocks: PackedBlock[];
109
113
  copies: Copy[];
110
114
  /** The first of the two free pages where the copier runs. */
@@ -168,12 +172,12 @@ export function startScreenPlan(row: StartScreenRow): StartScreenPlan {
168
172
  bank,
169
173
  border: row.border,
170
174
  background: row.background,
171
- colourMode: row.colours !== undefined ? 2 : row.colour !== undefined ? 1 : 0,
175
+ colourMode: row.colours !== undefined || row.colourRam === true ? 2 : row.colour !== undefined ? 1 : 0,
172
176
  };
173
177
  }
174
178
 
175
179
  /** The lines of loader.asm that give the start screen code its values. */
176
- function startScreenValues(row: StartScreenRow, plan: StartScreenPlan): string[] {
180
+ export function startScreenValues(row: StartScreenRow, plan: StartScreenPlan): string[] {
177
181
  const value = (name: string, number: number, comment?: string) => `c64_source_ss_${name} = ${formatC64Byte(number)}${comment === undefined ? "" : ` ; ${comment}`}`;
178
182
  const font = row.charset !== undefined && isRomFont(row.charset) ? " (the character ROM)" : "";
179
183
  const what = [`screen ${formatC64Address(row.screen)}`, ...(row.bitmap === undefined ? [] : [`bitmap ${formatC64Address(row.bitmap)}`]), ...(row.charset === undefined ? [] : [`charset ${formatC64Address(row.charset)}${font}`])];
@@ -187,7 +191,8 @@ function startScreenValues(row: StartScreenRow, plan: StartScreenPlan): string[]
187
191
  value("background", plan.background),
188
192
  value("colour_mode", plan.colourMode),
189
193
  value("colour", row.colour ?? 0),
190
- `c64_source_ss_colours = ${formatC64Address(row.colours ?? 0)}`,
194
+ // The colour RAM of a captured stage is in the show code: STAGE_COLOURS in stage.ts.
195
+ `c64_source_ss_colours = ${row.colourRam === true ? "c64_source_stage_colours" : formatC64Address(row.colours ?? 0)}`,
191
196
  ];
192
197
  }
193
198
 
@@ -223,7 +228,7 @@ const overlaps = (a: AddressRange, b: AddressRange) => a.start <= b.end && b.sta
223
228
  const show = (range: AddressRange) => `${formatC64Address(range.start)}-${formatC64Address(range.end)}`;
224
229
 
225
230
  /** Parts of `range` that no range in `holes` covers. */
226
- function subtract(range: AddressRange, holes: AddressRange[]): AddressRange[] {
231
+ export function subtract(range: AddressRange, holes: AddressRange[]): AddressRange[] {
227
232
  let pieces = [range];
228
233
  for (const hole of holes) {
229
234
  pieces = pieces.flatMap((piece) => {
@@ -445,7 +450,7 @@ export function ciaSection(state: EntryState): { ops: Op[]; plan: CiaPlan } | un
445
450
  }
446
451
 
447
452
  export interface LoaderInput {
448
- /** The segments with the files that hold them, in address order. */
453
+ /** The ranges to load, each with the files that hold it, in address order: the segments without the leftovers. */
449
454
  segments: Array<AddressRange & { files: string[] }>;
450
455
  byteAt: (address: number) => number;
451
456
  state: EntryState;
@@ -461,6 +466,8 @@ export interface LoaderInput {
461
466
  config?: boolean;
462
467
  /** The start screen of the knowledge: the copier shows it after the copies. */
463
468
  startScreen?: StartScreenRow;
469
+ /** Always the packed form: the show stage of a start screen from a captured stage holds the packed program while it shows the screen. */
470
+ packed?: boolean;
464
471
  }
465
472
 
466
473
  /** The checks of a start screen against the program and the entry state. Refuses by name. */
@@ -545,11 +552,12 @@ export function planLoader(input: LoaderInput): LoaderPlan {
545
552
  const codeSize = COPIER_CODE_SIZE + (state.vic === undefined ? 0 : VIC_SIZE) + ciaSize + (screen === undefined ? 0 : START_SCREEN_SIZES[screen.colourMode]);
546
553
  const copierImage = at;
547
554
  const end = copierImage + codeSize + COPY_ENTRY * plain.length + 2 - 1;
555
+ if (input.packed === true) return planPacked(input, blocks, cia, codeSize, screen, "The start screen of a captured stage shows while the program is still packed.");
548
556
  // The end can be past $ffff, which is no address.
549
557
  if (end > LOAD_LIMIT) return planPacked(input, blocks, cia, codeSize, screen, `The plain loader would end ${end > 0xffff ? "past $ffff" : `at ${formatC64Address(end)}`}, after ${formatC64Address(LOAD_LIMIT)}: loading it would write the I/O area.`);
550
558
  // The CIA part and the start screen take room from the copy table in the copier's pages.
551
559
  const maxCopies = Math.max(0, Math.min(TABLE_COPIES, Math.floor((copierBytes - codeSize - 2) / COPY_ENTRY)));
552
- if (plain.length > maxCopies) throw new WireFailure("invalid-input", `The loader needs ${plain.length} copies; it can do at most ${maxCopies}. Capture the program again with fewer segments, or write the loader by hand.`);
560
+ if (plain.length > maxCopies) return planPacked(input, blocks, cia, codeSize, screen, `The plain loader needs ${plain.length} copies, and its copier can do at most ${maxCopies}.`);
553
561
 
554
562
  const order = copyOrder(plain);
555
563
  if (order === undefined) {
@@ -621,6 +629,7 @@ export function planLoader(input: LoaderInput): LoaderPlan {
621
629
  lines.push(" !word 0", "}", "}");
622
630
 
623
631
  return {
632
+ loaded: input.segments.map(({ start, end }) => ({ start, end })),
624
633
  blocks: blocks.map((block, index) => ({ what: block.what, range: block.range, packedAt: packedAt[index]!, bytes: block.bytes })),
625
634
  copies,
626
635
  copier,
@@ -719,6 +728,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
719
728
  parts.sort((a, b) => a.range.start - b.range.start);
720
729
  for (const part of parts) lines.push("", ...part.text);
721
730
  return {
731
+ loaded: input.segments.map(({ start, end }) => ({ start, end })),
722
732
  blocks: pieces.map((piece) => ({ what: piece.what, range: piece.target, packedAt: piece.at, bytes: piece.bytes })),
723
733
  copies,
724
734
  copier,
@@ -735,7 +745,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
735
745
  const MAX_PACKED_COPIES = Math.floor((256 - 2) / COPY_ENTRY);
736
746
 
737
747
  /** A piece of pages 0-3 in the packed form: its target and where the copier reads it. */
738
- interface Piece {
748
+ export interface Piece {
739
749
  what: string;
740
750
  target: AddressRange;
741
751
  at: number;
@@ -748,7 +758,7 @@ interface Piece {
748
758
  * A part that does not fit in one range is split, and each piece is a copy.
749
759
  * Undefined when the ranges are too small.
750
760
  */
751
- function placePieces(ranges: AddressRange[], low: ReadonlyArray<{ what: string; range: AddressRange; bytes: (address: number) => number }>, distance: (range: AddressRange) => number): Piece[] | undefined {
761
+ export function placePieces(ranges: AddressRange[], low: ReadonlyArray<{ what: string; range: AddressRange; bytes: (address: number) => number }>, distance: (range: AddressRange) => number): Piece[] | undefined {
752
762
  const left = ranges.map((range) => ({ ...range }));
753
763
  const pieces: Piece[] = [];
754
764
  let rest = low.reduce((sum, block) => sum + block.range.end - block.range.start + 1, 0);
@@ -815,24 +825,43 @@ export interface PackedLoader {
815
825
  }
816
826
 
817
827
  /**
818
- * Packs the build of main.asm from $0400 and the build of loader.asm (the
819
- * copier wins where they overlap) with the entry at the copier and $01 = $34,
820
- * and checks the unpack in the emulator of Exomizer: every byte of the two
821
- * builds, and the jump to the copier. Refuses by name when it does not hold.
828
+ * Packs the loaded ranges of the build of main.asm from $0400 and the build of
829
+ * loader.asm (the copier wins where they overlap) with the entry at the copier
830
+ * and $01 = $34, and checks the unpack in the emulator of Exomizer: every byte
831
+ * of the two builds, and the jump to the copier. Refuses by name when it does
832
+ * not hold.
822
833
  */
823
834
  export async function packLoader(main: Uint8Array, copier: Uint8Array, plan: LoaderPlan, context: ToolContext): Promise<PackedLoader> {
824
- // The unpacker uses pages 0-3; the copier writes them.
835
+ return packParts(packedParts(main, copier, plan), plan.copier, 0x34, "main.asm and loader.asm", "the copier", context);
836
+ }
837
+
838
+ /** What Exomizer packs in the packed form: the loaded ranges of the build of main.asm from $0400, and the build of loader.asm. */
839
+ function packedParts(main: Uint8Array, copier: Uint8Array, plan: Pick<LoaderPlan, "loaded">): Array<{ start: number; body: Uint8Array }> {
840
+ // The unpacker uses pages 0-3; the copier writes them. The leftovers between the loaded ranges are not packed.
825
841
  const program = prgRange(main);
826
- const skip = Math.max(0, 0x0400 - program.start);
827
- const parts = [...(skip < program.body.length ? [{ start: program.start + skip, body: program.body.subarray(skip) }] : []), prgRange(copier)];
842
+ const ranges = plan.loaded.flatMap((range) => {
843
+ const start = Math.max(range.start, 0x0400, program.start);
844
+ const end = Math.min(range.end, program.start + program.body.length - 1);
845
+ return start <= end ? [{ start, body: program.body.subarray(start - program.start, end - program.start + 1) }] : [];
846
+ });
847
+ return [...ranges, prgRange(copier)];
848
+ }
849
+
850
+ /**
851
+ * Packs parts (a later one wins where they overlap) into one program that
852
+ * unpacks itself, starts at `entry` with $01 = `exitMemory`, and checks the
853
+ * unpack in the emulator of Exomizer: every byte of the parts, and the jump
854
+ * to the entry. Refuses by name when it does not hold.
855
+ */
856
+ export async function packParts(parts: ReadonlyArray<{ start: number; body: Uint8Array }>, entry: number, exitMemory: number, what: string, entryName: string, context: ToolContext): Promise<PackedLoader> {
828
857
  const prg = (part: { start: number; body: Uint8Array }) => Buffer.concat([Buffer.from([part.start & 0xff, part.start >> 8]), part.body]);
829
- const packed = await pack({ programs: parts.map(prg), entry: plan.copier, exitMemory: 0x34 }, context);
830
- if (packed.entry !== plan.copier) throw new WireFailure("operation-failed", `The unpack in the emulator of Exomizer jumps to ${formatC64Address(packed.entry)}, not to the copier at ${formatC64Address(plan.copier)}.`);
858
+ const packed = await pack({ programs: parts.map(prg), entry, exitMemory }, context);
859
+ if (packed.entry !== entry) throw new WireFailure("operation-failed", `The unpack in the emulator of Exomizer jumps to ${formatC64Address(packed.entry)}, not to ${entryName} at ${formatC64Address(entry)}.`);
831
860
  const reference = mergedPrograms(parts);
832
861
  const wrong = compareBuild(packed.unpacked, reference).segments.find((segment) => segment.result !== "identical");
833
862
  if (wrong !== undefined) {
834
863
  const first = wrong.firstDifference === undefined ? "" : `: the first is ${wrong.firstDifference.address}, ${wrong.firstDifference.built} and not ${wrong.firstDifference.reference}`;
835
- throw new WireFailure("operation-failed", `The unpack in the emulator of Exomizer does not give ${wrong.start}-${wrong.end} of main.asm and loader.asm (${wrong.result}${first}).`);
864
+ throw new WireFailure("operation-failed", `The unpack in the emulator of Exomizer does not give ${wrong.start}-${wrong.end} of ${what} (${wrong.result}${first}).`);
836
865
  }
837
866
  const unpackedBytes = reference.segments.reduce((sum, segment) => sum + segment.end - segment.start + 1, 0);
838
867
  return { program: packed.program, packedBytes: packed.program.length, unpackedBytes, ...(packed.cycles === undefined ? {} : { cycles: packed.cycles }) };
@@ -9,12 +9,15 @@
9
9
  // patch is written as !if SWITCH { code } else { original }, with the
10
10
  // condition of the state that the program does not have, and a macro use as
11
11
  // one +name args line. config.asm holds the value of each switch, and
12
- // switches.asm the values of each release.
12
+ // switches.asm the values of each release. A range of leftovers (bytes that
13
+ // nothing uses) is a file of its own, in the build only with LEFTOVERS = 1:
14
+ // each release has it, the default build does not, and the loader never
15
+ // loads it.
13
16
 
14
17
  import { type AddressRange, COVERAGE, formatC64Address, formatC64Byte, POINTER_TABLE_TYPES, pointerTableEntries, type PointerTableType } from "#src/c64.ts";
15
18
  import { WireFailure } from "#src/host-client/tools.ts";
16
19
  import { identifiers, operandText, replaceIdentifiers, type OperandExpression } from "#src/knowledge/expression.ts";
17
- import { type CommentPlacement, isAnalyzer, isGeneratedFile, RELEASE_DEFINE, START_SCREEN_SWITCH, type Origin, type RegionType, type SwitchKind } from "#src/knowledge/schema.ts";
20
+ import { type CommentPlacement, isAnalyzer, isGeneratedFile, LEFTOVERS_SWITCH, RELEASE_DEFINE, START_SCREEN_SWITCH, type Origin, type RegionType, type SwitchKind } from "#src/knowledge/schema.ts";
18
21
  import type { Area } from "#src/platform.ts";
19
22
  import { hasZeroPageForm, instructionWith, labelProblem, MODE_LENGTH, OPCODES, takesAddress, USE_KINDS, useKind, type UseKind } from "#src/opcodes.ts";
20
23
 
@@ -59,6 +62,8 @@ export interface SourceInput {
59
62
  macros?: ReadonlyArray<{ name: string; params: readonly string[]; body: string; comment?: string }>;
60
63
  /** Macro uses of the knowledge: the instructions of a range, written as one use of a macro. */
61
64
  macroUses?: ReadonlyArray<{ start: number; end: number; macro: string; args: readonly string[] }>;
65
+ /** The leftovers: ranges inside the segments that nothing uses, in address order. Each one is a file that only LEFTOVERS = 1 builds. */
66
+ leftovers?: readonly AddressRange[];
62
67
  }
63
68
 
64
69
  /** A macro use that the source writes, with its args in the names of this source. */
@@ -213,6 +218,8 @@ export interface Piece {
213
218
  title: string;
214
219
  /** True when the piece starts a segment: the source sets the address there. */
215
220
  segmentStart: boolean;
221
+ /** True for a range of leftovers: only LEFTOVERS = 1 builds it, and the loader does not load it. */
222
+ leftover: boolean;
216
223
  items: Item[];
217
224
  }
218
225
 
@@ -254,6 +261,8 @@ export interface Layout {
254
261
  macrosAsInstructions: MacroAsInstructions[];
255
262
  /** The knowledge has a start screen: config.asm gets START_SCREEN. */
256
263
  startScreen: boolean;
264
+ /** The ranges of leftovers: config.asm gets LEFTOVERS. */
265
+ leftovers: AddressRange[];
257
266
  }
258
267
 
259
268
  /** ACME reads leading zeros as a 16-bit value, so a zero-page name gets two digits. */
@@ -305,19 +314,32 @@ export function layout(input: SourceInput): Layout {
305
314
  // A patch starts and ends at an item boundary, so a data run stops there.
306
315
  const patches = [...(input.patches ?? [])].sort((a, b) => a.start - b.start);
307
316
  const macroUses = [...(input.macroUses ?? [])].sort((a, b) => a.start - b.start);
308
- const cuts = new Set([...patches, ...macroUses].flatMap((range) => [range.start, range.end + 1]));
317
+ const leftovers = (input.leftovers ?? []).filter((range) => input.segments.some((segment) => range.start >= segment.start && range.end <= segment.end));
318
+ const cuts = new Set([...patches, ...macroUses, ...leftovers].flatMap((range) => [range.start, range.end + 1]));
309
319
 
310
320
  const pieces: Piece[] = [];
321
+ const hex = (address: number) => address.toString(16).padStart(4, "0");
311
322
  for (const segment of input.segments) {
312
- const starts = modules.filter((module) => module.start > segment.start && module.start <= segment.end).map((module) => module.start);
313
- const bounds = [segment.start, ...starts, segment.end + 1];
323
+ const inside = (address: number) => address > segment.start && address <= segment.end;
324
+ // A range of leftovers is one file: a module that starts in it goes on after it.
325
+ const inLeftovers = (address: number) => leftovers.some((range) => address > range.start && address <= range.end);
326
+ const starts = [...modules.map((module) => module.start).filter((start) => !inLeftovers(start)), ...leftovers.flatMap((range) => [range.start, range.end + 1])].filter(inside);
327
+ const bounds = [...new Set([segment.start, ...starts, segment.end + 1])].sort((a, b) => a - b);
314
328
  for (let index = 0; index + 1 < bounds.length; index++) {
315
329
  const start = bounds[index]!;
316
330
  const end = bounds[index + 1]! - 1;
331
+ const segmentTitle = `Segment ${formatC64Address(segment.start)}-${formatC64Address(segment.end)}`;
332
+ if (leftovers.some((range) => range.start === start)) {
333
+ pieces.push({ start, end, file: `leftover_${hex(start)}.asm`, title: `Leftovers ${formatC64Address(start)}-${formatC64Address(end)}: ${end - start + 1} bytes that nothing uses. Only LEFTOVERS = 1 builds them.`, segmentStart: index === 0, leftover: true, items: [] });
334
+ continue;
335
+ }
336
+ // A module that leftovers cut goes on in a file of its own after them: <module>_xxxx.asm.
317
337
  const module = modules.find((row) => row.start === start);
318
- const file = module?.file ?? `segment_${start.toString(16).padStart(4, "0")}.asm`;
319
- const title = module?.title?.replace(/\s*\r?\n\s*/g, " ") ?? `Segment ${formatC64Address(segment.start)}-${formatC64Address(segment.end)}`;
320
- pieces.push({ start, end, file, title, segmentStart: index === 0, items: [] });
338
+ const holder = module ?? modules.filter((row) => row.start >= segment.start && row.start < start).at(-1);
339
+ const title = (text: string | undefined) => text?.replace(/\s*\r?\n\s*/g, " ");
340
+ const file = module?.file ?? (holder === undefined ? `segment_${hex(start)}.asm` : `${holder.file.replace(/\.asm$/i, "")}_${hex(start)}.asm`);
341
+ const named = module === undefined && holder !== undefined ? `${title(holder.title) ?? holder.file}, from ${formatC64Address(start)}` : title(module?.title);
342
+ pieces.push({ start, end, file, title: named ?? segmentTitle, segmentStart: index === 0, leftover: false, items: [] });
321
343
  }
322
344
  }
323
345
  const files = new Map<string, number>();
@@ -658,6 +680,7 @@ export function layout(input: SourceInput): Layout {
658
680
  macroUses: usesWritten,
659
681
  macrosAsInstructions: macrosAsInstructions.sort((a, b) => a.start - b.start),
660
682
  startScreen: input.startScreen === true,
683
+ leftovers: [...leftovers],
661
684
  };
662
685
  }
663
686
 
@@ -901,11 +924,11 @@ const SWITCH_GROUPS: ReadonlyArray<{ kind: SwitchKind; title: string }> = [
901
924
  { kind: "change", title: "Other changes" },
902
925
  ];
903
926
 
904
- /** True when the source has switches.asm: the knowledge has switches or releases. */
905
- export const hasSwitchFile = (layout: Pick<Layout, "switches" | "releases">) => layout.switches.length > 0 || layout.releases.length > 0;
927
+ /** True when the source has switches.asm: the knowledge has switches or releases, or the source has leftovers, which main.asm builds by LEFTOVERS. */
928
+ export const hasSwitchFile = (layout: Pick<Layout, "switches" | "releases" | "leftovers">) => layout.switches.length > 0 || layout.releases.length > 0 || layout.leftovers.length > 0;
906
929
 
907
- /** True when the source has config.asm: the knowledge has switches or a start screen. */
908
- export const hasConfigFile = (layout: Pick<Layout, "switches" | "startScreen">) => layout.switches.length > 0 || layout.startScreen;
930
+ /** True when the source has config.asm: the knowledge has switches or a start screen, or the source has leftovers. */
931
+ export const hasConfigFile = (layout: Pick<Layout, "switches" | "startScreen" | "leftovers">) => layout.switches.length > 0 || layout.startScreen || layout.leftovers.length > 0;
909
932
 
910
933
  /** The file with the value of each switch. The user edits it, and generate keeps the values. */
911
934
  export const CONFIG_FILE = "config.asm";
@@ -928,7 +951,7 @@ export function configValues(text: string): Map<string, 0 | 1> {
928
951
  * kind. Without a value, a switch has its default. A comment tells the
929
952
  * releases that have the switch on, and its patches.
930
953
  */
931
- export function configText(layout: Pick<Layout, "switches" | "patches" | "startScreen">, values: ReadonlyMap<string, number> = new Map()): string {
954
+ export function configText(layout: Pick<Layout, "switches" | "patches" | "startScreen" | "leftovers">, values: ReadonlyMap<string, number> = new Map()): string {
932
955
  const patches = switchesOf(layout);
933
956
  const out = [
934
957
  "; Generated by c64-source. Edit the values here: generate keeps them.",
@@ -954,7 +977,15 @@ export function configText(layout: Pick<Layout, "switches" | "patches" | "startS
954
977
  }
955
978
  }
956
979
  if (layout.startScreen) {
957
- out.push("", "; Start screen: on by default", `${START_SCREEN_SWITCH} = ${values.get(START_SCREEN_SWITCH) ?? 1} ; the loader shows the start screen and waits for a key or a fire button. 0 starts the program at once`);
980
+ out.push("", "; Start screen: on by default", `${START_SCREEN_SWITCH} = ${values.get(START_SCREEN_SWITCH) ?? 1} ; the loader shows the start screen and waits for a key or a fire button. 0 starts the program at once. Only the clean build has it: a release and LEFTOVERS = 1 have none`);
981
+ }
982
+ if (layout.leftovers.length > 0) {
983
+ const bytes = layout.leftovers.reduce((sum, range) => sum + range.end - range.start + 1, 0);
984
+ out.push(
985
+ "",
986
+ "; Leftovers: off by default",
987
+ `${LEFTOVERS_SWITCH} = ${values.get(LEFTOVERS_SWITCH) ?? 0} ; ${bytes} bytes in ${layout.leftovers.length} leftover_xxxx.asm ${layout.leftovers.length === 1 ? "file" : "files"} that nothing uses. 1 builds them, so main.asm gives the bytes of the program. Each release has them. The loader never loads them`,
988
+ );
958
989
  }
959
990
  return `${out.join("\n")}\n`;
960
991
  }
@@ -974,6 +1005,9 @@ function switchesText(layout: Layout): string {
974
1005
  out.push("", `; ${release.label}${release.base ? " (the program of the knowledge)" : ""}: ${release.file}${release.comment === undefined ? "" : `. ${release.comment.replace(/\s*\r?\n\s*/g, " ")}`}`);
975
1006
  out.push(`!ifdef ${RELEASE_DEFINE}${release.label} {`);
976
1007
  for (const row of layout.switches) out.push(`${INDENT}${row.name} = ${row.releases.includes(release.label) ? 1 : 0}`);
1008
+ if (layout.leftovers.length > 0) out.push(`${INDENT}${LEFTOVERS_SWITCH} = 1`);
1009
+ // The start screen is part of the clean build only: the build of a release is the bytes of its file.
1010
+ if (layout.startScreen) out.push(`${INDENT}${START_SCREEN_SWITCH} = 0`);
977
1011
  out.push("}");
978
1012
  }
979
1013
  if (hasConfigFile(layout)) {
@@ -1310,7 +1344,8 @@ export function render(layout: Layout, asBytes: ReadonlySet<string>, header: str
1310
1344
  const main = [...header.map((line) => `; ${line}`), "", "!cpu 6510", ...(hasSwitchFile(layout) ? ['!source "switches.asm"'] : []), '!source "constants.asm"', ...(layout.macros.length > 0 ? ['!source "macros.asm"'] : [])];
1311
1345
  for (const piece of layout.pieces) {
1312
1346
  if (piece.segmentStart) main.push("", `* = ${formatC64Address(piece.start)}`);
1313
- main.push(`!source "${piece.file}"`);
1347
+ // Without the leftovers, the build skips their bytes: the addresses after them stay.
1348
+ main.push(piece.leftover ? `!if ${LEFTOVERS_SWITCH} { !source "${piece.file}" } else { !skip ${piece.end - piece.start + 1} }` : `!source "${piece.file}"`);
1314
1349
  }
1315
1350
  result.files.push({ name: "main.asm", text: `${main.join("\n")}\n` });
1316
1351
  if (coverage !== undefined) result.notExecuted = notExecuted;
@@ -0,0 +1,273 @@
1
+ // The show stage of a start screen from a captured stage: the picture is not
2
+ // in the program at the entry, so it shows before the loader. Exomizer packs
3
+ // the loader as it is in memory before it starts (the plain loader file, or
4
+ // the parts of the packed form), the bytes of the stage that the start screen
5
+ // uses at their own addresses, the bytes of the loader that those cover in a
6
+ // stash, and the show code into one loader.prg. The show code shows the
7
+ // screen with start-screen.asm, calls the routine of the stage, waits for a
8
+ // key or a fire button, stops the interrupts of the stage, sets the CIAs as
9
+ // RUN leaves them, copies the stash back and starts the loader.
10
+
11
+ import { type AddressRange, formatC64Address, formatC64Byte } from "#src/c64.ts";
12
+ import { WireFailure } from "#src/host-client/tools.ts";
13
+ import type { StartScreenRow } from "#src/knowledge/read.ts";
14
+ import { placePieces, START_SCREEN_FILE, startScreenValues, subtract, type StartScreenPlan } from "./loader.ts";
15
+
16
+ /** Bytes at an address. */
17
+ export interface StagePart {
18
+ start: number;
19
+ body: Uint8Array;
20
+ }
21
+
22
+ export interface StageInput {
23
+ /** The loader as it is in memory before it starts: the plain loader file, or the parts of the packed form. */
24
+ inner: StagePart[];
25
+ /** Where the loader starts, and the value of $01 that it needs there: $080d with $37, or the copier of the packed form with $34. */
26
+ innerStart: number;
27
+ innerPort: number;
28
+ /** The bytes of the stage that the start screen uses, in address order, at $0400 or higher. */
29
+ stage: StagePart[];
30
+ /** The colour RAM of the capture of the stage, when the start screen takes its colours from it: the show code holds it. */
31
+ colourRam?: Uint8Array;
32
+ row: StartScreenRow;
33
+ plan: StartScreenPlan;
34
+ /** The lines that include switches.asm or config.asm, for START_SCREEN. */
35
+ settings: string[];
36
+ header: string[];
37
+ /** The bytes of the show code without its copy table (stageCodeSize). */
38
+ codeSize: number;
39
+ }
40
+
41
+ export interface StagePlan {
42
+ /** Where the show code runs. */
43
+ code: number;
44
+ /** The parts of the loader under the bytes of the stage: where the show code copies them back from. */
45
+ stash: Array<{ target: AddressRange; at: number }>;
46
+ /** start_screen_stage.asm: the show code at `code`, then each part of the stage, packed after it. */
47
+ text: string;
48
+ }
49
+
50
+ /** The file of the show stage in the generated source. */
51
+ export const STAGE_FILE = "start_screen_stage.asm";
52
+ /** The labels of the show stage: its start and the end of the show code. */
53
+ export const STAGE_START = "c64_source_stage";
54
+ export const STAGE_CODE_END = "c64_source_stage_code_end";
55
+ /** The label of the colour RAM of the capture in the show code. */
56
+ export const STAGE_COLOURS = "c64_source_stage_colours";
57
+ /** The label of a part of the stage: its first byte and the byte after it in the build of start_screen_stage.asm. */
58
+ export const stageLabel = (start: number, part: "from" | "end") => `stage_${part}_${start.toString(16).padStart(4, "0")}`;
59
+
60
+ /** One copy of the stash: the length, where it is read and where it is written. */
61
+ const COPY_ENTRY = 6;
62
+ /** X indexes the table, so the table holds at most this many copies in 256 bytes. */
63
+ const MAX_COPIES = Math.floor((256 - 2) / COPY_ENTRY);
64
+ /** Where the show code can run: RAM that no ROM and no I/O hides when $01 is $37, as for the call of the stage. */
65
+ const CODE_AREAS: readonly AddressRange[] = [
66
+ { start: 0x0400, end: 0x9fff },
67
+ { start: 0xc000, end: 0xcfff },
68
+ ];
69
+ /** The RAM that the stash can use: the copy runs with all RAM in, and not on the hardware vectors. */
70
+ const STASH_AREA: AddressRange = { start: 0x0400, end: 0xfff9 };
71
+ /** The free ranges that a refusal names. */
72
+ const SHOWN_FREE = 8;
73
+
74
+ const show = (range: AddressRange) => `${formatC64Address(range.start)}-${formatC64Address(range.end)}`;
75
+ const rangeOf = (part: StagePart): AddressRange => ({ start: part.start, end: part.start + part.body.length - 1 });
76
+
77
+ /** The ranges in address order, with each run of touching or overlapping ranges as one. */
78
+ function merged(ranges: readonly AddressRange[]): AddressRange[] {
79
+ const out: AddressRange[] = [];
80
+ for (const range of [...ranges].sort((a, b) => a.start - b.start)) {
81
+ const last = out.at(-1);
82
+ if (last !== undefined && range.start <= last.end + 1) last.end = Math.max(last.end, range.end);
83
+ else out.push({ ...range });
84
+ }
85
+ return out;
86
+ }
87
+
88
+ /** The byte of the parts at an address; the last part that holds it wins. */
89
+ function byteOf(parts: readonly StagePart[], address: number): number {
90
+ for (let index = parts.length - 1; index >= 0; index--) {
91
+ const part = parts[index]!;
92
+ if (address >= part.start && address < part.start + part.body.length) return part.body[address - part.start]!;
93
+ }
94
+ throw new WireFailure("operation-failed", `No part holds ${formatC64Address(address)}. This is a defect of the script.`);
95
+ }
96
+
97
+ /**
98
+ * Plans the show stage: the show code in a free range where it can run with
99
+ * the KERNAL in, and the bytes of the loader under the stage in the other free
100
+ * ranges. Refuses by name when the memory is too small.
101
+ */
102
+ export function planStage(input: StageInput): StagePlan {
103
+ const used = merged([...input.inner.map(rangeOf), ...input.stage.map(rangeOf)]);
104
+ const free = subtract(STASH_AREA, used);
105
+ const covered = merged(input.inner.map(rangeOf)).flatMap((inner) => input.stage.map(rangeOf).flatMap((part) => (part.start <= inner.end && inner.start <= part.end ? [{ start: Math.max(part.start, inner.start), end: Math.min(part.end, inner.end) }] : [])));
106
+ const stashed = merged(covered).map((range) => ({ what: `the loader at ${show(range)}`, range, bytes: (address: number) => byteOf(input.inner, address) }));
107
+ const refuse = (why: string): never => {
108
+ const largest = [...free].sort((a, b) => b.end - b.start - (a.end - a.start)).slice(0, SHOWN_FREE);
109
+ const ranges = largest.length === 0 ? "none" : largest.map((range) => `${show(range)} (${range.end - range.start + 1} bytes)`).join(", ");
110
+ throw new WireFailure("invalid-input", `${why} The largest free ranges outside the loader and the bytes of the stage: ${ranges}. Capture the stage with less memory, so that its program holds only the start screen and the routine of the call.`);
111
+ };
112
+ for (let copies = Math.max(stashed.length, 1); copies <= MAX_COPIES; ) {
113
+ const size = input.codeSize + COPY_ENTRY * copies + 2;
114
+ let best: { code: number; pieces: NonNullable<ReturnType<typeof placePieces>> } | undefined;
115
+ for (const range of free) {
116
+ for (const area of CODE_AREAS) {
117
+ const start = Math.max(range.start, area.start);
118
+ const code = { start, end: start + size - 1 };
119
+ if (code.end > Math.min(range.end, area.end)) continue;
120
+ const pieces = placePieces(free.flatMap((other) => subtract(other, [code])), stashed, (other) => Math.abs(other.start - code.start));
121
+ if (pieces !== undefined && (best === undefined || pieces.length < best.pieces.length)) best = { code: code.start, pieces };
122
+ }
123
+ }
124
+ if (best === undefined) return refuse(`The show stage needs ${size} free bytes for its code in $0400-$9fff or $c000-$cfff, and ${stashed.reduce((sum, item) => sum + item.range.end - item.range.start + 1, 0)} more free bytes for the bytes of the loader under the stage.`);
125
+ if (best.pieces.length <= copies) {
126
+ const stash = best.pieces.map((piece) => ({ target: piece.target, at: piece.at }));
127
+ return { code: best.code, stash, text: stageText(input, best.code, stash) };
128
+ }
129
+ copies = best.pieces.length;
130
+ }
131
+ return refuse(`The show stage needs more than ${MAX_COPIES} copies for the bytes of the loader under the stage.`);
132
+ }
133
+
134
+ /** The bytes as !byte lines of 16. */
135
+ function byteLines(part: StagePart): string[] {
136
+ const lines: string[] = [];
137
+ for (let offset = 0; offset < part.body.length; offset += 16) lines.push(` !byte ${[...part.body.subarray(offset, offset + 16)].map(formatC64Byte).join(",")}`);
138
+ return lines;
139
+ }
140
+
141
+ /** start_screen_stage.asm with the show code at `code` and the stash table of `stash`. */
142
+ export function stageText(input: StageInput, code: number, stash: StagePlan["stash"]): string {
143
+ const { row } = input;
144
+ const lines = [
145
+ ...input.header.map((line) => `; ${line}`),
146
+ `; The show stage of the start screen from ${row.stage}: Exomizer packs it with the loader into loader.prg, with --entry '${formatC64Address(code)}'.`,
147
+ "; It shows the start screen, waits for a key or a fire button, copies back the bytes of the loader that the stage covers, and starts the loader.",
148
+ "",
149
+ "!cpu 6510",
150
+ ...input.settings,
151
+ "",
152
+ ...startScreenValues(row, input.plan),
153
+ ...(row.call === undefined ? [] : [`c64_source_ss_call = ${formatC64Address(row.call)} ; the routine of ${row.stage} that the start screen calls before it waits`]),
154
+ "",
155
+ `* = ${formatC64Address(code)}`,
156
+ STAGE_START,
157
+ " sei",
158
+ `!zone c64_source_start_screen {`,
159
+ `!source "${START_SCREEN_FILE}"`,
160
+ "}",
161
+ "!zone c64_source_stage {",
162
+ " sei",
163
+ " lda #$35",
164
+ " sta $01",
165
+ " ; The interrupts and the sound of the stage stop, and the display is off.",
166
+ " lda #$7f",
167
+ " sta $dc0d",
168
+ " sta $dd0d",
169
+ " lda #$00",
170
+ " sta $d01a",
171
+ " sta $d418",
172
+ " sta $d015",
173
+ " lda #$0f",
174
+ " sta $d019",
175
+ " lda #$0b",
176
+ " sta $d011",
177
+ " ; The CIA timers as RUN leaves them, as the loader expects: CIA 1 timer A",
178
+ " ; runs with the latch $4025 for the interrupt, the others stop at $ffff.",
179
+ " lda #$00",
180
+ " sta $dc0e",
181
+ " sta $dc0f",
182
+ " sta $dd0e",
183
+ " sta $dd0f",
184
+ " lda #$ff",
185
+ " sta $dc06",
186
+ " sta $dc07",
187
+ " sta $dd04",
188
+ " sta $dd05",
189
+ " sta $dd06",
190
+ " sta $dd07",
191
+ " lda #$08",
192
+ " sta $dc0f",
193
+ " sta $dd0e",
194
+ " sta $dd0f",
195
+ " lda #$25",
196
+ " sta $dc04",
197
+ " lda #$40",
198
+ " sta $dc05",
199
+ " lda #$11",
200
+ " sta $dc0e",
201
+ " lda #$81",
202
+ " sta $dc0d",
203
+ " lda $dc0d",
204
+ " lda $dd0d",
205
+ " ; The stash goes back to the loader, with all RAM in.",
206
+ " lda #$34",
207
+ " sta $01",
208
+ " ldx #0",
209
+ ".next lda .table,x",
210
+ " ora .table+1,x",
211
+ " beq .done",
212
+ " lda .table,x",
213
+ " sta .count",
214
+ " lda .table+1,x",
215
+ " sta .count+1",
216
+ " lda .table+2,x",
217
+ " sta .read+1",
218
+ " lda .table+3,x",
219
+ " sta .read+2",
220
+ " lda .table+4,x",
221
+ " sta .write+1",
222
+ " lda .table+5,x",
223
+ " sta .write+2",
224
+ " ldy #0",
225
+ ".read lda $ffff,y",
226
+ ".write sta $ffff,y",
227
+ " iny",
228
+ " bne +",
229
+ " inc .read+2",
230
+ " inc .write+2",
231
+ "+ lda .count",
232
+ " bne +",
233
+ " dec .count+1",
234
+ "+ dec .count",
235
+ " lda .count",
236
+ " ora .count+1",
237
+ " bne .read",
238
+ " txa",
239
+ " clc",
240
+ ` adc #${COPY_ENTRY}`,
241
+ " tax",
242
+ " jmp .next",
243
+ `.done lda #${formatC64Byte(input.innerPort)}`,
244
+ " sta $01",
245
+ ` jmp ${formatC64Address(input.innerStart)}`,
246
+ ".count !word 0",
247
+ ".table",
248
+ ...stash.map((item) => ` !word ${item.target.end - item.target.start + 1}, ${formatC64Address(item.at)}, ${formatC64Address(item.target.start)} ; ${show(item.target)} of the loader`),
249
+ " !word 0",
250
+ "}",
251
+ ...(input.colourRam === undefined ? [] : [`; The colour RAM of the capture of ${row.stage}.`, STAGE_COLOURS, ...byteLines({ start: 0, body: input.colourRam })]),
252
+ STAGE_CODE_END,
253
+ ];
254
+ for (const part of input.stage) {
255
+ lines.push("", `; ${row.stage} ${show(rangeOf(part))}`, stageLabel(part.start, "from"), `!pseudopc ${formatC64Address(part.start)} {`, ...byteLines(part), "}", stageLabel(part.start, "end"));
256
+ }
257
+ return `${lines.join("\n")}\n`;
258
+ }
259
+
260
+ /**
261
+ * What Exomizer packs: the loader without the bytes under the stage, the
262
+ * stash, the bytes of the stage at their addresses and the show code. `build`
263
+ * is the build of start_screen_stage.asm; `labels` gives its labels.
264
+ */
265
+ export function stageParts(input: StageInput, plan: StagePlan, build: Uint8Array, labels: (name: string) => number): StagePart[] {
266
+ const start = build[0]! | (build[1]! << 8);
267
+ const slice = (from: number, to: number) => build.subarray(2 + from - start, 2 + to - start);
268
+ const stageRanges = input.stage.map(rangeOf);
269
+ const loader = input.inner.flatMap((part) => subtract(rangeOf(part), stageRanges).map((range) => ({ start: range.start, body: part.body.subarray(range.start - part.start, range.end - part.start + 1) })));
270
+ const stash = plan.stash.map((item) => ({ start: item.at, body: Uint8Array.from({ length: item.target.end - item.target.start + 1 }, (_, offset) => byteOf(input.inner, item.target.start + offset)) }));
271
+ const stage = input.stage.map((part) => ({ start: part.start, body: slice(labels(stageLabel(part.start, "from")), labels(stageLabel(part.start, "end"))) }));
272
+ return [...loader, ...stash, ...stage, { start: plan.code, body: slice(plan.code, labels(STAGE_CODE_END)) }];
273
+ }