Examples:
- The four .asm examples used generic period syntax no installed assembler
accepts. They are now ca65 with BASIC stubs, and pass c64 test.
- bitmap-demo: SET_PIXEL clobbered the loop counter, colors went to $0400
while $D018 pointed at $8400, the clear missed 64 bytes, and ORA under
BASIC ROM copied ROM bytes into the bitmap. It now draws 200 clean pixels.
- kernal-io: GETIN clobbers X; the line index now lives in memory. The
stray SETLFS is replaced by a real drive-status read.
- irq-handler: the raster IRQ exits via $EA81 instead of re-running the
Kernal handler (which double-counted the jiffy clock).
- sound-demo: NOTE% and WAVEFORM tokenized as NOT/FOR (SYNTAX error).
- disk-access: closing channel 15 closed the data files, the error path
left file 1 open, LOAD "$" replaced the running program, and the read
loop tested ST too early. It now writes, reads, lists, and renames.
Toolchain: BASIC builds sort lines like the C64 editor and warn about
variable names that contain keywords; BASIC errors report their line;
-Disk attaches an image; each target gets build/test/<name>/;
-refreshonbreak keeps screenshots in step with the dump; absolute paths
resolve. tools/regress.ps1 runs all 17 cases (all pass).
AGENTS.md is now a short entry point (workflow, rules, skill/reference/
project indexes); README describes the commands and layout.
newLang's regression suite gives the same 22 pass / 4 fail as on cfa64d1
(map-artifact baselines and a Get-FileHash lookup in prepare-disk.ps1).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
refactor/agent-workflow
| @@ -85,9 +85,15 @@ fires it dumps RAM and I/O, decodes the text screen, and closes VICE. | |||
| If a program replaces the Kernal IRQ (`$0314` to code that never reaches `$EA31`), the | |||
| jiffy trigger never fires. Pass `-TickAddress <your IRQ entry>` instead. | |||
| Disk I/O also stops the jiffy count: the Kernal's serial routines run with IRQs off | |||
| while the C64 waits on the drive. Programs that use the disk should report through | |||
| `$D7FF` instead. | |||
| `-Disk <image>` attaches a disk image to drive 8 for programs that use files (make a | |||
| blank one with `c1541 -format "work,01" d64 work.d64`). A manifest can set `"disk"` under `test`. | |||
| Verdict: FAIL on timeout, on a non-zero `$D7FF` code, on a BASIC error (the runner | |||
| breaks on `$A437` and names the error, e.g. `BASIC error 11 (SYNTAX)`), or when any | |||
| breaks on `$A437` and names the error and line, e.g. `BASIC error 11 (SYNTAX) in line 40`), or when any | |||
| `-Expect "TEXT"` is missing from the screen (case-insensitive; repeat `-Expect` for | |||
| several strings). | |||
| @@ -110,7 +116,7 @@ On real hardware `$D7FF` is an unused SID register image, so these stores do not | |||
| and can stay in shipped code. `x64sc -debugcart` uses the same register (VICE exits | |||
| with the stored value) if you need a bare-VICE check. | |||
| ### Artifacts (`<project>/build/test/`) | |||
| ### Artifacts (`<project>/build/test/<name>/`) | |||
| | File | Contents | | |||
| |------|----------| | |||
| @@ -123,7 +129,7 @@ with the stored value) if you need a bare-VICE check. | |||
| Inspect a variable: find it in `build/<name>.lbl`, then read `ram.bin` at | |||
| `2 + address`. For example, with pwsh: | |||
| `$r=[IO.File]::ReadAllBytes("build/test/ram.bin"); $r[2+0x0834]`. | |||
| `$r=[IO.File]::ReadAllBytes("build/test/<name>/ram.bin"); $r[2+0x0834]`. | |||
| ### Testing patterns that work | |||
| @@ -135,6 +141,7 @@ Inspect a variable: find it in `build/<name>.lbl`, then read `ram.bin` at | |||
| scripted moves) or check the state after a fixed number of jiffies. | |||
| - **Regression set**: `c64 test projects/a projects/b examples/x.c` runs several and | |||
| prints `n/m passed`. | |||
| - **Toolchain changes**: `pwsh tools/regress.ps1` runs the repository's full suite. | |||
| ## Live debugging: `c64 run -Monitor` + `c64 mon` | |||
| @@ -158,6 +165,15 @@ leading dot. Use `watch store <addr>` to find who corrupts a variable, and `bank | |||
| | BASIC (`.bas` via petcat) | either; it is lowered by default | petcat tokenizes lower-case keywords; `{clr}`, `{wht}`, `{down}` are control codes | | |||
| | Screen RAM pokes | screen codes, not PETSCII | `A` = 1, `@` = 0, space = 32 | | |||
| BASIC builds sort lines by number, as the C64 editor does when you type them in (petcat | |||
| alone keeps file order, which breaks `GOTO` to a line placed earlier in the file). The | |||
| build warns about variable names that contain a keyword: `NOTE` tokenizes as `NOT E`, | |||
| and `WAVEFORM` as `WAVE FOR M` (even `SCORE` hides `OR`). Only the first two characters | |||
| of a variable name count, so `PLAYER1` and `PLAYER2` are the same variable `PL`. | |||
| 1541 gotcha: closing channel 15 makes the drive close every other open file. Open 15 | |||
| once, send commands with `PRINT#15,"S0:NAME"`, and close it last (`examples/disk-access.bas`). | |||
| ## Memory and build gotchas | |||
| - cc65 C programs load at `$0801`. The C stack and heap sit below `$D000` by default. | |||
| @@ -182,6 +198,9 @@ These shaped `tools/C64Tools.psm1`. Read them before you script VICE yourself: | |||
| - `quit` is ignored inside a `command` string but works from a playback file. Quitting | |||
| cleanly flushes `-monlog` and writes `-exitscreenshot`; killing the process loses both. | |||
| - The monitor `screenshot` command hangs when it runs from a checkpoint. Use `-exitscreenshot`. | |||
| - Warp mode skips rendering frames, so `-exitscreenshot` can show a frame from well | |||
| before the trigger. `-refreshonbreak` redraws the display when the checkpoint hits, | |||
| which makes the screenshot match the dump. VICE 3.10 has no `-refresh` option. | |||
| - `ignore <n> <count>` on `break exec ea31` gives a deterministic "after N jiffies" | |||
| trigger. A full-range `break exec 0000 ffff` with an ignore count never fired. | |||
| - Autostarting a `.d64` is about 10 s slower than injecting the PRG | |||
| @@ -344,7 +344,7 @@ The VICE manual explicitly warns that snapshot compatibility is not reliable acr | |||
| Use the repository toolchain (`.claude/skills/c64-workflow/SKILL.md`) instead of raw command lines: | |||
| 1. `c64 test <project>`: headless run. Prints the decoded screen and PASS/FAIL, and leaves | |||
| `ram.bin`, `io.bin`, `screenshot.png`, and `monitor.log` in `build/test/`. | |||
| `ram.bin`, `io.bin`, `screenshot.png`, and `monitor.log` in `build/test/<name>/`. | |||
| 2. `c64 test <project> -Until <label>`: capture state when a routine is reached. | |||
| 3. `c64 run <project> -Monitor`: interactive run with the remote monitor on port 6510 and | |||
| the build's labels loaded. | |||
| @@ -1,338 +1,117 @@ | |||
| # AGENTS.md — Commodore 64 Developer Knowledge Base | |||
| # AGENTS.md: Commodore 64 / 128 Development | |||
| > **Assembled by a collective of 150 expert Commodore 64 developers.** | |||
| > This file is the primary reference for AI agents assisting with Commodore 64 application development. | |||
| > Core C64 platform knowledge is sourced from canonical reference books (see Sources below). | |||
| > Supplemental modern emulator workflow guidance is included for **VICE 3.10** from the manual installed as `C:\Program Files\GTK3VICE-3.10-win64\doc\vice.pdf` (copy kept at `reference/vice.pdf`). | |||
| This repository is a workbench for writing Commodore 64 and C128 software with AI | |||
| agents. It provides a toolchain that builds, runs, and **checks** programs in VICE | |||
| without a human watching the screen; topic skills compiled from the classic | |||
| reference books; register and ROM reference tables; and several working projects. | |||
| --- | |||
| ## Start here | |||
| ## How to Use This Knowledge Base | |||
| 1. Load `.claude/skills/c64-workflow/SKILL.md`. It covers the build/test/debug loop and | |||
| the traps that cost the most time. | |||
| 2. Run `c64 doctor` once per machine. It needs cc65 and VICE 3.x; `pwsh` runs the tools. | |||
| 3. Load the topic skill for the domain (table below) before you write hardware code. | |||
| 4. Finish only when `c64 test` passes and you have read the screen it prints. | |||
| This repository contains structured skills and reference material for developing software on the Commodore 64. Each subdirectory under `.claude/skills/` is a self-contained topic skill. When answering a C64 development question, consult the most relevant skill first, then cross-reference the `reference/` files. | |||
| ### Skill Index | |||
| | Directory | Topic | When to Use | | |||
| |-----------|-------|-------------| | |||
| | `.claude/skills/6510-assembly/` | 6510 CPU, opcodes, addressing modes, registers | Writing or debugging assembly/ML programs | | |||
| | `.claude/skills/memory-map/` | Complete C64 memory layout, zero page, banking | Memory management, PEEK/POKE, ML placement | | |||
| | `.claude/skills/graphics-vic2/` | VIC-II chip, sprites, character modes, color | All graphics programming | | |||
| | `.claude/skills/sound-sid/` | SID 6581, ADSR, waveforms, filters | Music and sound effects | | |||
| | `.claude/skills/disk-io-1541/` | 1541 DOS, file types, direct access | Disk operations, file I/O | | |||
| | `.claude/skills/kernal-routines/` | OS jump table, screen/serial/tape I/O | Using built-in OS calls from ML | | |||
| | `.claude/skills/basic-programming/` | BASIC 2.0 interpreter, extending BASIC, tokens | BASIC programs, BASIC extensions | | |||
| | `.claude/skills/interrupts/` | IRQ, NMI, CIA timers, raster interrupts | Interrupt-driven code, timing | | |||
| | `.claude/skills/compiler-design/` | Compiler & assembler construction for C64/128 | Writing compilers, assemblers, parsers | | |||
| | `.claude/skills/vice-emulator/` | VICE emulator, autostart, monitor, snapshots, automation | Running, testing, and debugging C64 software in VICE | | |||
| | `.claude/skills/powerc/` | Power C compiler on the C64 | Writing, compiling, linking, and running C programs with Power C (reference/POWERc.d81); load this whenever Power C or on-C64 C development is requested | | |||
| ### Reference Files | |||
| | File | Contents | | |||
| |------|----------| | |||
| | `reference/memory-map-complete.md` | All C64 memory locations with descriptions | | |||
| | `reference/6510-opcodes.md` | Full 6510 opcode table | | |||
| | `reference/kernal-jumplist.md` | All Kernal jump table addresses and parameters | | |||
| | `reference/vic-registers.md` | VIC-II chip register map | | |||
| | `reference/sid-registers.md` | SID chip register map | | |||
| | `reference/cia-registers.md` | CIA 6526 register map | | |||
| | `reference/disk-dos-commands.md` | 1541 DOS command reference | | |||
| | `reference/vice-usage.md` | VICE 3.10 emulator, monitor, autostart, and automation reference | | |||
| | `reference/vice.pdf` | VICE 3.10 manual as shipped with the emulator | | |||
| | `reference/POWERc.d81` | Power C compiler, libraries, and headers (copy before writing to it) | | |||
| | `reference/Power_C_Instruction_Manual.pdf` | Power C Instruction Manual (Spinnaker, 1986) | | |||
| ### Example Programs | |||
| | File | Description | | |||
| |------|-------------| | |||
| | `examples/hello-world.asm` | Minimal 6510 assembly hello world | | |||
| | `examples/bitmap-demo.asm` | Hi-res 320×200 bitmap mode: draws a diagonal line, key returns to text mode | | |||
| | `examples/sprite-demo.bas` | BASIC sprite programming demo | | |||
| | `examples/sprite-music-demo.bas` | Multicolor sprite moving to a SID bass line | | |||
| | `examples/sound-demo.bas` | SID chip sound demo in BASIC | | |||
| | `examples/disk-access.bas` | Sequential and relative file access | | |||
| | `examples/irq-handler.asm` | Custom IRQ handler skeleton | | |||
| | `examples/kernal-io.asm` | Using Kernal routines for I/O | | |||
| | `examples/moonlander.c` | Lunar Lander game in C (cc65), joystick control | | |||
| | `examples/moonlander.prg` | Built `moonlander.c` binary | | |||
| | `examples/moonlander-build.bat` | Build `moonlander.c` with `cl65`; `-run` also launches it | | |||
| | `examples/run.bat` | Rebuild if needed, then autostart `moonlander.prg` in VICE | | |||
| | `examples/linked-list-test.c` | `malloc`-backed linked list tests plus a heap capacity probe (cc65) | | |||
| | `examples/linked-list-test.prg` | Built `linked-list-test.c` binary | | |||
| | `examples/linked-list-test-build.bat` | Build `linked-list-test.c` with `cl65`; `-run` also launches it | | |||
| | `examples/powerc-hello.c` | Minimal Power C program; ASCII source converted to PETSCII for the disk | | |||
| | `examples/powerc-hello.d81` | Power C work disk with `hello.c` compiled, linked, and ready to run | | |||
| | `examples/powerc-work.d81` | Writable working copy of the Power C system disk | | |||
| | `examples/powerc-build.bat` | Run a Power C Shell command sequence on a work disk via `-keybuf` | | |||
| | `examples/powerc-ced.bat` | Boot the Power C system disk and enter the `ced` editor | | |||
| | `examples/vice-autostart-c64os.bat` | Launch `c64os.prg` directly in `x64sc` | | |||
| | `examples/vice-monitor-c64os.txt` | VICE monitor playback script for debugging `c64os.prg` | | |||
| | `examples/vice-debug-c64os.bat` | Launch `c64os.prg` with VICE native monitor and debug-friendly options | | |||
| | `examples/vice-monitor-c64os-debug.txt` | Repeatable VICE debugging session with breakpoints, watchpoints, and keyboard injection | | |||
| --- | |||
| ## System Overview | |||
| The Commodore 64 (1982) features: | |||
| - **CPU**: MOS 6510 (6502-compatible, 1 MHz NTSC / ~0.985 MHz PAL) | |||
| - **RAM**: 64KB (not all simultaneously accessible) | |||
| - **ROM**: 20KB total — 8KB BASIC ($A000–$BFFF), 8KB Kernal ($E000–$FFFF), 4KB Character ROM ($D000 when banked in) | |||
| - **Graphics**: VIC-II (MOS 6567 NTSC / 6569 PAL) at $D000–$D3FF | |||
| - **Sound**: SID MOS 6581 at $D400–$D7FF | |||
| - **I/O**: Two CIA 6526 chips at $DC00–$DCFF (CIA #1) and $DD00–$DDFF (CIA #2) | |||
| - **Screen**: 40×25 text, 320×200 bitmap, 160×200 multicolor | |||
| - **Colors**: 16 colors | |||
| - **Sprites**: 8 hardware sprites (24×21 pixels each) | |||
| --- | |||
| ## Memory Architecture Quick Reference | |||
| ``` | |||
| $0000–$00FF Zero Page — CPU registers, BASIC/Kernal variables (fast access) | |||
| $0100–$01FF Stack — 6510 hardware stack | |||
| $0200–$03FF Pages 2–3 — OS/BASIC working storage, vectors | |||
| $0400–$07FF Screen RAM — Default video matrix (40×25 = 1000 bytes) | |||
| $0800–$9FFF BASIC RAM — BASIC program area (default: $0801–$9FFF) | |||
| $A000–$BFFF BASIC ROM — Microsoft BASIC 2.0 (or RAM when banked out) | |||
| $C000–$CFFF Free RAM — ML programs, data (4KB always RAM) | |||
| $D000–$D3FF VIC-II — Graphics chip registers (I/O mode) | |||
| $D400–$D7FF SID — Sound chip registers (I/O mode) | |||
| $D800–$DBFF Color RAM — Screen color data (nybble wide, 1000 bytes) | |||
| $DC00–$DCFF CIA #1 — Keyboard, joystick, IRQ timer | |||
| $DD00–$DDFF CIA #2 — Serial bus, NMI timer, VIC-II bank select | |||
| $E000–$FFFF Kernal ROM — Operating system (or RAM when banked out) | |||
| ``` | |||
| **Memory bank control** — Location $0001 (6510 I/O port), bits 2-0 = CHAREN HIRAM LORAM: | |||
| ``` | |||
| %111 $37 BASIC ROM, I/O, Kernal ROM (default) | |||
| %110 $36 RAM at $A000, I/O, Kernal ROM | |||
| %101 $35 RAM at $A000 and $E000, I/O visible | |||
| %100 $34 all RAM | |||
| %011 $33 BASIC + Kernal ROM, character ROM at $D000 (no I/O) | |||
| %000 $30 all RAM | |||
| c64 new <name> -Template c|asm|basic # projects/<name> | |||
| c64 build <project|file.c|file.s|file.bas> | |||
| c64 test <project|file|prg> [-Expect TEXT] [-Until label] [-AfterJiffies n] [-Keys "x\n"] | |||
| c64 run <project|file|prg|d64> [-Monitor] [-FromDisk] | |||
| c64 mon "r" "m .label .label+8" # talk to a run started with -Monitor | |||
| ``` | |||
| BASIC ROM needs LORAM=1 and HIRAM=1. Full table: `.claude/skills/memory-map/SKILL.md`. | |||
| --- | |||
| ## Critical Zero-Page Locations | |||
| | Address | Dec | Name | Description | | |||
| |---------|-----|------|-------------| | |||
| | $0000 | 0 | D6510 | 6510 data direction register | | |||
| | $0001 | 1 | R6510 | 6510 I/O port (memory banking, cassette) | | |||
| | $0002 | 2 | — | Unused (free for user) | | |||
| | $0014-$0015 | 20-21 | LINNUM | Integer value / line number / SYS address | | |||
| | $002B-$002C | 43-44 | TXTTAB | Start of BASIC program | | |||
| | $002D-$002E | 45-46 | VARTAB | Start of BASIC variables | | |||
| | $0033-$0034 | 51-52 | FRETOP | Bottom of string storage | | |||
| | $0037-$0038 | 55-56 | MEMSIZ | Top of BASIC RAM + 1 | | |||
| | $0061-$0066 | 97-102 | FAC1 | Floating-point accumulator #1 | | |||
| | $007A-$007B | 122-123 | TXTPTR | BASIC text pointer (inside CHRGET $73-$8A) | | |||
| | $0090 | 144 | STATUS | Kernal I/O status (ST) | | |||
| | $00A0-$00A2 | 160-162 | TIME | Jiffy clock (big-endian) | | |||
| | $00AC-$00AF | 172-175 | SAL/EAL | LOAD/SAVE current and end address | | |||
| | $00BA | 186 | FA | Current device number | | |||
| | $00C6 | 198 | NDX | Keyboard buffer count | | |||
| | $00FB-$00FE | 251-254 | FREKZP | Free zero page (user) | | |||
| Complete table: `reference/memory-map-complete.md`. | |||
| ---------|-----|------|-------------| | |||
| | $0000 | 0 | R6510 | 6510 I/O direction register | | |||
| | $0001 | 1 | M6510 | 6510 I/O port (memory bank/tape) | | |||
| | $0002 | 2 | — | Unused (free for user) | | |||
| | $0003-$0004 | 3-4 | ADRAY1 | Float→fixed vector | | |||
| | $0005-$0006 | 5-6 | ADRAY2 | Fixed→float vector | | |||
| | $0007 | 7 | CHARAC | Search character | | |||
| | $0014-$0015 | 20-21 | — | Integer value | | |||
| | $002B-$002C | 43-44 | TXTTAB | Start of BASIC program | | |||
| | $002D-$002E | 45-46 | VARTAB | Start of variable area | | |||
| | $0030-$0031 | 48-49 | FRETOP | Top of string storage | | |||
| | $0037-$0038 | 55-56 | MEMSIZ | Pointer to end of BASIC RAM | | |||
| | $0039-$003A | 57-58 | CURLIN | Current BASIC line number | | |||
| | $003E-$003F | 62-63 | OLDLIN | Previous BASIC line number | | |||
| | $0052-$0053 | 82-83 | OLDTXT | Previous BASIC text pointer | | |||
| | $007A-$007B | 122-123 | FNPNT | Floating point accumulator | | |||
| | $00AC-$00AD | 172-173 | STRNG1 | Start of string 1 | | |||
| | $00C1 | 193 | SAL | Save start address (low) | | |||
| | $00C2 | 194 | SAH | Save start address (high) | | |||
| | $00AE-$00AF | 174-175 | FRESPC | String utility pointer | | |||
| | $00FB-$00FE | 251-254 | — | Free zero-page (user) | | |||
| --- | |||
| ## Kernal Jump Table Quick Reference | |||
| All Kernal routines are called via JSR to their jump table address ($FFxx). The jump table is always available regardless of ROM banking mode. | |||
| | Address | Name | Function | | |||
| |---------|------|----------| | |||
| | $FF81 | CINT | Initialize screen editor | | |||
| | $FF84 | IOINIT | Initialize I/O devices | | |||
| | $FF87 | RAMTAS | Test/initialize RAM | | |||
| | $FF8A | RESTOR | Restore default I/O vectors | | |||
| | $FF8D | VECTOR | Read/set RAM vectors | | |||
| | $FF90 | SETMSG | Control OS messages | | |||
| | $FF93 | SECOND | Send secondary address after LISTEN | | |||
| | $FF96 | TKSA | Send secondary address after TALK | | |||
| | $FF99 | MEMTOP | Read/set top of memory | | |||
| | $FF9C | MEMBOT | Read/set bottom of memory | | |||
| | $FF9F | SCNKEY | Scan keyboard | | |||
| | $FFA2 | SETTMO | Set serial bus timeout | | |||
| | $FFA5 | ACPTR | Input byte from serial bus | | |||
| | $FFA8 | CIOUT | Output byte to serial bus | | |||
| | $FFAB | UNTLK | Send UNTALK to serial bus | | |||
| | $FFAE | UNLSN | Send UNLISTEN to serial bus | | |||
| | $FFB1 | LISTEN | Command device to LISTEN | | |||
| | $FFB4 | TALK | Command device to TALK | | |||
| | $FFB7 | READST | Read I/O status word | | |||
| | $FFBA | SETLFS | Set logical/device/command | | |||
| | $FFBD | SETNAM | Set filename | | |||
| | $FFC0 | OPEN | Open logical file | | |||
| | $FFC3 | CLOSE | Close logical file | | |||
| | $FFC6 | CHKIN | Open channel for input | | |||
| | $FFC9 | CHKOUT | Open channel for output | | |||
| | $FFCC | CLRCH | Close input/output channels | | |||
| | $FFCF | BASIN | Input character from channel | | |||
| | $FFD2 | BSOUT | Output character to channel | | |||
| | $FFD5 | LOAD | Load from device | | |||
| | $FFD8 | SAVE | Save to device | | |||
| | $FFDB | SETTIM | Set real-time clock | | |||
| | $FFDE | RDTIM | Read real-time clock | | |||
| | $FFE1 | STOP | Test STOP key | | |||
| | $FFE4 | GETIN | Get character from queue | | |||
| | $FFE7 | CLALL | Close all files | | |||
| | $FFEA | UDTIM | Increment real-time clock | | |||
| | $FFED | SCREEN | Return screen dimensions | | |||
| | $FFF0 | PLOT | Read/set cursor position | | |||
| | $FFF3 | IOBASE | Return base address of I/O | | |||
| --- | |||
| ## Source Books | |||
| `c64` is `c64.cmd` at the repo root (from PowerShell: `.\c64.cmd`; from Git Bash: | |||
| `./c64.cmd`). Exit codes: 0 ok, 1 test failed, 2 usage or tool error. | |||
| ## Rules | |||
| - **Verify on the emulator.** A program that compiles is not done. Use `c64 test` | |||
| with `-Expect` for screen text, or report from code through `$D7FF` (`lib/c64test.h`, | |||
| `lib/c64test.inc`). Use `build/test/<name>/screenshot.png` for graphics and sprites. | |||
| - **Pick the toolchain the user asked for.** cc65 C and ca65 assembly are the defaults. | |||
| Power C means on-machine K&R C: load `.claude/skills/powerc/SKILL.md`, and never write | |||
| to `reference/POWERc.d81` (copy it first). | |||
| - **Write addresses in hex with `$`**, adding decimal when they appear in BASIC `PEEK` | |||
| or `POKE` (`$D020` = 53280). | |||
| - **Check banking** before touching `$A000-$BFFF`, `$D000-$DFFF`, or `$E000-$FFFF`. The | |||
| CPU sees ROM, RAM, I/O, or character ROM depending on `$01`. | |||
| - **Prefer Kernal routines** (`$FFD2` CHROUT, `$FFE4` GETIN, `$FFBA`/`$FFBD`/`$FFC0` for | |||
| files) over custom I/O unless speed or banking rules them out. | |||
| - **State PAL or NTSC** for anything timing-sensitive (raster splits, SID pitch). | |||
| VICE defaults to PAL. | |||
| - **Free zero page** while BASIC and the Kernal are live: `$02`, `$FB-$FE`. cc65 C | |||
| programs own `$02-$1B` for their runtime. | |||
| - **Keep the suite green.** After changing `tools/`, `templates/`, `lib/`, or an example, | |||
| run `pwsh tools/regress.ps1` (about 2 minutes, 17 cases). | |||
| - **Respect sub-project rules.** `newLang/` has its own `AGENTS.md`; read it before | |||
| changing anything there. | |||
| ## Skills (`.claude/skills/`) | |||
| | Skill | Use for | | |||
| |-------|---------| | |||
| | `c64-workflow` | **Always**: c64 commands, c64project.json, testing, debugging, charset traps | | |||
| | `6510-assembly` | Opcodes, addressing modes, ML idioms, calling ML from BASIC | | |||
| | `memory-map` | Zero page, banking via `$01`, VIC banks, safe places for code and data | | |||
| | `graphics-vic2` | Text/bitmap/multicolor modes, sprites, scrolling, raster tricks | | |||
| | `sound-sid` | SID registers, ADSR, waveforms, filters, music drivers | | |||
| | `interrupts` | IRQ/NMI, CIA timers, raster interrupts, stable raster | | |||
| | `kernal-routines` | Kernal jump table, screen/serial/disk I/O from ML | | |||
| | `disk-io-1541` | 1541 DOS commands, file types, direct access, error channel | | |||
| | `basic-programming` | BASIC 2.0 internals, tokens, extending BASIC, FP routines | | |||
| | `compiler-design` | Compilers and assemblers that run on or target the 64/128 | | |||
| | `vice-emulator` | VICE options, monitor commands, checkpoints, snapshots | | |||
| | `powerc` | Spinnaker Power C on the C64 (`reference/POWERc.d81`) | | |||
| ## Reference (`reference/`) | |||
| This knowledge base was compiled from these canonical references: | |||
| 1. **The Anatomy of the Commodore 64** — Angerhausen, Becker, Englisch, Gerits (Abacus/Data Becker) | |||
| 2. **The Machine Language Book for the Commodore 64** — Lothar Englisch (Abacus) | |||
| 3. **The Advanced Machine Language Book for the Commodore 64** — (Abacus) | |||
| 4. **COMPUTE!'s Mapping the Commodore 64** — Sheldon Leemon (COMPUTE! Publications) | |||
| 5. **COMPUTE!'s VIC-20 and Commodore 64 Tool Kit: BASIC** — Dan Heeb (COMPUTE!) | |||
| 6. **COMPUTE!'s VIC-20 and Commodore 64 Tool Kit: Kernal** — (COMPUTE!) | |||
| 7. **The Anatomy of the 1541 Disk Drive (Revised Edition)** — (Abacus) | |||
| 8. **The Complete Commodore 64 ROM Disassembly** — P.G. & K.B. (Melbourne House) | |||
| 9. **Compiler Design and Implementation (64 and 128)** — (Abacus) | |||
| 10. **COMPUTE!'s SpeedScript** — (COMPUTE!) — word processor source & techniques | |||
| 11. **Invaluable Utilities for the Commodore 64** — (various) | |||
| ### Supplemental Emulator Source | |||
| 12. **VICE 3.10 Manual** — `C:\Program Files\GTK3VICE-3.10-win64\doc\vice.pdf` (copy: `reference/vice.pdf`) | |||
| - Use for emulator operation, autostart behavior, monitor commands, snapshots, and automation interfaces | |||
| --- | |||
| ## Agent Workflow | |||
| When an AI agent receives a C64 development question: | |||
| 1. **Identify the domain** using the Skill Index table above | |||
| 2. **Load the relevant SKILL.md** from the appropriate `.claude/skills/` subdirectory | |||
| 3. **Cross-reference** `reference/` files for specific register values, addresses, or opcodes | |||
| 4. **Check examples/** for working code patterns | |||
| 5. **If the task involves running or debugging software in an emulator**, load `.claude/skills/vice-emulator/SKILL.md` and `reference/vice-usage.md` | |||
| 6. **If the task involves writing C for the C64** (user mentions C, Power C, `ced`, `cc`, `link`, or `reference/POWERc.d81`), load `.claude/skills/powerc/SKILL.md` first. Power C is K&R C (no prototypes/`void`, 2-byte `int`, 8-char identifiers), sources on disk are PETSCII, and `cc`/`link` need specific steps. Also load `.claude/skills/vice-emulator/SKILL.md` to automate the build in VICE (copy `reference/POWERc.d81` first; never write to the original). Note: `examples/moonlander.c` and `examples/linked-list-test.c` use **cc65**, not Power C; pick the toolchain the user asked for. | |||
| 7. **Apply the 150-expert consensus**: prefer documented Kernal routines over custom implementations; use zero-page for speed; always consider memory banking when accessing $D000–$DFFF | |||
| --- | |||
| ## Development Conventions | |||
| - Write machine addresses in hexadecimal with a `$` prefix (for example, `$D000` and `$FFD2`). Include decimal equivalents when an address is used with BASIC `PEEK` or `POKE` (for example, `$D000` = `53248`). | |||
| - Check memory banking before accessing `$A000–$FFFF`; the CPU may see ROM, RAM, I/O, or character ROM depending on the 6510 port at `$0001`. | |||
| - Prefer Kernal routines for standard I/O and use zero page for variables that benefit from faster access. Keep BASIC's memory ceiling below machine code that BASIC might otherwise overwrite. | |||
| - State whether timing-sensitive code assumes PAL or NTSC, especially for raster timing and sound frequencies. | |||
| ### Hardware Limits to Check | |||
| | Resource | Limit or behavior | | |||
| |----------|-------------------| | |||
| | Default BASIC program area | `$0801–$9FFF` (38,911 addressable bytes; usable free space is lower) | | |||
| | 6510 hardware stack | `$0100–$01FF` (256 bytes) | | |||
| | Default screen matrix | `$0400–$07E7` (1,000 visible character cells) | | |||
| | Color RAM | `$D800–$DBE7` (1,000 visible 4-bit color cells when I/O is mapped in) | | |||
| | VIC-II address space | One 16KB bank at a time, selected by CIA #2 at `$DD00`, bits 0–1 | | |||
| | Sprite data | 64 bytes per block; at most 256 block positions in a 16KB VIC bank | | |||
| | SID reads | `$D400–$D418` are write-only; `$D419–$D41C` provide paddle, oscillator 3, and envelope 3 readings | | |||
| | Character ROM | CPU-readable at `$D000–$DFFF` only under the appropriate `$0001` banking configuration | | |||
| ### Development Tools | |||
| VICE is the emulator used by the examples in this repository. Common modern assemblers include KickAssembler, ACME, ca65, and 64tass; CBM .prg Studio is a Windows IDE, C64 debugger provides visual debugging with VICE integration, and Exomizer and Pucrunch are executable crunchers. Period tools include SUPERMON, Mikro Assembler, PAL, and Simon's BASIC. | |||
| --- | |||
| ## VICE Debug Workflow | |||
| When debugging a C64 program in VICE, agents should prefer this flow: | |||
| 1. Launch `x64sc` rather than the older `x64` | |||
| 2. Prefer `-nativemonitor -keepmonopen -refreshonbreak` for interactive debugging | |||
| 3. Start the monitor session with `sidefx off` | |||
| 4. Break at the machine-code entry point or suspicious routine | |||
| 5. Use `step`, `next`, `return`, and `backtrace` intentionally rather than single-stepping blindly | |||
| 6. Use watchpoints for critical C64 state such as `$0001`, `$0314/$0315`, screen RAM, color RAM, and I/O registers | |||
| 7. Use monitor playback files from `examples/` to make debug sessions repeatable | |||
| 8. Use snapshots for short-lived checkpoints only, not archival state | |||
| For this repository specifically: | |||
| - `examples/vice-debug-c64os.bat` launches `c64os.prg` with monitor-friendly options | |||
| - `examples/vice-monitor-c64os-debug.txt` sets up a practical debug session for startup, banking, and command input | |||
| --- | |||
| ## Common Development Patterns | |||
| | File | Contents | | |||
| |------|----------| | |||
| | `memory-map-complete.md` | Complete zero page, pages 2-3, I/O map, `$01` banking | | |||
| | `6510-opcodes.md` | All opcodes with modes, cycles, flags | | |||
| | `kernal-jumplist.md` | Kernal jump table with inputs and outputs | | |||
| | `vic-registers.md`, `sid-registers.md`, `cia-registers.md` | Chip register maps | | |||
| | `disk-dos-commands.md` | 1541 DOS commands, error codes, disk layout | | |||
| | `vice-usage.md` | VICE 3.10 command line and monitor quick reference | | |||
| | `vice.pdf` | VICE 3.10 manual | | |||
| | `POWERc.d81`, `Power_C_Instruction_Manual.pdf` | Power C system disk (read-only) and manual | | |||
| | `powerc-re/` | Power C reverse engineering: patched compiler/runtime, smaller and faster output | | |||
| ## Projects | |||
| | Path | What | Build / check | | |||
| |------|------|---------------| | |||
| | `projects/` | New programs from `c64 new` | `c64 test projects/<name>` | | |||
| | `templates/{c,asm,basic}` | Skeletons with a passing self-test | used by `c64 new` | | |||
| | `examples/` | Single-file examples (BASIC, ca65, cc65 C, Power C disks) | exact commands in `tools/regress.ps1` | | |||
| | `skirmish-game/` | Tactical game in ca65 assembly | `c64 test skirmish-game` | | |||
| | `samples/kernal-os-skeleton/` | Kernal-resident OS shell (+ `vim.asm` via `build_vim.bat`) | `c64 test samples/kernal-os-skeleton` | | |||
| | `samples/cc65-mouse-driver-demo/` | cc65 1351 mouse driver demo | `c64 test samples/cc65-mouse-driver-demo` | | |||
| | `vim/` | vi clone: Power C on the C64, cc65 port for the C128 (`vim128.c`) | see `vim/NOTES.md` | | |||
| | `newLang/` | Nova128: an OO language and on-machine compiler for the C128 | see `newLang/AGENTS.md` | | |||
| ## Platform summary | |||
| ### Running ML from BASIC | |||
| ```basic | |||
| 10 FOR I=49152 TO 49162 : READ D : POKE I,D : NEXT | |||
| 20 SYS 49152 | |||
| 30 DATA 169,0,141,32,208,169,15,141,33,208,96 | |||
| ``` | |||
| $0000-$00FF zero page $0100-$01FF stack $0200-$03FF OS work area, vectors | |||
| $0400-$07E7 screen (default) $0801-$9FFF BASIC program $A000-$BFFF BASIC ROM / RAM | |||
| $C000-$CFFF free RAM $D000-$DFFF I/O or char ROM / RAM | |||
| $D000 VIC-II $D400 SID $D800 color RAM $DC00 CIA 1 (keyboard, joystick, IRQ) $DD00 CIA 2 (VIC bank, serial, NMI) | |||
| $E000-$FFFF Kernal ROM / RAM | |||
| ### Protecting ML from BASIC | |||
| ```basic | |||
| POKE 56,192 : CLR ' Sets BASIC top to $C000 (49152) | |||
| $01 bits 2-0 (CHAREN HIRAM LORAM): %111 $37 default | %110 $36 BASIC out | %101 $35 all RAM + I/O | %100 $34 all RAM | |||
| ``` | |||
| ### Reading the Kernal status after I/O | |||
| ```asm | |||
| JSR $FFB7 ; READST — status in Accumulator | |||
| BNE error ; any non-zero means error | |||
| ``` | |||
| CPU: 6510 at 0.985 MHz (PAL) or 1.023 MHz (NTSC). 16 colors, 8 hardware sprites (24×21), | |||
| 40×25 text, 320×200 hi-res, 160×200 multicolor. Full details are in the skills and `reference/`. | |||
| ### Setting up a custom IRQ | |||
| ```asm | |||
| SEI ; disable interrupts | |||
| LDA #<my_irq ; low byte of handler | |||
| STA $0314 | |||
| LDA #>my_irq ; high byte | |||
| STA $0315 | |||
| CLI ; enable interrupts | |||
| ``` | |||
| ## Sources | |||
| ### Assembly program skeleton | |||
| ```asm | |||
| *=$C000 ; assemble at $C000 (49152) | |||
| START JSR $FF81 ; CINT: initialize the screen editor | |||
| ; program code goes here | |||
| RTS ; return to BASIC when entered with SYS 49152 | |||
| ``` | |||
| Platform knowledge was compiled from: *The Anatomy of the Commodore 64*; *The Machine | |||
| Language Book* and *The Advanced Machine Language Book for the Commodore 64* (Abacus); | |||
| *COMPUTE!'s Mapping the Commodore 64*; *COMPUTE!'s VIC-20 and Commodore 64 Tool Kit* | |||
| (BASIC and Kernal); *The Anatomy of the 1541 Disk Drive*; *The Complete Commodore 64 | |||
| ROM Disassembly*; *Compiler Design and Implementation (64 and 128)*; *COMPUTE!'s | |||
| SpeedScript*; and *Invaluable Utilities for the Commodore 64*. Emulator material comes | |||
| from the VICE 3.10 manual. Toolchain behavior was verified on this repository. | |||
| @@ -1,130 +1,89 @@ | |||
| # C64 Developer Knowledge Base | |||
| ### Built by 150 Expert Commodore 64 Developers | |||
| # C64 DevSetup | |||
| A comprehensive reference system for AI agents and human developers building applications on the Commodore 64. Synthesized from 11 canonical C64 reference books, with supplemental VICE 3.10 emulator workflow notes for modern testing and debugging. | |||
| --- | |||
| ## Source Books | |||
| 1. *The Anatomy of the Commodore 64* | |||
| 2. *The Machine Language Book for the Commodore 64* | |||
| 3. *The Advanced Machine Language Book for the Commodore 64* | |||
| 4. *Compute's Mapping the Commodore 64* | |||
| 5. *Compute's VIC-20 & C64 Tool Kit: BASIC* | |||
| 6. *Compute's VIC-20 & C64 Tool Kit: Kernal* | |||
| 7. *The Anatomy of the 1541 Disk Drive (Revised Edition)* | |||
| 8. *The Complete Commodore 64 ROM Disassembly* | |||
| 9. *Compiler Design and Implementation (64 and 128)* | |||
| 10. *Compute's SpeedScript* | |||
| 11. *Invaluable Utilities for the Commodore 64* | |||
| --- | |||
| ## File Structure | |||
| A workbench for writing Commodore 64 and C128 software, set up for AI coding agents | |||
| and the people working with them. One command builds a program, runs it headlessly in | |||
| VICE, and prints what the C64 screen shows, so changes are checked on the (emulated) | |||
| machine rather than assumed. | |||
| ``` | |||
| c64-dev-knowledge/ | |||
| ├── README.md ← This file | |||
| ├── CLAUDE.md ← AI agent entry point | |||
| ├── AGENTS.md ← Full AI reference document | |||
| │ | |||
| ├── skills/ ← Topic skill files (SKILL.md in each) | |||
| │ ├── 6510-assembly/ ← CPU, registers, opcodes, idioms | |||
| │ ├── memory-map/ ← Address space, banking, zero page | |||
| │ ├── graphics-vic2/ ← VIC-II modes, sprites, raster IRQ | |||
| │ ├── sound-sid/ ← SID registers, music, effects | |||
| │ ├── disk-io-1541/ ← 1541 DOS, file types, error codes | |||
| │ ├── kernal-routines/ ← Kernal jump table, I/O patterns | |||
| │ ├── basic-programming/ ← BASIC internals, extending BASIC | |||
| │ ├── interrupts/ ← IRQ/NMI handlers, CIA, VIC timing | |||
| │ ├── compiler-design/ ← Assembler/compiler construction | |||
| │ └── vice-emulator/ ← VICE launch, monitor, autostart, automation | |||
| │ | |||
| ├── reference/ ← Quick-lookup tables | |||
| │ ├── memory-map-complete.md ← Full $0000–$FFFF address map | |||
| │ ├── 6510-opcodes.md ← All opcodes with cycles/flags | |||
| │ ├── vic-registers.md ← VIC-II $D000–$D02E register table | |||
| │ ├── sid-registers.md ← SID $D400–$D418 register table | |||
| │ ├── cia-registers.md ← CIA #1 and #2 register tables | |||
| │ ├── kernal-jumplist.md ← All Kernal jump table entries | |||
| │ ├── disk-dos-commands.md ← DOS commands, error codes, disk layout | |||
| │ └── vice-usage.md ← VICE 3.10 emulator and monitor quick reference | |||
| │ | |||
| └── examples/ ← Working code examples | |||
| ├── hello-world.asm ← Minimal 6510 assembly hello world | |||
| ├── irq-handler.asm ← Custom raster IRQ installation | |||
| ├── kernal-io.asm ← File I/O using Kernal routines | |||
| ├── bitmap-demo.asm ← Hi-res 320×200 bitmap mode | |||
| ├── sprite-demo.bas ← Sprite animation in BASIC | |||
| ├── sprite-music-demo.bas ← Multicolor sprite + SID music | |||
| ├── sound-demo.bas ← SID waveforms, ADSR, chords | |||
| ├── disk-access.bas ← Sequential/relative file I/O | |||
| ├── vice-autostart-c64os.bat ← Launch c64os.prg in x64sc | |||
| ├── vice-debug-c64os.bat ← Launch c64os.prg with VICE native monitor | |||
| ├── vice-monitor-c64os.txt ← VICE monitor playback commands | |||
| └── vice-monitor-c64os-debug.txt ← Repeatable VICE debug session | |||
| > c64 new invaders -Template c | |||
| created projects\invaders from templates\c | |||
| > c64 test projects/invaders | |||
| built projects\invaders\build\invaders.prg $0801-$0B27 (807 bytes) | |||
| +----------------------------------------+ | |||
| |invaders | | |||
| |READY TO GO | | |||
| +----------------------------------------+ | |||
| PASS invaders [d7ff, 3.1s] artifacts: projects\invaders\build\test\invaders | |||
| ``` | |||
| --- | |||
| ## Quick-Start by Topic | |||
| ## Requirements | |||
| | I want to… | Start here | | |||
| |-----------|-----------| | |||
| | Write 6510 machine code | `.claude/skills/6510-assembly/SKILL.md` | | |||
| | Understand the memory map | `.claude/skills/memory-map/SKILL.md` + `reference/memory-map-complete.md` | | |||
| | Program sprites or bitmap graphics | `.claude/skills/graphics-vic2/SKILL.md` | | |||
| | Make sound or music | `.claude/skills/sound-sid/SKILL.md` | | |||
| | Read/write disk files | `.claude/skills/disk-io-1541/SKILL.md` | | |||
| | Use Kernal routines | `.claude/skills/kernal-routines/SKILL.md` + `reference/kernal-jumplist.md` | | |||
| | Extend or interface with BASIC | `.claude/skills/basic-programming/SKILL.md` | | |||
| | Write custom IRQ handlers | `.claude/skills/interrupts/SKILL.md` | | |||
| | Build a compiler or assembler | `.claude/skills/compiler-design/SKILL.md` | | |||
| | Run or debug software in VICE | `.claude/skills/vice-emulator/SKILL.md` + `reference/vice-usage.md` | | |||
| | Look up an opcode | `reference/6510-opcodes.md` | | |||
| | Look up a chip register | `reference/vic-registers.md`, `sid-registers.md`, `cia-registers.md` | | |||
| | Find a Kernal routine | `reference/kernal-jumplist.md` | | |||
| | Understand a disk error | `reference/disk-dos-commands.md` | | |||
| - Windows with [PowerShell 7](https://github.com/PowerShell/PowerShell) (`pwsh`) | |||
| - [cc65](https://cc65.github.io/) (`cl65`, `ca65`, `ld65`) | |||
| - [VICE 3.x](https://vice-emu.sourceforge.io/) (`x64sc`, `x128`, `c1541`, `petcat`), e.g. | |||
| `winget install VICE-Team.VICE.GTK3` | |||
| --- | |||
| `c64 doctor` finds the tools on `PATH`, in Program Files, or in WinGet's package folder, | |||
| and says what is missing. Set `C64_TOOLS_PATH` (semicolon-separated folders) to point it | |||
| somewhere else. | |||
| ## AI Agent Instructions | |||
| ## Commands | |||
| See **CLAUDE.md** for the primary agent entry point. | |||
| See **AGENTS.md** for the comprehensive reference used by AI to answer C64 development questions. | |||
| | Command | Does | | |||
| |---------|------| | |||
| | `c64 doctor` | Check the toolchain | | |||
| | `c64 new <name> [-Template c\|asm\|basic]` | Create `projects/<name>` with a passing self-test | | |||
| | `c64 build <project\|file>` | Build `.prg`, plus `.lbl` (VICE labels), `.map`, and optionally `.d64` | | |||
| | `c64 run <project\|file\|prg\|d64> [-Monitor] [-FromDisk] [-Disk x.d64]` | Autostart in VICE | | |||
| | `c64 test <...> [-Expect TEXT] [-Until label] [-AfterJiffies n] [-Keys "x\n"] [-Disk x.d64]` | Headless run: prints the screen, PASS/FAIL, exit code 0/1 | | |||
| | `c64 mon "r" "m .label"` | Query a program started with `run -Monitor` | | |||
| | `pwsh tools/regress.ps1` | Regression suite for templates, projects, and examples | | |||
| All skill files follow a consistent structure: | |||
| 1. Overview | |||
| 2. Hardware/ROM details with addresses | |||
| 3. Code patterns and templates | |||
| 4. Worked examples | |||
| 5. Common pitfalls | |||
| A project is a folder with `c64project.json` (see `templates/`). Any single `.c`, `.s`, | |||
| `.asm`, or `.bas` file also works as a target. | |||
| Supplemental emulator material is intentionally kept separate from the canonical platform references so agents can distinguish between C64 hardware facts and modern tooling workflows. | |||
| ## Layout | |||
| ## VICE Debugging | |||
| ``` | |||
| AGENTS.md / CLAUDE.md agent entry point (CLAUDE.md includes AGENTS.md) | |||
| c64.cmd command wrapper -> tools/c64.ps1 | |||
| tools/ C64Tools.psm1 (build, run, test, monitor), c64.ps1, regress.ps1 | |||
| lib/ c64test.h / c64test.inc: report test results via $D7FF | |||
| templates/ c, asm, basic project skeletons | |||
| projects/ new programs | |||
| .claude/skills/ topic skills: c64-workflow, 6510-assembly, memory-map, graphics-vic2, | |||
| sound-sid, interrupts, kernal-routines, disk-io-1541, | |||
| basic-programming, compiler-design, vice-emulator, powerc | |||
| reference/ register, opcode, Kernal, memory, DOS, and VICE references; | |||
| Power C disk and manual; powerc-re/ (Power C improvements) | |||
| examples/ single-file examples in BASIC, ca65, and cc65 C; Power C disks | |||
| skirmish-game/ tactical game in ca65 assembly | |||
| samples/ kernal-os-skeleton (OS shell), cc65-mouse-driver-demo | |||
| vim/ vi clone (Power C on the C64, cc65 on the C128) | |||
| newLang/ Nova128: OO language and on-machine compiler for the C128 | |||
| ``` | |||
| For emulator debugging, start with `.claude/skills/vice-emulator/SKILL.md`, then use `reference/vice-usage.md` as the command quick reference. | |||
| ## How testing works | |||
| The most useful repo examples are: | |||
| `c64 test` starts `x64sc` (or `x128`) minimized in warp mode, injects the program, and | |||
| waits for a trigger: | |||
| - `examples/vice-debug-c64os.bat` for launching `c64os.prg` in `x64sc` with native monitor, keep-open, and refresh-on-break enabled | |||
| - `examples/vice-monitor-c64os-debug.txt` for a repeatable monitor session with breakpoints, watchpoints, stepping hints, and keyboard-buffer injection | |||
| - **`$D7FF` store** (default): the program writes its result: 0 = pass, otherwise a | |||
| failure code. `lib/c64test.h` and `lib/c64test.inc` wrap it; BASIC uses `POKE 55295,0`. | |||
| On real hardware the store does nothing. | |||
| - **`-Until <label>`**: execution reaches a label from the build's `.lbl` file. | |||
| - **`-AfterJiffies <n>`**: after n Kernal IRQs, for programs you don't want to modify. | |||
| --- | |||
| At the trigger it saves RAM, I/O, the decoded text screen, and a screenshot to | |||
| `build/test/<name>/`, then checks `-Expect` strings. BASIC errors fail immediately | |||
| with the error name and line number. | |||
| ## C64 Hardware at a Glance | |||
| ## Sources | |||
| | Component | Details | | |||
| |-----------|---------| | |||
| | CPU | MOS 6510 @ 1.02MHz (PAL) / 0.985MHz (NTSC) | | |||
| | RAM | 64 KB (with banking) | | |||
| | ROM | 20 KB (BASIC 8KB + Kernal 8KB + Char 4KB) | | |||
| | Video | MOS 6569 VIC-II (PAL) / 6567 (NTSC) | | |||
| | Sound | MOS 6581/8580 SID — 3 voices, 4 waveforms, filter | | |||
| | I/O | MOS 6526 CIA × 2 (keyboard, joystick, serial, timer) | | |||
| | Storage | Commodore 1541 (170KB, 35 tracks, GCR encoding) | | |||
| | Display | 40×25 text / 320×200 hi-res / 160×200 multicolor | | |||
| | Sprites | 8 hardware sprites (24×21 pixels each) | | |||
| | Colors | 16 fixed colors | | |||
| The topic skills were compiled from *The Anatomy of the Commodore 64*, *The Machine | |||
| Language Book* and *The Advanced Machine Language Book for the Commodore 64*, | |||
| *COMPUTE!'s Mapping the Commodore 64*, *COMPUTE!'s VIC-20 and Commodore 64 Tool Kit* | |||
| (BASIC and Kernal), *The Anatomy of the 1541 Disk Drive*, *The Complete Commodore 64 | |||
| ROM Disassembly*, *Compiler Design and Implementation (64 and 128)*, *COMPUTE!'s | |||
| SpeedScript*, *Invaluable Utilities for the Commodore 64*, and the VICE 3.10 manual. | |||
| @@ -1,256 +1,202 @@ | |||
| ; ============================================================ | |||
| ; C64 HI-RES BITMAP DEMO | |||
| ; Switches to 320x200 hi-res bitmap mode, draws a diagonal | |||
| ; line, then waits for a key before restoring text mode. | |||
| ; bitmap-demo.asm - 320x200 hi-res bitmap on the C64 (ca65) | |||
| ; | |||
| ; Assemble to $C000 and run with: | |||
| ; LOAD"BITMAP",8,1 : SYS 49152 | |||
| ; Switches to hi-res bitmap mode, draws a diagonal line from (0,0) to | |||
| ; (199,199), waits for a key, and restores the text screen. | |||
| ; | |||
| ; Bitmap: $A000-$BFFF (8000 bytes, under BASIC ROM) | |||
| ; Screen color RAM: $0400-$07E7 (1000 bytes) | |||
| ; c64 run examples/bitmap-demo.asm | |||
| ; c64 test examples/bitmap-demo.asm -Until wait_key (see build/test/screenshot.png) | |||
| ; | |||
| ; Memory (VIC bank 2, $8000-$BFFF): | |||
| ; $8400-$87E7 screen matrix = bitmap colors (high nybble = ink, low = paper) | |||
| ; $A000-$BF3F bitmap (8000 bytes). The CPU writes go to the RAM under BASIC | |||
| ; ROM; the VIC-II always reads RAM there. | |||
| ; The program itself must end below $8400 (it is far smaller). | |||
| ; ============================================================ | |||
| * = $C000 | |||
| ; --- Zero-page pointers --- | |||
| PTR = $FB ; 2-byte pointer | |||
| BPTR = $FD ; 2-byte bitmap pointer | |||
| ; --- Constants --- | |||
| BITMAP = $A000 ; bitmap base | |||
| SCREEN = $0400 ; color nybble RAM (foreground hi/background lo) | |||
| START: | |||
| JSR INIT_BITMAP | |||
| JSR DRAW_DIAGONAL | |||
| JSR WAIT_KEY | |||
| JSR RESTORE_TEXT | |||
| RTS | |||
| ptr = $FB ; 2-byte work pointer (free zero page) | |||
| bptr = $FD ; 2-byte bitmap pointer | |||
| BITMAP = $A000 | |||
| COLORS = $8400 | |||
| CIA2_PRA = $DD00 ; bits 0-1: VIC bank (inverted) | |||
| VIC_CTRL1 = $D011 ; bit 5: bitmap mode | |||
| VIC_MEM = $D018 ; screen matrix and bitmap location in the bank | |||
| VIC_CTRL2 = $D016 ; bit 4: multicolor | |||
| VIC_BORDER = $D020 | |||
| VIC_BG = $D021 | |||
| GETIN = $FFE4 | |||
| CHROUT = $FFD2 | |||
| .segment "CODE" | |||
| start: | |||
| jsr init_bitmap | |||
| jsr draw_diagonal | |||
| wait_key: ; label for `c64 test -Until` | |||
| jsr GETIN | |||
| beq wait_key | |||
| jsr restore_text | |||
| rts | |||
| ; ============================================================ | |||
| ; INIT_BITMAP | |||
| ; Sets up VIC-II for hi-res bitmap mode | |||
| ; init_bitmap: VIC bank 2, bitmap at $A000, colors at $8400 | |||
| ; ============================================================ | |||
| INIT_BITMAP: | |||
| ; Turn off interrupts temporarily | |||
| SEI | |||
| ; Set VIC bank to 0 ($0000-$3FFF is default bank) | |||
| ; Bitmap at $A000 requires bank 2 ($8000-$BFFF) — switch! | |||
| LDA $DD00 | |||
| AND #$FC ; clear bits 0-1 | |||
| ORA #$01 ; bank 2: VIC sees $8000-$BFFF | |||
| STA $DD00 | |||
| ; VIC memory setup: $D018 | |||
| ; Bitmap at $A000 = offset $2000 from bank base $8000 | |||
| ; $2000 >> 13 = bit 3 set → bitmap pointer bit = 1 | |||
| ; Screen RAM at $8400 (color nybbles) — offset $0400 >> 10 = $0 → bits 7-4 = 0001 | |||
| LDA #%00011000 ; screen at $8400 (bits 7-4 = 0001), bitmap at $A000 (bit 3) | |||
| STA $D018 | |||
| ; Enable bitmap mode: $D011 bit 5 = 1 | |||
| LDA $D011 | |||
| ORA #%00100000 | |||
| STA $D011 | |||
| ; Multicolor off (hi-res): $D016 bit 4 = 0 | |||
| LDA $D016 | |||
| AND #%11101111 | |||
| STA $D016 | |||
| ; Set border color to black | |||
| LDA #0 | |||
| STA $D020 | |||
| ; Set background color to black | |||
| STA $D021 | |||
| ; Clear bitmap (8000 bytes of zeros = black pixels) | |||
| LDA #<BITMAP | |||
| STA PTR | |||
| LDA #>BITMAP | |||
| STA PTR+1 | |||
| LDA #0 | |||
| LDY #0 | |||
| LDX #$1F ; 32 pages = 8192 bytes (covers 8000) | |||
| CLRLOOP: | |||
| STA (PTR),Y | |||
| INY | |||
| BNE CLRLOOP | |||
| INC PTR+1 | |||
| DEX | |||
| BNE CLRLOOP | |||
| ; Set all color RAM nybbles: foreground=white(1), background=black(0) | |||
| ; Each byte = $10 = white fg, black bg | |||
| LDA #<SCREEN | |||
| STA PTR | |||
| LDA #>SCREEN | |||
| STA PTR+1 | |||
| LDA #$10 | |||
| LDY #0 | |||
| COLLOOP: | |||
| STA (PTR),Y | |||
| INY | |||
| CPY #232 ; 1000 - 8 = 232? No: LDY loops 0-255 then second pass | |||
| BNE COLLOOP | |||
| ; Handle full 1000 bytes (4 pages) | |||
| ; Simple approach: just fill $0400-$07E7 | |||
| LDX #3 | |||
| LDY #0 | |||
| COLLOOP2: | |||
| STA (PTR),Y | |||
| INY | |||
| BNE COLLOOP2 | |||
| INC PTR+1 | |||
| DEX | |||
| BNE COLLOOP2 | |||
| CLI | |||
| RTS | |||
| .proc init_bitmap | |||
| lda CIA2_PRA | |||
| and #%11111100 | |||
| ora #%00000001 ; %01 = bank 2 ($8000-$BFFF) | |||
| sta CIA2_PRA | |||
| ; $D018: bits 7-4 = screen matrix / $0400 (1 -> $8400), | |||
| ; bit 3 = bitmap at bank + $2000 ($A000) | |||
| lda #%00011000 | |||
| sta VIC_MEM | |||
| lda VIC_CTRL1 | |||
| ora #%00100000 ; bitmap mode on | |||
| sta VIC_CTRL1 | |||
| lda VIC_CTRL2 | |||
| and #%11101111 ; multicolor off (hi-res) | |||
| sta VIC_CTRL2 | |||
| lda #0 ; black border; the background register is | |||
| sta VIC_BORDER ; not used in hi-res bitmap mode | |||
| sta VIC_BG | |||
| ; Clear the bitmap: 32 pages ($A000-$BFFF) covers the 8000 bytes. | |||
| lda #<BITMAP | |||
| sta ptr | |||
| lda #>BITMAP | |||
| sta ptr+1 | |||
| lda #0 | |||
| tay | |||
| ldx #32 | |||
| clear: sta (ptr),y | |||
| iny | |||
| bne clear | |||
| inc ptr+1 | |||
| dex | |||
| bne clear | |||
| ; Colors: white ink ($1x) on black paper ($x0) in all 1000 cells. | |||
| ; Four pages from $8400 cover $8400-$87FF (24 bytes past the matrix, harmless). | |||
| lda #<COLORS | |||
| sta ptr | |||
| lda #>COLORS | |||
| sta ptr+1 | |||
| lda #$10 | |||
| ldy #0 | |||
| ldx #4 | |||
| fill: sta (ptr),y | |||
| iny | |||
| bne fill | |||
| inc ptr+1 | |||
| dex | |||
| bne fill | |||
| rts | |||
| .endproc | |||
| ; ============================================================ | |||
| ; DRAW_DIAGONAL | |||
| ; Draws a white diagonal line from (0,0) to (199,199) | |||
| ; In hi-res bitmap, pixel (x,y) is in: | |||
| ; byte = bitmap + (y AND $F8)*40 + (x AND $F8) + (y AND 7) | |||
| ; bit = 7 - (x AND 7) | |||
| ; draw_diagonal: pixels (n, n) for n = 0..199 | |||
| ; ============================================================ | |||
| DRAW_DIAGONAL: | |||
| LDX #0 ; X pixel (0-199) | |||
| DLOOP: | |||
| TXA ; Y = X (diagonal) | |||
| JSR SETPIXEL | |||
| INX | |||
| CPX #200 | |||
| BNE DLOOP | |||
| RTS | |||
| .proc draw_diagonal | |||
| ; set_pixel reads the bitmap (ORA) before writing it. With BASIC ROM | |||
| ; banked in, reads at $A000-$BFFF return ROM bytes, which would then be | |||
| ; written into the bitmap. Bank BASIC out while drawing; the Kernal and | |||
| ; I/O stay visible, so IRQs keep working. | |||
| lda $01 | |||
| pha | |||
| and #%11111110 ; LORAM = 0: RAM at $A000-$BFFF ($37 -> $36) | |||
| sta $01 | |||
| ldx #0 | |||
| loop: txa ; y = x | |||
| jsr set_pixel ; preserves X | |||
| inx | |||
| cpx #200 | |||
| bne loop | |||
| pla | |||
| sta $01 ; BASIC back in before returning to it | |||
| rts | |||
| .endproc | |||
| ; ============================================================ | |||
| ; SETPIXEL — set pixel (.X=x, .A=y) | |||
| ; set_pixel: X = x (0-255), A = y (0-199). Preserves X. | |||
| ; address = BITMAP + (y / 8) * 320 + (x / 8) * 8 + (y & 7) | |||
| ; bit = 7 - (x & 7) | |||
| ; ============================================================ | |||
| SETPIXEL: | |||
| ; Calculate byte address | |||
| ; addr = $A000 + (Y>>3)*320 + (X>>3)*8 + (Y AND 7) | |||
| ; Uses simple approach via table lookup or shift math | |||
| STX XCOORD | |||
| STA YCOORD | |||
| ; Step 1: row base = (Y>>3) * 320 | |||
| ; Y>>3 * 320 = Y>>3 * 256 + Y>>3 * 64 | |||
| LSR ; Y>>1 | |||
| LSR ; Y>>2 | |||
| LSR ; Y>>3 (char row 0-24) | |||
| TAX ; X = row number | |||
| LDA ROWLO,X ; low byte of row base | |||
| STA BPTR | |||
| LDA ROWHI,X | |||
| STA BPTR+1 | |||
| .proc set_pixel | |||
| stx xcoord | |||
| sta ycoord | |||
| lsr ; y / 8 = character row | |||
| lsr | |||
| lsr | |||
| tay | |||
| lda rowlo,y ; row * 320 | |||
| sta bptr | |||
| lda rowhi,y | |||
| clc | |||
| adc #>BITMAP | |||
| sta bptr+1 | |||
| lda xcoord | |||
| and #%11111000 ; (x / 8) * 8 | |||
| clc | |||
| adc bptr | |||
| sta bptr | |||
| bcc :+ | |||
| inc bptr+1 | |||
| : | |||
| lda ycoord | |||
| and #%00000111 ; line within the character cell | |||
| tay | |||
| lda xcoord | |||
| and #%00000111 | |||
| tax | |||
| lda bitmask,x | |||
| ora (bptr),y | |||
| sta (bptr),y | |||
| ldx xcoord ; restore X for the caller | |||
| rts | |||
| .endproc | |||
| ; Step 2: add (X>>3)*8 = column offset | |||
| LDA XCOORD | |||
| LSR ; X>>1 | |||
| LSR ; X>>2 | |||
| LSR ; X>>3 (char col 0-39) | |||
| ASL ; *2 | |||
| ASL ; *4 | |||
| ASL ; *8 | |||
| CLC | |||
| ADC BPTR | |||
| STA BPTR | |||
| BCC NOINC1 | |||
| INC BPTR+1 | |||
| NOINC1: | |||
| ; Step 3: add (Y AND 7) for sub-row | |||
| LDA YCOORD | |||
| AND #$07 | |||
| CLC | |||
| ADC BPTR | |||
| STA BPTR | |||
| BCC NOINC2 | |||
| INC BPTR+1 | |||
| NOINC2: | |||
| ; Step 4: add bitmap base $A000 | |||
| LDA BPTR+1 | |||
| CLC | |||
| ADC #>BITMAP | |||
| STA BPTR+1 | |||
| ; (low byte already correct) | |||
| ; Step 5: set bit (7 - (X AND 7)) | |||
| LDA XCOORD | |||
| AND #$07 | |||
| TAX | |||
| LDA BITMASK,X | |||
| LDY #0 | |||
| ORA (BPTR),Y | |||
| STA (BPTR),Y | |||
| RTS | |||
| XCOORD: .BYTE 0 | |||
| YCOORD: .BYTE 0 | |||
| ; Bit masks for bit positions 7..0 | |||
| BITMASK: | |||
| .BYTE %10000000 ; bit 7 (x mod 8 = 0) | |||
| .BYTE %01000000 | |||
| .BYTE %00100000 | |||
| .BYTE %00010000 | |||
| .BYTE %00001000 | |||
| .BYTE %00000100 | |||
| .BYTE %00000010 | |||
| .BYTE %00000001 ; bit 0 (x mod 8 = 7) | |||
| ; Row base address table (40*8 = 320 bytes per char row) | |||
| ; Row N base = N * 320; precomputed for rows 0-24 | |||
| ROWLO: | |||
| .BYTE <(0*320),<(1*320),<(2*320),<(3*320),<(4*320) | |||
| .BYTE <(5*320),<(6*320),<(7*320),<(8*320),<(9*320) | |||
| .BYTE <(10*320),<(11*320),<(12*320),<(13*320),<(14*320) | |||
| .BYTE <(15*320),<(16*320),<(17*320),<(18*320),<(19*320) | |||
| .BYTE <(20*320),<(21*320),<(22*320),<(23*320),<(24*320) | |||
| ROWHI: | |||
| .BYTE >(0*320),>(1*320),>(2*320),>(3*320),>(4*320) | |||
| .BYTE >(5*320),>(6*320),>(7*320),>(8*320),>(9*320) | |||
| .BYTE >(10*320),>(11*320),>(12*320),>(13*320),>(14*320) | |||
| .BYTE >(15*320),>(16*320),>(17*320),>(18*320),>(19*320) | |||
| .BYTE >(20*320),>(21*320),>(22*320),>(23*320),>(24*320) | |||
| ; ============================================================ | |||
| ; WAIT_KEY — spin until any key pressed | |||
| ; ============================================================ | |||
| WAIT_KEY: | |||
| JSR $FFE4 ; GETIN | |||
| BEQ WAIT_KEY | |||
| RTS | |||
| ; restore_text: bank 0, screen $0400, charset ROM, text mode | |||
| ; ============================================================ | |||
| ; RESTORE_TEXT — return to standard text mode | |||
| ; ============================================================ | |||
| RESTORE_TEXT: | |||
| ; Restore VIC bank 0 | |||
| LDA $DD00 | |||
| ORA #$03 | |||
| STA $DD00 | |||
| ; Restore VIC memory map ($D018) | |||
| LDA #$15 ; screen at $0400, charset at $1000 | |||
| STA $D018 | |||
| ; Turn off bitmap mode | |||
| LDA $D011 | |||
| AND #%11011111 | |||
| STA $D011 | |||
| ; Restore background/border | |||
| LDA #14 ; light blue border (default) | |||
| STA $D020 | |||
| LDA #6 ; blue background (default) | |||
| STA $D021 | |||
| ; Clear screen | |||
| LDA #147 ; PETSCII clear | |||
| JSR $FFD2 | |||
| RTS | |||
| .proc restore_text | |||
| lda CIA2_PRA | |||
| ora #%00000011 ; bank 0 | |||
| sta CIA2_PRA | |||
| lda #$15 ; screen $0400, upper-case charset | |||
| sta VIC_MEM | |||
| lda VIC_CTRL1 | |||
| and #%11011111 ; bitmap mode off | |||
| sta VIC_CTRL1 | |||
| lda #14 ; default light blue border, blue background | |||
| sta VIC_BORDER | |||
| lda #6 | |||
| sta VIC_BG | |||
| lda #147 ; clear screen | |||
| jmp CHROUT | |||
| .endproc | |||
| .segment "RODATA" | |||
| bitmask: .byte $80, $40, $20, $10, $08, $04, $02, $01 | |||
| rowlo: | |||
| .repeat 25, row | |||
| .byte <(row * 320) | |||
| .endrepeat | |||
| rowhi: | |||
| .repeat 25, row | |||
| .byte >(row * 320) | |||
| .endrepeat | |||
| .segment "BSS" | |||
| xcoord: .res 1 | |||
| ycoord: .res 1 | |||
| @@ -7,14 +7,12 @@ | |||
| 100 REM ===================== | |||
| 101 REM SECTION 1: ERROR CHANNEL SUBROUTINE | |||
| 102 REM ===================== | |||
| 103 REM Call GOSUB 9000 after any disk operation | |||
| 104 REM Sets EN=error number, EM$=message, ET=track, ES=sector | |||
| 105 GOTO 200 | |||
| 103 REM Open the command channel once and keep it open: closing 15 makes the | |||
| 104 REM drive close every other file. GOSUB 9000 sets EN, EM$, ET, ES. | |||
| 105 OPEN 15,8,15 : GOTO 200 | |||
| 9000 REM --- READ ERROR CHANNEL --- | |||
| 9010 OPEN 15,8,15 | |||
| 9020 INPUT#15, EN, EM$, ET, ES | |||
| 9030 CLOSE 15 | |||
| 9040 IF EN > 1 THEN PRINT "DISK ERROR" EN EM$ "T"ET "S"ES | |||
| 9050 RETURN | |||
| @@ -23,7 +21,7 @@ | |||
| 202 REM ===================== | |||
| 210 PRINT "WRITING SEQUENTIAL FILE..." | |||
| 220 OPEN 1, 8, 2, "MYDATA,S,W" | |||
| 230 GOSUB 9000 : IF EN > 1 THEN GOTO 299 | |||
| 230 GOSUB 9000 : IF EN > 1 THEN CLOSE 1 : GOTO 299 | |||
| 240 PRINT#1, "RECORD 1" | |||
| 250 PRINT#1, "RECORD 2" | |||
| @@ -38,12 +36,11 @@ | |||
| 302 REM ===================== | |||
| 310 PRINT "READING SEQUENTIAL FILE..." | |||
| 320 OPEN 1, 8, 2, "MYDATA,S,R" | |||
| 330 GOSUB 9000 : IF EN > 1 THEN GOTO 399 | |||
| 330 GOSUB 9000 : IF EN > 1 THEN CLOSE 1 : GOTO 399 | |||
| 340 IF ST <> 0 THEN GOTO 380 : REM check status | |||
| 350 INPUT#1, LINE$ | |||
| 360 PRINT "READ: "; LINE$ | |||
| 370 GOTO 340 | |||
| 340 INPUT#1, LINE$ : S=ST : REM read first; ST is valid right after the read | |||
| 350 PRINT "READ: "; LINE$ | |||
| 360 IF S = 0 THEN GOTO 340 : REM 64 = end of file, other values = error | |||
| 380 CLOSE 1 | |||
| 390 GOSUB 9000 | |||
| 399 PRINT "READ DONE." | |||
| @@ -52,17 +49,14 @@ | |||
| 401 REM SECTION 4: READ DIRECTORY | |||
| 402 REM ===================== | |||
| 410 PRINT "DIRECTORY:" | |||
| 420 LOAD "$",8 | |||
| 430 REM (After LOAD, program is gone! Use OPEN method instead:) | |||
| 440 REM Alternative: open $ and read it | |||
| 420 REM LOAD "$",8 in a program would replace the program; read "$" as a file: | |||
| 450 OPEN 1, 8, 0, "$" | |||
| 460 GET#1, A$, B$ : REM skip first two bytes (load address) | |||
| 470 LOOP$="" | |||
| 480 GET#1, A$ : IF ST<>0 THEN GOTO 520 | |||
| 490 IF A$ = CHR$(0) THEN GOTO 480 : REM skip nulls | |||
| 500 IF ASC(A$+CHR$(0)) = 13 THEN PRINT LOOP$ : LOOP$="" : GOTO 480 | |||
| 510 LOOP$ = LOOP$ + A$ : GOTO 480 | |||
| 520 IF LOOP$ <> "" THEN PRINT LOOP$ | |||
| 460 GET#1, A$, B$ : REM load address (2 bytes) | |||
| 470 GET#1, A$, B$ : IF ST <> 0 THEN GOTO 530 : REM line link; 0,0 = end | |||
| 480 GET#1, A$, B$ : N = ASC(A$+CHR$(0)) + 256*ASC(B$+CHR$(0)) : REM blocks | |||
| 490 L$ = "" | |||
| 500 GET#1, C$ : IF C$ <> "" THEN L$ = L$ + C$ : GOTO 500 | |||
| 510 PRINT N; L$ : GOTO 470 | |||
| 530 CLOSE 1 | |||
| 600 REM ===================== | |||
| @@ -70,28 +64,26 @@ | |||
| 602 REM ===================== | |||
| 610 REM Scratch a file | |||
| 620 PRINT "SCRATCHING OLD BACKUP..." | |||
| 630 OPEN 15,8,15,"S0:BACKUP" | |||
| 640 CLOSE 15 | |||
| 630 PRINT#15, "S0:BACKUP" | |||
| 650 GOSUB 9000 | |||
| 660 REM Rename a file | |||
| 670 PRINT "RENAMING FILE..." | |||
| 680 OPEN 15,8,15,"R0:NEWNAME=MYDATA" | |||
| 690 CLOSE 15 | |||
| 680 PRINT#15, "R0:NEWNAME=MYDATA" | |||
| 700 GOSUB 9000 | |||
| 710 REM Validate disk | |||
| 720 PRINT "VALIDATING DISK..." | |||
| 730 OPEN 15,8,15,"V0:" | |||
| 740 CLOSE 15 | |||
| 730 PRINT#15, "V0:" | |||
| 750 GOSUB 9000 | |||
| 800 REM ===================== | |||
| 801 REM SECTION 6: LOAD ML PROGRAM | |||
| 802 REM ===================== | |||
| 810 REM Load ML at its original address (SA=1) | |||
| 820 LOAD "MLPROG",8,1 | |||
| 830 REM (after LOAD, program continues or use SYS) | |||
| 810 REM Load ML at its original address (SA=1), e.g.: | |||
| 820 REM LOAD "MLPROG",8,1 (in a program, LOAD restarts the program after loading) | |||
| 830 CLOSE 15 : PRINT "DONE." | |||
| 835 POKE 55295,0 : REM $D7FF: tells `c64 test` the run finished (no effect on hardware) | |||
| 840 END | |||
| 900 REM ===================== | |||
| @@ -1,30 +1,28 @@ | |||
| ; ============================================================= | |||
| ; hello-world.asm — Minimal C64 Assembly Hello World | |||
| ; Assemble to $C000 (49152) | |||
| ; Run with: POKE 56,192:CLR then SYS 49152 | |||
| ; hello-world.asm - minimal C64 assembly program (ca65) | |||
| ; | |||
| ; c64 run examples/hello-world.asm | |||
| ; c64 test examples/hello-world.asm -Until done -Expect "HELLO, WORLD!" | |||
| ; | |||
| ; Built with cc65's BASIC stub (10 SYS 2061): RUN starts at `start`. | |||
| ; ============================================================= | |||
| * = $C000 ; Assemble starting at $C000 | |||
| CINT = $FF81 ; Kernal: initialize screen editor (clears screen) | |||
| CHROUT = $FFD2 ; Kernal: output character (BSOUT) | |||
| ; --------------------------------------------------------------- | |||
| ; Main entry point | |||
| ; --------------------------------------------------------------- | |||
| START JSR $FF81 ; CINT — Initialize screen editor | |||
| .segment "CODE" | |||
| start: jsr CINT | |||
| ; Print message using BSOUT (Kernal output routine) | |||
| LDX #0 ; X = index into message | |||
| LOOP LDA MSG,X ; load character | |||
| BEQ DONE ; zero byte = end of message | |||
| JSR $FFD2 ; BSOUT — output character to screen | |||
| INX ; next character | |||
| BNE LOOP ; (X wraps at 256, but our msg is short) | |||
| ldx #0 ; X = index into message | |||
| loop: lda msg,x ; load character | |||
| beq done ; zero byte = end of message | |||
| jsr CHROUT ; print it | |||
| inx | |||
| bne loop ; (X wraps at 256; the message is short) | |||
| DONE RTS ; return to BASIC | |||
| done: rts ; back to BASIC | |||
| ; --------------------------------------------------------------- | |||
| ; Message data (PETSCII) | |||
| ; $0D = carriage return, $00 = end of string | |||
| ; --------------------------------------------------------------- | |||
| MSG .BYTE 147 ; clear screen (CHR$(147)) | |||
| .TEXT "HELLO, WORLD!" | |||
| .BYTE $0D,$00 ; CR + terminator | |||
| .segment "RODATA" | |||
| ; ca65 converts strings to PETSCII: write lower case to get the upper-case | |||
| ; letters the C64 shows by default. | |||
| msg: .byte "hello, world!", $0D, 0 | |||
| @@ -1,97 +1,108 @@ | |||
| ; ============================================================= | |||
| ; irq-handler.asm — Custom IRQ Handler Skeleton for C64 | |||
| ; Demonstrates: raster IRQ, custom border color flash | |||
| ; Assemble to $C000. Run with SYS 49152 to install, SYS 49166 to remove. | |||
| ; irq-handler.asm - raster IRQ skeleton for the C64 (ca65) | |||
| ; | |||
| ; Changes the border color at raster lines 100 and 200, on top of the normal | |||
| ; Kernal IRQ (keyboard scan, jiffy clock), and returns to BASIC. | |||
| ; | |||
| ; RUN install (SYS 2061) | |||
| ; SYS 2064 remove | |||
| ; | |||
| ; c64 run examples/irq-handler.asm | |||
| ; c64 test examples/irq-handler.asm -AfterJiffies 300 (see build/test/screenshot.png) | |||
| ; | |||
| ; Timing: line numbers are valid on PAL (312 lines) and NTSC (263 lines). | |||
| ; ============================================================= | |||
| * = $C000 | |||
| VIC_CTRL1 = $D011 ; bit 7 = raster compare bit 8 | |||
| VIC_RASTER = $D012 | |||
| VIC_IRR = $D019 ; interrupt request register (write 1s to acknowledge) | |||
| VIC_IMR = $D01A ; interrupt mask register | |||
| VIC_BORDER = $D020 | |||
| CIA1_ICR = $DC0D | |||
| CINV = $0314 ; Kernal IRQ vector (RAM) | |||
| KERNAL_IRQ_EXIT = $EA81 ; pull Y, X, A and RTI (end of the Kernal handler) | |||
| .segment "CODE" | |||
| entry: jmp install ; SYS 2061 | |||
| jmp remove ; SYS 2064 | |||
| ; --------------------------------------------------------------- | |||
| ; INSTALL — Patches IRQ vector to our handler | |||
| ; install: hook CINV and enable the raster interrupt | |||
| ; --------------------------------------------------------------- | |||
| INSTALL SEI ; disable interrupts while patching | |||
| .proc install | |||
| sei ; no IRQs while the vector is half-written | |||
| ; Save original IRQ vector | |||
| LDA $0314 | |||
| STA OLDIRQ | |||
| LDA $0315 | |||
| STA OLDIRQ+1 | |||
| lda CINV ; save the current handler so we can chain to it | |||
| sta oldirq | |||
| lda CINV+1 | |||
| sta oldirq+1 | |||
| ; Install our handler | |||
| LDA #<RASTER_IRQ | |||
| STA $0314 | |||
| LDA #>RASTER_IRQ | |||
| STA $0315 | |||
| lda #<raster_irq | |||
| sta CINV | |||
| lda #>raster_irq | |||
| sta CINV+1 | |||
| ; Set up VIC-II raster interrupt at line 100 | |||
| LDA $D011 | |||
| AND #$7F ; clear raster bit 8 | |||
| STA $D011 | |||
| LDA #100 ; trigger at raster line 100 | |||
| STA $D012 | |||
| lda VIC_CTRL1 | |||
| and #$7F ; raster compare bit 8 = 0 | |||
| sta VIC_CTRL1 | |||
| lda #100 | |||
| sta VIC_RASTER | |||
| ; Enable VIC-II raster IRQ, keep CIA #1 timer IRQ enabled too | |||
| LDA #$01 | |||
| STA $D01A ; VIC IRQ mask: raster | |||
| lda #$01 ; enable the raster IRQ (CIA 1 timer IRQ stays on) | |||
| sta VIC_IMR | |||
| sta VIC_IRR ; clear any stale raster request | |||
| CLI ; re-enable interrupts | |||
| RTS | |||
| cli | |||
| rts | |||
| .endproc | |||
| ; --------------------------------------------------------------- | |||
| ; REMOVE — Restores original IRQ vector | |||
| ; remove: restore the saved vector and disable the raster IRQ | |||
| ; --------------------------------------------------------------- | |||
| REMOVE SEI | |||
| LDA OLDIRQ | |||
| STA $0314 | |||
| LDA OLDIRQ+1 | |||
| STA $0315 | |||
| LDA #$00 | |||
| STA $D01A ; disable VIC IRQs | |||
| CLI | |||
| RTS | |||
| .proc remove | |||
| sei | |||
| lda oldirq | |||
| sta CINV | |||
| lda oldirq+1 | |||
| sta CINV+1 | |||
| lda #$00 | |||
| sta VIC_IMR | |||
| lda #$01 | |||
| sta VIC_IRR ; acknowledge a raster IRQ that may be pending | |||
| cli | |||
| rts | |||
| .endproc | |||
| ; --------------------------------------------------------------- | |||
| ; RASTER_IRQ — Our custom interrupt handler | |||
| ; Called when VIC-II raster reaches line 100 | |||
| ; raster_irq: runs for every IRQ (the Kernal pushed A, X, Y already) | |||
| ; --------------------------------------------------------------- | |||
| RASTER_IRQ: | |||
| ; Acknowledge VIC-II interrupt (write-back clears flags) | |||
| LDA $D019 ; read VIC interrupt status | |||
| STA $D019 ; acknowledge by writing back | |||
| ; Check if this is really a raster interrupt | |||
| AND #$01 ; bit 0 = raster IRQ | |||
| BEQ NOT_RASTER | |||
| .proc raster_irq | |||
| lda VIC_IRR | |||
| and #$01 ; raster interrupt? | |||
| beq not_raster ; no: it is the CIA timer, run the Kernal handler | |||
| sta VIC_IRR ; acknowledge (write 1 to bit 0) | |||
| ; --- RASTER EFFECT: Flash border color --- | |||
| INC COLORIDX | |||
| LDA COLORIDX | |||
| AND #$0F ; keep in 0-15 range | |||
| STA COLORIDX | |||
| STA $D020 ; write border color | |||
| inc coloridx ; next border color | |||
| lda coloridx | |||
| and #$0F | |||
| sta VIC_BORDER | |||
| ; Schedule next IRQ at line 200 | |||
| LDA $D012 | |||
| CMP #200 | |||
| BEQ FLIP_RASTER | |||
| LDA #200 | |||
| STA $D012 | |||
| JMP DONE_IRQ | |||
| FLIP_RASTER: | |||
| LDA #100 | |||
| STA $D012 | |||
| lda VIC_RASTER ; alternate between lines 100 and 200 | |||
| cmp #200 | |||
| bcs top | |||
| lda #200 | |||
| bne set ; always taken | |||
| top: lda #100 | |||
| set: sta VIC_RASTER | |||
| DONE_IRQ: | |||
| NOT_RASTER: | |||
| ; Chain to original IRQ for keyboard/timer/jiffy updates | |||
| JMP (OLDIRQ) | |||
| ; The raster IRQ must not run the Kernal handler: it would advance the | |||
| ; jiffy clock and scan the keyboard an extra time per frame. | |||
| jmp KERNAL_IRQ_EXIT | |||
| ; --------------------------------------------------------------- | |||
| ; Data | |||
| ; --------------------------------------------------------------- | |||
| OLDIRQ .WORD $EA31 ; default IRQ handler address | |||
| COLORIDX .BYTE 0 | |||
| not_raster: | |||
| jmp (oldirq) ; usually $EA31: keyboard, clock, acknowledges CIA 1 | |||
| .endproc | |||
| ; --------------------------------------------------------------- | |||
| ; End of code | |||
| ; --------------------------------------------------------------- | |||
| .segment "DATA" | |||
| oldirq: .word $EA31 | |||
| coloridx: .byte 0 | |||
| @@ -1,182 +1,182 @@ | |||
| ; ============================================================= | |||
| ; kernal-io.asm — Using Kernal Routines for I/O | |||
| ; Demonstrates: screen output, keyboard input, file I/O | |||
| ; Assemble to $C000. Run with SYS 49152. | |||
| ; kernal-io.asm - screen, keyboard, and disk I/O through the Kernal (ca65) | |||
| ; | |||
| ; Reads a line from the keyboard, echoes it, writes a SEQ file to drive 8, | |||
| ; and prints the drive's status message. | |||
| ; | |||
| ; c64 run examples/kernal-io.asm | |||
| ; c64 test examples/kernal-io.asm -Keys "hello\n" -Until main_done -Expect "YOU TYPED: HELLO" | |||
| ; ============================================================= | |||
| * = $C000 | |||
| CINT = $FF81 | |||
| SETLFS = $FFBA | |||
| SETNAM = $FFBD | |||
| OPEN = $FFC0 | |||
| CLOSE = $FFC3 | |||
| CHKIN = $FFC6 | |||
| CHKOUT = $FFC9 | |||
| CLRCHN = $FFCC | |||
| CHRIN = $FFCF | |||
| CHROUT = $FFD2 | |||
| GETIN = $FFE4 | |||
| READST = $FFB7 | |||
| ptr = $FB ; free zero page | |||
| .segment "CODE" | |||
| .proc main | |||
| jsr CINT | |||
| lda #<msg_welcome | |||
| ldx #>msg_welcome | |||
| jsr print_str | |||
| jsr read_line ; text in inbuf, length in inlen | |||
| lda #<msg_you_typed | |||
| ldx #>msg_you_typed | |||
| jsr print_str | |||
| lda #<inbuf | |||
| ldx #>inbuf | |||
| jsr print_str | |||
| lda #$0D | |||
| jsr CHROUT | |||
| jsr write_file | |||
| jsr print_drive_status | |||
| .endproc | |||
| main_done: ; label for `c64 test -Until` | |||
| rts | |||
| ; --------------------------------------------------------------- | |||
| ; MAIN — Demo entry point | |||
| ; print_str: print a zero-terminated string; A = low, X = high byte | |||
| ; --------------------------------------------------------------- | |||
| MAIN JSR $FF81 ; CINT — init screen | |||
| ; Print a string | |||
| LDA #<MSG_WELCOME | |||
| LDX #>MSG_WELCOME | |||
| JSR PRINT_STR | |||
| ; Read a line of input | |||
| JSR READ_LINE ; result in INBUF, length in INLEN | |||
| ; Echo it back | |||
| LDA #<MSG_YOU_TYPED | |||
| LDX #>MSG_YOU_TYPED | |||
| JSR PRINT_STR | |||
| LDX #0 | |||
| ECHO LDA INBUF,X | |||
| BEQ ECHO_DONE | |||
| JSR $FFD2 ; BSOUT | |||
| INX | |||
| BNE ECHO | |||
| ECHO_DONE: | |||
| LDA #$0D | |||
| JSR $FFD2 ; print CR | |||
| ; Write a file to disk | |||
| JSR WRITE_FILE | |||
| RTS | |||
| ; --------------------------------------------------------------- | |||
| ; PRINT_STR — Print null-terminated string | |||
| ; Input: A = low byte, X = high byte of string address | |||
| ; --------------------------------------------------------------- | |||
| PRINT_STR: | |||
| STA $FB ; store address in zero page | |||
| STX $FC | |||
| LDY #0 | |||
| PS_LOOP LDA ($FB),Y ; load character | |||
| BEQ PS_DONE ; zero = end | |||
| JSR $FFD2 ; BSOUT — output to screen | |||
| INY | |||
| BNE PS_LOOP | |||
| PS_DONE RTS | |||
| ; --------------------------------------------------------------- | |||
| ; READ_LINE — Read keyboard input until RETURN | |||
| ; Output: INBUF filled, INLEN = number of chars read | |||
| ; --------------------------------------------------------------- | |||
| READ_LINE: | |||
| LDX #0 ; buffer index | |||
| RL_LOOP JSR $FFE4 ; GETIN — get character (non-blocking) | |||
| BEQ RL_LOOP ; no key, keep waiting | |||
| CMP #$0D ; RETURN key? | |||
| BEQ RL_DONE | |||
| CMP #$14 ; DELETE key? | |||
| BEQ RL_DEL | |||
| CPX #79 ; buffer full? | |||
| BEQ RL_LOOP | |||
| STA INBUF,X ; store character | |||
| JSR $FFD2 ; echo to screen | |||
| INX | |||
| BNE RL_LOOP | |||
| RL_DEL CPX #0 | |||
| BEQ RL_LOOP ; nothing to delete | |||
| DEX | |||
| LDA #$14 | |||
| JSR $FFD2 ; output DELETE | |||
| BNE RL_LOOP | |||
| RL_DONE LDA #0 | |||
| STA INBUF,X ; null terminate | |||
| STX INLEN | |||
| LDA #$0D | |||
| JSR $FFD2 ; echo CR | |||
| RTS | |||
| .proc print_str | |||
| sta ptr | |||
| stx ptr+1 | |||
| ldy #0 | |||
| loop: lda (ptr),y | |||
| beq done | |||
| jsr CHROUT | |||
| iny | |||
| bne loop | |||
| done: rts | |||
| .endproc | |||
| ; --------------------------------------------------------------- | |||
| ; WRITE_FILE — Write data to a sequential disk file | |||
| ; read_line: read keys until RETURN; handles DEL; max 79 characters | |||
| ; --------------------------------------------------------------- | |||
| WRITE_FILE: | |||
| ; SETLFS: logical=2, device=8, secondary=2 | |||
| LDA #2 | |||
| LDX #8 | |||
| LDY #2 | |||
| JSR $FFBA ; SETLFS | |||
| ; SETNAM: filename "OUTPUT,S,W" | |||
| LDA #OUTNAME_LEN | |||
| LDX #<OUTNAME | |||
| LDY #>OUTNAME | |||
| JSR $FFBD ; SETNAM | |||
| ; OPEN | |||
| JSR $FFC0 ; OPEN | |||
| BCS WF_OERR ; error if carry set | |||
| ; CHKOUT: redirect output to file | |||
| LDX #2 | |||
| JSR $FFC9 ; CHKOUT | |||
| BCS WF_CERR | |||
| ; Write data | |||
| LDX #0 | |||
| WF_LOOP LDA FILEDATA,X | |||
| BEQ WF_DONE | |||
| JSR $FFD2 ; BSOUT to file | |||
| INX | |||
| BNE WF_LOOP | |||
| WF_DONE JSR $FFCC ; CLRCH — restore default channels | |||
| LDA #2 | |||
| JSR $FFC3 ; CLOSE | |||
| ; Check disk error channel | |||
| JSR $FFBA ; reuse: SETLFS 15,8,15 | |||
| ; Actually let's just print success | |||
| LDA #<MSG_SAVED | |||
| LDX #>MSG_SAVED | |||
| JMP PRINT_STR | |||
| WF_OERR LDA #<MSG_OERR | |||
| LDX #>MSG_OERR | |||
| JMP PRINT_STR | |||
| WF_CERR LDA #<MSG_CERR | |||
| LDX #>MSG_CERR | |||
| JMP PRINT_STR | |||
| .proc read_line | |||
| lda #0 | |||
| sta inlen ; the index lives in memory: GETIN clobbers X and Y | |||
| loop: jsr GETIN ; 0 = no key yet | |||
| beq loop | |||
| ldx inlen | |||
| cmp #$0D ; RETURN | |||
| beq done | |||
| cmp #$14 ; DEL | |||
| beq del | |||
| cpx #79 ; buffer full: ignore further keys | |||
| beq loop | |||
| sta inbuf,x | |||
| inc inlen | |||
| jsr CHROUT ; echo (CHROUT preserves X and Y) | |||
| jmp loop | |||
| del: cpx #0 | |||
| beq loop | |||
| dec inlen | |||
| jsr CHROUT ; A is still $14: erase on screen | |||
| jmp loop | |||
| done: lda #0 | |||
| sta inbuf,x | |||
| lda #$0D | |||
| jmp CHROUT | |||
| .endproc | |||
| ; --------------------------------------------------------------- | |||
| ; Data | |||
| ; write_file: OPEN 2,8,2,"@0:OUTPUT,S,W" and print data into it | |||
| ; --------------------------------------------------------------- | |||
| MSG_WELCOME: | |||
| .BYTE 147 ; clear screen | |||
| .TEXT "KERNAL I/O DEMO" | |||
| .BYTE $0D | |||
| .TEXT "TYPE SOMETHING AND PRESS RETURN:" | |||
| .BYTE $0D,0 | |||
| MSG_YOU_TYPED: | |||
| .TEXT "YOU TYPED: " | |||
| .BYTE 0 | |||
| MSG_SAVED: | |||
| .BYTE $0D | |||
| .TEXT "FILE WRITTEN TO DISK." | |||
| .BYTE $0D,0 | |||
| MSG_OERR: | |||
| .TEXT "ERROR: COULD NOT OPEN FILE" | |||
| .BYTE $0D,0 | |||
| MSG_CERR: | |||
| .TEXT "ERROR: COULD NOT REDIRECT OUTPUT" | |||
| .BYTE $0D,0 | |||
| OUTNAME: | |||
| .TEXT "OUTPUT,S,W" | |||
| OUTNAME_LEN = * - OUTNAME | |||
| FILEDATA: | |||
| .TEXT "DATA LINE 1" | |||
| .BYTE $0D | |||
| .TEXT "DATA LINE 2" | |||
| .BYTE $0D,0 | |||
| .proc write_file | |||
| lda #2 ; logical file 2, device 8, secondary 2 | |||
| ldx #8 | |||
| ldy #2 | |||
| jsr SETLFS | |||
| lda #outname_len | |||
| ldx #<outname | |||
| ldy #>outname | |||
| jsr SETNAM | |||
| jsr OPEN | |||
| bcs open_error ; carry set = Kernal error (A = error number) | |||
| ldx #2 | |||
| jsr CHKOUT ; send CHROUT output to file 2 | |||
| bcs chkout_error | |||
| ldx #0 | |||
| loop: lda filedata,x | |||
| beq close | |||
| jsr CHROUT | |||
| inx | |||
| bne loop | |||
| close: jsr CLRCHN ; output back to the screen | |||
| lda #2 | |||
| jmp CLOSE | |||
| chkout_error: | |||
| jsr CLRCHN | |||
| lda #2 | |||
| jsr CLOSE | |||
| lda #<msg_chkout_error | |||
| ldx #>msg_chkout_error | |||
| jmp print_str | |||
| open_error: | |||
| lda #<msg_open_error | |||
| ldx #>msg_open_error | |||
| jmp print_str | |||
| .endproc | |||
| ; --------------------------------------------------------------- | |||
| ; Variables | |||
| ; print_drive_status: read the command channel (15) and print it, | |||
| ; e.g. "00, OK,00,00" or "74,DRIVE NOT READY,00,00" | |||
| ; --------------------------------------------------------------- | |||
| INBUF .FILL 80,0 ; 80-byte input buffer | |||
| INLEN .BYTE 0 ; length of input | |||
| .proc print_drive_status | |||
| lda #15 | |||
| ldx #8 | |||
| ldy #15 | |||
| jsr SETLFS | |||
| lda #0 ; no filename | |||
| jsr SETNAM | |||
| jsr OPEN | |||
| bcs done | |||
| ldx #15 | |||
| jsr CHKIN | |||
| bcs close | |||
| loop: jsr CHRIN | |||
| pha | |||
| jsr READST ; status bit 6 = EOI after the last byte | |||
| tax | |||
| pla | |||
| jsr CHROUT | |||
| txa | |||
| and #$40 | |||
| beq loop | |||
| close: jsr CLRCHN | |||
| lda #15 | |||
| jsr CLOSE | |||
| done: rts | |||
| .endproc | |||
| .segment "RODATA" | |||
| ; Lower-case source text displays as upper case on the C64 (ca65 PETSCII charmap). | |||
| msg_welcome: .byte $93, "kernal i/o demo", $0D, "type something and press return:", $0D, 0 | |||
| msg_you_typed: .byte "you typed: ", 0 | |||
| msg_open_error: .byte "error: could not open file", $0D, 0 | |||
| msg_chkout_error: .byte "error: could not redirect output", $0D, 0 | |||
| outname: .byte "@0:output,s,w" | |||
| outname_len = * - outname | |||
| filedata: .byte "data line 1", $0D, "data line 2", $0D, 0 | |||
| .segment "BSS" | |||
| inbuf: .res 80 | |||
| inlen: .res 1 | |||
| @@ -10,30 +10,30 @@ | |||
| 110 REM Frequency values for NTSC C64 | |||
| 120 REM C4=4313, D4=4842, E4=5431, F4=5760, G4=6433, A4=7372, B4=7992, C5=8627 | |||
| 130 DIM NOTE%(7) | |||
| 140 NOTE%(0) = 4313 : REM C4 | |||
| 150 NOTE%(1) = 4842 : REM D4 | |||
| 160 NOTE%(2) = 5431 : REM E4 | |||
| 170 NOTE%(3) = 5760 : REM F4 | |||
| 180 NOTE%(4) = 6433 : REM G4 | |||
| 190 NOTE%(5) = 7372 : REM A4 | |||
| 200 NOTE%(6) = 7992 : REM B4 | |||
| 130 DIM NT%(7) | |||
| 140 NT%(0) = 4313 : REM C4 | |||
| 150 NT%(1) = 4842 : REM D4 | |||
| 160 NT%(2) = 5431 : REM E4 | |||
| 170 NT%(3) = 5760 : REM F4 | |||
| 180 NT%(4) = 6433 : REM G4 | |||
| 190 NT%(5) = 7372 : REM A4 | |||
| 200 NT%(6) = 7992 : REM B4 | |||
| 210 REM ADSR for voice 1: fast attack, short decay, sustain 12, medium release | |||
| 220 POKE SID+5, 9 : REM attack=0(2ms), decay=9(250ms) | |||
| 230 POKE SID+6, 192 : REM sustain=12, release=0 | |||
| 240 REM Sawtooth waveform | |||
| 250 WAVEFORM = 32 : REM %00100000 = sawtooth | |||
| 250 WV = 32 : REM %00100000 = sawtooth | |||
| 300 REM --- MELODY LOOP --- | |||
| 310 FOR I = 0 TO 6 | |||
| 320 F = NOTE%(I) | |||
| 320 F = NT%(I) | |||
| 330 POKE SID, F AND 255 : REM frequency low | |||
| 340 POKE SID+1, INT(F/256) : REM frequency high | |||
| 350 POKE SID+4, WAVEFORM OR 1 : REM start note (gate on) | |||
| 350 POKE SID+4, WV OR 1 : REM start note (gate on) | |||
| 360 FOR W = 1 TO 150 : NEXT : REM hold note | |||
| 370 POKE SID+4, WAVEFORM : REM release (gate off) | |||
| 370 POKE SID+4, WV : REM release (gate off) | |||
| 380 FOR W = 1 TO 50 : NEXT : REM short gap | |||
| 390 NEXT I | |||
| @@ -77,6 +77,12 @@ function Invoke-C64Native { | |||
| return $output | |||
| } | |||
| function Resolve-C64Path([string]$Path) { | |||
| <# Absolute or relative-to-current-directory path -> full path. #> | |||
| if ([IO.Path]::IsPathRooted($Path)) { return [IO.Path]::GetFullPath($Path) } | |||
| return [IO.Path]::GetFullPath((Join-Path (Get-Location).Path $Path)) | |||
| } | |||
| # --------------------------------------------------------------------------- | |||
| # Projects | |||
| # --------------------------------------------------------------------------- | |||
| @@ -87,7 +93,7 @@ function Get-C64Project { | |||
| manifest itself, or a single source file (.c, .s, .asm, .bas). | |||
| #> | |||
| param([Parameter(Mandatory)][string]$Path) | |||
| $full = [IO.Path]::GetFullPath((Join-Path (Get-Location) $Path)) | |||
| $full = (Resolve-C64Path $Path) | |||
| if (Test-Path -LiteralPath $full -PathType Container) { | |||
| $manifest = Join-Path $full "c64project.json" | |||
| if (-not (Test-Path -LiteralPath $manifest)) { | |||
| @@ -163,8 +169,57 @@ function Convert-C64BasicSource { | |||
| $Text = $Text -replace '[–—]', '-' -replace '[‘’]', "'" -replace '[“”]', '"' -replace '←', '_' | |||
| $Text = $Text -replace '[^\t\r\n\x20-\x7E]', '?' | |||
| if (-not $Preserve) { $Text = $Text.ToLowerInvariant() } | |||
| $lines = $Text -split "`r?`n" | Where-Object { $_.Trim() -ne "" } | |||
| return ($lines -join "`n") + "`n" | |||
| # Order lines the way the C64 screen editor stores them: by line number, a later | |||
| # duplicate replacing an earlier one. petcat keeps file order, and a GOTO to a | |||
| # higher line that sits earlier in the file then fails with UNDEF'D STATEMENT. | |||
| $script:BasicWarned = [System.Collections.Generic.HashSet[string]]::new() | |||
| $byNumber = [System.Collections.Generic.SortedDictionary[int, string]]::new() | |||
| foreach ($line in ($Text -split "`r?`n")) { | |||
| if ($line.Trim() -eq "") { continue } | |||
| if ($line -notmatch '^\s*(\d+)') { throw "BASIC line without a line number: '$line'" } | |||
| $num = [int]$Matches[1] | |||
| if ($num -gt 63999) { throw "BASIC line number $num is above 63999" } | |||
| if ($byNumber.ContainsKey($num)) { Write-Warning "BASIC line $num appears twice; the later one wins" } | |||
| $byNumber[$num] = $line.TrimStart() | |||
| Test-C64BasicVariableNames $line | |||
| } | |||
| return (@($byNumber.Values) -join "`n") + "`n" | |||
| } | |||
| function Test-C64BasicVariableNames([string]$Line) { | |||
| <# | |||
| Warns about variable names that the tokenizer splits around a keyword, such as | |||
| NOTE% (NOT E%) or WAVEFORM (WAVE FOR M). Only assignment targets and DIM entries | |||
| are checked, and names that start with a statement keyword are skipped, so | |||
| compact code like FORI=1TO10 does not trigger it. | |||
| #> | |||
| $keywords = @("end","for","next","data","input","dim","read","let","goto","run","if","restore", | |||
| "gosub","return","stop","on","wait","load","save","verify","def","poke","print","cont","list", | |||
| "clr","cmd","sys","open","close","get","new","to","fn","then","not","step","and","or","sgn", | |||
| "int","abs","usr","fre","pos","sqr","rnd","log","exp","cos","sin","tan","atn","peek","len", | |||
| "str$","val","asc","chr$","left$","right$","mid$","go") | |||
| $statements = @("end","for","next","data","input","dim","read","let","goto","run","if","restore", | |||
| "gosub","return","stop","on","wait","load","save","verify","def","poke","print","cont","list", | |||
| "clr","cmd","sys","open","close","get","new","rem","go") | |||
| $code = [regex]::Replace($Line.ToLowerInvariant(), '"[^"]*"?', '""') | |||
| $code = [regex]::Replace($code, '^\s*\d+', '') | |||
| $code = ($code -split '\brem')[0] | |||
| $names = @() | |||
| foreach ($stmt in ($code -split ':|then')) { | |||
| if ($stmt -match '^\s*dim\s+(.*)$') { | |||
| $names += @([regex]::Matches($Matches[1], '([a-z][a-z0-9]*)[%$]?\s*\(') | ForEach-Object { $_.Groups[1].Value }) | |||
| } elseif ($stmt -match '^\s*(let\s+)?([a-z][a-z0-9]*)[%$]?\s*(\([^)]*\))?\s*=') { | |||
| $names += $Matches[2] | |||
| } | |||
| } | |||
| foreach ($word in $names) { | |||
| if ($keywords -contains $word) { continue } | |||
| if (@($statements | Where-Object { $word.StartsWith($_) })) { continue } | |||
| $hits = @($keywords | Where-Object { $_.Length -gt 1 -and $word.Contains($_.TrimEnd('$')) }) | |||
| if ($hits -and $script:BasicWarned.Add($word)) { | |||
| Write-Warning ("BASIC: variable {0} contains the keyword {1}, which the tokenizer splits out: {2}" -f $word.ToUpperInvariant(), ($hits -join "/").ToUpperInvariant(), $Line.Trim()) | |||
| } | |||
| } | |||
| } | |||
| function Get-C64PrgInfo { | |||
| @@ -254,7 +309,7 @@ function Resolve-C64Program { | |||
| param([Parameter(Mandatory)][string]$Path, [switch]$NoBuild, [string]$Machine, [switch]$FromDisk) | |||
| $ext = [IO.Path]::GetExtension($Path).ToLowerInvariant() | |||
| if ($ext -in ".prg", ".d64", ".d71", ".d81", ".t64", ".crt") { | |||
| $full = [IO.Path]::GetFullPath((Join-Path (Get-Location) $Path)) | |||
| $full = (Resolve-C64Path $Path) | |||
| if (-not (Test-Path -LiteralPath $full)) { throw "not found: $Path" } | |||
| $lbl = [IO.Path]::ChangeExtension($full, ".lbl") | |||
| $outDir = Join-Path (Split-Path $full -Parent) "build" | |||
| @@ -271,6 +326,14 @@ function Resolve-C64Program { | |||
| Machine = $(if ($Machine) { $Machine } else { $p.Machine }); OutDir = (Split-Path $p.Output -Parent); Test = $p.Test } | |||
| } | |||
| function Get-C64DiskArgs([string]$Disk) { | |||
| <# Attach an extra disk image to drive 8 (the autostarted program is injected separately). #> | |||
| if (-not $Disk) { return @() } | |||
| $full = (Resolve-C64Path $Disk) | |||
| if (-not (Test-Path -LiteralPath $full)) { throw "disk image not found: $Disk" } | |||
| return @("-8", ('"' + $full + '"')) | |||
| } | |||
| function Get-C64AutostartArgs($Target) { | |||
| $argv = @("-autostart", ('"' + $Target.Program + '"'), "-autostart-warp") | |||
| if ([IO.Path]::GetExtension($Target.Program) -ieq ".prg") { $argv += @("-autostartprgmode", "1") } | |||
| @@ -280,7 +343,8 @@ function Get-C64AutostartArgs($Target) { | |||
| function Start-C64 { | |||
| <# Launch a program interactively. -Monitor opens the remote monitor on port 6510 with labels loaded. #> | |||
| param([Parameter(Mandatory)][string]$Path, [switch]$Monitor, [switch]$Warp, [string]$Keys, | |||
| [int]$MonitorPort = 6510, [string]$Machine, [switch]$NoBuild, [switch]$FromDisk, [string[]]$ViceArgs = @()) | |||
| [int]$MonitorPort = 6510, [string]$Machine, [switch]$NoBuild, [switch]$FromDisk, [string]$Disk, | |||
| [string[]]$ViceArgs = @()) | |||
| $t = Resolve-C64Program -Path $Path -NoBuild:$NoBuild -Machine $Machine -FromDisk:$FromDisk | |||
| $argv = @("-default") | |||
| if ($Monitor) { | |||
| @@ -289,6 +353,7 @@ function Start-C64 { | |||
| } | |||
| if ($Warp) { $argv += "-warp" } | |||
| if ($Keys) { $argv += @("-keybuf", ('"' + $Keys + '"')) } | |||
| $argv += Get-C64DiskArgs $Disk | |||
| $argv += $ViceArgs | |||
| $argv += Get-C64AutostartArgs $t | |||
| $emu = Get-C64Tool (Get-C64Emulator $t.Machine) | |||
| @@ -372,7 +437,7 @@ function Invoke-C64Test { | |||
| Verdict: fail on timeout; with the $D7FF trigger, fail unless the stored value is 0; | |||
| fail if any -Expect text is missing from the screen. | |||
| Outputs in <build>/test/: screen.txt, screenshot.png, ram.bin, io.bin, monitor.log, result.json | |||
| Outputs in <build>/test/<name>/: screen.txt, screenshot.png, ram.bin, io.bin, monitor.log, result.json | |||
| #> | |||
| param( | |||
| [Parameter(Mandatory)][string]$Path, | |||
| @@ -387,6 +452,7 @@ function Invoke-C64Test { | |||
| [switch]$NoBuild, | |||
| [switch]$Ntsc, | |||
| [switch]$FromDisk, | |||
| [string]$Disk, | |||
| [string[]]$ViceArgs = @() | |||
| ) | |||
| $t = Resolve-C64Program -Path $Path -NoBuild:$NoBuild -Machine $Machine -FromDisk:$FromDisk | |||
| @@ -401,7 +467,7 @@ function Invoke-C64Test { | |||
| if ($TimeoutSeconds -eq 0) { $TimeoutSeconds = if ($cfg.Contains("timeoutSeconds")) { [int]$cfg.timeoutSeconds } else { 60 } } | |||
| if ($MaxCycles -eq 0) { $MaxCycles = if ($cfg.Contains("maxCycles")) { [long]$cfg.maxCycles } else { 150000000 } } | |||
| $out = Join-Path $t.OutDir "test" | |||
| $out = Join-Path (Join-Path $t.OutDir "test") $t.Name | |||
| if (Test-Path -LiteralPath $out) { Remove-Item -LiteralPath $out -Recurse -Force } | |||
| New-Item -ItemType Directory -Force -Path $out | Out-Null | |||
| $o = $out -replace '\\', '/' | |||
| @@ -439,13 +505,17 @@ function Invoke-C64Test { | |||
| $log = Join-Path $out "monitor.log" | |||
| $shot = Join-Path $out "screenshot.png" | |||
| $argv = @("-default", "-sounddev", "dummy", "-minimized", "-warp", | |||
| # -refreshonbreak: warp mode skips rendering frames, so without it the exit | |||
| # screenshot can be several frames older than the RAM dump. | |||
| $argv = @("-default", "-sounddev", "dummy", "-minimized", "-warp", "-refreshonbreak", | |||
| "-limitcycles", "$MaxCycles", | |||
| "-moncommands", ('"' + (Join-Path $out "setup.mon") + '"'), | |||
| "-monlog", "-monlogname", ('"' + $log + '"'), | |||
| "-exitscreenshot", ('"' + $shot + '"')) | |||
| if ($Ntsc) { $argv += "-ntsc" } | |||
| if ($Keys) { $argv += @("-keybuf", ('"' + $Keys + '"')) } | |||
| if (-not $Disk -and $cfg.Contains("disk")) { $Disk = Join-Path (Split-Path $t.OutDir -Parent) $cfg.disk } | |||
| $argv += Get-C64DiskArgs $Disk | |||
| $argv += $ViceArgs | |||
| $argv += Get-C64AutostartArgs $t | |||
| @@ -481,7 +551,10 @@ function Invoke-C64Test { | |||
| if ($t.Machine -eq "c64" -and $Matches[1] -eq "a437") { | |||
| $num = [Convert]::ToInt32($Matches[3], 16) | |||
| $result.code = $num | |||
| $reasons += "BASIC error $num ($(Get-C64BasicErrorName $num))" | |||
| $ram = [IO.File]::ReadAllBytes((Join-Path $out "ram.bin")) | |||
| $line = $ram[2 + 0x39] + 256 * $ram[2 + 0x3A] # CURLIN; $FFxx = direct mode | |||
| $where = if ($ram[2 + 0x3A] -eq 0xFF) { "in direct mode" } else { "in line $line" } | |||
| $reasons += "BASIC error $num ($(Get-C64BasicErrorName $num)) $where" | |||
| $mode = "basic-error"; $result.mode = $mode | |||
| } | |||
| } | |||
| @@ -35,7 +35,8 @@ function Split-C64Args([object[]]$Items) { | |||
| if ($item -match '^-([A-Za-z][A-Za-z0-9]*)$') { | |||
| $key = $Matches[1] | |||
| $next = if ($i + 1 -lt $Items.Count) { "$($Items[$i + 1])" } else { $null } | |||
| if ($null -ne $next -and $next -notmatch '^-[A-Za-z]') { | |||
| # -ViceArgs always takes the next token verbatim ("-ViceArgs '-refresh 1'"). | |||
| if ($null -ne $next -and ($key -eq "ViceArgs" -or $next -notmatch '^-[A-Za-z]')) { | |||
| if ($named.ContainsKey($key)) { $named[$key] = @($named[$key]) + $next } else { $named[$key] = $next } | |||
| $i += 2 | |||
| } else { | |||
| @@ -50,6 +51,9 @@ function Split-C64Args([object[]]$Items) { | |||
| function Use-Array($named, [string[]]$keys) { | |||
| foreach ($k in $keys) { if ($named.ContainsKey($k)) { $named[$k] = [string[]]@($named[$k]) } } | |||
| if ($named.ContainsKey("ViceArgs")) { | |||
| $named["ViceArgs"] = [string[]]@($named["ViceArgs"] | ForEach-Object { $_ -split '\s+' } | Where-Object { $_ }) | |||
| } | |||
| } | |||
| try { | |||
| @@ -83,8 +87,14 @@ try { | |||
| Use-Array $n @("Expect", "ViceArgs") | |||
| $failed = 0 | |||
| foreach ($p in $pos) { | |||
| $r = Invoke-C64Test -Path $p @n | |||
| if (-not $r.passed) { $failed++ } | |||
| try { | |||
| $r = Invoke-C64Test -Path $p @n | |||
| if (-not $r.passed) { $failed++ } | |||
| } catch { | |||
| # One broken target must not hide the results of the others. | |||
| Write-Host "FAIL $p $($_.Exception.Message)" -ForegroundColor Red | |||
| $failed++ | |||
| } | |||
| } | |||
| if ($pos.Count -gt 1) { Write-Host "$($pos.Count - $failed)/$($pos.Count) passed" } | |||
| exit $(if ($failed) { 1 } else { 0 }) | |||
| @@ -0,0 +1,59 @@ | |||
| <# | |||
| .SYNOPSIS | |||
| Regression suite for the toolchain, templates, projects, and examples. | |||
| .DESCRIPTION | |||
| Run after changing tools/, templates/, lib/, or an example: | |||
| pwsh tools/regress.ps1 (or: .\c64.cmd is not needed; this calls the module) | |||
| Exit code 0 when every case passes. About 2 minutes. | |||
| #> | |||
| $ErrorActionPreference = "Stop" | |||
| Import-Module (Join-Path $PSScriptRoot "C64Tools.psm1") -Force | |||
| $root = Split-Path $PSScriptRoot -Parent | |||
| Push-Location $root | |||
| $scratch = Join-Path ([IO.Path]::GetTempPath()) ("c64-regress-" + [Guid]::NewGuid().ToString("N").Substring(0, 8)) | |||
| New-Item -ItemType Directory -Path $scratch | Out-Null | |||
| $blank = Join-Path $scratch "blank.d64" | |||
| & (Get-C64Tool "c1541") -format "work,01" d64 $blank 2>&1 | Out-Null | |||
| $cases = @( | |||
| @{ Path = "$scratch\t-c"; New = "c" }, | |||
| @{ Path = "$scratch\t-asm"; New = "asm" }, | |||
| @{ Path = "$scratch\t-basic"; New = "basic" }, | |||
| @{ Path = "skirmish-game" }, | |||
| @{ Path = "samples/kernal-os-skeleton" }, | |||
| @{ Path = "samples/kernal-os-skeleton"; Keys = "help\n"; AfterJiffies = 700; Expect = @("ABOUT EXIT") }, | |||
| @{ Path = "samples/cc65-mouse-driver-demo" }, | |||
| @{ Path = "examples/hello-world.asm"; Until = "done"; Expect = @("HELLO, WORLD!") }, | |||
| @{ Path = "examples/kernal-io.asm"; Keys = "hello\n"; Until = "main_done"; Expect = @("YOU TYPED: HELLO") }, | |||
| @{ Path = "examples/bitmap-demo.asm"; Until = "wait_key" }, | |||
| @{ Path = "examples/irq-handler.asm"; AfterJiffies = 300; Expect = @("READY.") }, | |||
| @{ Path = "examples/moonlander.c"; AfterJiffies = 400; Expect = @("MOONLANDER", "PRESS FIRE") }, | |||
| @{ Path = "examples/linked-list-test.c"; AfterJiffies = 400; Expect = @("N=1000 PASS") }, | |||
| @{ Path = "examples/sprite-demo.bas"; AfterJiffies = 400 }, | |||
| @{ Path = "examples/sprite-music-demo.bas"; AfterJiffies = 400 }, | |||
| @{ Path = "examples/sound-demo.bas"; AfterJiffies = 400 }, | |||
| @{ Path = "examples/disk-access.bas"; Disk = $blank; Expect = @("READ: LAST RECORD", "BLOCKS FREE", "DONE.") } | |||
| ) | |||
| $results = foreach ($c in $cases) { | |||
| $label = if ($c.New) { "template $($c.New)" } else { $c.Path } | |||
| if ($c.ContainsKey("Keys")) { $label += " (keys)" } | |||
| try { | |||
| if ($c.New) { [void](New-C64Project -Name (Split-Path $c.Path -Leaf) -Template $c.New -Destination $c.Path) } | |||
| $testArgs = @{ Path = $c.Path } | |||
| foreach ($k in "Until", "AfterJiffies", "Keys", "Disk", "Expect") { if ($c.ContainsKey($k)) { $testArgs[$k] = $c[$k] } } | |||
| $r = Invoke-C64Test @testArgs 6>$null | |||
| [pscustomobject]@{ Case = $label; Passed = $r.passed; Reason = $r.reason; Seconds = $r.seconds } | |||
| } catch { | |||
| [pscustomobject]@{ Case = $label; Passed = $false; Reason = $_.Exception.Message; Seconds = 0 } | |||
| } | |||
| } | |||
| Pop-Location | |||
| Remove-Item -LiteralPath $scratch -Recurse -Force -ErrorAction SilentlyContinue | |||
| $results | Format-Table Case, Passed, Seconds, Reason -AutoSize | Out-String -Width 200 | Write-Host | |||
| $failed = @($results | Where-Object { -not $_.Passed }) | |||
| Write-Host ("{0}/{1} passed" -f ($results.Count - $failed.Count), $results.Count) -ForegroundColor $(if ($failed) { "Red" } else { "Green" }) | |||
| exit $(if ($failed) { 1 } else { 0 }) | |||
Powered by TurnKey Linux.