diff --git a/.gitignore b/.gitignore index 7fdf3c7..260c645 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,24 @@ test-output/ *.lst *.o *.srec -# Deliverable Quadrapassel.DSK and selected screenshots are intentionally tracked. +# Numbered QUADPSLxx.DSK deliveries and selected screenshots are intentionally tracked. + +# Native build products (selected DSK deliverables remain explicit). +obj/ +generated/ +HELLO.bin +HELLO.dsk +*.link + +/QUAD.bin +/QUAD.map +/QUAD.link + +# Personal writable disks retained across game updates; never commit. +/local-media-backups/ + +# Clean staging image; numbered deliveries are retained separately. +/Quadrapassel.DSK + +# Historical probe build product; source and selected evidence are retained. +/APIProbe.DSK diff --git a/AGENTS.md b/AGENTS.md index edea016..6d86a92 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,12 +9,15 @@ Brian take precedence. Read `SPECIFICATION.md` and `docs/VCC_PLUS_WORKFLOW.md`. by default for authorized solo work. Preserve unrelated edits and user disks. - The chat may be organized within the VCC Plus project. This does not authorize reading or editing other project repositories. -- Use official `/Applications/VCC Plus.app` **3.5.5 (48)** and its supported MCP. +- Use official `/Applications/VCC Plus.app` **3.6.0 (51)** (approved by Brian November 11, 2026) and its supported MCP. No custom VCC Plus builds, emulator patches, private protocol calls, replacement MCP integration, or requests for VCC Plus feature changes. - Do not inspect VCC Plus implementation source, private developer guides or binary internals. Do not inspect the Mac Quadrapassel source or its development - chat. Use this repository's behavioral specification instead. Do not ask another + chat. Brian explicitly permitted read-only inspection of scoring-related Mac + source in `/Users/bholman/Development/Personal/quadrapassel/` on November 11, + 2026 to compare Modern and Classic (40.2). Other Mac implementation remains + outside scope. Use this repository's behavioral specification otherwise. Do not ask another agent to obtain excluded information for you. - MCP manuals, published APIs and historical archive references are allowed and preferred. Read relevant returned topics. Installed public SDK headers/examples @@ -65,6 +68,17 @@ exceptions at repository creation**. Continue unaffected work while waiting. project identity and revision. Do not use another game's shared connection. - Preserve BASIC workspace, disk state and media. Use disposable writable copies for tests and keep the top-level deliverable disk pristine. +- Brian's latest November 11 direction: deliver `QUADPSLxx.DSK`, where `xx` is + a two-digit build number, beginning with 01. Each newly delivered build starts + with a fresh, empty high-score database and default preferences; do not carry + personal QPSAVE files into it. Record delivered numbers/hashes in docs/BUILDS.md + and increment for the next changed delivery. Keep old numbered builds and + personal score disks untouched. Score migration is only done if requested. + The official recipe's Quadrapassel.DSK is the clean staging artifact; verify it + contains no QPSAVE files before copying to a new numbered delivery filename. + Never overwrite an existing numbered delivery or remount active media while + building. If an explicit personal-disk update is requested, back it up and + verify both QPSAVE files remain byte-identical. - Desktop automation requires a current unlocked, idle-desktop grant. Use an isolated supported test context; do not reset or replace the user's session. - Test actual target configurations. A 512 KB MCP run is not a 128 KB test, and a diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..ff2028f --- /dev/null +++ b/Makefile @@ -0,0 +1,64 @@ +# VCC Plus Hello Disk recipe adapted for Quadrapassel; DOS helper retained below. +CMOC ?= cmoc +PERL ?= perl +WRITECOCOFILE ?= writecocofile +INSTALL_LOADER ?= install-coco-boot-loader +VCC_CONFIGURATION ?= Debug +ifeq ($(VCC_CONFIGURATION),Release) +OPTIM ?= -O2 --no-relocate --switch=jump +else +OPTIM ?= -O0 +DEBUG_FRAME ?= -fno-omit-frame-pointer +endif +CPPFLAGS += -Isrc/game -Isrc/platform -Isrc/APIProbe/include +CFLAGS += --coco --intermediate --deps --stack-space=1024 $(OPTIM) $(DEBUG_FRAME) +VPATH := src/game:src/platform +LDFLAGS += --coco --no-relocate --intermediate --org=1400 --data=0E00 --limit=7B00 --stack-space=1024 +ifeq ($(VCC_PROBE),1) +ENTRY := src/APIProbe/mapped.c +SOURCES := src/game/rules.c src/platform/coco3_video.c src/APIProbe/src/disk.c generated/word-count.c +LDLIBS += -ldecbfile +else +ENTRY := main.c +SOURCES := src/game/rules.c src/game/input.c src/game/store.c src/platform/coco3_video.c src/platform/video.c src/platform/disk_store.c +LDLIBS += -lcardgame -lbsound -ldecbfile +endif +OBJECTS := obj/entry.o $(SOURCES:%.c=obj/%.o) +.PHONY: all build disk clean +all: disk +build: QUAD.bin +QUAD.bin: $(OBJECTS) Makefile + "$(CMOC)" $(LDFLAGS) -o $@ $(OBJECTS) $(LDLIBS) + $(PERL) tools/check_memory.pl QUAD.map +obj/entry.o: $(ENTRY) Makefile + @mkdir -p $(dir $@) + "$(CMOC)" $(CPPFLAGS) $(CFLAGS) --intdir=$(dir $@) -c -o $@ $< +obj/%.o: %.c Makefile + @mkdir -p $(dir $@) + "$(CMOC)" $(CPPFLAGS) $(CFLAGS) --intdir=$(dir $@) -c -o $@ $< +generated/word-count.c generated/WORDS.DAT &: src/APIProbe/tools/build-data.pl src/APIProbe/assets/words.txt Makefile + @mkdir -p generated + $(PERL) src/APIProbe/tools/build-data.pl src/APIProbe/assets/words.txt generated/word-count.c generated/WORDS.DAT + +# DOS helper: Pierre Sarrazin, autostart.c 0.1.2, public domain. +obj/vcc-dos-boot/loader.bin: Makefile + @mkdir -p $(dir $@) + @printf '%s\n' '// autostart.c - Program to be run by the Disk Basic DOS command.' '// By Pierre Sarrazin ' '// This file is in the public domain.' '//' '// Reference: Roger Schrag, "A Special Use For The DOS Command",' '// The Rainbow, November 1984, p.140.' '//' '// To compile: cmoc --dos autostart.c' '// To install on CoCo disk image: install-coco-boot-loader some-image.dsk autostart.bin' '// To run on CoCo: type DOS and to automatically run *.BAS.' '//' '// Version history:' '// 0.1.0 2016-01-16 Use of legacy.h discontinued.' '// 0.1.1 2018-04-03 Adapted to CMOC 0.1.51 (const).' '// 0.1.2 2018-08-04 Basic line now forced to be uppercase.' '' '#include ' '' '#define ENDFLG 0x00 // STOP/END FLAG: POSITIVE=STOP, NEG=END' '#define CINBFL 0x70 // CONSOLE IN BUFFER FLAG: 00=NOT EMPTY, $$FF=EMPTY' '#define RVEC4 0x016a // RAM hook: CONSOLE IN' '' '' 'byte oldHookInstr;' 'word oldHookAddr;' 'const char *basicLineReader;' '' '' 'void feedKeyboard()' '{' ' word preservedX;' ' asm("stx", preservedX);' '' ' * (byte *) CINBFL = 0; // console in buffer now not empty' '' ' char nextBasicByte = (char) toupper(*basicLineReader);' ' ++basicLineReader;' ' if (nextBasicByte == 0) // if finished returning Basic line' ' {' ' * (byte *) RVEC4 = oldHookInstr;' ' * (word *) (RVEC4 + 1) = oldHookAddr;' ' nextBasicByte = '"'"'\r'"'"'; // return "Enter" to cause execution of Basic line' ' }' '' ' asm {' ' lda nextBasicByte' ' ldx preservedX' ' tfr u,s // discard stack frame' ' leas 4,s // discard previous stack frame ptr and return addr' ' rts // return to caller of CONSOLE IN' ' }' '}' '' '' 'int main()' '{' ' * (byte *) ENDFLG = - * (byte *) ENDFLG; // why?' '' ' basicLineReader =' ' #ifndef COMMAND' ' "RUN\"*.BAS\""' ' #else' ' COMMAND' ' #endif' ' ;' '' ' // Install function feedKeyboard() as CONSOLE IN routine.' ' //' ' oldHookInstr = * (byte *) RVEC4;' ' oldHookAddr = * (word *) (RVEC4 + 1);' '' ' * (byte *) RVEC4 = 0x7e; // JMP instruction' ' * (void **) (RVEC4 + 1) = (void *) feedKeyboard;' '' ' * (word *) 0x2600 = 0; // overwrite "OS" marker with two null bytes' '' ' asm("jmp", "$$ac7c"); // go interpret a Basic line (which is read from console)' '' ' return 0; // avoids compiler error' '}' > obj/vcc-dos-boot/loader.c + "$(CMOC)" --dos -O0 --limit=2800 -o $@ '-DCOMMAND="PCLEAR1:LOADM\"QUAD.BIN\":EXEC"' obj/vcc-dos-boot/loader.c + + +generated/QPTEXT.DAT: assets/ui-text.tsv tools/build_ui.pl + @mkdir -p generated + $(PERL) tools/build_ui.pl $< $@ + +disk: Quadrapassel.DSK +Quadrapassel.DSK: QUAD.bin generated/QPTEXT.DAT generated/WORDS.DAT obj/vcc-dos-boot/loader.bin Makefile + $(PERL) -e 'print chr(255) x (35*18*256)' > $@ + $(INSTALL_LOADER) $@ obj/vcc-dos-boot/loader.bin + $(WRITECOCOFILE) $@ QUAD.bin + $(WRITECOCOFILE) $@ generated/WORDS.DAT + $(WRITECOCOFILE) $@ generated/QPTEXT.DAT +clean: + rm -rf obj generated + rm -f QUAD.bin QUAD.map QUAD.link Quadrapassel.DSK +-include $(OBJECTS:.o=.d) diff --git a/QUADPSL01.DSK b/QUADPSL01.DSK new file mode 100644 index 0000000..3435aa2 Binary files /dev/null and b/QUADPSL01.DSK differ diff --git a/README.md b/README.md index 55f50f4..e1ddb74 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,22 @@ # Quadrapassel for CoCo -A specification for bringing Quadrapassel to the Tandy Color Computer in C, +A CoCo 3 implementation of Quadrapassel in C, using CMOC and the installed VCC Plus development tools. +Build this candidate with the **Release** configuration. -**Status: specification and implementation prompt ready for Brian's review. -Game implementation has not started. No playable DSK is included yet.** +**Status: CoCo 3 implementation in progress. A playable stage has run in official +VCC Plus 3.6.0 (51), with earlier gameplay/persistence checks on 3.5.5 (48). Persistent high scores/settings have saved and reloaded after cold boot on the +official 512 KB MC6809 playtest. Brian also reported successful play on a physical +512 KB CoCo 3 on November 11, 2026. A clean game disk is available; actual +128 KB qualification is pending.** | Target | Experience | | --- | --- | | CoCo 3, 128 KB | Primary target: complete game, seven distinct piece colors, keyboard and joystick | -| CoCo 2, 64 KB | Same game rules and controls, with a lower-color presentation | +| CoCo 2, 64 KB | Future adaptation; not included in this candidate | | CoCo 3, 512 KB or more | Runs the baseline game; enhancements only when they offer a measured benefit | -The intended delivery is one floppy image, `Quadrapassel.DSK`, with a convenient +Deliveries use `QUADPSLxx.DSK`, with a two-digit build number and a convenient DOS launcher and a documented manual launch path. RAM sizes above are **KB**. ## Start here @@ -20,14 +24,41 @@ DOS launcher and a documented manual launch path. RAM sizes above are **KB**. - [START_HERE.md](START_HERE.md): prompt for a separate chat within the existing VCC Plus project. - [SPECIFICATION.md](SPECIFICATION.md): self-contained game behavior and acceptance requirements. - [AGENTS.md](AGENTS.md): development boundaries and required exception review. -- [VCC Plus workflow](docs/VCC_PLUS_WORKFLOW.md): official build 48, MCP, manuals, API and archive access, and testing. +- [VCC Plus workflow](docs/VCC_PLUS_WORKFLOW.md): approved official build 51, MCP, manuals, API and archive access, and testing. - [Implementation stages](docs/IMPLEMENTATION_PLAN.md): deliverables and verification checkpoints. - [Provenance](docs/PROVENANCE.md): source revision, credits, licenses and reference data. -Use standard CMOC APIs first. Assembly and custom low-level work outside those -APIs require review by Brian and the coordinating chat before implementation. -The implementation chat must not inspect VCC Plus internals or the Mac port's -source. The supplied specification is its behavioral reference. +Use standard CMOC APIs first. Brian approved a narrowly scoped C graphics +exception; its exact scope and measured evidence are in [DECISIONS.md](docs/DECISIONS.md). +Other low-level exceptions still require review before implementation. +VCC Plus internals remain outside scope. The supplied specification is the +behavioral reference, with Brian's explicit read-only exception for checking +the Mac port's scoring source recorded in AGENTS.md. + +## Current development checks + +The current priority is the complete CoCo 3 game with 128 KB support. CoCo 2 work +will follow after that version is working and tested. See the +[implementation status](docs/IMPLEMENTATION_STATUS.md), +[MCP setup](docs/MCP_SETUP.md), and [memory layout](docs/MEMORY_LAYOUT.md). + +Host complements to the official-app build/playtest workflow: + +```sh +python3 tools/test_rules.py +python3 tools/test_components.py +python3 tools/test_video.py +``` + +Keyboard: arrows or A/D move, Down/S soft drop, Up/W preferred rotation, Q/E +counterclockwise/clockwise, Space hard drop, H hold, P pause, Enter select, BREAK +back/pause. The title also accepts Space. A short joystick fire press rotates on +release; holding fire for 400 ms opens actions, including Hold and Settings. + +High scores are designed to reload from `QPSAVE0.DAT`/`QPSAVE1.DAT` on the game +disk. The two-slot store covers all difficulty/normal-or-difficult categories and +reports write failures. Guest save/reload has passed on official build 48 / MC6809 / 512 KB. See the +[128 KB manual check](docs/TESTING_128K.md) for the remaining target validation. ## Credits and license @@ -40,3 +71,43 @@ Specification text and derived piece/reference data are provided under **GPL-3.0-or-later**; see [COPYING](COPYING). The supplied title image is a design reference with a separate notice in the provenance document. No Mac application, ROM, emulator implementation, or third-party sound payload is included. + +## Run the current CoCo 3 disk + +Mount a writable copy of [QUADPSL01.DSK](QUADPSL01.DSK) in drive 0 and type +`DOS`. Keep the downloaded original pristine. The current build targets the +CoCo 3; CoCo 2 adaptation is deferred. Allow disk loading and explicit saves to +finish before the next action. High scores/settings use QPSAVE0.DAT and +QPSAVE1.DAT; QPTEXT.DAT contains read-only menu text. +Each numbered build starts with empty high scores and default preferences. +Existing personal score disks remain untouched; scores are not copied into the +new build. The current delivery is **build 01**; the next changed delivery will +be build 02. See [build records](docs/BUILDS.md). The official recipe still uses +Quadrapassel.DSK as its clean staging artifact. + +The separately verified manual fallback on the 512 KB test machine is: + +```basic +PCLEAR1 +LOADM"QUAD.BIN" +EXEC +``` + +Audio is explicitly muted between brief effects, including during analog +joystick sampling, using standard CMOC library calls. See +[audio validation](docs/AUDIO_VALIDATION.md) for direct MCP capture results and +the remaining actual-application retest. + +## November 11 visual update + +The menu and HUD now use Pierre Sarrazin's public-domain CardGame font, with +attribution and original source retained. Modern blocks have dark gray outlines +(RGB 1,1,1); the background remains black. The title credit is +`(c) 2026 Brian Holman` (rendered in the font's uppercase character set). +The font/border pixel fixtures and enforced memory bounds pass. Current official +app qualification and disk identities are recorded in [the latest update](docs/TITLE_AND_SCORING_UPDATE.md). + +Settings names the scoring choices **Modern** and **Classic (40.2)**. Switching +changes the next game and defaults to keeping existing high scores. Both +formulas match the supplied Mac source. The reported normal-window buzz remains +unconfirmed fixed; isolated audio is quiet between effects. diff --git a/assets/ui-text.tsv b/assets/ui-text.tsv new file mode 100644 index 0000000..8812d43 --- /dev/null +++ b/assets/ui-text.tsv @@ -0,0 +1,111 @@ +# scene id text - original Quadrapassel menu text, GPL-3.0-or-later +0 1 (c) 2026 Brian Holman +0 2 PRESS SPACE OR FIRE +0 37 START +0 38 SETTINGS +0 39 CONTROLS +0 40 SCORES +0 41 CREDITS +0 42 QUIT +2 3 HOLD USED ONLY ONCE PER PIECE +2 38 SETTINGS +2 42 QUIT +2 43 RESUME +2 44 HOLD +2 45 ROTATE OTHER WAY +2 46 NEW GAME +2 47 BACK +2 75 GAME OVER +2 76 PAUSED +2 77 HOLD - UNAVAILABLE +2 78 ROTATE - UNAVAILABLE +3 8 JOYSTICK +3 38 SETTINGS +3 47 BACK +3 48 DIFFICULTY +3 49 SCORING RULES +3 50 STYLE +3 51 GRID +3 52 LANDING SHADOW +3 53 SOUND +3 54 PREFERRED ROTATION +3 55 DIFFICULT PIECES +3 56 CUSTOM SEED +3 57 EDIT SEED +3 58 CALIBRATE NEUTRAL +3 59 VIDEO TIMING +3 60 RULES AND SEED: NEXT GAME +3 61 LOOK SOUND CONTROLS: NOW +3 62 RELAX +3 63 CLASSIC (40.2) +3 64 MODERN +3 65 PLAIN +3 66 CLEAN +3 67 ON +3 68 OFF +3 69 CW +3 70 CCW +3 71 RIGHT +3 72 LEFT +3 73 LEFT RIGHT ADJUST ENTER SELECT +3 74 BACK KEEPS CURRENT CHANGES +4 4 KEYBOARD +4 5 ARROWS A D MOVE DOWN S DROP +4 6 UP W ROTATE Q CCW E CW +4 7 SPACE HARD DROP H HOLD P PAUSE +4 8 JOYSTICK +4 9 LEFT RIGHT MOVE DOWN SOFT DROP +4 10 UP HARD DROP TAP FIRE ROTATE +4 11 HOLD FIRE FOR ACTIONS MENU +4 12 RIGHT XY +4 13 LEFT XY +4 14 BUTTONS +4 47 BACK +5 30 HIGH SCORES +5 31 RANK NAME SCORE RULE +5 32 M MODERN C CLASSIC +5 33 LEFT RIGHT CHANGE CATEGORY +5 47 BACK +5 48 DIFFICULTY +5 87 RELAXED +5 88 DIFFICULT +5 89 NORMAL +5 90 C +5 91 M +6 15 QUADRAPASSEL FOR COCO +6 16 BASED ON GNOME QUADRAPASSEL +6 17 J MARCIN GORYCKI +6 18 LUBOMIR RINTEL ROBERT ANCELL +6 19 JOHN WARD WILL WARNER +6 20 Brian Holman - Mac & Coco +6 21 DIFFICULT PIECES - F POLONI +6 22 BASTET ALGORITHM +6 23 FONT CMOC LIBRARIES P SARRAZIN +6 24 GAME SOURCE GPL 3 OR LATER +6 47 BACK +7 79 START A NEW GAME? +7 80 QUIT THIS GAME? +7 81 CURRENT PLAY WILL END +7 82 CANCEL +7 83 YES +8 79 START A NEW GAME? +8 80 QUIT THIS GAME? +8 81 CURRENT PLAY WILL END +8 82 CANCEL +8 83 YES +9 25 NEW RULE STARTS NEXT GAME +9 26 KEEP OR ERASE YOUR HIGH SCORES? +9 82 CANCEL +9 84 KEEP HIGH SCORES +9 85 ERASE ALL HIGH SCORES +10 27 32 BIT SEED - HEXADECIMAL +10 28 LEFT RIGHT CHOOSE DIGIT +10 29 UP DOWN CHANGE FIRE DONE +10 86 ^ +11 34 NEW HIGH SCORE +11 35 TYPE NAME OR USE LEFT RIGHT +11 36 UP DOWN CHOOSE FIRE SELECT +11 82 CANCEL +11 92 INITIAL +11 93 SAVE TO DISK +9 94 ERASE CLEARS ALL DIFFICULTIES diff --git a/docs/AUDIO_VALIDATION.md b/docs/AUDIO_VALIDATION.md new file mode 100644 index 0000000..d7766eb --- /dev/null +++ b/docs/AUDIO_VALIDATION.md @@ -0,0 +1,123 @@ +# Audio routing correction — November 10, 2026 + +Brian reported constant noise during keyboard play, including while idle. That +is outside the specification: sound should consist of brief event effects with +silence between them. His earlier pacing feedback remains keyboard evidence; +physical joystick testing is still pending. + +## Correction + +The old code initialized CardGame audio once at startup, then continuously called +`readJoystickPositions`. The public CMOC documentation explicitly states that +analog sound routing shares hardware with joystick measurements. The permitted +CardGame example's initSound.c selects the DAC and enables sound; beep.c does not +close that path on return. This leaves audio routing unmanaged between events. + +The game now calls the documented `Player_disableSound()` helper before joystick +sampling and at startup. Each enabled effect calls `initSound()` immediately +before `beep()` and `Player_disableSound()` immediately afterward. This keeps the +speaker path closed while idle and while the joystick selector is being changed. + +The implementation uses standard CardGame and bsound APIs only. It installs no +Player IRQ, supplies no custom interrupt/sound driver, and adds no direct hardware +access. The quiet movement volume and existing event pitches/durations are kept. +The half-frequency constants are the same values the previous code obtained by +integer division; gameplay timing, scoring and save format are unchanged. + +Public references read through the installed MCP manual: + +- `programming-in-c/api.html#api-player-disablesound`: analog-path enable/disable + shares hardware with joystick measurements; link bsound. +- `programming-in-c/api.html#api-beep` and public cardgame.h: initialization, + positive period/duration and bounded volume. +- Public Player.h: standalone enable/disable helpers; Player_init/shutdown are + associated with the optional player/IRQ service, which this game does not use. +- Pierre Sarrazin's local CardGame 0.1.15 initSound.c/beep.c (public-domain + examples) were read for reference. No assembly or register code was copied. + +## Actual MCP captures + +Official VCC Plus 3.5.5 (48), disposable CoCo 3 / 512 KB workers, stock fast mode. +Each WAV captures 120 emulated fields directly, at 44,100 Hz, PCM16 stereo, +88,651 or 88,652 sample frames. Both channels were checked. + +| Context | Result | +| --- | --- | +| MC6809 title idle | Every sample zero | +| MC6809 gameplay idle | Every sample zero in the captured no-event window | +| MC6809 right-move action window | Short effect, peak 1,792 in each channel; 10 changing edges; last 500 ms exactly zero | +| MC6809 idle after movement | Every sample zero | +| MC6809 hard-drop/lock window | Short effect, peak 5,120 in each channel; 10 changing edges; last 500 ms exactly zero | +| MC6809 pause menu idle | Every sample zero | +| MC6809 Sound OFF, following a left-key action | Every sample zero; OFF was also verified on the guest settings screen | +| MC6809 Sound OFF idle | Every sample zero | +| HD6309 gameplay idle, reset emulation mode | Every sample zero | +| HD6309 right-move action window | Short effect, peak 1,792 in each channel; 10 changing edges; last 500 ms exactly zero | + +The movement peak is lower than the landing peak, preserving relative volume. +Positive effect captures establish that silent windows are not simply a globally +muted capture endpoint. Captures start after bounded input, so a silent post-key +window alone does not establish whether an earlier very short effect played. + +The unchanged baseline disk was also captured. Its sampled idle and post-movement +windows were zero. **The reported continuous noise was not reproduced in the +isolated worker.** The routing defect was corrected from the public contracts +and source usage; confirmation that Brian's actual-app idle noise is gone still +requires retesting that environment. These are direct guest PCM checks, not a +claim of human listening, Mac output-device qualification or a 128 KB pass. + +`tools/check_audio.py` checks all PCM channels for exact digital silence, or for +a nonconstant effect with a silent final 500 ms. Example: + +```sh +python3 tools/check_audio.py test-output/audio/after-idle-game.wav --expect silent +python3 tools/check_audio.py test-output/audio/after-lock-effect.wav --expect effect +``` + +Raw WAVs and full receipts remain in ignored test-output/audio/. The MCP baseline +used a freshly built disposable disk. The pre-update local writable image also +contained QPSAVE0.DAT/QPSAVE1.DAT; that original is preserved under ignored +local-media-backups/. A second private copy there replaces only QUAD.BIN with +the corrected executable. Every other file and the DOS boot track were verified +byte-identical. These personal save files are excluded from Git and MCP inputs. +The personal emulator session was not operated or reset. + +## Build identity + +- Project revision 16, Release, build `CFC0A2F2-9247-4B1C-9CF8-8CC1AFE896B6`. +- Artifact `261716EE-81C8-487D-A7BF-E5C9F51BC044`. +- Binary: 26,370 bytes, SHA-256 + `5c9f3be05fde79e09a5a583740e676f2fb06eddc136dd9d419f62f12da6bebfe`. +- Pristine Quadrapassel.DSK: 161,280 bytes, SHA-256 + `d23bc2a1aa60970becaf7ff8be064efc8ea47a5043adf9661d9a6c22bcedfd9b`. +- Code/constants end $7AE8; static data end $1318; existing memory checks passed. +- MC6809 run `0B67B031-7CEE-4CD7-98CA-649B295FECB3`. +- HD6309 run `356B3452-D3AA-4EBA-8111-1D41EC9F9277`. +- All owned runs are stopped. No implementation commit or push was requested. + +## November 11 — normal-window buzz still reported + +Brian confirmed the font candidate buzzes on its title screen before Start, +including after quitting/reopening VCC Plus. The real 512 KB CoCo 3 does not +buzz. During the authorized desktop check, pausing VCC Plus stopped the noise; +Run was then restored without resetting the game or replacing mounted media. +This establishes a normal-window playback symptom, not its cause. + +The visible normal setup is MC6809/512 KB at 1x, with an FD-502/floppy controller, +Speech/Sound Cartridge, Orchestra-90 and a stopped Hello World cassette. App +sound is enabled at 50%. Those peripherals differ from the supported disposable +worker; their presence alone does not establish that any cartridge causes the +buzz. The public MCP audio tool captures only the disposable worker, not the +normal window or microphone. No claim of hearing the actual speaker is made. + +The new standard candidate reasserts Player_disableSound after joystick button/ +position sampling as well as before it. This is a defensive public-library +change, not a demonstrated cure. It adds no custom audio code or hardware access. +Official build 51, project revision 2, run +`0174149F-48E6-4EB6-8D96-BC1BF0BF4C87`: title and gameplay idle captures are +zero in both channels; movement peak 1792 in both channels, nine changing edges, +last 500 ms zero. Each direct stereo capture covers 120 fields; the effect +capture contains 88,651 frames, idle captures 88,652 at 44,100 Hz. Checks pass. +Owned runs are stopped. The normal-window buzz remains unconfirmed fixed and +needs the new candidate retested in that same environment. Full final identity +and preserved-score disk are in TITLE_AND_SCORING_UPDATE.md. diff --git a/docs/BUILDS.md b/docs/BUILDS.md new file mode 100644 index 0000000..820427d --- /dev/null +++ b/docs/BUILDS.md @@ -0,0 +1,35 @@ +# Numbered game disks + +Brian requested this delivery convention on November 11, 2026: +`QUADPSLxx.DSK`, with a two-digit build number and fresh high scores for each +new delivered build. Begin at 01. The next changed delivery is 02. This number +identifies the game disk, independently of the VCC Plus application build. + +| Build | Date | Filename | Contents / validation | +| --- | --- | --- | --- | +| 01 | 2026-11-11 | QUADPSL01.DSK | Current title spacing, credits, scoring labels and extra standard-library mute; byte-identical to the verified clean official artifact described in TITLE_AND_SCORING_UPDATE.md | + +Build 01 is 161,280 bytes, SHA-256: +`4ac171e87c51dfd99b302b9e035a91a59c030144e5ae0661a6d2dfc84ba3a63f`. +It contains only QUAD.BIN, WORDS.DAT and QPTEXT.DAT, plus the existing DOS boot +track. Neither QPSAVE file is present, so the game starts with default preferences +and an empty scoreboard, creating save data through the normal save path. + +The official build recipe continues producing the clean `Quadrapassel.DSK` +staging artifact. After a successful qualified build, inspect its directory for +unexpected files and personal QPSAVE data, then copy it without overwriting to +the next `QUADPSLxx.DSK`. Verify the copy hash equals the official artifact hash +and record the delivery here. Rebuilding unchanged content does not consume a +new number; a changed delivered candidate does. Do not reuse an old numbered +filename, migrate personal scores automatically, or overwrite/remount a user's +disk. Keep numbered deliveries distinct from writable playtest copies. + +The name change alone required no guest code rebuild or new gameplay test: +build 01's bytes match the already-tested artifact. It does not establish that +the reported normal-window buzzing is fixed. Existing personal score disks and +backups were left unchanged. + +Brian authorized committing and pushing the implementation and build 01 on +November 11. The Git commit adding QUADPSL01.DSK records its source snapshot; +use `git log -- QUADPSL01.DSK` to identify that commit. The game bytes were +qualified before committing and are unchanged from the official artifact. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md new file mode 100644 index 0000000..b378c29 --- /dev/null +++ b/docs/DECISIONS.md @@ -0,0 +1,41 @@ +# Reviewed decisions + +## November 10, 2026 — C graphics exception + +Brian's explicit decision, relayed by the coordinating chat **Deploy VCC Plus +Gitea** (`01a1c3a8-8bde-77f0-b8af-d0d29b874c7c`): **“Approve the C graphics +exception.”** The approved wording was: + +> C code for screen-memory mapping and drawing changed regions, using CMOC/BGraph +> where practical, with no assembly or emulator changes and explicit 128 KB validation. + +Allowed scope: the narrowly proposed CoCo 3 C framebuffer/MMU renderer in +`src/platform/coco3_video.c/.h` and associated memory/build documentation. Prefer +standard CMOC/BGraph primitives where practical. Bound dirty-region/text drawing, +preserve code, stack, BASIC graphics/disk workspace and interrupt behavior during +temporary mapping, and restore the state needed by standard APIs and disk calls. +Retain the public-API fallback and compare measured drawing and visible input. + +This approval does **not** authorize hand-written assembly, custom sound/input/ +interrupt drivers, emulator source access or changes, custom app builds, or a +replacement MCP integration. Official VCC Plus 3.5.5 (48) and reference boundaries +remain required. Further exceptions need review. Actual 128 KB testing remains +separate from the 512 KB MCP worker; Brian offered to perform that manual check. + +### Evidence prompting review + +Official build 48, Release `-O2`, isolated MC6809, 512 KB, NTSC-rate worker: + +- One 8×8 block erase/redraw through `hset`: worst 4 BASIC ticks at ordinary speed. +- T-piece one-cell shift: only four changed 8×8 cells (256 plotted pixels), worst + 12 ticks at ordinary approximately 0.895 MHz speed. +- Same 60-shift test using standard `setHighSpeed(TRUE)` at approximately + 1.79 MHz: p95 and worst both 6 ticks, approximately 100 ms. + +Build `B928140E-6147-4DB5-BEF0-729678C498B0`, MCP revision 2, artifact +`12931271-4662-4B9F-B138-03913F23E58B`, disk SHA-256 +`87f9d22c0afe7313f08031b9b4d88c2e0b6eeb4e81050739d108d82fe1fe76ad`. +These measure foreground drawing cost, not full-game input-to-display latency. +Smaller blocks, sparse outlines and staged `hset` drawing remain possible API-only +alternatives, with board-area, appearance or latency compromises. No direct screen +code was implemented before this approval was received and recorded. diff --git a/docs/FONT_UPDATE.md b/docs/FONT_UPDATE.md new file mode 100644 index 0000000..eca8180 --- /dev/null +++ b/docs/FONT_UPDATE.md @@ -0,0 +1,79 @@ +# Font and block-outline update — November 11, 2026 + +Brian approved the installed official VCC Plus 3.6.0 (51), project reconnection +and isolated build/playtest. Base source revision remains +`8a4b44bc7358b1a999296d14d8c5272e57b65992`, main, plus uncommitted implementation. +Nothing was committed or pushed. + +## Result + +Menu/HUD text now uses unchanged public-domain CardGame 0.1.15 glyph row data +by Pierre Sarrazin, also used by Color8. Original files, notices and hashes are +retained in `third_party/cardgame-font/`; the bounded subset is in +`src/platform/pierre_font.h`. The renderer uses six visible columns and seven +rows in the existing 8x8 cells. Lowercase input maps to uppercase glyphs. +No other game's renderer or assembly was copied. + +Modern tile outlines now use palette slot 10, RGB(1,1,1); the black background, +seven piece colors and Plain/Clean styles are preserved. The title credit asset +is exactly `(c) 2026 Brian Holman`, displayed in the uppercase character set. +Pierre's font contribution is also credited on the credits screen. + +## Validation and identity + +- `python3 tools/test_video.py`: passed ASan/UBSan. All supported glyphs match + the original font pixel-for-pixel, including parentheses and lowercase mapping. + Last-cell boundaries, all eleven palette colors, all seven Modern block colors, + black background and Plain/Clean styles pass. +- Official MCP Release disk build: project + `84772EFC-B651-4A98-B09E-932247575EA7`, revision 1, + build `FAD8FBEA-F07D-4FE8-AE45-E569EEA5E5CC`, + artifact `4566B606-6576-482A-BA3E-BCC673EC729B`, zero diagnostics. +- QUAD.bin: 26,589 bytes, SHA-256 + `9eec745d50544884d74211492f0118360d79212f05864d9e81fa43a1a56ed041`. +- Clean Quadrapassel.DSK: 161,280 bytes, SHA-256 + `12f0ee508d5b48bbbe44d1f2b701eb31ae5bd5d3cbb863e1005540524d5dbfb3`. + Local deliverables match the official artifact hashes. +- Enforced map: code/constants end $7AFE, static data end $13DD. Existing + $7B00/$1400 bounds and 1,024-byte stack reserve retained. Alphabet, punctuation + codes and packing table use 197 bytes in the existing low data region and + are only read by the renderer. No new graphics mode or 512 KB requirement. +- Approved C renderer's compiler output still reads the MMU bank via the separate + read function, performs the bounded copy and restores the prior mapping. +- Owned run `1EBBD56F-EB22-4E17-BF49-8C943FB25F04`: MC6809, 512 KB, current + artifact verified. DOS startup, title, settings, normal settings save/return, + gameplay, Hold/drop, title credit and gray outlines inspected. Run stopped. +- Direct 120-field stereo WAV capture: idle peak 0 in both channels; movement + peak 1792 in each channel, nine changing edges, final 500 ms silent. + `tools/check_audio.py` passed both checks. Raw receipts/WAVs remain ignored. + +Actual framebuffer evidence (320x192 HSCREEN 2): + +![Title](screenshots/font-title-512k.png) +![Settings](screenshots/font-settings-512k.png) +![Gameplay](screenshots/font-gameplay-512k.png) + +These are supported paused guest framebuffer captures, not host-test renderings. +The host pixel preview is supplemental only. The larger title lettering remains +code-drawn from its existing compact shape data. + +## Existing saves + +A new ignored copy, `local-media-backups/2026-11-11-font-update/Quadrapassel-Font-Update-With-Saves.DSK`, +contains the new QUAD.BIN and QPTEXT.DAT. QPSAVE0.DAT, QPSAVE1.DAT, WORDS.DAT and +DOS track 34 were verified unchanged. The source disk and a before-update copy +are retained. Verification hashes are in that folder's private VERIFICATION.json. +Updated saved-disk SHA-256: +`f5ec52d909eb6adc58c7feb5c8497ca04b25a6f7a49247a9793554787970cb60`. +The clean top-level disk contains no personal saves. The normal running emulator +and its mounted media were not replaced or reset. + +## Limits + +This update was tested in the official 512 KB worker. Actual 128 KB testing, +physical display appearance and physical joystick checks remain pending. Earlier +user-reported physical 512 KB gameplay and prior earned-score cold-boot evidence +are recorded separately in IMPLEMENTATION_STATUS.md. The font update changes +neither persistence codec nor rules. It does not establish a new 6309 pass or a +full timing/stack qualification. The memory budget has only two code bytes and +35 static bytes spare, so further feature work needs compaction first. diff --git a/docs/IMPLEMENTATION_STATUS.md b/docs/IMPLEMENTATION_STATUS.md new file mode 100644 index 0000000..1fa6883 --- /dev/null +++ b/docs/IMPLEMENTATION_STATUS.md @@ -0,0 +1,164 @@ +# CoCo 3 implementation status — November 11, 2026 + +The current disk contains a playable CoCo 3 game with standard CMOC sound, +settings and disk-backed high scores. Actual 128 KB qualification remains +pending; CoCo 2 adaptation is deferred at Brian's direction. + +## Current numbered delivery + +Brian requested `QUADPSLxx.DSK` with a two-digit build number and fresh high +scores. The first is **QUADPSL01.DSK**, byte-identical to the clean official +artifact below. No QPSAVE files are included; old personal score disks remain +untouched. The next changed delivery is 02. See [BUILDS.md](BUILDS.md). + +## Current title, scoring-label and audio follow-up + +The standard Release candidate now has an eight-pixel gap before the title +copyright, the credits entry `Brian Holman - Mac & Coco`, and explicit +**Scoring Rules: Modern / Classic (40.2)**. Keep high scores is the default; +no personal records were erased. Inspection of Brian's supplied Mac source +confirmed the existing scoring formulas, including the Classic 40.2 bottom-row +bonus. All 25 cases also pass through actual piece drops. + +Official build 51, project revision 2, build +`DFDE8C57-3165-44B5-9027-E8B2F16DDF28`, artifact +`BB277DE8-07A2-437B-9998-FFD1FB2C36C5`, zero diagnostics. +Clean disk SHA-256: +`4ac171e87c51dfd99b302b9e035a91a59c030144e5ae0661a6d2dfc84ba3a63f`. +Code/constants end $7AF4; static data end $13DE. The normal-window buzz persists +in Brian's prior candidate after restart and stops when paused; it remains +unconfirmed fixed. An extra standard-library mute after input sampling passes +worker silence/effect checks. Details, captures and score-preservation proof: +[TITLE_AND_SCORING_UPDATE.md](TITLE_AND_SCORING_UPDATE.md). + +## Previous font candidate + +The November 11 font/border/copyright candidate passed an official VCC Plus +3.6.0 (51) Release build and MC6809 / 512 KB disposable playtest. The font uses +Pierre Sarrazin's public-domain CardGame data, with attribution. Modern outlines +are dark gray while the background stays black. Title text is +`(c) 2026 Brian Holman`, displayed in the font's uppercase character set. + +- Project `84772EFC-B651-4A98-B09E-932247575EA7`, revision 1. +- Build `FAD8FBEA-F07D-4FE8-AE45-E569EEA5E5CC`, artifact + `4566B606-6576-482A-BA3E-BCC673EC729B`; no compiler diagnostics. +- Binary 26,589 bytes, SHA-256 + `9eec745d50544884d74211492f0118360d79212f05864d9e81fa43a1a56ed041`. +- Pristine DSK SHA-256 + `12f0ee508d5b48bbbe44d1f2b701eb31ae5bd5d3cbb863e1005540524d5dbfb3`. +- Code/constants end $7AFE; static data end $13DD. Existing limits and + 1,024-byte stack reserve retained. Further growth needs compaction. +- Pixel tests compare against the unmodified upstream font; palette, all seven + Modern tile colors, Plain/Clean behavior and edge-cell clipping pass under + AddressSanitizer/UndefinedBehaviorSanitizer. +- Actual title, settings and gameplay framebuffer captures inspected. Hold/drop + exercised; a normal settings save wrote the disposable disk successfully. +- Captured idle audio is zero in both channels; movement has a brief effect and + silent final 500 ms. Owned run stopped. +- New private disk copy preserves both existing high-score files byte-for-byte. + +Details, screenshots, saved-disk identity and remaining limits: +[FONT_UPDATE.md](FONT_UPDATE.md). Persistence code and gameplay rules are unchanged; +prior cold-boot score evidence below remains applicable to that unchanged code. +Actual 128 KB and physical joystick qualification remain pending. + +## Previous audio candidate — November 10 build identity + +- Base Git revision: `8a4b44bc7358b1a999296d14d8c5272e57b65992`, main, with + uncommitted implementation. No implementation commit or push was requested. +- Official application: VCC Plus 3.5.5 (48), supported C-project MCP connection. +- Previous code build: project revision 16, Release, + build `CFC0A2F2-9247-4B1C-9CF8-8CC1AFE896B6`, + artifact `261716EE-81C8-487D-A7BF-E5C9F51BC044`. +- Binary: 26,370 bytes, + SHA-256 `5c9f3be05fde79e09a5a583740e676f2fb06eddc136dd9d419f62f12da6bebfe`. +- Previous pristine `Quadrapassel.DSK`: 161,280 bytes, + SHA-256 `d23bc2a1aa60970becaf7ff8be064efc8ea47a5043adf9661d9a6c22bcedfd9b`. + This matched that official MCP artifact, not a saved playtest copy. +- Linked code/constants end at $7AE8 (24 bytes before the enforced $7B00 limit). + Writable static data ends at $1318 (232 bytes before $1400). The stack reserve + is 1,024 bytes; detailed contract and qualification limits are in MEMORY_LAYOUT.md. +- The pristine disk has 50 free granules and no save files. Two 35-sector save + files need four granules each. DOS loader tracks are reserved by the template. + +## Implemented + +- All 28 piece states, safe above-board behavior, specified kicks, gravity, + hard/soft drop, persistent Hold swap, shadow and simultaneous compaction. +- Modern/Classic 32-bit saturating scoring, level transitions and Relaxed mode. +- Version-1 xorshift32 seeded stream, inverse-square balancing, prefill and + Difficult Pieces metric/selection. Difficult search is currently synchronous. +- Keyboard controls and a one-button joystick input state machine, settings, + seed editor, pause/actions/confirmation screens, score browser and initials. +- Code-drawn title and cached tiles; menu focus updates without full redraws. + Scene text is a bounded, checksummed disk asset sharing the display cache. +- Standard CardGame `initSound`/`beep` effects, with the standard bsound mute + helper closing audio around joystick sampling and between effects. No custom driver. +- Versioned QPSAVE0.DAT/QPSAVE1.DAT store for all 34 categories, ten records each, + initials and scoring-rule markers. CRC/range/length validation, generation + selection, older-slot recovery, header-last commits and readback verification. + Only those two named files are written; errors are visible and play can continue. + +## Evidence and limits + +| Check | Result | +| --- | --- | +| Host rule fixtures, sanitizer build | Passed: 28 states, all kick fixtures, bounds/top-out, compaction, 25 scoring cases, gravity, Hold, RNG/prefill and Difficult metrics | +| Host input fixtures, sanitizer build | Passed: repeat/conflicts/edges, fire timing, hysteresis, diagonal and disconnected-stick keyboard behavior | +| Host persistence fixtures, sanitizer build | Passed: 34 categories, stable ties, rule markers, 32-bit values, CRC, read-only reset, all 36 logical torn-write boundaries and recovery | +| Official Release build and memory bounds | Passed, final build above, no compiler diagnostics | +| MC6809 / 512 KB | Passed: DOS title, gameplay, movement/rotation/Hold/hard drop, settings, cached settings redraw and fast menu focus | +| Settings save and cold-boot reload | Passed on revision 12: Sound OFF and Custom Seed ON reloaded from the same disposable disk | +| Earned high score save and cold-boot reload | Passed on revision 12: seed zero, 12 authored placements, one line/40 points, initials BRH, Modern marker in difficulty-0 Normal category; survived another cold boot | +| Clean BASIC return and manual fallback | Passed on revision 13: Quit returned OK; PCLEAR1, LOADM"QUAD.BIN", EXEC reached the title | +| HD6309 / 512 KB | Revision 16 idle/effect audio checks and prior title/gameplay framebuffer smoke passed in reset emulation mode; not a native-mode qualification | +| Physical CoCo 3 / 512 KB | Brian reported successful gameplay on November 11, 2026 ("It worked great"); RAM confirmed as 512 KB. Exact disk hash, CPU upgrade status and individual audio/save/joystick checks were not specified | +| CoCo 3 / 128 KB | Pending actual application/manual test; MCP workers remain fixed at 512 KB | +| Physical joystick ports and joystick-only usability | Pending; logical fixtures/neutral samples are not physical-port passes | +| Guest read-only/corrupt media and interrupted FAT/directory writes | Pending; logical host fault tests do not establish these physical disk cases | +| Direct guest audio, idle/mute and bounded effects | Passed captured windows on 6809 and 6309; actual-app reported noise retest pending; see AUDIO_VALIDATION.md | +| Current input/render latency, sound-on worst case, clears and Difficult search | Not fully qualified; earlier renderer probe timing is not a complete-game timing pass | +| PAL/50 Hz, physical Intel, CoCo 2 | Not qualified by these runs | +| Debug/Probe configurations with the final split layout | Not qualified; use Release for this disk | + +The earned-score run was `9AFA5124-4FDE-4E3D-95EE-228FCE945951`. +Its retained writable disk SHA-256 is +`44ca3987b8d3a1e02ee41f1a0de8bd587be5a6835f8bdc5186b22138e6be0355`. +That disk is separate from the pristine deliverable. All owned runs are stopped. +Final menu/cache and 6309 changes did not alter the validated persistence codec. + +## Capture interpretation + +Presented-frame PNGs sometimes omitted unchanged screen content during these +runs. The supported paused `capture_playtest_graphics` preview showed the title, +HUD/frame and cached settings intact in the current physical HSCREEN 2 buffer. +Visual verification therefore uses these direct guest-framebuffer previews in +addition to ordinary screenshots. No emulator internals were inspected and no +emulator change is required for the current disk. + +Selected evidence is under docs/screenshots/, including +high-score-saved-512k.png, high-score-reloaded-512k.png, +title-clean-512k.png, gameplay-framebuffer-512k.png, +settings-cached-framebuffer-512k.png and +gameplay-6309-framebuffer-512k.png. Reference art is not runtime evidence. + +Next qualification: follow TESTING_128K.md, measure complete-game latency and +Difficult search separately, then physical joystick/read-only/fault cases. +Further feature growth needs code compaction before exceeding the enforced limit. + +## Latest user feedback and sound correction + +Brian reported good keyboard pacing, then constant audio noise even while idle. +The standard-library audio routing correction and direct MCP stereo WAV checks +are recorded in [AUDIO_VALIDATION.md](AUDIO_VALIDATION.md). The isolated worker +did not reproduce the original constant noise; the actual application needs a +retest. The save codec and gameplay rules were not changed. + +## November 11 — physical CoCo 3 playtest + +Brian reported playing Quadrapassel successfully on a real Color Computer 3 +and described it as working great. He confirmed the RAM size as **512 KB**. +This is user-reported physical-hardware gameplay evidence, separate from the +isolated emulator runs. It does not establish a 128 KB pass or separate passes +for the audio correction, persistence, joystick ports or every game option. +The exact tested disk/build and detailed machine configuration were not supplied. diff --git a/docs/MCP_SETUP.md b/docs/MCP_SETUP.md new file mode 100644 index 0000000..26f1f28 --- /dev/null +++ b/docs/MCP_SETUP.md @@ -0,0 +1,61 @@ +# MCP kickoff and connection inventory + +Verified November 10, 2026 against installed official VCC Plus **3.5.5 (48)**. +Keep private grant files and tokens outside Git. This is a connection record, +not permission to inspect emulator implementation or another game's project. + +| Connection | Live tools used | Verification | +| --- | --- | --- | +| Quadrapassel C project | `get_capabilities`, `read_project_inputs`, `refresh_project`, `build_project`, `get_build`, owned-playtest tools | Project `A1AFAA7E-C427-4437-8D1C-EB68D8C225EF`; this repository's root Makefile, files and hashes | +| Installed manuals/API (through the C connection) | `search_help`, `read_topic` | Read HSCREEN/HSET, keyboard, joystick, timer, SOUND, beep and PCLEAR topics | +| Archive Library (separate connection) | `search_archive`, `get_archive_citation` | Both succeeded; found Tandy's Color Computer 3 Extended Basic, PDF pages 152–153 | + +At this chat's start no VCC Plus tools appeared in its tool catalog. Connections +were exported through the installed app's normal native interface. Its public +manual, `vibe-coding-with-chatgpt/01-first-connection.html`, explicitly permits +ordinary STDIO MCP through `/Applications/VCC Plus.app/Contents/Helpers/vcc-mcp` +with the two arguments `--grant` and the private grant filename. The unmodified +installed helper is used by a small MCP client; no alternative server, private +bridge or integration endpoint is used. + +Archive Library has its own link button and **Save Archive Search Connection…** +flow. Brian explicitly approved this connection on November 10. Its advertised +build-48 tools return citations/locations, rather than full page text. Use the +Archive Library native reader for the original page when needed. Do not infer +that Archive MCP is unavailable from the C connection's tool inventory. + +For future kickoff checks, distinguish **configured**, **tools discovered**, and +**successful request**. Inventory each required connection separately before +implementation or web fallback. Confirm the intended project and current revision +before builds. Connection identity and advertised tools may change after a new +export; discover them again, rather than inventing tool names or endpoints. + +Example verified Archive reference: + +- Title: *Color Computer 3 Extended Basic (Tandy)*. +- Citation: `sha256:26d4ca51f3477263f3e85269091104079ae88ad83c842cef0e3bc531324e7f5e:pdf_page:152`. +- Read in Archive Library: printed page 143, “Adding Pages (The PCLEAR Command)”. + It describes the default four PMODE pages and reserving fewer pages. + +Initial hardware-reference web lookups occurred before discovering the separate +Archive connection. That was a discovery error, not a demonstrated Archive gap. +Brian asked that the kickoff feedback be sent to **Deploy VCC Plus Gitea**; the +approved concise feedback was delivered there. No emulator update is requested. + +## November 11 reconnection + +Brian approved installed official VCC Plus 3.6.0 (51) and an idle desktop window. +The same repository was opened through C Development and its private project +connection renewed outside Git. A successful `get_capabilities` returned project +`84772EFC-B651-4A98-B09E-932247575EA7`, session +`185C8449-CB9B-4A38-81C8-D43CDA4A3ABE`, app build 51, approved Make recipe, +and the expected Quadrapassel files. This connection still advertises fixed +512 KB disposable workers, MC6809/HD6309, graphics and audio captures. +Archive access is separate and was not needed for this local font adaptation. + +After Brian's November 11 restart, the old private grant expired. The same +project connection was renewed through the supported interface. Current project +`3D6A502C-E06D-46BC-9D19-191D741A16B9`, revision 2, built and ran successfully +on official build 51. get_machine_status read normal-session configuration; +no writable disks or peripherals were removed to satisfy native-run blockers. +The new candidate used only disposable playtests. diff --git a/docs/MEMORY_LAYOUT.md b/docs/MEMORY_LAYOUT.md new file mode 100644 index 0000000..8796a25 --- /dev/null +++ b/docs/MEMORY_LAYOUT.md @@ -0,0 +1,49 @@ +# CoCo 3 memory contract + +Current candidate uses stock Disk BASIC and `PCLEAR1`, then +`LOADM"QUAD.BIN":EXEC`. `PCLEAR0` was tested in an isolated official build-48 +MC6809/512 KB machine and returned `?FC ERROR`; it is not used. + +The standard CMOC linker places code/constant data at $1400 and writable static +data at $0E00. The one reserved legacy PMODE page ($0E00–$13FF) is deliberately +used for the game's static variables. This is a CoCo 3-only program: it never +calls PMODE or PCLS. HSCREEN 2 uses its separate physical graphics banks $30–$33. +Graphics is initialized once before preferences are created. Scene changes clear +only the framebuffer through the approved renderer, keeping ROM initialization +outside live game state. No BASIC user program or prior +low-resolution picture is preserved by launching +this game. BASIC system RAM, text RAM and disk buffers below $0E00 remain intact. + +The November 11 layout/scoring-label update ends code/constants at $7AF4 and static data at +$13DE (1,502 bytes including initialized variables). The limits remain unchanged. +The font uses 336 row bytes plus 12 punctuation codes; 198 bytes of font/packing +data are stored in the low data region and only read by the renderer. $7B00–$7FFF is kept free for +the foreground/ROM stack, with CMOC configured for 1,024 bytes. The split layout has passed settings and earned-score save/reload checks on +MC6809/512 KB in the official app. Full stack qualification and actual 128 KB +testing remain pending. This is a checked +address budget, not a claim that 128 KB has passed. + +`tools/check_memory.pl` verifies every nonempty link-map section independently. +This is necessary because CMOC's `--limit` checks `program_end`, which is the low +static-data end when `--data` is used. The build fails if code/constants extend +past $7B00 or static data extends past $1400. No data or stack may occupy the +renderer’s temporary $8000–$9FFF MMU window. + +The approved C renderer temporarily maps task-0 slot 4 to graphics banks $30–$33, +copies bounded chunks and restores the prior mapping before standard APIs run. +CMOC does not implement volatile: a separate read function is used and emitted +reads/stores must be audited in each delivered candidate. No authored assembly, +custom interrupt handler or custom sound driver is used. + +Menu text is loaded through standard decbfile APIs from twelve independently +checksummed 512-byte pages in QPTEXT.DAT. The menu buffer shares storage with the +288-byte tile cache and 200-byte board cache; gameplay rebuilds those caches on +resume. Original title lettering uses 84 bytes of shape data and a scanline +scratch buffer, rather than a full-screen bitmap. + +The score store keeps one 256-byte page and one 80-byte top-ten table in RAM. +QPSAVE0.DAT/QPSAVE1.DAT each hold 35 sectors, with the commit header written last. +Files longer than the schema allows are rejected and reported; the program does +not truncate an unexpectedly oversized file. Missing/short inactive files can be +created/extended using the documented file API. Only the two named save files +are written. QPTEXT.DAT is read-only game data. diff --git a/docs/PROVENANCE.md b/docs/PROVENANCE.md index ca9f3a5..05830ce 100644 --- a/docs/PROVENANCE.md +++ b/docs/PROVENANCE.md @@ -71,3 +71,39 @@ of pieces above the board. They must not be described as byte-for-byte Mac parit Hardware feasibility, timing, physical palette appearance, API performance and disk layout are still to be demonstrated by the implementation. The arithmetic memory estimates and reference tests do not establish a working CoCo build. + +## CMOC example references consulted during implementation + +Pierre Sarrazin's local CardGame 0.1.15 `beep-demo.c` (public domain) was consulted +for `initSound`, `getTicksForFrequency` and `beep` usage. CoCoLetters 0.1.0 +`file.c`/`file.h` (Copyright 2026 Pierre Sarrazin, GPL-3.0-or-later) were consulted +for `decb_init`/`decb_registerDrive` initialization. The disk adapter follows +that initialization pattern, adds error handling, and uses the installed public +API contracts for writes, lengths and close/flush behavior. No standalone disk +driver, assembly sound routine or other game's rendering engine was copied. + +The existing DOS loader is Pierre Sarrazin's public-domain autostart.c 0.1.2, +retained from the official disk-project template with the launch command adapted. + +The audio correction also uses the documented bsound Player_disableSound API. +Only its standard mute helper is used; no Player IRQ or custom sound driver is +installed. The CardGame public-domain example implementation was consulted to +understand setup/teardown, without copying its assembly/register code. + +## November 11 font update + +The menu/HUD font is an unchanged subset of Pierre Sarrazin's public-domain +CardGame 0.1.15 font, also used by Color8. The original two font files, exact +SHA-256 values, source URL and public-domain notice are retained in +`third_party/cardgame-font/`. `src/platform/pierre_font.h` contains 26 letters, +ten digits and twelve punctuation glyphs. No drawing engine or assembly was +imported. Existing lowercase input maps to uppercase glyphs. The new C renderer +uses the original six visible columns/seven rows in each eight-pixel cell. + +Brian explicitly permitted inspecting the supplied Mac scoring source on +November 11. The read-only checkout at revision +`be8769a403e506edb930372f963a9c4c83a0881e` confirms the existing Modern and +Classic (40.2) formulas. `scoring_through_drop` in tests/rules_test.c adapts the +GPL-3.0-or-later setup in its tests/test-scoring.vala to exercise actual piece +drops, bottom-row detection and level changes in the CoCo rules engine. No Mac +application code was changed or bundled. diff --git a/docs/TESTING_128K.md b/docs/TESTING_128K.md new file mode 100644 index 0000000..d5d6561 --- /dev/null +++ b/docs/TESTING_128K.md @@ -0,0 +1,35 @@ +# Manual CoCo 3 / 128 KB check + +Use the official installed VCC Plus application. The MCP worker is fixed at +512 KB; its results below do not establish a 128 KB pass. + +1. Preserve your current setup and media. In a separate disposable test setup, + select CoCo 3, 128 KB, MC6809 and ordinary stock speed. Use RGB/NTSC initially. +2. Mount a **writable copy** of the pristine top-level `Quadrapassel.DSK` in drive + 0. Do not overwrite a disk containing your own programs or scores. Type `DOS`. +3. Confirm the title, menus and seven piece colors appear. Start a game; test + movement, rotation, soft/hard drop, Hold and pause/resume. Check that the board + frame and score/level/line labels remain visible while pieces move. +4. Change Sound and Custom Seed in Settings, use Back to save, and wait for the + save message to finish. Reboot the same writable disk and verify the settings. +5. Earn a positive score, end the game, enter initials and choose Save to Disk. + Reboot again and verify initials, score, category and Modern/Classic marker. +6. Repeat with sound on. The audio-routing correction should keep the title, + paused game and idle intervals quiet between event sounds. Check menu focus + moves promptly, tones are audible and + distinct, and ordinary actions are responsive. Try Difficult Pieces separately + and report any long stalls; its worst-case timing is not yet qualified. +7. On a separate read-only copy, try saving a setting. Expect an error and + continued play, without a claim that the setting was saved. +8. If available, check both physical joystick ports, neutral calibration, + one-button rotation/actions, and joystick-only menu/game use. Keyboard tests + are not joystick qualification. + +The fallback launch sequence is `PCLEAR1`, then `LOADM"QUAD.BIN"`, then `EXEC`. +Do not use PCLEAR0: official build-48 Disk BASIC rejected it with `?FC ERROR`. +The fallback was separately verified on the clean MC6809/512 KB build; actual +128 KB qualification remains pending. + +Please record the disk hash, machine/RAM/CPU, video standard, results and a +representative guest screenshot. The game targets 128 KB by address layout; a +manual pass is needed before claiming actual compatibility. diff --git a/docs/TITLE_AND_SCORING_UPDATE.md b/docs/TITLE_AND_SCORING_UPDATE.md new file mode 100644 index 0000000..54ce173 --- /dev/null +++ b/docs/TITLE_AND_SCORING_UPDATE.md @@ -0,0 +1,85 @@ +# Title, credits and scoring labels — November 11, 2026 + +## Changes + +The title's lower decorative blocks move up eight native pixels, leaving a blank +vertical gap before `(c) 2026 Brian Holman`. The credits entry is exactly +`Brian Holman - Mac & Coco`, rendered in the uppercase font. Pierre's unchanged +public-domain ampersand was added to the subset and pixel comparison fixture. +The redundant pixel wrapper was removed; fallback drawing calls standard hset +directly. No graphics mode or memory requirement changed. + +Settings now names **Scoring Rules** and displays **Modern** or **Classic (40.2)**. +The confirmation says the new rule starts next game and offers **Keep high +scores**, **Erase all high scores**, **Cancel**. Keep is the initial selection; +the explanation says erasing clears every difficulty. No personal scores were +reset or recalculated during this work. + +Brian supplied and authorized reading the Mac scoring source at +`/Users/bholman/Development/Personal/quadrapassel/`, revision +`be8769a403e506edb930372f963a9c4c83a0881e`. The existing CoCo arithmetic matches +src/game.vala, tests/test-scoring.vala and the settings schema in that checkout. +The Mac checkout remains unchanged. Scoring rules were not modified. + +| Rows cleared | Regular points × level | Modern bottom-row bonus × level | Classic (40.2) bottom-row bonus × level | +| --- | --- | --- | --- | +| 1 | 40 | 100 | 10000 | +| 2 | 100 | 200 | 10000 | +| 3 | 300 | 300 | 10000 | +| 4 | 1200 | 400 | 10000 | + +The bonus applies only when the cleared rows include the bottom row. Both modes +use the newly reached level when crossing ten total lines; Relaxed stays level 1. +A Modern single line above the bottom earns 40 at level 1, while a bottom-row +single earns 140. Classic's bottom-row single earns 10040. Existing records are +preserved even when switching rules and carry their saved M/C marker. + +## Verification + +- Official VCC Plus 3.6.0 (51), Release, project + `3D6A502C-E06D-46BC-9D19-191D741A16B9`, revision 2. +- Build `DFDE8C57-3165-44B5-9027-E8B2F16DDF28`, artifact + `BB277DE8-07A2-437B-9998-FFD1FB2C36C5`, zero diagnostics. +- QUAD.bin: 26,580 bytes, SHA-256 + `4fbd37aeec7f4edb39037a65f9573fc6b6886136ed87a6b3979e26e4c3020eed`. +- Clean Quadrapassel.DSK: 161,280 bytes, SHA-256 + `4ac171e87c51dfd99b302b9e035a91a59c030144e5ae0661a6d2dfc84ba3a63f`. + The local standard build matches those official artifact hashes. +- Link guard passes: code/constants end $7AF4; static data end $13DE; existing + $7B00/$1400 limits and 1,024-byte stack reserve retained. +- Host ASan/UBSan rules fixtures pass, including all 25 score cases through both + direct arithmetic and actual vertical-I drops adapted from the supplied Mac + test. Bottom-row detection, compaction and level transitions are exercised. +- Font pixel tests pass, now including the unchanged upstream ampersand. +- Official MC6809/512 KB run `0174149F-48E6-4EB6-8D96-BC1BF0BF4C87`: title gap, + credits, both scoring labels and Keep-default confirmation inspected. Choosing + Keep and saving settings worked. All owned runs are stopped. +- A standard-library mute call now follows analog input sampling too. Direct + title/gameplay idle and positive movement audio checks pass, but Brian's + normal-window buzzing has not been reproduced in this worker or confirmed + fixed. See AUDIO_VALIDATION.md for the reported restart/pause evidence. + +Guest framebuffer evidence: + +![Title spacing](screenshots/title-spacing-512k.png) +![Credits](screenshots/credits-mac-coco-512k.png) +![Classic setting](screenshots/scoring-classic-512k.png) +![Keep default](screenshots/scoring-keep-default-512k.png) + +## Preserved high scores and delivery + +The standard clean top-level disk contains no personal save files. An updated +standard-named private copy is at +`local-media-backups/2026-11-11-title-spacing-final/Quadrapassel.DSK`. Its source +was Brian's mounted font-update disk; the source and a before-update backup are +retained. Only QUAD.BIN and QPTEXT.DAT were replaced in the new copy. Both +QPSAVE files, WORDS.DAT and DOS track 34 were verified byte-identical, and the +source disk is unchanged. The private folder contains VERIFICATION.json. +Updated saved-disk SHA-256: +`2ca5f1f95896f660af998d2f913477205e23814b9fede7e7dbe2110e24143d88`. +No normal-session disk was replaced or remounted. + +Actual 128 KB, physical joystick and final-candidate physical-machine tests +remain pending. No new HD6309 qualification was performed. Base source remains +main at `8a4b44bc7358b1a999296d14d8c5272e57b65992` plus uncommitted work; no +commit or push was requested. diff --git a/docs/VCC_PLUS_WORKFLOW.md b/docs/VCC_PLUS_WORKFLOW.md index ec57338..c13d930 100644 --- a/docs/VCC_PLUS_WORKFLOW.md +++ b/docs/VCC_PLUS_WORKFLOW.md @@ -2,9 +2,10 @@ ## Required installed app -Use `/Applications/VCC Plus.app`, **version 3.5.5, build 48**. These values were -read from the installed app's `Info.plist` on November 10, 2026 after Brian -confirmed installation of official build 48. Verify again at implementation start. +Use `/Applications/VCC Plus.app`, **version 3.6.0, build 51**, explicitly approved by Brian +on November 11, 2026 for reconnection and isolated build/playtest. The installed +Info.plist was verified. Earlier build-48 evidence remains historical. +Verify again at implementation start. If the app differs, report it and wait for Brian to approve a different version. Do not downgrade, overwrite, or build a replacement app. @@ -139,3 +140,12 @@ For XRoar, give Brian a pristine DSK copy, exact machine/RAM/clock/ROM requireme loading steps, controls, expected results and an evidence checklist. Do not redistribute private ROMs. Separate user-confirmed CoCo 2 results from VCC Plus CoCo 3 compatibility runs. Keep screenshots limited to the guest display. + +## Numbered game delivery + +Brian's latest November 11 convention is `QUADPSLxx.DSK`, beginning with 01, +with empty high scores/default preferences for each new delivery. Keep the +official recipe and MCP artifact at its existing staging name, Quadrapassel.DSK. +Verify no QPSAVE data is present, copy to a new numbered filename without +overwriting, compare hashes, and record it in BUILDS.md. Old personal disks +remain untouched; automatic score migration is no longer part of delivery. diff --git a/docs/reference/cocoman-start-screen.md b/docs/reference/cocoman-start-screen.md new file mode 100644 index 0000000..889e98f --- /dev/null +++ b/docs/reference/cocoman-start-screen.md @@ -0,0 +1,13 @@ +# CoCoMan start-screen reference + +Brian explicitly authorized sharing this start-screen image with the Quadrapassel implementation chat on November 10, 2026. + +![CoCoMan start screen](cocoman-start-screen.png) + +Unchanged screenshot supplied from CoCoMan, originally named `convoy38-disk-title.png`. The image retains its visible Brian K. Holman credit. + +Use it as a visual reference for a polished CoCo title screen: strong title lettering, a composed illustration, a limited bright palette against black, and a clear keyboard/joystick start prompt. Quadrapassel should use its own game identity and falling-block imagery. + +This image-specific authorization does not expand access to CoCoMan source, documentation, other assets, chat history, or its MCP connection. It supplements the existing Quadrapassel title reference. + +SHA-256: `2e141915f02743a54db5b9bcdc93d36d74fe080fb7dfd4da945d290b6941cdfc` diff --git a/docs/reference/cocoman-start-screen.png b/docs/reference/cocoman-start-screen.png new file mode 100644 index 0000000..61d3cb7 Binary files /dev/null and b/docs/reference/cocoman-start-screen.png differ diff --git a/docs/screenshots/api-probe-mapped.png b/docs/screenshots/api-probe-mapped.png new file mode 100644 index 0000000..d2030d1 Binary files /dev/null and b/docs/screenshots/api-probe-mapped.png differ diff --git a/docs/screenshots/api-probe-results.png b/docs/screenshots/api-probe-results.png new file mode 100644 index 0000000..dfecca8 Binary files /dev/null and b/docs/screenshots/api-probe-results.png differ diff --git a/docs/screenshots/api-probe-standard.png b/docs/screenshots/api-probe-standard.png new file mode 100644 index 0000000..c2fe6bc Binary files /dev/null and b/docs/screenshots/api-probe-standard.png differ diff --git a/docs/screenshots/credits-mac-coco-512k.png b/docs/screenshots/credits-mac-coco-512k.png new file mode 100644 index 0000000..1cf7c73 Binary files /dev/null and b/docs/screenshots/credits-mac-coco-512k.png differ diff --git a/docs/screenshots/font-gameplay-512k.png b/docs/screenshots/font-gameplay-512k.png new file mode 100644 index 0000000..224702d Binary files /dev/null and b/docs/screenshots/font-gameplay-512k.png differ diff --git a/docs/screenshots/font-settings-512k.png b/docs/screenshots/font-settings-512k.png new file mode 100644 index 0000000..b33bf6b Binary files /dev/null and b/docs/screenshots/font-settings-512k.png differ diff --git a/docs/screenshots/font-title-512k.png b/docs/screenshots/font-title-512k.png new file mode 100644 index 0000000..b2baae6 Binary files /dev/null and b/docs/screenshots/font-title-512k.png differ diff --git a/docs/screenshots/gameplay-6309-framebuffer-512k.png b/docs/screenshots/gameplay-6309-framebuffer-512k.png new file mode 100644 index 0000000..27ad74c Binary files /dev/null and b/docs/screenshots/gameplay-6309-framebuffer-512k.png differ diff --git a/docs/screenshots/gameplay-clean-512k.png b/docs/screenshots/gameplay-clean-512k.png new file mode 100644 index 0000000..1a5b010 Binary files /dev/null and b/docs/screenshots/gameplay-clean-512k.png differ diff --git a/docs/screenshots/gameplay-framebuffer-512k.png b/docs/screenshots/gameplay-framebuffer-512k.png new file mode 100644 index 0000000..cfcb659 Binary files /dev/null and b/docs/screenshots/gameplay-framebuffer-512k.png differ diff --git a/docs/screenshots/high-score-reloaded-512k.png b/docs/screenshots/high-score-reloaded-512k.png new file mode 100644 index 0000000..43582da Binary files /dev/null and b/docs/screenshots/high-score-reloaded-512k.png differ diff --git a/docs/screenshots/high-score-saved-512k.png b/docs/screenshots/high-score-saved-512k.png new file mode 100644 index 0000000..43582da Binary files /dev/null and b/docs/screenshots/high-score-saved-512k.png differ diff --git a/docs/screenshots/scoring-classic-512k.png b/docs/screenshots/scoring-classic-512k.png new file mode 100644 index 0000000..6cd4274 Binary files /dev/null and b/docs/screenshots/scoring-classic-512k.png differ diff --git a/docs/screenshots/scoring-keep-default-512k.png b/docs/screenshots/scoring-keep-default-512k.png new file mode 100644 index 0000000..612cc92 Binary files /dev/null and b/docs/screenshots/scoring-keep-default-512k.png differ diff --git a/docs/screenshots/scoring-modern-512k.png b/docs/screenshots/scoring-modern-512k.png new file mode 100644 index 0000000..34c4f13 Binary files /dev/null and b/docs/screenshots/scoring-modern-512k.png differ diff --git a/docs/screenshots/settings-cached-framebuffer-512k.png b/docs/screenshots/settings-cached-framebuffer-512k.png new file mode 100644 index 0000000..4dc3422 Binary files /dev/null and b/docs/screenshots/settings-cached-framebuffer-512k.png differ diff --git a/docs/screenshots/title-clean-512k.png b/docs/screenshots/title-clean-512k.png new file mode 100644 index 0000000..4019625 Binary files /dev/null and b/docs/screenshots/title-clean-512k.png differ diff --git a/docs/screenshots/title-spacing-512k.png b/docs/screenshots/title-spacing-512k.png new file mode 100644 index 0000000..8272561 Binary files /dev/null and b/docs/screenshots/title-spacing-512k.png differ diff --git a/main.c b/main.c new file mode 100644 index 0000000..d00decb --- /dev/null +++ b/main.c @@ -0,0 +1,415 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#include +#include +#include +#include "rules.h" +#include "input.h" +#include "preferences.h" +#include "video.h" +#include "disk_store.h" + +#define KEY(name) isKeyPressed(KEY_PROBE_##name,KEY_BIT_##name) +enum { TITLE,PLAY,PAUSED,SETTINGS,CONTROLS,SCORES,CREDITS,NEW_CONFIRM,QUIT_CONFIRM,RULE_CHANGE,SEED_EDIT,INITIALS }; +static QGame game; +static QPreferences preferences; +static QInput input; +static Q8 scene=TITLE,selected,parent=TITLE,active,score_eligible=1,rule_pending; +static Q8 joystick_axes[4],joystick_buttons,dirty=1,draw_flags=3,soft_before; +static Q16 gravity_ms; +static Q8 ui_scene=255; +static Q16 clock_fraction; +static Q8 seed_digit,save_status,score_category,initial_guard=1,last_initial; +static char initials[3]={'A','A','A'}; +static QScore score_table[10]; +static const Q8 title_items[]={37,38,39,40,41,42}; +static const Q8 pause_items[]={43,44,45,38,46,42,47}; +static const Q8 setting_names[]={48,49,50,51,52,53,54,55,56,57,8,58,59,47}; + +static void enter(Q8 next) +{ + ui_scene=255;scene=next;selected=0;dirty=1;q_input_reset(&input); + gravity_ms=0;soft_before=0; + if(next==PLAY)draw_flags=3; + if(next==INITIALS){initial_guard=1;last_initial=0;} +} + +static void tone(Q8 event) +{ + /* Half the desired Hz compensates this API for stock CoCo 3 fast mode. */ + static const Q16 half_frequencies[7]={210,440,120,330,440,550,90}; + static const Q8 durations[7]={5,5,5,6,8,10,12}; + if(preferences.sound){ + /* JOYSTK and audio share the mux: select DAC only for this effect. */ + initSound(); + beep(durations[event],getTicksForFrequency(half_frequencies[event]),event?20:7); + Player_disableSound(); + } +} + +static void new_game(void) +{ + QOptions options=preferences.game; + if(!preferences.custom_seed)options.seed=((Q32)getTimer()<<16)|((Q32)getTimer()+1); + q_start(&game,&options);active=1;score_eligible=1;enter(PLAY); +} + +typedef struct { Q8 probe,bit;Q16 action; } KeyBinding; +#define BIND(name,action) {KEY_PROBE_##name,KEY_BIT_##name,action} +static const KeyBinding keys[]={ + BIND(LEFT,Q_LEFT),BIND(RIGHT,Q_RIGHT),BIND(UP,Q_UP),BIND(DOWN,Q_DOWN), + BIND(ENTER,Q_CONFIRM),BIND(BREAK,Q_BACK), + BIND(A,Q_LEFT),BIND(D,Q_RIGHT),BIND(W,Q_UP),BIND(S,Q_DOWN), + BIND(Q,Q_CCW),BIND(E,Q_CW),BIND(SPACE,Q_CONFIRM),BIND(H,Q_HOLD),BIND(P,Q_PAUSE) +}; +static Q16 keyboard(void) +{ + Q16 held=0,action;Q8 i,count=scene==INITIALS?6:sizeof(keys)/sizeof(keys[0]); + for(i=0;i":" ");video_text(4,row,name); +} + +static Q8 save_changes(signed char category,const QScore *scores,Q8 reset_all) +{ + video_text(1,23,"SAVING TO DISK... "); + save_status=q_store_save(&preferences,category,scores,reset_all); + return save_status; +} + +static void show_store_status(void) +{ + if(save_status==Q_STORE_RECOVERED)video_text(1,23,"RECOVERED PREVIOUS SAVE"); + else if(save_status==Q_STORE_CORRUPT)video_text(1,23,"BAD SAVE DATA - CHECK DISK"); + else if(save_status)video_text(1,23,"DISK ERROR - CHANGES NOT SAVED"); +} + +static void game_over(void) +{ + video_game(&game,preferences.shadow,draw_flags|2); + score_category=q_score_category(game.options.difficulty,game.options.difficult); + save_status=q_store_scores(score_category,score_table); + if(score_eligible&&game.score&&(save_status||game.score>score_table[9].score)){ + initials[0]=initials[1]=initials[2]='A';enter(INITIALS); + }else enter(PAUSED); +} + +static void settings_picture(void) +{ + Q8 i,row; + video_text(2,0,ui_label(38));video_text(1,1,ui_label(60)); + video_text(1,2,ui_label(61)); + for(i=0;i<14;++i){ + row=i+4;menu_line(row,i,ui_label(setting_names[i])); + if(i==0){if(preferences.game.difficulty<0)video_text(26,row,ui_label(62));else video_number(27,row,preferences.game.difficulty);} + if(i==1)video_text(18,row,preferences.game.scoring?ui_label(63):ui_label(64)); + if(i==2)video_text(24,row,preferences.style==0?ui_label(65):preferences.style==1?ui_label(64):ui_label(66)); + if(i==3)video_text(27,row,preferences.grid?ui_label(67):ui_label(68)); + if(i==4)video_text(27,row,preferences.shadow?ui_label(67):ui_label(68)); + if(i==5)video_text(27,row,preferences.sound?ui_label(67):ui_label(68)); + if(i==6)video_text(27,row,preferences.clockwise?ui_label(69):ui_label(70)); + if(i==7)video_text(27,row,preferences.game.difficult?ui_label(67):ui_label(68)); + if(i==8)video_text(27,row,preferences.custom_seed?ui_label(67):ui_label(68)); + if(i==10)video_text(24,row,preferences.port==0?ui_label(71):preferences.port==1?ui_label(72):ui_label(68)); + if(i==12)video_number(27,row,preferences.hz); + } + video_text(1,20,ui_label(73)); + video_text(1,22,ui_label(74)); +} + +static const Q8 captions[][4]={ + {0,5,20,1}, + {0,6,22,2}, + {2,1,20,3}, + {4,1,1,4}, + {4,1,3,5}, + {4,1,5,6}, + {4,1,7,7}, + {4,1,10,8}, + {4,1,12,9}, + {4,1,14,10}, + {4,1,16,11}, + {4,1,18,12}, + {4,1,19,13}, + {4,1,20,14}, + {6,1,1,15}, + {6,1,3,16}, + {6,1,5,17}, + {6,1,6,18}, + {6,1,7,19}, + {6,1,9,20}, + {6,1,11,21}, + {6,1,12,22}, + {6,1,14,23}, + {6,1,16,24}, + {9,1,2,25}, + {9,1,5,26}, + {9,1,7,94}, + {10,1,2,27}, + {10,1,14,28}, + {10,1,16,29}, + {5,1,0,30}, + {5,1,4,31}, + {5,1,18,32}, + {5,1,20,33}, + {11,2,1,34}, + {11,1,19,35}, + {11,1,21,36}, +}; + +static void fixed_captions(void) +{ + Q8 i;for(i=0;i>((7-i)*4))&15);ch[0]="0123456789ABCDEF"[n];ch[1]=0;video_text(7+i*2,8,ch);} + video_text(7+seed_digit*2,10,ui_label(86)); + }else if(scene==SCORES){ + if(score_category<2)video_text(1,2,ui_label(87));else {video_text(1,2,ui_label(48));video_number(12,2,score_category/2-1);} + video_text(17,2,(score_category&1)?ui_label(88):ui_label(89)); + for(i=0;i<10;++i){ + video_number(1,6+i,i+1); + if(score_table[i].score){ + char name[4];name[0]=score_table[i].initials[0];name[1]=score_table[i].initials[1];name[2]=score_table[i].initials[2];name[3]=0; + video_text(6,6+i,name);video_number(11,6+i,score_table[i].score); + video_text(25,6+i,score_table[i].rule==Q_CLASSIC?ui_label(90):ui_label(91)); + } + } + menu_line(22,0,ui_label(47)); + }else if(scene==INITIALS){ + video_number(2,3,game.score); + for(i=0;i<3;++i){ + menu_line(7+i*2,i,ui_label(92));video_number(12,7+i*2,i+1); + ch[0]=initials[i];ch[1]=0;video_text(20,7+i*2,ch); + } + menu_line(14,3,ui_label(93));menu_line(16,4,ui_label(82)); + } + show_store_status(); + +} + +static Q8 item_count(void) +{ + if(scene==TITLE)return 6;if(scene==PAUSED)return 7;if(scene==SETTINGS)return 14; + if(scene==INITIALS)return 5; + if(scene==NEW_CONFIRM||scene==QUIT_CONFIRM)return 2;if(scene==RULE_CHANGE)return 3;return 1; +} + +/* Focus-only movement keeps menus responsive without clearing or reloading text. */ +static void select_item(signed char delta) +{ + static const Q8 starts[12]={12,0,4,4,23,22,22,10,10,9,0,7}; + static const Q8 spacing[12]={1,0,2,1,0,0,0,2,2,2,0,2}; + Q8 count=item_count(),old=selected,row; + selected=(selected+count+delta)%count; + row=starts[scene]+old*spacing[scene];if(scene==INITIALS&&old>=3)++row; + video_text(2,row," "); + row=starts[scene]+selected*spacing[scene];if(scene==INITIALS&&selected>=3)++row; + video_text(2,row,">"); +} + +static void change_setting(signed char delta) +{ + int n; + switch(selected){ + case 0:n=preferences.game.difficulty+delta;if(n<-1)n=15;if(n>15)n=-1;preferences.game.difficulty=(signed char)n;break; + case 1:rule_pending=!preferences.game.scoring;enter(RULE_CHANGE);return; + case 2:preferences.style=(preferences.style+(delta>0?1:2))%3;break; + case 3:preferences.grid=!preferences.grid;break; + case 4:preferences.shadow=!preferences.shadow;break; + case 5:preferences.sound=!preferences.sound;break; + case 6:preferences.clockwise=!preferences.clockwise;break; + case 7:preferences.game.difficult=!preferences.game.difficult;break; + case 8:preferences.custom_seed=!preferences.custom_seed;break; + case 9:seed_digit=0;enter(SEED_EDIT);return; + case 10:preferences.port=(preferences.port+(delta>0?1:2))%3;break; + case 11:preferences.centers[0]=joystick_axes[0];preferences.centers[1]=joystick_axes[1]; + preferences.centers[2]=joystick_axes[2];preferences.centers[3]=joystick_axes[3];break; + case 12:preferences.hz=preferences.hz==60?50:60;clock_fraction=0;break; + default:save_changes(-1,0,0);enter(parent);return; + } + video_style(preferences.style,preferences.grid);dirty=1; +} + +static Q8 choose(void) +{ + if(scene==TITLE){ + if(selected==0)new_game();else if(selected==1){parent=TITLE;enter(SETTINGS);} + else if(selected==2)enter(CONTROLS);else if(selected==3){ + parent=TITLE;score_category=q_score_category(preferences.game.difficulty,preferences.game.difficult); + save_status=q_store_scores(score_category,score_table);enter(SCORES); + } + else if(selected==4)enter(CREDITS);else return 0; + }else if(scene==PAUSED){ + if(selected==0||selected==6)enter(game.over?TITLE:PLAY); + else if(selected==1){if(!game.over&&q_hold(&game)){tone(1);enter(PLAY);}else dirty=1;} + else if(selected==2){if(!game.over){if(q_rotate(&game,!preferences.clockwise))tone(1);enter(PLAY);}else dirty=1;} + else if(selected==3){parent=PAUSED;enter(SETTINGS);} + else if(selected==4)enter(NEW_CONFIRM);else enter(QUIT_CONFIRM); + }else if(scene==SETTINGS)change_setting(1); + else if(scene==NEW_CONFIRM){if(selected)new_game();else enter(PAUSED);} + else if(scene==QUIT_CONFIRM){if(selected){active=0;enter(TITLE);}else enter(PAUSED);} + else if(scene==RULE_CHANGE){ + if(selected<2){ + Q8 old_rule=preferences.game.scoring;preferences.game.scoring=rule_pending; + if(selected==1){ + if(!save_changes(-1,0,1)){if(active)score_eligible=0;} + else preferences.game.scoring=old_rule; + }else save_changes(-1,0,0); + } + enter(SETTINGS); + }else if(scene==SEED_EDIT)enter(SETTINGS); + else if(scene==INITIALS){ + if(selected<3){initials[selected]=initials[selected]=='Z'?'A':initials[selected]+1;dirty=1;} + else if(selected==3){ + save_status=q_store_scores(score_category,score_table); + if(!save_status){ + q_score_insert(score_table,game.score,initials,game.options.scoring); + save_changes((signed char)score_category,score_table,0); + } + if(!save_status){score_eligible=0;parent=PAUSED;enter(SCORES);}else dirty=1; + }else {score_eligible=0;enter(PAUSED);} + }else if(scene==SCORES)enter(parent); + else enter(TITLE); + return 1; +} + +int main(void) +{ + Q16 now,last,ms,scaled,ticks;QActions action;Q8 i,changed,info,old_over,full_scene; + initCoCoSupport();setHighSpeed(FALSE); + if(!isCoCo3){putstr("COCO 3 VERSION - 128 KB MINIMUM\n",sizeof("COCO 3 VERSION - 128 KB MINIMUM\n")-1);return 1;} + if(!video_open(1))return 2; + q_preferences_default(&preferences); + setHighSpeed(TRUE);Player_disableSound();video_text(4,12,"READING SAVED SCORES"); + save_status=disk_store_open(&preferences); + video_style(preferences.style,preferences.grid);q_input_reset(&input);last=getTimer(); + for(;;){ + now=getTimer();ticks=(Q16)(now-last);last=now; + if(ticks>preferences.hz)ticks=preferences.hz; + scaled=ticks*1000+clock_fraction;ms=scaled/preferences.hz;clock_fraction=scaled%preferences.hz; + if(ms>1000)ms=1000; + action=sample(ms); + if(scene==PLAY){ + if(action.pressed&(Q_PAUSE|Q_BACK)){enter(PAUSED);continue;} + changed=info=0;old_over=game.over; + for(i=0;i=3?5:game.last_clear?2+game.last_clear:2);}} + else { + if((action.held&Q_DOWN)&&!soft_before){changed|=q_move(&game,0,1);gravity_ms=0;} + soft_before=(action.held&Q_DOWN)!=0; + gravity_ms+=ms; + while(gravity_ms>=(soft_before?(Q16)80:q_gravity_ms(game.level))&&!game.over){ + gravity_ms-=soft_before?(Q16)80:q_gravity_ms(game.level); + if(!q_move(&game,0,1)){q_lock(&game);info=1;tone(game.last_clear>=3?5:game.last_clear?2+game.last_clear:2);}changed=1; + } + } + if(game.over&&!old_over){tone(6);changed=1;} + if(changed){draw_flags|=info?2:0;dirty=1;} + if(game.over)game_over(); + }else{ + if(scene==INITIALS){ + Q8 c=inkey(); + if(!c){initial_guard=0;last_initial=0;} + else if(!initial_guard&&c!=last_initial&&c>='A'&&c<='Z'&&selected<3){ + initials[selected]=c;selected=(selected+1)%3;last_initial=c;dirty=1; + } + if(selected<3&&(action.pressed&(Q_LEFT|Q_RIGHT))){ + initials[selected]=(char)('A'+(initials[selected]-'A'+((action.pressed&Q_LEFT)?25:1))%26);dirty=1; + } + } + if(scene==SEED_EDIT){ + Q8 shift=(7-seed_digit)*4;Q32 mask=(Q32)15<>shift)&15; + if(action.pressed&Q_LEFT){seed_digit=(seed_digit+7)&7;dirty=1;} + if(action.pressed&Q_RIGHT){seed_digit=(seed_digit+1)&7;dirty=1;} + if(action.pressed&(Q_UP|Q_DOWN)){n=(n+((action.pressed&Q_UP)?1:15))&15;preferences.game.seed=(preferences.game.seed&~mask)|(n<' '// This file is in the public domain.' '//' '// Reference: Roger Schrag, "A Special Use For The DOS Command",' '// The Rainbow, November 1984, p.140.' '//' '// To compile: cmoc --dos autostart.c' '// To install on CoCo disk image: install-coco-boot-loader some-image.dsk autostart.bin' '// To run on CoCo: type DOS and to automatically run *.BAS.' '//' '// Version history:' '// 0.1.0 2016-01-16 Use of legacy.h discontinued.' '// 0.1.1 2018-04-03 Adapted to CMOC 0.1.51 (const).' '// 0.1.2 2018-08-04 Basic line now forced to be uppercase.' '' '#include ' '' '#define ENDFLG 0x00 // STOP/END FLAG: POSITIVE=STOP, NEG=END' '#define CINBFL 0x70 // CONSOLE IN BUFFER FLAG: 00=NOT EMPTY, $$FF=EMPTY' '#define RVEC4 0x016a // RAM hook: CONSOLE IN' '' '' 'byte oldHookInstr;' 'word oldHookAddr;' 'const char *basicLineReader;' '' '' 'void feedKeyboard()' '{' ' word preservedX;' ' asm("stx", preservedX);' '' ' * (byte *) CINBFL = 0; // console in buffer now not empty' '' ' char nextBasicByte = (char) toupper(*basicLineReader);' ' ++basicLineReader;' ' if (nextBasicByte == 0) // if finished returning Basic line' ' {' ' * (byte *) RVEC4 = oldHookInstr;' ' * (word *) (RVEC4 + 1) = oldHookAddr;' ' nextBasicByte = '"'"'\r'"'"'; // return "Enter" to cause execution of Basic line' ' }' '' ' asm {' ' lda nextBasicByte' ' ldx preservedX' ' tfr u,s // discard stack frame' ' leas 4,s // discard previous stack frame ptr and return addr' ' rts // return to caller of CONSOLE IN' ' }' '}' '' '' 'int main()' '{' ' * (byte *) ENDFLG = - * (byte *) ENDFLG; // why?' '' ' basicLineReader =' ' #ifndef COMMAND' ' "RUN\"*.BAS\""' ' #else' ' COMMAND' ' #endif' ' ;' '' ' // Install function feedKeyboard() as CONSOLE IN routine.' ' //' ' oldHookInstr = * (byte *) RVEC4;' ' oldHookAddr = * (word *) (RVEC4 + 1);' '' ' * (byte *) RVEC4 = 0x7e; // JMP instruction' ' * (void **) (RVEC4 + 1) = (void *) feedKeyboard;' '' ' * (word *) 0x2600 = 0; // overwrite "OS" marker with two null bytes' '' ' asm("jmp", "$$ac7c"); // go interpret a Basic line (which is read from console)' '' ' return 0; // avoids compiler error' '}' > obj/vcc-dos-boot/loader.c + "$(CMOC)" --dos -O0 --limit=2800 -o $@ '-DCOMMAND="LOADM\"HELLO.BIN\":EXEC"' obj/vcc-dos-boot/loader.c + +disk: HELLO.dsk +HELLO.dsk: HELLO.bin generated/WORDS.DAT obj/vcc-dos-boot/loader.bin Makefile + @mkdir -p $(dir $@) + $(PERL) -e 'print chr(255) x (35*18*256)' > $@ + $(INSTALL_LOADER) $@ obj/vcc-dos-boot/loader.bin + $(WRITECOCOFILE) $@ HELLO.bin + $(WRITECOCOFILE) $@ generated/WORDS.DAT + +clean: + rm -rf obj + rm -f HELLO.bin HELLO.map HELLO.link HELLO.dsk generated/word-count.c generated/WORDS.DAT + +-include $(OBJECTS:.o=.d) diff --git a/src/APIProbe/README.md b/src/APIProbe/README.md new file mode 100644 index 0000000..fd36585 --- /dev/null +++ b/src/APIProbe/README.md @@ -0,0 +1,34 @@ +# Quadrapassel CMOC API probes + +These diagnostic sources retain the official VCC Plus Hello Disk template's +GPL-3.0-or-later example and public-domain ROM-backed decbfile/DOS-loader notices. +No ROMs, standalone disk driver, personal save files or generated disks are +included here. Original template resources are in assets/, include/, src/ and +tools/. The diagnostic screens are authored for this game project. + +- main.c measures standard CMOC hset drawing, keyboard/joystick sampling, + bounded tones and standard disk reading. +- mapped.c adds a drawing comparison through the Brian-approved C renderer in + ../platform/coco3_video.c; see ../../docs/DECISIONS.md for the exception scope. +- The local Makefile/project settings build the original standalone probe at + the template's layout; the root project's Probe configuration selects + mapped.c and the split-layout renderer. Neither path is the delivered game. + +Historical measurements and selected guest screenshots are retained in the +project's decisions/status documents and docs/screenshots/. A historical probe +measurement is not a final-game timing, audio or 128 KB qualification. The +current final split-layout Probe configuration is not qualified; use Release +for the delivered game. + +For the standalone probe, use the installed official VCC Plus C Development +Open workflow on this directory, review its Make recipe, and build Release. +The command-line complement uses the installed bundled tools on PATH and +`make VCC_CONFIGURATION=Release disk`. It creates HELLO.bin/HELLO.dsk in this +folder; native app builds use an isolated workspace. Normal disk replacement +safeguards still apply; retain user media before an explicit launch. The +probe requires CoCo 3 and functioning Disk BASIC ROM services. + +The DOS launcher retained in the recipe is Pierre Sarrazin's public-domain +autostart.c 0.1.2. Its original source notice is preserved in the generated +loader. These examples call documented CMOC APIs; the mapped variant's only +additional low-level component is the separately approved C renderer. diff --git a/src/APIProbe/assets/words.txt b/src/APIProbe/assets/words.txt new file mode 100644 index 0000000..b88f98d --- /dev/null +++ b/src/APIProbe/assets/words.txt @@ -0,0 +1,5 @@ +HELLO +WORLD +CMOC +VCC +PLUS diff --git a/src/APIProbe/include/hello.h b/src/APIProbe/include/hello.h new file mode 100644 index 0000000..2ba7d41 --- /dev/null +++ b/src/APIProbe/include/hello.h @@ -0,0 +1,8 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#ifndef HELLO_DISK_H +#define HELLO_DISK_H +#include +extern const unsigned char generatedWordCount; +void showHeading(void); +unsigned char showDiskWords(void); +#endif diff --git a/src/APIProbe/main.c b/src/APIProbe/main.c new file mode 100644 index 0000000..6cd4ecd --- /dev/null +++ b/src/APIProbe/main.c @@ -0,0 +1,214 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Quadrapassel standard-CMOC API experiment; no game rules here. */ +#include +#include "hello.h" + +/* All drawing is composed from coco.h hset(), including this original font. */ +static const word letters[26] = { + 0x2BED,0x6BAE,0x3923,0x6B6E,0x79A7,0x79A4,0x396B,0x5BED,0x7497,0x126A,0x5BAD,0x4927,0x5FED,0x5FFD,0x2B6A,0x6BA4,0x2B7B,0x6BAD,0x388E,0x7492,0x5B6F,0x5B6A,0x5BFD,0x5AAD,0x5A92,0x72A7 +}; +static const word digits[10] = { + 0x7B6F,0x2492,0x73E7,0x73CF,0x5BC9,0x79CF,0x79EF,0x7249,0x7BEF,0x7BCF +}; +/* Public globals for artifact-bound guest debugger inspection. */ +word draw_histogram[64]; +word sample_histogram[64]; +word draw_count, draw_worst, sample_worst; +byte fast_mode; +word tone_at; +byte tone_pending; +byte sampled_axes[4], sampled_buttons; +word block_x = 152, block_y = 88; +byte disk_before, disk_after; + +#define KEY(name) isKeyPressed(KEY_PROBE_##name, KEY_BIT_##name) + +static void rectangle(word x, word y, byte w, byte h, byte color) +{ + byte dx, dy; + for (dy = 0; dy < h; ++dy) + for (dx = 0; dx < w; ++dx) + hset(x + dx, y + dy, color); +} + +static word glyph(byte c) +{ + if (c >= 'A' && c <= 'Z') return letters[c - 'A']; + if (c >= '0' && c <= '9') return digits[c - '0']; + return 0; +} + +static void label(word x, word y, const char *s) +{ + word bits; + byte row, col; + while (*s) + { + bits = glyph(*s++); + for (row = 0; row < 5; ++row) + for (col = 0; col < 3; ++col) + if (bits & ((word)0x4000 >> (row * 3 + col))) + rectangle(x + 2 * col, y + row, 2, 1, 8); + x += 8; + } +} + +static void number(word x, word y, word value) +{ + char text[6]; + sprintf(text, "%u", value); + rectangle(x, y, 40, 5, 0); + label(x, y, text); +} + +static void record(word elapsed, word *histogram, word *worst) +{ + if (elapsed > *worst) *worst = elapsed; + ++histogram[elapsed < 63 ? elapsed : (word)63]; +} + +static void setup_picture(void) +{ + byte i; + rgb(); + paletteRGB(0,0,0,0); + paletteRGB(1,3,0,0); /* L red */ + paletteRGB(2,0,3,0); /* J green */ + paletteRGB(3,0,1,3); /* T blue */ + paletteRGB(4,2,2,2); /* S gray */ + paletteRGB(5,3,3,0); /* Z yellow */ + paletteRGB(6,2,0,3); /* I purple */ + paletteRGB(7,3,1,0); /* O orange */ + paletteRGB(8,3,3,3); + label(32,8,"QUADRAPASSEL FOR COCO"); + label(32,20,"STANDARD CMOC API PROBE"); + for (i = 0; i < 7; ++i) + rectangle(32 + 36 * i, 34, 24, 12, i + 1); + label(16,58,"ARROWS MOVE T TONE J AXES"); + label(16,68,"B BLOCK N PIECE F SPEED Q EXIT"); + label(16,140,"DRAW WORST TICKS"); + label(16,152,"SAMPLE WORST TICKS"); + label(16,164,"RIGHT XY LEFT XY BUTTONS"); + rectangle(block_x,block_y,8,8,3); +} + +/* A one-cell T shift: four changed cells, not a full-piece redraw. */ +static void move_t(byte right) +{ + word start = getTimer(); + rectangle(136 + (right ? 8 : 16),88,8,8,0); + rectangle(136 + (right ? 16 : 8),88,8,8,3); + rectangle(136 + (right ? 0 : 24),96,8,8,0); + rectangle(136 + (right ? 24 : 0),96,8,8,3); + record((word)(getTimer() - start),draw_histogram,&draw_worst); + ++draw_count; +} + +static word percentile(void) +{ + word n = 0, target = (draw_count * 95 + 99) / 100; + byte i; + for (i = 0; i < 64; ++i) + { + n += draw_histogram[i]; + if (n >= target) return i; + } + return 63; +} + +static void sample(void) +{ + const byte *axes; + word start = getTimer(); + byte i; + axes = readJoystickPositions(); + for (i = 0; i < 4; ++i) sampled_axes[i] = axes[i]; + sampled_buttons = readJoystickButtons(); + record((word)(getTimer() - start),sample_histogram,&sample_worst); +} + +static void move_block(word x, word y) +{ + word start = getTimer(); + rectangle(block_x,block_y,8,8,0); + rectangle(x,y,8,8,3); + block_x = x; + block_y = y; + record((word)(getTimer() - start),draw_histogram,&draw_worst); + ++draw_count; +} + +int main(void) +{ + word x, y; + byte i, key, prior = 0; + initCoCoSupport(); /* Documented standard detection; no raw machine probe. */ + setHighSpeed(FALSE); /* Stock 0.895 MHz baseline; no speed boost. */ + if (!isCoCo3) + { + printf("THIS PROBE NEEDS A COCO 3\n"); + return 1; + } + disk_before = showDiskWords(); + if (!hscreen(2)) return 2; + setup_picture(); + for (;;) + { + sample(); + if (tone_pending && (word)(getTimer() - tone_at) < 32768) + { + tone_pending = 0; + sound(180,1); + } + key = inkey(); + if (key == 'Q' || key == 'q' || KEY(BREAK)) break; + x = block_x; y = block_y; + if (KEY(LEFT) && x > 16) --x; + if (KEY(RIGHT) && x < 296) ++x; + if (KEY(UP) && y > 82) --y; + if (KEY(DOWN) && y < 126) ++y; + if (x != block_x || y != block_y) move_block(x,y); + if ((key == 'T' || key == 't') && !prior) + { + tone_at = getTimer() + 30; + tone_pending = 1; + } + if (key == 'F' || key == 'f') + { + fast_mode = !fast_mode; + setHighSpeed(fast_mode); + } + if (key == 'B' || key == 'b' || key == 'N' || key == 'n') + { + draw_count = draw_worst = 0; + memset(draw_histogram,0,sizeof(draw_histogram)); + if (key == 'N' || key == 'n') + { + rectangle(144,88,8,8,3); + rectangle(136,96,24,8,3); + for (i = 0; i < 60; ++i) move_t(!(i & 1)); + } + else for (i = 0; i < 60; ++i) + move_block(block_x == 152 ? 164 : 152,88); + number(208,140,draw_worst); + number(208,152,sample_worst); + } + if (key == 'J' || key == 'j') + { + for (i = 0; i < 4; ++i) number(16 + i * 56,176,sampled_axes[i]); + number(248,176,sampled_buttons); + } + prior = key; + } + hscreen(0); + resetPalette(TRUE); + width(32); + setHighSpeed(FALSE); + cls(1); + disk_after = showDiskWords(); + printf("DISK BEFORE %u AFTER %u\n",disk_before,disk_after); + printf("FAST %u DRAW %u P95 %u MAX %u\n",fast_mode,draw_count,percentile(),draw_worst); + printf("SAMPLE WORST %u TICKS\n",sample_worst); + printf("RIGHT %u %u LEFT %u %u BTN %u\n",sampled_axes[0],sampled_axes[1],sampled_axes[2],sampled_axes[3],sampled_buttons); + return 0; +} diff --git a/src/APIProbe/mapped.c b/src/APIProbe/mapped.c new file mode 100644 index 0000000..2ff5263 --- /dev/null +++ b/src/APIProbe/mapped.c @@ -0,0 +1,218 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Quadrapassel standard-CMOC API experiment; no game rules here. */ +#include +#include "hello.h" +#include "coco3_video.h" + +/* All drawing is composed from coco.h hset(), including this original font. */ +static const word letters[26] = { + 0x2BED,0x6BAE,0x3923,0x6B6E,0x79A7,0x79A4,0x396B,0x5BED,0x7497,0x126A,0x5BAD,0x4927,0x5FED,0x5FFD,0x2B6A,0x6BA4,0x2B7B,0x6BAD,0x388E,0x7492,0x5B6F,0x5B6A,0x5BFD,0x5AAD,0x5A92,0x72A7 +}; +static const word digits[10] = { + 0x7B6F,0x2492,0x73E7,0x73CF,0x5BC9,0x79CF,0x79EF,0x7249,0x7BEF,0x7BCF +}; +/* Public globals for artifact-bound guest debugger inspection. */ +word draw_histogram[64]; +word sample_histogram[64]; +word draw_count, draw_worst, sample_worst; +byte fast_mode, mapped_mode; +word tone_at; +byte tone_pending; +byte sampled_axes[4], sampled_buttons; +word block_x = 152, block_y = 88; +byte disk_before, disk_after; + +#define KEY(name) isKeyPressed(KEY_PROBE_##name, KEY_BIT_##name) + +static void rectangle(word x, word y, byte w, byte h, byte color) +{ + byte dx, dy; + if (mapped_mode && c3_fill(x,(byte)y,w,h,color)) return; + for (dy = 0; dy < h; ++dy) + for (dx = 0; dx < w; ++dx) + hset(x + dx, y + dy, color); +} + +static word glyph(byte c) +{ + if (c >= 'A' && c <= 'Z') return letters[c - 'A']; + if (c >= '0' && c <= '9') return digits[c - '0']; + return 0; +} + +static void label(word x, word y, const char *s) +{ + word bits; + byte row, col; + while (*s) + { + bits = glyph(*s++); + for (row = 0; row < 5; ++row) + for (col = 0; col < 3; ++col) + if (bits & ((word)0x4000 >> (row * 3 + col))) + rectangle(x + 2 * col, y + row, 2, 1, 8); + x += 8; + } +} + +static void number(word x, word y, word value) +{ + char text[6]; + sprintf(text, "%u", value); + rectangle(x, y, 40, 5, 0); + label(x, y, text); +} + +static void record(word elapsed, word *histogram, word *worst) +{ + if (elapsed > *worst) *worst = elapsed; + ++histogram[elapsed < 63 ? elapsed : (word)63]; +} + +static void setup_picture(void) +{ + byte i; + rgb(); + paletteRGB(0,0,0,0); + paletteRGB(1,3,0,0); /* L red */ + paletteRGB(2,0,3,0); /* J green */ + paletteRGB(3,0,1,3); /* T blue */ + paletteRGB(4,2,2,2); /* S gray */ + paletteRGB(5,3,3,0); /* Z yellow */ + paletteRGB(6,2,0,3); /* I purple */ + paletteRGB(7,3,1,0); /* O orange */ + paletteRGB(8,3,3,3); + label(32,8,"QUADRAPASSEL FOR COCO"); + label(32,20,"STANDARD CMOC API PROBE"); + for (i = 0; i < 7; ++i) + rectangle(32 + 36 * i, 34, 24, 12, i + 1); + label(16,58,"ARROWS MOVE T TONE J AXES"); + label(16,68,"B BLOCK N PIECE F SPEED V DRAW Q"); + label(16,140,"DRAW WORST TICKS"); + label(16,152,"SAMPLE WORST TICKS"); + label(16,164,"RIGHT XY LEFT XY BUTTONS"); + rectangle(block_x,block_y,8,8,3); +} + +/* A one-cell T shift: four changed cells, not a full-piece redraw. */ +static void move_t(byte right) +{ + word start = getTimer(); + rectangle(136 + (right ? 8 : 16),88,8,8,0); + rectangle(136 + (right ? 16 : 8),88,8,8,3); + rectangle(136 + (right ? 0 : 24),96,8,8,0); + rectangle(136 + (right ? 24 : 0),96,8,8,3); + record((word)(getTimer() - start),draw_histogram,&draw_worst); + ++draw_count; +} + +static word percentile(void) +{ + word n = 0, target = (draw_count * 95 + 99) / 100; + byte i; + for (i = 0; i < 64; ++i) + { + n += draw_histogram[i]; + if (n >= target) return i; + } + return 63; +} + +static void sample(void) +{ + const byte *axes; + word start = getTimer(); + byte i; + axes = readJoystickPositions(); + for (i = 0; i < 4; ++i) sampled_axes[i] = axes[i]; + sampled_buttons = readJoystickButtons(); + record((word)(getTimer() - start),sample_histogram,&sample_worst); +} + +static void move_block(word x, word y) +{ + word start = getTimer(); + rectangle(block_x,block_y,8,8,0); + rectangle(x,y,8,8,3); + block_x = x; + block_y = y; + record((word)(getTimer() - start),draw_histogram,&draw_worst); + ++draw_count; +} + +int main(void) +{ + word x, y; + byte i, key, prior = 0; + initCoCoSupport(); /* Documented standard detection; no raw machine probe. */ + setHighSpeed(FALSE); /* Stock 0.895 MHz baseline; no speed boost. */ + if (!isCoCo3) + { + printf("THIS PROBE NEEDS A COCO 3\n"); + return 1; + } + disk_before = showDiskWords(); + if (!hscreen(2)) return 2; + enableInterrupts(); /* Explicit standard CMOC foreground interrupt policy. */ + setup_picture(); + for (;;) + { + sample(); + if (tone_pending && (word)(getTimer() - tone_at) < 32768) + { + tone_pending = 0; + sound(180,1); + } + key = inkey(); + if (key == 'Q' || key == 'q' || KEY(BREAK)) break; + x = block_x; y = block_y; + if (KEY(LEFT) && x > 16) --x; + if (KEY(RIGHT) && x < 296) ++x; + if (KEY(UP) && y > 82) --y; + if (KEY(DOWN) && y < 126) ++y; + if (x != block_x || y != block_y) move_block(x,y); + if ((key == 'T' || key == 't') && !prior) + { + tone_at = getTimer() + 30; + tone_pending = 1; + } + if (key == 'V' || key == 'v') mapped_mode = !mapped_mode && c3_video_ready(); + if (key == 'F' || key == 'f') + { + fast_mode = !fast_mode; + setHighSpeed(fast_mode); + } + if (key == 'B' || key == 'b' || key == 'N' || key == 'n') + { + draw_count = draw_worst = 0; + memset(draw_histogram,0,sizeof(draw_histogram)); + if (key == 'N' || key == 'n') + { + rectangle(144,88,8,8,3); + rectangle(136,96,24,8,3); + for (i = 0; i < 60; ++i) move_t(!(i & 1)); + } + else for (i = 0; i < 60; ++i) + move_block(block_x == 152 ? 164 : 152,88); + number(208,140,draw_worst); + number(208,152,sample_worst); + } + if (key == 'J' || key == 'j') + { + for (i = 0; i < 4; ++i) number(16 + i * 56,176,sampled_axes[i]); + number(248,176,sampled_buttons); + } + prior = key; + } + hscreen(0); + resetPalette(TRUE); + width(32); + setHighSpeed(FALSE); + cls(1); + disk_after = showDiskWords(); + printf("DISK BEFORE %u AFTER %u\n",disk_before,disk_after); + printf("FAST %u DRAW %u P95 %u MAX %u\n",fast_mode,draw_count,percentile(),draw_worst); + printf("MAPPED %u ERR %u SAMPLE %u\n",mapped_mode,c3_mapping_errors,sample_worst); + printf("RIGHT %u %u LEFT %u %u BTN %u\n",sampled_axes[0],sampled_axes[1],sampled_axes[2],sampled_axes[3],sampled_buttons); + return 0; +} diff --git a/src/APIProbe/src/disk.c b/src/APIProbe/src/disk.c new file mode 100644 index 0000000..e945a1c --- /dev/null +++ b/src/APIProbe/src/disk.c @@ -0,0 +1,28 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#include +#include +#include "hello.h" + +static DECBDrive drives[1]; +static DECBFile file; +static byte words[256]; + +byte showDiskWords(void) +{ + byte status = decb_init(drives, 1); + if (status != DECB_OK) + return status; + status = decb_registerDrive(0); + if (status == DECB_OK) + status = decb_openSectorFile(&file, 0, "WORDS.DAT"); + if (status == DECB_OK) + { + status = decb_readSector(&file, words, 0); + words[255] = 0; + if (status == DECB_OK) + printf("%s\n", words); + decb_closeSectorFile(&file); + } + decb_shutdown(); + return status; +} diff --git a/src/APIProbe/src/display.c b/src/APIProbe/src/display.c new file mode 100644 index 0000000..f4f277d --- /dev/null +++ b/src/APIProbe/src/display.c @@ -0,0 +1,8 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#include +#include "hello.h" +void showHeading(void) +{ + printf("HELLO FROM A MULTI-FILE PROJECT\n"); + printf("WORDS READ FROM THE FLOPPY:\n"); +} diff --git a/src/APIProbe/tools/build-data.pl b/src/APIProbe/tools/build-data.pl new file mode 100644 index 0000000..5dca810 --- /dev/null +++ b/src/APIProbe/tools/build-data.pl @@ -0,0 +1,24 @@ +#!/usr/bin/env perl +# SPDX-License-Identifier: GPL-3.0-or-later +use strict; +use warnings; +@ARGV == 3 or die "Usage: build-data.pl words.txt generated.c WORDS.DAT\n"; +my ($input, $source, $disk_data) = @ARGV; +open my $in, '<', $input or die "$input: $!\n"; +my @words; +while (<$in>) { + s/\r?\n\z//; + next if $_ eq ''; + /\A[A-Z]+\z/ or die "Words must contain uppercase A-Z only\n"; + push @words, $_; +} +close $in; +@words <= 255 or die "Too many words\n"; +my $bytes = join("\r", @words) . "\r\0"; +length($bytes) <= 256 or die "Example data must fit one disk sector\n"; +open my $c, '>', $source or die "$source: $!\n"; +print {$c} "/* Generated from assets/words.txt. */\n#include \nconst unsigned char generatedWordCount = " . scalar(@words) . ";\n"; +close $c or die "$source: $!\n"; +open my $data, '>:raw', $disk_data or die "$disk_data: $!\n"; +print {$data} $bytes . ("\0" x (256 - length($bytes))); +close $data or die "$disk_data: $!\n"; diff --git a/src/APIProbe/vccplus-project.json b/src/APIProbe/vccplus-project.json new file mode 100644 index 0000000..3892924 --- /dev/null +++ b/src/APIProbe/vccplus-project.json @@ -0,0 +1,79 @@ +{ + "binary" : "HELLO.bin", + "buildTarget" : "disk", + "cleanTarget" : "clean", + "configurations" : [ + { + "makeArguments" : [ + + ], + "name" : "Debug" + }, + { + "makeArguments" : [ + "VCC_CONFIGURATION=Release" + ], + "name" : "Release" + } + ], + "diskImage" : "HELLO.dsk", + "diskTarget" : "disk", + "entrySource" : "main.c", + "jobs" : 4, + "launchCommands" : [ + "DOS" + ], + "launchMode" : "disk", + "makefile" : "Makefile", + "makefileSettings" : { + "compilerOptions" : [ + + ], + "defines" : [ + + ], + "diskBootMode" : "program", + "diskFiles" : [ + "generated/WORDS.DAT" + ], + "diskImage" : "HELLO.dsk", + "executable" : "HELLO.bin", + "generatedResources" : [ + { + "command" : "$(PERL) tools/build-data.pl assets/words.txt generated/word-count.c generated/WORDS.DAT", + "inputs" : [ + "tools/build-data.pl", + "assets/words.txt" + ], + "outputs" : [ + "generated/word-count.c", + "generated/WORDS.DAT" + ] + } + ], + "includePaths" : [ + "include" + ], + "libraries" : [ + "decbfile" + ], + "libraryPaths" : [ + + ], + "libraryProjects" : [ + + ], + "linkerOptions" : [ + + ], + "origin" : "2800", + "releaseOptimization" : "-O2", + "sources" : [ + "main.c", + "src/display.c", + "src/disk.c", + "generated/word-count.c" + ], + "stackSpace" : 2048 + } +} \ No newline at end of file diff --git a/src/game/input.c b/src/game/input.c new file mode 100644 index 0000000..5dff385 --- /dev/null +++ b/src/game/input.c @@ -0,0 +1,71 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#include "input.h" + +void q_input_reset(QInput *s) +{ + s->previous=s->repeat_ms=s->button_ms=0; + s->direction=s->axis_x=s->axis_y=0; + s->guard=1;s->button_before=s->button_used=s->up_armed=s->stick_armed=0; +} + +static signed char axis(signed char old,int delta) +{ + if(old<0&&delta<-6)return -1; + if(old>0&&delta>6)return 1; + if(delta<-10)return -1; + if(delta>10)return 1; + return 0; +} + +QActions q_input_step(QInput *s,Q16 keys,Q8 button,Q8 x,Q8 y,Q8 cx,Q8 cy,Q8 joystick,Q16 ms,Q8 playing,Q8 clockwise) +{ + QActions a; + int dx=(int)x-cx,dy=(int)y-cy,ax,ay; + Q16 held=keys; + signed char direction=0; + a.held=a.pressed=0;a.move=0;a.repeats=0; + if(!joystick){button=0;dx=dy=0;} + s->axis_x=axis(s->axis_x,dx);s->axis_y=axis(s->axis_y,dy); + if(!s->axis_x&&!s->axis_y){s->stick_armed=1;s->up_armed=1;} + if(s->guard){ + if(!keys&&!button)s->guard=0; + s->button_before=button; + return a; + } + if(s->stick_armed){ + if(s->axis_x<0)held|=Q_LEFT; + if(s->axis_x>0)held|=Q_RIGHT; + if(s->axis_y>0)held|=Q_DOWN; + ax=dx<0?-dx:dx;ay=dy<0?-dy:dy; + if(s->axis_y<0){ + if(!playing)held|=Q_UP; + else if(s->up_armed){if(ay>=ax)a.pressed|=Q_HARD;s->up_armed=0;} + } + } + a.held=held; + a.pressed|=held&~s->previous; + if(button){ + if(!s->button_before){s->button_ms=0;s->button_used=0;} + if(s->button_ms<400)s->button_ms=ms>=400-s->button_ms?(Q16)400:(Q16)(s->button_ms+ms); + if(playing&&s->button_ms>=400&&!s->button_used){a.pressed|=Q_PAUSE;s->button_used=1;} + }else if(s->button_before&&!s->button_used) + a.pressed|=playing?(clockwise?(Q16)Q_CW:(Q16)Q_CCW):(Q16)Q_CONFIRM; + s->button_before=button; + /* Keep the first horizontal direction until that direction is released. */ + if(s->direction<0&&(held&Q_LEFT))direction=-1; + else if(s->direction>0&&(held&Q_RIGHT))direction=1; + else if(held&Q_LEFT)direction=-1; + else if(held&Q_RIGHT)direction=1; + if(direction!=s->direction){ + s->direction=direction;s->repeat_ms=200; + if(direction){a.move=direction;a.repeats=1;} + }else if(direction){ + if(ms>=s->repeat_ms){ + Q16 remainder=ms-s->repeat_ms; + a.move=direction;a.repeats=remainder>=360?10:(Q8)(1+remainder/40); + s->repeat_ms=40-remainder%40; + }else s->repeat_ms-=ms; + } + s->previous=held; + return a; +} diff --git a/src/game/input.h b/src/game/input.h new file mode 100644 index 0000000..91542f7 --- /dev/null +++ b/src/game/input.h @@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#ifndef QUAD_INPUT_H +#define QUAD_INPUT_H +#include "rules.h" +#define Q_LEFT 1 +#define Q_RIGHT 2 +#define Q_UP 4 +#define Q_DOWN 8 +#define Q_CCW 16 +#define Q_CW 32 +#define Q_HARD 64 +#define Q_HOLD 128 +#define Q_PAUSE 256 +#define Q_CONFIRM 512 +#define Q_BACK 1024 + +typedef struct { + Q16 previous,repeat_ms,button_ms; + signed char direction,axis_x,axis_y; + Q8 guard,button_before,button_used,up_armed,stick_armed; +} QInput; +typedef struct { Q16 held,pressed; signed char move; Q8 repeats; } QActions; +void q_input_reset(QInput *state); +QActions q_input_step(QInput *state,Q16 keys,Q8 button,Q8 x,Q8 y,Q8 cx,Q8 cy,Q8 joystick,Q16 ms,Q8 playing,Q8 clockwise); +#endif diff --git a/src/game/preferences.h b/src/game/preferences.h new file mode 100644 index 0000000..e357f4d --- /dev/null +++ b/src/game/preferences.h @@ -0,0 +1,9 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#ifndef QUAD_PREFERENCES_H +#define QUAD_PREFERENCES_H +#include "rules.h" +typedef struct { + QOptions game; + Q8 style,grid,shadow,sound,clockwise,custom_seed,port,hz,centers[4]; +} QPreferences; +#endif diff --git a/src/game/rules.c b/src/game/rules.c new file mode 100644 index 0000000..3ca6415 --- /dev/null +++ b/src/game/rules.c @@ -0,0 +1,360 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Rules and piece data derived from SPECIFICATION.md and GPL reference fixtures. + * Original Quadrapassel authors/port attribution: docs/PROVENANCE.md. + * Difficult-piece evaluation follows Federico Poloni's Bastet algorithm. + */ +#include "rules.h" + +const Q16 q_masks[7][4] = { + {0x2E00,0xC440,0x0E80,0x4460}, + {0x8E00,0x44C0,0x0E20,0x6440}, + {0x4E00,0x4C40,0x0E40,0x4640}, + {0x06C0,0x4620,0x06C0,0x4620}, + {0x0C60,0x2640,0x0C60,0x2640}, + {0x0F00,0x4444,0x0F00,0x4444}, + {0x0660,0x0660,0x0660,0x0660} +}; + +static Q32 add_saturating(Q32 a, Q32 b) +{ + return Q_SCORE_MAX - a < b ? Q_SCORE_MAX : a + b; +} + +Q8 q_occupied(Q8 type, Q8 rotation, Q8 x, Q8 y) +{ + if (type > 6 || rotation > 3 || x > 3 || y > 3) return 0; + return (q_masks[type][rotation] & ((Q16)0x8000 >> (y * 4 + x))) != 0; +} + +QPiece q_spawn(Q8 type, Q8 rotation) +{ + QPiece p; + Q8 x, y, xmin = 4, xmax = 0, ymin = 4; + p.type = type; p.rotation = rotation; + p.x = p.y = 0; + if (type > 6 || rotation > 3) return p; + for (y = 0; y < 4; ++y) for (x = 0; x < 4; ++x) + if (q_occupied(type,rotation,x,y)) + { + if (x < xmin) xmin = x; + if (x > xmax) xmax = x; + if (y < ymin) ymin = y; + } + p.x = (10 - (xmax - xmin + 1)) / 2 - xmin; + p.y = -(signed char)ymin; + return p; +} + +Q8 q_fits(const QBoard *board, const QPiece *p) +{ + Q8 x,y; + int bx,by; + if (p->type > 6 || p->rotation > 3) return 0; + for (y = 0; y < 4; ++y) for (x = 0; x < 4; ++x) + if (q_occupied(p->type,p->rotation,x,y)) + { + bx = (int)p->x + x; by = (int)p->y + y; + if (bx < 0 || bx >= 10 || by >= 20) return 0; + if (by >= 0 && board->cells[by][bx]) return 0; + } + return 1; +} + +Q8 q_move(QGame *g, signed char dx, signed char dy) +{ + QPiece p = g->active; + int x = (int)p.x + dx, y = (int)p.y + dy; + if (g->over || x < -4 || x > 10 || y < -4 || y > 20) return 0; + p.x = (signed char)x; p.y = (signed char)y; + if (!q_fits(&g->board,&p)) return 0; + g->active = p; + return 1; +} + +Q8 q_rotate(QGame *g, Q8 clockwise) +{ + static const signed char kicks[5] = {0,1,-1,2,-2}; + QPiece p = g->active; + Q8 i; + if (g->over) return 0; + p.rotation = (p.rotation + (clockwise ? 3 : 1)) & 3; + if (p.y < 0) ++p.y; + for (i = 0; i < 5; ++i) + { + p.x = (signed char)(g->active.x + kicks[i]); + if (q_fits(&g->board,&p)) { g->active = p; return 1; } + } + return 0; +} + +QPiece q_shadow(const QGame *g) +{ + QPiece p = g->active, next; + if (!q_fits(&g->board,&p)) return p; + for (;;) { + next = p; ++next.y; + if (!q_fits(&g->board,&next)) return p; + p = next; + } +} + +Q8 q_compact(QBoard *board, Q8 *bottom) +{ + int source, dest = 19; + Q8 x, full, cleared = 0; + *bottom = 0; + for (source = 19; source >= 0; --source) + { + full = 1; + for (x = 0; x < 10; ++x) if (!board->cells[source][x]) full = 0; + if (full) { ++cleared; if (source == 19) *bottom = 1; } + else { + if (dest != source) + for (x = 0; x < 10; ++x) board->cells[dest][x] = board->cells[source][x]; + --dest; + } + } + while (dest >= 0) { + for (x = 0; x < 10; ++x) board->cells[dest][x] = 0; + --dest; + } + return cleared; +} + +Q16 q_level(signed char difficulty, Q32 lines) +{ + Q32 level; + if (difficulty < 0) return 1; + level = (Q32)difficulty + 1 + lines / 10; + return level > 65535UL ? (Q16)65535 : (Q16)level; +} + +Q32 q_clear_points(Q8 rule, Q16 level, Q8 rows, Q8 bottom) +{ + static const Q16 regular[5] = {0,40,100,300,1200}; + Q32 base; + if (!rows || rows > 4) return 0; + base = regular[rows]; + if (bottom) base += rule == Q_CLASSIC ? 10000UL : (Q32)100 * rows; + return base * level; /* Max 11200 * 65535 fits unsigned 32 bits. */ +} + +void q_score_clear(QGame *g, Q8 rows, Q8 bottom) +{ + g->lines = add_saturating(g->lines,rows); + g->level = q_level(g->options.difficulty,g->lines); + g->score = add_saturating(g->score,q_clear_points(g->options.scoring,g->level,rows,bottom)); +} + +Q16 q_gravity_ms(Q16 level) +{ + static const Q16 intervals[] = { + 880,680,530,418,333,270,222,187,160,140,125,114,105,99,94,91, + 88,86,85,83,83,82,81,81,81,81,80 + }; + if (!level) level = 1; + return level > sizeof(intervals)/sizeof(intervals[0]) ? (Q16)80 : intervals[level-1]; +} + +void q_random_init(QRandom *r, Q32 seed) +{ + Q8 i; + r->state = seed ? seed : 0x6D2B79F5UL; + for (i = 0; i < 7; ++i) r->counts[i] = 0; +} + +Q32 q_random_next(QRandom *r) +{ + /* Frozen xorshift32 (13,17,5); seed zero has the documented nonzero mapping. */ + Q32 x = r->state; + x ^= x << 13; x ^= x >> 17; x ^= x << 5; + r->state = x; + return x; +} + +static Q32 below(QRandom *r, Q32 n) +{ + Q32 x, limit = (Q_SCORE_MAX / n) * n; + do { x = q_random_next(r); } while (x >= limit); + return x % n; +} + +Q8 q_weighted(QRandom *r) +{ + Q16 min = r->counts[0], d, weights[7]; + Q32 total = 0, pick; + Q8 i; + for (i = 1; i < 7; ++i) if (r->counts[i] < min) min = r->counts[i]; + for (i = 0; i < 7; ++i) + { + r->counts[i] -= min; + d = r->counts[i]; + if (d < 1) d = 1; + /* Q16 fixed-point inverse-square; floor at one never excludes a type. */ + weights[i] = d > 255 ? (Q16)1 : (Q16)(65535U / ((Q16)d * d)); + total += weights[i]; + } + pick = below(r,total); + for (i = 0; i < 6 && pick >= weights[i]; ++i) pick -= weights[i]; + if (r->counts[i] < 65535) ++r->counts[i]; + return i; +} + +static void place(QBoard *b, const QPiece *p) +{ + Q8 x,y; + for (y = 0; y < 4; ++y) for (x = 0; x < 4; ++x) + if (q_occupied(p->type,p->rotation,x,y)) + b->cells[(int)p->y+y][(int)p->x+x] = p->type + 1; +} + +static QS16 candidate(const QBoard *original, QPiece p) +{ + QBoard b; + QPiece next; + Q8 x,y,bottom,rows; + Q16 height = 0; + for (;;) { + next = p; ++next.y; + if (!q_fits(original,&next)) break; + p = next; + } + for (y = 0; y < 4; ++y) for (x = 0; x < 4; ++x) + if (q_occupied(p.type,p.rotation,x,y) && (int)p.y+y < 0) return -30000; + b = *original; + place(&b,&p); + rows = q_compact(&b,&bottom); + for (x = 0; x < 10; ++x) + for (y = 0; y < 20; ++y) if (b.cells[y][x]) { height += 20-y; break; } + return (QS16)(5000 * rows - 5 * height); +} + +QS16 q_best_metric(const QBoard *board, Q8 type) +{ + Q8 rotation; + int direction; + QS16 best = -30000, metric; + QPiece p, start; + for (rotation = 0; rotation < 4; ++rotation) + { + start = q_spawn(type,rotation); + if (!q_fits(board,&start)) continue; + /* Walking each way only through valid positions preserves reachability. */ + for (direction = -1; direction <= 1; direction += 2) + { + p = start; + do { + metric = candidate(board,p); + if (metric > best) best = metric; + p.x = (signed char)(p.x + direction); + } while (q_fits(board,&p)); + } + } + return best; +} + +QChoice q_difficult(const QBoard *board, QRandom *r) +{ + QS16 metrics[7], metric; + Q8 order[7], i, j, type, draw; + QChoice choice; + for (i = 0; i < 7; ++i) + { + metrics[i] = q_best_metric(board,i) + (QS16)below(r,4) - 2; + order[i] = i; + } + for (i = 1; i < 7; ++i) + { + type = order[i]; metric = metrics[type]; j = i; + while (j && metrics[order[j-1]] > metric) { order[j] = order[j-1]; --j; } + order[j] = type; + } + draw = (Q8)below(r,99); + choice.type = order[draw < 75 ? 0 : draw < 92 ? 1 : draw < 98 ? 2 : 3]; + choice.rotation = (Q8)below(r,4); + return choice; +} + +static QChoice choose(QGame *g) +{ + QChoice c; + if (g->options.difficult) return q_difficult(&g->board,&g->random); + c.type = q_weighted(&g->random); c.rotation = 0; + return c; +} + +static void activate(QGame *g, QChoice c) +{ + g->active = q_spawn(c.type,c.rotation); + if (!q_fits(&g->board,&g->active)) g->over = 1; +} + +void q_start(QGame *g, const QOptions *options) +{ + Q8 x,y,hole; + QChoice first; + g->options = *options; + if (g->options.difficulty < -1) g->options.difficulty = -1; + if (g->options.difficulty > 15) g->options.difficulty = 15; + g->options.scoring = options->scoring == Q_CLASSIC ? Q_CLASSIC : Q_MODERN; + q_random_init(&g->random,options->seed); + g->score = g->lines = 0; + g->level = q_level(g->options.difficulty,0); + g->held = Q_EMPTY_HOLD; + g->hold_used = g->over = g->last_clear = g->last_bottom = 0; + for (y = 0; y < 20; ++y) for (x = 0; x < 10; ++x) g->board.cells[y][x] = 0; + for (y = 20 - (g->options.difficulty > 0 ? g->options.difficulty : 0); y < 20; ++y) + { + hole = (Q8)below(&g->random,10); + for (x = 0; x < 10; ++x) + if (x != hole && below(&g->random,2)) g->board.cells[y][x] = (Q8)(below(&g->random,7)+1); + } + first = choose(g); activate(g,first); + g->next = choose(g); /* Frozen preview timing: current settled board. */ +} + +Q8 q_lock(QGame *g) +{ + Q8 x,y; + QChoice next; + if (g->over) return 0; + if (!q_fits(&g->board,&g->active)) { g->over = 1; return 0; } + /* Check every cell before writing any cell: top-out has no partial writes. */ + for (y = 0; y < 4; ++y) for (x = 0; x < 4; ++x) + if (q_occupied(g->active.type,g->active.rotation,x,y) && (int)g->active.y+y < 0) + { g->over = 1; return 0; } + place(&g->board,&g->active); + g->last_clear = q_compact(&g->board,&g->last_bottom); + q_score_clear(g,g->last_clear,g->last_bottom); + g->hold_used = 0; + next = g->next; + activate(g,next); + if (!g->over) g->next = choose(g); + return 1; +} + +Q8 q_drop(QGame *g) +{ + if (g->over) return 0; + g->active = q_shadow(g); + return q_lock(g); +} + +Q8 q_hold(QGame *g) +{ + Q8 type; + QChoice c; + if (g->over || g->hold_used) return 0; + type = g->active.type; + if (g->held == Q_EMPTY_HOLD) + { + c = g->next; + c.rotation = 0; + activate(g,c); + if (!g->over) g->next = choose(g); + } + else { c.type = g->held; c.rotation = 0; activate(g,c); } + g->held = type; + g->hold_used = 1; + return 1; +} diff --git a/src/game/rules.h b/src/game/rules.h new file mode 100644 index 0000000..1a00e50 --- /dev/null +++ b/src/game/rules.h @@ -0,0 +1,58 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#ifndef QUAD_RULES_H +#define QUAD_RULES_H +#ifdef QUAD_HOST +#include +typedef uint32_t Q32; +typedef int32_t QS32; +#else +typedef unsigned long Q32; +typedef signed long QS32; +#endif +typedef unsigned char Q8; +typedef unsigned short Q16; +typedef signed short QS16; +#define Q_SCORE_MAX ((Q32)0xFFFFFFFFUL) +#define Q_EMPTY_HOLD 7 +#define Q_MODERN 0 +#define Q_CLASSIC 1 +#define Q_RNG_VERSION 1 + +typedef struct { Q8 cells[20][10]; } QBoard; +typedef struct { Q8 type, rotation; signed char x, y; } QPiece; +typedef struct { Q8 type, rotation; } QChoice; +typedef struct { Q32 state; Q16 counts[7]; } QRandom; +typedef struct { signed char difficulty; Q8 scoring, difficult; Q32 seed; } QOptions; +typedef struct { + QBoard board; + QPiece active; + QChoice next; + QRandom random; + QOptions options; + Q32 score, lines; + Q16 level; + Q8 held, hold_used, over, last_clear, last_bottom; +} QGame; + +extern const Q16 q_masks[7][4]; +Q8 q_occupied(Q8 type, Q8 rotation, Q8 x, Q8 y); +QPiece q_spawn(Q8 type, Q8 rotation); +Q8 q_fits(const QBoard *board, const QPiece *piece); +Q8 q_move(QGame *game, signed char dx, signed char dy); +Q8 q_rotate(QGame *game, Q8 clockwise); +QPiece q_shadow(const QGame *game); +Q8 q_compact(QBoard *board, Q8 *includes_bottom); +Q16 q_level(signed char difficulty, Q32 lines); +Q32 q_clear_points(Q8 rule, Q16 level, Q8 rows, Q8 includes_bottom); +void q_score_clear(QGame *game, Q8 rows, Q8 includes_bottom); +Q16 q_gravity_ms(Q16 level); +void q_random_init(QRandom *random, Q32 seed); +Q32 q_random_next(QRandom *random); +Q8 q_weighted(QRandom *random); +QS16 q_best_metric(const QBoard *board, Q8 type); +QChoice q_difficult(const QBoard *board, QRandom *random); +void q_start(QGame *game, const QOptions *options); +Q8 q_lock(QGame *game); +Q8 q_drop(QGame *game); +Q8 q_hold(QGame *game); +#endif diff --git a/src/game/store.c b/src/game/store.c new file mode 100644 index 0000000..3fa3f16 --- /dev/null +++ b/src/game/store.c @@ -0,0 +1,191 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Versioned two-slot store. Commit header is written only after all payloads. + * A table occupies one sector; only one table and one sector are needed in RAM. + */ +#ifdef QUAD_HOST +#include +#else +#include +#endif +#include "store.h" +static const QStoreIO *io; +static signed char active_slot=-1; +static Q32 generation; +static Q8 page[256]; + +Q16 q_store_crc(const Q8 *data,Q16 length) +{ + Q16 crc=0xFFFF;Q8 bit; + while(length--){crc^=(Q16)*data++<<8;for(bit=0;bit<8;++bit)crc=(crc&0x8000)?(Q16)((crc<<1)^0x1021):(Q16)(crc<<1);} + return crc; +} + +static Q32 get32(const Q8 *p) +{ +#ifdef QUAD_HOST + return ((Q32)p[0]<<24)|((Q32)p[1]<<16)|((Q32)p[2]<<8)|p[3]; +#else + /* CMOC's CoCo target stores unsigned long in big-endian byte order. */ + Q32 n;memcpy(&n,p,4);return n; +#endif +} + +static void put32(Q8 *p,Q32 n) +{ +#ifdef QUAD_HOST + p[0]=(Q8)(n>>24);p[1]=(Q8)(n>>16);p[2]=(Q8)(n>>8);p[3]=(Q8)n; +#else + memcpy(p,&n,4); +#endif +} + +static Q8 checksum_ok(void) +{ + return q_store_crc(page,254)==((Q16)page[254]<<8|page[255]); +} + +static void checksum_finish(void) +{ + Q16 crc=q_store_crc(page,254);page[254]=(Q8)(crc>>8);page[255]=(Q8)crc; +} + +void q_preferences_default(QPreferences *p) +{ + Q8 i;memset(p,0,sizeof(*p));p->style=1;p->sound=1;p->hz=60; + for(i=0;i<4;++i)p->centers[i]=31; +} + +static Q8 preferences_ok(void) +{ + static const Q8 maximum[15]={16,1,1,2,1,1,1,1,1,2,60,63,63,63,63}; + Q8 i;for(i=0;i<15;++i)if(page[12+i]>maximum[i])return 0; + if(page[22]!=50&&page[22]!=60)return 0; + return 1; +} + +static void decode_preferences(QPreferences *p) +{ + p->game.difficulty=(signed char)(page[12]-1); + memcpy(&p->game.scoring,page+13,2); + memcpy(&p->style,page+15,12);p->game.seed=get32(page+27); +} + +static void encode_header(const QPreferences *p,Q32 gen) +{ + memset(page,0,sizeof(page));page[0]='Q';page[1]='P';page[2]='S';page[3]='V'; + page[4]=1;page[5]=34;page[6]=8;page[7]=10;put32(page+8,gen); + page[12]=(Q8)(p->game.difficulty+1); + memcpy(page+13,&p->game.scoring,2);memcpy(page+15,&p->style,12); + put32(page+27,p->game.seed);checksum_finish(); +} + +static Q8 table_ok(Q8 category) +{ + Q8 i,j,empty=0;Q32 score,previous=Q_SCORE_MAX; + if(page[80]!=category||page[81]!=1||page[82]!=80||!checksum_ok())return 0; + for(i=0;i<10;++i){ + score=get32(page+i*8); + if(score>previous)return 0; + previous=score; + if(!score){empty=1;for(j=0;j<8;++j)if(page[i*8+j])return 0;} + else{ + if(empty||page[i*8+7]>1)return 0; + for(j=4;j<7;++j)if(page[i*8+j]<'A'||page[i*8+j]>'Z')return 0; + } + } + return 1; +} + +static void encode_table(Q8 category,const QScore *scores) +{ + Q8 i,j;memset(page,0,sizeof(page));page[80]=category;page[81]=1;page[82]=80; + if(scores)for(i=0;i<10;++i)if(scores[i].score){ + put32(page+i*8,scores[i].score); + for(j=0;j<3;++j)page[i*8+4+j]=scores[i].initials[j]; + page[i*8+7]=scores[i].rule; + } + checksum_finish(); +} + +static Q8 validate_slot(Q8 slot,Q32 *gen,QPreferences *prefs) +{ + Q8 status,index; + status=io->open(slot,0);if(status)return status; + status=io->read(slot,0,page); + if(!status&&(page[0]!='Q'||page[1]!='P'||page[2]!='S'||page[3]!='V'||page[4]!=1|| + page[5]!=34||page[6]!=8||page[7]!=10||!checksum_ok()||!preferences_ok()))status=Q_STORE_CORRUPT; + if(!status){*gen=get32(page+8);decode_preferences(prefs);} + for(index=0;!status&&index<34;++index){ + status=io->read(slot,index+1,page); + if(!status&&!table_ok(index))status=Q_STORE_CORRUPT; + } + if(io->close(slot)&&!status)status=Q_STORE_IO; + return status; +} + +Q8 q_store_load(const QStoreIO *ops,QPreferences *p) +{ + Q8 a,b;Q32 generations[2];QPreferences candidates[2]; + io=ops;active_slot=-1;generation=0; + a=validate_slot(0,generations,candidates);b=validate_slot(1,generations+1,candidates+1); + if(!a||!b){ + active_slot=!a&&!b?((Q32)(generations[1]-generations[0])<0x80000000UL&&generations[1]!=generations[0]?1:0):(!a?0:1); + generation=generations[active_slot];*p=candidates[active_slot]; + return (a>Q_STORE_MISSING||b>Q_STORE_MISSING)?Q_STORE_RECOVERED:Q_STORE_OK; + } + return a==Q_STORE_MISSING&&b==Q_STORE_MISSING?Q_STORE_OK:Q_STORE_CORRUPT; +} + +Q8 q_store_scores(Q8 category,QScore scores[10]) +{ + Q8 status,i,j;memset(scores,0,sizeof(QScore)*10); + if(category>=34)return Q_STORE_CORRUPT; + if(active_slot<0)return Q_STORE_OK; + status=io->open(active_slot,0);if(status)return status; + status=io->read(active_slot,category+1,page); + if(!status&&!table_ok(category))status=Q_STORE_CORRUPT; + if(!status)for(i=0;i<10;++i){scores[i].score=get32(page+i*8);for(j=0;j<3;++j)scores[i].initials[j]=page[i*8+4+j];scores[i].rule=page[i*8+7];} + if(io->close(active_slot)&&!status)status=Q_STORE_IO; + return status; +} + +Q8 q_store_save(const QPreferences *prefs,signed char category,const QScore *scores,Q8 reset_all) +{ + Q8 target=active_slot==0?1:0,index,status,source_open=0,target_open=0; + Q32 next=generation+1,verified;QPreferences checked; + if(category < -1 || category>=34)return Q_STORE_CORRUPT; + if(active_slot>=0&&!reset_all){status=io->open(active_slot,0);if(status)return status;source_open=1;} + status=io->open(target,1);if(!status)target_open=1; + if(!status){memset(page,0,sizeof(page));status=io->write(target,0,page);} + for(index=0;!status&&index<34;++index){ + if((signed char)index==category){encode_table(index,scores);if(!table_ok(index)){status=Q_STORE_CORRUPT;break;}} + else if(reset_all||active_slot<0)encode_table(index,0); + else {status=io->read(active_slot,index+1,page);if(!status&&!table_ok(index))status=Q_STORE_CORRUPT;} + if(!status)status=io->write(target,index+1,page); + } + if(!status){encode_header(prefs,next);if(!preferences_ok())status=Q_STORE_CORRUPT;else status=io->write(target,0,page);} + if(target_open&&io->close(target)&&!status)status=Q_STORE_IO; + if(source_open&&io->close(active_slot)&&!status)status=Q_STORE_IO; + if(!status)status=validate_slot(target,&verified,&checked); + if(!status&&verified!=next)status=Q_STORE_CORRUPT; + if(!status){active_slot=target;generation=next;} + return status; +} + +Q8 q_score_insert(QScore scores[10],Q32 score,const char initials[3],Q8 rule) +{ + Q8 i,j; + if(!score||rule>1)return 0; + for(j=0;j<3;++j)if(initials[j]<'A'||initials[j]>'Z')return 0; + for(i=0;i<10&&scores[i].score&&scores[i].score>=score;++i){} + if(i==10)return 0; + for(j=9;j>i;--j)scores[j]=scores[j-1]; + scores[i].score=score;scores[i].rule=rule; + for(j=0;j<3;++j)scores[i].initials[j]=initials[j]; + return 1; +} + +Q8 q_score_category(signed char difficulty,Q8 difficult) +{ + return (Q8)((difficulty+1)*2+(difficult?1:0)); +} diff --git a/src/game/store.h b/src/game/store.h new file mode 100644 index 0000000..7e36022 --- /dev/null +++ b/src/game/store.h @@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#ifndef QUAD_STORE_H +#define QUAD_STORE_H +#include "preferences.h" +#define Q_STORE_OK 0 +#define Q_STORE_MISSING 1 +#define Q_STORE_CORRUPT 2 +#define Q_STORE_IO 3 +#define Q_STORE_RECOVERED 4 +#define Q_STORE_SECTORS 35 + +typedef struct { Q32 score; char initials[3]; Q8 rule; } QScore; +typedef struct { + Q8 (*open)(Q8 slot,Q8 write); + Q8 (*read)(Q8 slot,Q8 sector,Q8 *data); + Q8 (*write)(Q8 slot,Q8 sector,const Q8 *data); + Q8 (*close)(Q8 slot); +} QStoreIO; +void q_preferences_default(QPreferences *p); +Q8 q_store_load(const QStoreIO *ops,QPreferences *p); +Q8 q_store_scores(Q8 category,QScore scores[10]); +Q8 q_store_save(const QPreferences *p,signed char category,const QScore *scores,Q8 reset_all); +Q8 q_score_insert(QScore scores[10],Q32 score,const char initials[3],Q8 rule); +Q8 q_score_category(signed char difficulty,Q8 difficult); +Q16 q_store_crc(const Q8 *data,Q16 length); +#endif diff --git a/src/platform/coco3_video.c b/src/platform/coco3_video.c new file mode 100644 index 0000000..5a8157b --- /dev/null +++ b/src/platform/coco3_video.c @@ -0,0 +1,97 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Brian-approved C graphics exception: docs/DECISIONS.md, 2026-11-10. + * Hardware reference: Chris Lomont, CoCo Hardware v0.82, pp. 11-13, 67-69. + * The four BASIC graphics banks $30-$33 exist in the 128 KB machine. + * Only Disk BASIC task 0's $8000-$9FFF mapping changes. SAM ROM/RAM selection, + * video registers, BASIC system RAM, code and stack are never changed here. + */ +#include "coco3_video.h" +#define REG(address) (*(byte *)(address)) +word c3_mapping_errors; + +byte c3_video_ready(void) +{ + /* Stock Disk BASIC uses MMU task 0 and HSCREEN 2 page $60000. + * GIME control registers are not a dependable readback contract. The + * caller has already initialized standard CoCo support and HSCREEN 2; + * this renderer neither detects nor supports arbitrary custom mappings. + */ + return isCoCo3; +} + +/* CMOC does not implement volatile. A separate C call is an optimization + * boundary for MMU readback; audit the emitted reads/stores for each candidate. + */ +static byte read_bank(void) +{ + return REG(0xFFA4) & 63; +} + +static void copy_chunk(word offset, const byte *source, byte count) +{ + byte *bank_register; + byte *destination; + byte original, bank, i; + bank = (byte)(0x30 + (offset >> 13)); + destination = (byte *)(0x8000 + (offset & 0x1FFF)); + /* These are unmodified public coco.h interrupt APIs, not authored assembly. + * Limit each interval to at most 32 copied bytes. No standard API that + * needs BASIC/ROM is called until the prior mapping has been restored. + */ + disableInterrupts(); + bank_register = (byte *)0xFFA4; + original = read_bank(); + *bank_register = bank; + for (i = 0; i < count; ++i) destination[i] = source[i]; + *bank_register = original; + if (read_bank() != original) ++c3_mapping_errors; + enableInterrupts(); +} + +byte c3_blit(word x, byte y, word width, byte height, const byte *packed) +{ + word row_bytes, offset, remaining, until_boundary, source_address; + byte row, chunk; + if (!width || !height || x >= 320 || width > 320-x || y >= 192 || height > 192-y) + return FALSE; + if ((x | width) & 1) return FALSE; + row_bytes = width / 2; + source_address = (word)packed; + if (source_address >= 0x8000 || (word)(row_bytes * height) > 0x8000-source_address) + return FALSE; + for (row = 0; row < height; ++row) + { + offset = (word)(y+row) * 160 + x/2; + remaining = row_bytes; + while (remaining) + { + until_boundary = 8192 - (offset & 8191); + chunk = remaining > 32 ? 32 : (byte)remaining; + if (until_boundary < chunk) chunk = (byte)until_boundary; + copy_chunk(offset,packed,chunk); + packed += chunk; offset += chunk; remaining -= chunk; + } + } + return TRUE; +} + +byte c3_fill(word x, byte y, word width, byte height, byte color) +{ + byte fill[160], row; + if (!width || !height || color > 15 || x >= 320 || width > 320-x || y >= 192 || height > 192-y) + return FALSE; + /* Keep uncommon odd edges on the public API, outside every mapped interval. */ + if (x & 1) { + for (row = 0; row < height; ++row) hset(x,y+row,color); + ++x; --width; + } + if (width & 1) { + for (row = 0; row < height; ++row) hset(x+width-1,y+row,color); + --width; + } + if (!width) return TRUE; + memset(fill,(color<<4)|color,sizeof(fill)); + for(row=0;row +/* Call after standard hscreen(2), in the ordinary Disk BASIC foreground. + * Code/data/source buffers/stack must be below $8000. No disk operation may + * overlap a call. IRQ/FIRQ use the standard CMOC enabled foreground policy. + * No interrupt handlers, callbacks, ROM calls or allocation run while mapped. + */ +byte c3_video_ready(void); +byte c3_blit(word x, byte y, word width, byte height, const byte *packed); +byte c3_fill(word x, byte y, word width, byte height, byte color); +extern word c3_mapping_errors; +#endif diff --git a/src/platform/disk_store.c b/src/platform/disk_store.c new file mode 100644 index 0000000..02c3a68 --- /dev/null +++ b/src/platform/disk_store.c @@ -0,0 +1,85 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +/* Disk initialization follows Pierre Sarrazin, CoCoLetters 0.1.0 file.c + * (Copyright 2026 Pierre Sarrazin, GPL-3.0-or-later). See docs/PROVENANCE.md. */ +#include +#include +#include "disk_store.h" +static DECBDrive drive[1]; +static DECBFile files[2]; +static Q8 writing[2],ready; +static const char *names[2]={"QPSAVE0.DAT","QPSAVE1.DAT"}; + +static Q8 open_slot(Q8 slot,Q8 write) +{ + Q8 status;Q16 sectors;Q32 length; + if(!ready)return Q_STORE_IO; + setHighSpeed(FALSE);writing[slot]=0; + status=decb_openSectorFile(files+slot,0,names[slot]); + if(write&&status==DECB_ERR_NOT_FOUND)status=decb_createSectorFile(files+slot,0,names[slot],DECB_TYPE_BASIC_DATA,DECB_FORMAT_BINARY); + if(status){setHighSpeed(TRUE);return status==DECB_ERR_NOT_FOUND?Q_STORE_MISSING:Q_STORE_IO;} + /* This API returns the granule count, not an error code. */ + status=decb_getOpenFileSize(files+slot,§ors,&length)==0xFF?DECB_ERR_INVALID_ARGUMENT:DECB_OK; + if(!status&&((!write&&length!=(Q32)Q_STORE_SECTORS*256)||(write&&length>(Q32)Q_STORE_SECTORS*256)))status=DECB_ERR_INVALID_ARGUMENT; + if(status){decb_closeSectorFile(files+slot);setHighSpeed(TRUE);return Q_STORE_CORRUPT;} + writing[slot]=write;setHighSpeed(TRUE);return Q_STORE_OK; +} + +static Q8 read_slot(Q8 slot,Q8 sector,Q8 *data) +{ + Q8 status;setHighSpeed(FALSE);status=decb_readSector(files+slot,data,sector);setHighSpeed(TRUE);return status?Q_STORE_IO:Q_STORE_OK; +} + +static Q8 write_slot(Q8 slot,Q8 sector,const Q8 *data) +{ + Q8 status;setHighSpeed(FALSE);status=decb_writeSector(files+slot,data,sector);setHighSpeed(TRUE);return status?Q_STORE_IO:Q_STORE_OK; +} + +static Q8 close_slot(Q8 slot) +{ + Q8 status=0,closed;setHighSpeed(FALSE); + if(writing[slot])status=decb_setNumBytesUsedInLastSector(files+slot,256); + closed=decb_closeSectorFile(files+slot);writing[slot]=0;setHighSpeed(TRUE); + return status||closed?Q_STORE_IO:Q_STORE_OK; +} + +static QStoreIO ops; + +Q8 disk_store_open(QPreferences *preferences) +{ + Q8 status; + ops.open=open_slot;ops.read=read_slot;ops.write=write_slot;ops.close=close_slot; + setHighSpeed(FALSE);status=decb_init(drive,1); + if(!status)status=decb_registerDrive(0); + ready=!status;setHighSpeed(TRUE); + /* Even unavailable media gets an initialized store; writes report failure. */ + return q_store_load(&ops,preferences); +} + +void disk_store_close(void) +{ + setHighSpeed(FALSE);if(ready)decb_shutdown();ready=0; +} + +Q8 disk_store_menu(Q8 scene,Q8 *data) +{ + Q8 status,i;Q16 offset,j; + if(!ready||scene>=12)return Q_STORE_IO; + setHighSpeed(FALSE); + status=decb_openSectorFile(files,0,"QPTEXT.DAT"); + if(!status){ + status=decb_readSector(files,data,(Q16)scene*2); + if(!status)status=decb_readSector(files,data+256,(Q16)scene*2+1); + if(decb_closeSectorFile(files))status=Q_STORE_IO; + } + setHighSpeed(TRUE); + if(status)return Q_STORE_IO; + if(memcmp(data,"QPTX",4)||data[4]!=scene||data[6]!=1||data[5]>60|| + q_store_crc(data,510)!=((Q16)data[510]<<8|data[511]))return Q_STORE_CORRUPT; + for(i=0;i=510)return Q_STORE_CORRUPT; + for(j=offset;j<510&&data[j];++j){} + if(j==510)return Q_STORE_CORRUPT; + } + return Q_STORE_OK; +} diff --git a/src/platform/disk_store.h b/src/platform/disk_store.h new file mode 100644 index 0000000..5a621bb --- /dev/null +++ b/src/platform/disk_store.h @@ -0,0 +1,8 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#ifndef QUAD_DISK_STORE_H +#define QUAD_DISK_STORE_H +#include "store.h" +Q8 disk_store_open(QPreferences *preferences); +void disk_store_close(void); +Q8 disk_store_menu(Q8 scene,Q8 *data); +#endif diff --git a/src/platform/pierre_font.h b/src/platform/pierre_font.h new file mode 100644 index 0000000..fc62ffc --- /dev/null +++ b/src/platform/pierre_font.h @@ -0,0 +1,65 @@ +/* Adapted subset of 8-bit-wide-font.c, by Pierre Sarrazin . + * Original file: public domain. Glyph row bytes are unchanged. + * Source SHA-256: 2d58b3d966785d9fb8c34e9410ae62ded698fc7327987ae2d170fefcdb8feae3 + * The original 8x8 cells contain six visible columns and seven rows. + * Alphabet data resides in the existing low data area to respect code limits. + * The renderer only reads it. No other game's drawing code is imported. + */ +#ifndef QUAD_PIERRE_FONT_H +#define QUAD_PIERRE_FONT_H +static Q8 font_letters[26][7]={ + {0x1E,0x33,0x33,0x3F,0x33,0x33,0x33}, /* A */ + {0x3E,0x33,0x33,0x3E,0x33,0x33,0x3E}, /* B */ + {0x1E,0x33,0x30,0x30,0x30,0x33,0x1E}, /* C */ + {0x3E,0x33,0x33,0x33,0x33,0x33,0x3E}, /* D */ + {0x3F,0x30,0x30,0x3C,0x30,0x30,0x3F}, /* E */ + {0x3F,0x30,0x30,0x3C,0x30,0x30,0x30}, /* F */ + {0x1F,0x30,0x30,0x33,0x33,0x33,0x1F}, /* G */ + {0x33,0x33,0x33,0x3F,0x33,0x33,0x33}, /* H */ + {0x1E,0x0C,0x0C,0x0C,0x0C,0x0C,0x1E}, /* I */ + {0x03,0x03,0x03,0x03,0x03,0x33,0x1E}, /* J */ + {0x33,0x33,0x36,0x3C,0x36,0x33,0x33}, /* K */ + {0x30,0x30,0x30,0x30,0x30,0x30,0x3F}, /* L */ + {0x33,0x3F,0x3F,0x3F,0x33,0x33,0x33}, /* M */ + {0x33,0x33,0x3B,0x3F,0x37,0x33,0x33}, /* N */ + {0x1E,0x33,0x33,0x33,0x33,0x33,0x1E}, /* O */ + {0x3E,0x33,0x33,0x3E,0x30,0x30,0x30}, /* P */ + {0x1E,0x33,0x33,0x33,0x33,0x36,0x1F}, /* Q */ + {0x3E,0x33,0x33,0x3E,0x3C,0x36,0x33}, /* R */ + {0x1E,0x33,0x30,0x0C,0x03,0x33,0x1E}, /* S */ + {0x3F,0x0C,0x0C,0x0C,0x0C,0x0C,0x0C}, /* T */ + {0x33,0x33,0x33,0x33,0x33,0x33,0x1E}, /* U */ + {0x33,0x33,0x33,0x33,0x33,0x1E,0x0C}, /* V */ + {0x33,0x33,0x33,0x3F,0x3F,0x3F,0x33}, /* W */ + {0x33,0x33,0x1E,0x0C,0x1E,0x33,0x33}, /* X */ + {0x33,0x33,0x1E,0x0C,0x0C,0x0C,0x0C}, /* Y */ + {0x3F,0x03,0x06,0x0C,0x18,0x30,0x3F}, /* Z */ +}; +static const Q8 font_digits[10][7]={ + {0x1E,0x33,0x33,0x33,0x33,0x33,0x1E}, /* 0 */ + {0x1C,0x0C,0x0C,0x0C,0x0C,0x0C,0x1E}, /* 1 */ + {0x1E,0x33,0x03,0x06,0x0C,0x18,0x3F}, /* 2 */ + {0x1E,0x33,0x03,0x0E,0x03,0x33,0x1E}, /* 3 */ + {0x33,0x33,0x33,0x3F,0x03,0x03,0x03}, /* 4 */ + {0x3F,0x30,0x30,0x3E,0x03,0x03,0x3E}, /* 5 */ + {0x1E,0x33,0x30,0x3E,0x33,0x33,0x1E}, /* 6 */ + {0x3F,0x03,0x03,0x06,0x0C,0x0C,0x0C}, /* 7 */ + {0x1E,0x33,0x33,0x1E,0x33,0x33,0x1E}, /* 8 */ + {0x1E,0x33,0x33,0x1F,0x03,0x33,0x1E}, /* 9 */ +}; +static Q8 font_punctuation_codes[12]={45,43,46,58,47,62,60,63,94,40,41,38}; +static const Q8 font_punctuation[12][7]={ + {0x00,0x00,0x00,0x3F,0x00,0x00,0x00}, /* - */ + {0x00,0x0C,0x0C,0x3F,0x0C,0x0C,0x00}, /* + */ + {0x00,0x00,0x00,0x00,0x00,0x0C,0x0C}, /* . */ + {0x00,0x0C,0x0C,0x00,0x0C,0x0C,0x00}, /* : */ + {0x03,0x03,0x06,0x0C,0x18,0x30,0x30}, /* / */ + {0x30,0x18,0x0C,0x06,0x0C,0x18,0x30}, /* > */ + {0x03,0x06,0x0C,0x18,0x0C,0x06,0x03}, /* < */ + {0x1E,0x33,0x03,0x06,0x0C,0x00,0x0C}, /* ? */ + {0x0C,0x1E,0x3F,0x0C,0x0C,0x0C,0x0C}, /* ^ */ + {0x03,0x06,0x0C,0x0C,0x0C,0x06,0x03}, /* ( */ + {0x30,0x18,0x0C,0x0C,0x0C,0x18,0x30}, /* ) */ + {0x1C,0x36,0x30,0x18,0x3C,0x36,0x1B}, /* & */ +}; +#endif diff --git a/src/platform/video.c b/src/platform/video.c new file mode 100644 index 0000000..73c297a --- /dev/null +++ b/src/platform/video.c @@ -0,0 +1,217 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#include +#include "video.h" +#include "coco3_video.h" +static Q8 style, grid; +typedef struct {Q8 tiles[9][32],old_cells[200];} GameBuffers; +static union {GameBuffers game;Q8 menu[512];} buffers; +#define tiles buffers.game.tiles +#define old_cells buffers.game.old_cells +static Q8 menu_mode; +#include "pierre_font.h" +Q16 video_worst_ticks; + +static void palette_setup(void) +{ + static const Q8 colors[11]={0,48,12,7,42,60,35,52,63,1,21}; + Q8 i,c;rgb(); + for(i=0;i<11;++i){c=colors[i];paletteRGB(i,c>>4,(c>>2)&3,c&3);} +} + +static const Q8 *glyph(Q8 c) +{ + Q8 i; + if(c>='a'&&c<='z')c-=32; + if(c>='A'&&c<='Z')return font_letters[c-'A']; + if(c>='0'&&c<='9')return font_digits[c-'0']; + for(i=0;i<12;++i)if(c==font_punctuation_codes[i])return font_punctuation[i]; + return 0; +} + +static void make_tile(Q8 c,Q8 *tile) +{ + Q8 x,y,color; + for(y=0;y<8;++y)for(x=0;x<8;++x){ + color=c; + if(!c)color=grid&&(x==0||y==0)?9:0; + else if(c==8)color=((x==0||x==7||y==0||y==7)&&((x+y)&1))?4:0; + else if(style==1&&(x==0||x==7||y==0||y==7))color=10; + else if(style==2&&(x==0||y==0))color=8; + if(!(x&1))tile[y*4+x/2]=color<<4;else tile[y*4+x/2]|=color; + } +} + +Q8 *video_menu_buffer(void){menu_mode=1;return buffers.menu;} + +void video_style(Q8 requested_style,Q8 requested_grid) +{ + Q8 c;style=requested_style;grid=requested_grid; + if(menu_mode)return; + for(c=0;c<9;++c)make_tile(c,tiles[c]); + memset(old_cells,255,sizeof(old_cells)); +} + +Q8 video_open(Q8 coco3) +{ + if(!coco3||!hscreen(2))return 0; + enableInterrupts(); + palette_setup();video_style(1,0);return 1; +} + +void video_close(void) +{ + hscreen(0);resetPalette(TRUE);width(32); + setHighSpeed(FALSE); +} + +void video_clear(void) +{ + /* Keep ROM graphics initialization at startup; clear only our framebuffer. */ + c3_fill(0,0,320,192,0); + if(!menu_mode)memset(old_cells,255,sizeof(old_cells)); +} + +static void packed_plot(Q16 x,Q8 y,Q16 width,Q8 height,const Q8 *data) +{ + Q8 row;Q16 col; +#ifndef QUAD_API_FALLBACK + if(c3_blit(x,y,width,height,data))return; +#endif + for(row=0;row>((col&1)?0:4))&15); +} + +static void character(Q16 x,Q8 y,const Q8 *shape) +{ + static Q8 pairs[4]={0,8,0x80,0x88}; + Q8 packed[32],row,bits,*out=packed; + memset(packed,0,sizeof(packed)); + if(shape)for(row=0;row<7;++row){ + bits=shape[row]; + out[1]=pairs[bits>>4];out[2]=pairs[(bits>>2)&3];out[3]=pairs[bits&3]; + out+=4; + } + packed_plot(x,y,8,8,packed); +} + +void video_text(Q8 col,Q8 row,const char *text) +{ + Q16 x=(Q16)col*8+32; + if(row>=24)return; + while(*text&&col<32){character(x,row*8,glyph(*text++));x+=8;++col;} +} + +void video_big_title(void) +{ + /* Original 5x7 word data, 84 bytes; two drawing passes add a blue shadow. */ + static const Q8 word_rows[12][7]={ + {14,17,17,17,21,18,13},{17,17,17,17,17,17,14}, + {14,17,17,31,17,17,17},{30,17,17,17,17,17,30}, + {30,17,17,30,20,18,17},{14,17,17,31,17,17,17}, + {30,17,17,30,16,16,16},{14,17,17,31,17,17,17}, + {15,16,16,14,1,1,30},{15,16,16,14,1,1,30}, + {31,16,16,30,16,16,31},{16,16,16,16,16,16,31} + }; + Q8 scan[108],line,pass,i,col,dx,gy,color,px; + for(line=0;line<24;++line){ + memset(scan,0,sizeof(scan)); + for(pass=0;pass<2;++pass){ + if((!pass&&line<3)||(pass&&line>=21))continue; + gy=(line-(pass?0:3))/3; + if(gy>=7)continue; + color=pass?(gy<2?8:gy<5?5:7):3; + for(i=0;i<12;++i)for(col=0;col<5;++col)if(word_rows[i][gy]&(16>>col)) + for(dx=0;dx<3;++dx){ + px=i*18+col*3+dx+(pass?0:2); + if(px&1)scan[px/2]=(scan[px/2]&0xF0)|color; + else scan[px/2]=(scan[px/2]&15)|(color<<4); + } + } + packed_plot(52,48+line,216,1,scan); + } + video_text(12,9,"FOR COCO"); +} + +void video_cell(Q8 x,Q8 y,Q8 value) +{ + if(value>8||x>248||y>184)return; + if(menu_mode){Q8 tile[32];make_tile(value,tile);packed_plot(x+32,y,8,8,tile);} + else packed_plot(x+32,y,8,8,tiles[value]); +} + +void video_piece(Q8 x,Q8 y,Q8 type,Q8 rotation) +{ + Q8 row,col; + for(row=0;row<4;++row)for(col=0;col<4;++col) + video_cell(x+col*8,y+row*8,q_occupied(type,rotation,col,row)?type+1:0); +} + +static void compose(Q8 *cells,const QPiece *p,Q8 value) +{ + Q8 row,col;int x,y; + for(row=0;row<4;++row)for(col=0;col<4;++col)if(q_occupied(p->type,p->rotation,col,row)){ + x=(int)p->x+col;y=(int)p->y+row; + if(x>=0&&x<10&&y>=0&&y<20)cells[y*10+x]=value; + } +} + +void video_number(Q8 col,Q8 row,Q32 n) +{ + char text[11];Q8 i=10; + text[i]=0; + do{ text[--i]=(char)('0'+n%10);n/=10;}while(n); + video_text(col,row,text+i); +} + +void video_game(const QGame *g,Q8 shadow,Q8 force) +{ + Q8 cells[200],x,y; + Q16 start=getTimer(),elapsed; + QPiece ghost; + if(force&1){ + menu_mode=0;video_style(style,grid); + video_clear(); + c3_fill(118,22,84,2,4);c3_fill(118,184,84,2,4); + c3_fill(118,24,2,160,4);c3_fill(200,24,2,160,4); + video_text(0,0,"QUADRAPASSEL FOR COCO"); + video_text(0,4,"SCORE");video_text(0,8,"LEVEL");video_text(0,12,"LINES"); + video_text(23,3,"NEXT");video_text(23,10,"HOLD"); + video_text(0,18,g->options.scoring==Q_CLASSIC?"CLASSIC":"MODERN"); + video_text(0,21,"P ACTIONS"); + } + memcpy(cells,&g->board,sizeof(cells)); + if(shadow&&!g->over){ghost=q_shadow(g);compose(cells,&ghost,8);} + if(!g->over)compose(cells,&g->active,g->active.type+1); + for(y=0;y<20;++y)for(x=0;x<10;++x) + if(cells[y*10+x]!=old_cells[y*10+x]){ + video_cell(88+x*8,24+y*8,cells[y*10+x]);old_cells[y*10+x]=cells[y*10+x]; + } + /* Only update numeric/preview fields after a lock, hold, or full refresh. */ + if(force&3){ + video_number(0,5,g->score);video_number(0,9,g->level);video_number(0,13,g->lines); + video_piece(184,40,g->next.type,g->next.rotation); + video_piece(184,96,g->held,0); + video_text(23,17,g->hold_used?"USED":" "); + } + if(g->over)video_text(10,11,"GAME OVER"); + elapsed=(Q16)(getTimer()-start);if(elapsed>video_worst_ticks)video_worst_ticks=elapsed; +} + +static void title_piece(Q8 x,Q8 y,Q8 type,Q8 rotation) +{ + Q8 row,col; + for(row=0;row<4;++row)for(col=0;col<4;++col) + if(q_occupied(type,rotation,col,row))video_cell(x+col*8,y+row*8,type+1); +} + +void video_title_art(void) +{ + Q8 x,y,row[160]; + /* A dotted grid and an 84-byte word, never a stored full-screen bitmap. */ + for(x=0;x<160;++x)row[x]=(x&7)?0:0x90; + for(y=0;y<192;y+=16)packed_plot(0,y,320,1,row); + title_piece(0,8,0,2);title_piece(64,0,2,0); + title_piece(168,8,5,0);title_piece(224,8,1,0); + for(y=0;y<3;++y)for(x=0;x<8;++x) + if(x>2-y)video_cell(184+x*8,128+y*8,(x/2+y)%7+1); +} diff --git a/src/platform/video.h b/src/platform/video.h new file mode 100644 index 0000000..8679cfd --- /dev/null +++ b/src/platform/video.h @@ -0,0 +1,18 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#ifndef QUAD_VIDEO_H +#define QUAD_VIDEO_H +#include "rules.h" +Q8 video_open(Q8 coco3); +void video_close(void); +void video_clear(void); +void video_style(Q8 style,Q8 grid); +void video_text(Q8 col,Q8 row,const char *text); +void video_big_title(void); +void video_cell(Q8 x,Q8 y,Q8 value); +void video_piece(Q8 x,Q8 y,Q8 type,Q8 rotation); +void video_game(const QGame *game,Q8 shadow,Q8 force); +void video_title_art(void); +extern Q16 video_worst_ticks; +void video_number(Q8 col,Q8 row,Q32 n); +Q8 *video_menu_buffer(void); +#endif diff --git a/tests/include/coco.h b/tests/include/coco.h new file mode 100644 index 0000000..75f1ebb --- /dev/null +++ b/tests/include/coco.h @@ -0,0 +1,19 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#ifndef QUAD_TEST_COCO_H +#define QUAD_TEST_COCO_H +#include +typedef unsigned char byte; +typedef unsigned short word; +#define TRUE 1 +#define FALSE 0 +extern byte isCoCo3; +void rgb(void); +void paletteRGB(byte slot,byte r,byte g,byte b); +byte hscreen(byte mode); +void enableInterrupts(void); +void resetPalette(byte reset); +void width(byte columns); +void setHighSpeed(byte speed); +word getTimer(void); +byte hset(word x,word y,byte color); +#endif diff --git a/tests/input_test.c b/tests/input_test.c new file mode 100644 index 0000000..6c2912f --- /dev/null +++ b/tests/input_test.c @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#include +#include +#include "input.h" +static QInput s; +static QActions step(Q16 keys,Q8 button,Q8 x,Q8 y,Q16 ms,Q8 playing){return q_input_step(&s,keys,button,x,y,31,31,1,ms,playing,0);} +static void reset(void){q_input_reset(&s);step(0,0,31,31,0,1);} +int main(void){QActions a; + reset();a=step(Q_LEFT,0,31,31,0,1);assert(a.move==-1&&a.repeats==1); + a=step(Q_LEFT,0,31,31,199,1);assert(!a.repeats); + a=step(Q_LEFT,0,31,31,1,1);assert(a.move==-1&&a.repeats==1); + a=step(Q_LEFT,0,31,31,39,1);assert(!a.repeats); + a=step(Q_LEFT|Q_RIGHT,0,31,31,1,1);assert(a.move==-1&&a.repeats==1); + a=step(Q_RIGHT,0,31,31,1,1);assert(a.move==1&&a.repeats==1); + reset();a=step(Q_CCW,0,31,31,1,1);assert(a.pressed&Q_CCW); + a=step(Q_CCW,0,31,31,500,1);assert(!(a.pressed&Q_CCW)); + reset();step(0,1,31,31,100,1);a=step(0,0,31,31,1,1);assert(a.pressed&Q_CCW); + reset();step(0,1,31,31,399,1);a=step(0,1,31,31,1,1);assert(a.pressed&Q_PAUSE); + a=step(0,0,31,31,1,1);assert(!(a.pressed&Q_CCW)); + reset();a=step(0,0,31,10,1,1);assert(a.pressed&Q_HARD); + a=step(0,0,31,10,500,1);assert(!(a.pressed&Q_HARD)); + step(0,0,31,31,1,1);a=step(0,0,31,10,1,1);assert(a.pressed&Q_HARD); + reset();a=step(0,0,0,10,1,1);assert(!(a.pressed&Q_HARD)); + q_input_reset(&s);step(0,0,0,0,1,1);a=step(Q_LEFT,0,0,0,1,1);assert(a.move==-1); + reset();a=step(0,0,20,31,1,1);assert(a.move==-1); + a=step(0,0,24,31,1,1);assert(a.held&Q_LEFT); + a=step(0,0,25,31,1,1);assert(!(a.held&Q_LEFT)); + reset();step(0,1,31,31,100,0);a=step(0,0,31,31,1,0);assert(a.pressed&Q_CONFIRM); + puts("PASS: input repeat, conflicting directions, edges, one-button timing, hysteresis, diagonal guard, disconnected-stick keyboard");return 0;} diff --git a/tests/rules_test.c b/tests/rules_test.c new file mode 100644 index 0000000..f8b3b46 --- /dev/null +++ b/tests/rules_test.c @@ -0,0 +1,245 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#include +#include +#include +#include "rules.h" +#include "reference_cases.h" +static QOptions defaults = {0,Q_MODERN,0,1}; +static QGame game; + +static void pieces(void) +{ + unsigned t,r,x,y,n; + int minx,maxx,miny; + QPiece p; + QBoard empty = {{{0}}}; + for (t=0;t<7;++t) for (r=0;r<4;++r) { + assert(q_masks[t][r]==reference_masks[t][r]); + n=0;minx=miny=4;maxx=-1; + for (y=0;y<4;++y) for (x=0;x<4;++x) if (q_occupied(t,r,x,y)) { + ++n; + if ((int)xmaxx) maxx=x; + if ((int)ydifficulty;game.options.scoring=c->rule; + game.lines=c->prior;game.score=0; + q_score_clear(&game,c->rows,c->bottom); + assert(game.level==c->level && game.score==c->points); + } + game.options.difficulty=0; + game.score=Q_SCORE_MAX-5;game.lines=Q_SCORE_MAX-1; + q_score_clear(&game,4,1); + assert(game.lines==Q_SCORE_MAX && game.score==Q_SCORE_MAX && game.level==65535); + for(i=1;i<=100;++i) assert(q_gravity_ms(i)==reference_gravity[i-1]); +} + +/* Adapted from Brian Holman's GPL-3.0-or-later Mac test-scoring.vala: + * drop an actual vertical I piece through one-cell gaps in nearly full rows. + * This also checks bottom-row detection and level changes, not just arithmetic. + */ +static void scoring_through_drop(void) +{ + unsigned i,x;int y,bottom; + for(i=0;idifficulty;game.options.scoring=c->rule; + game.lines=c->prior;game.level=q_level(c->difficulty,c->prior); + bottom=c->bottom?19:18; + for(y=bottom-(int)c->rows+1;y<=bottom;++y) + for(x=0;x<10;++x)if(x!=4)game.board.cells[y][x]=1; + if(!c->bottom)game.board.cells[19][4]=1; + game.active=q_spawn(5,1);game.active.x=3;game.active.y=0; + assert(q_drop(&game)); + assert(game.last_clear==c->rows); + if(c->rows)assert(game.last_bottom==c->bottom); + assert(game.lines==c->prior+c->rows); + assert(game.level==c->level&&game.score==c->points); + } +} + +static void hold(void) +{ + QChoice preview; + Q8 original,held; + QRandom random; + q_start(&game,&defaults); + original=game.active.type;preview=game.next; + assert(q_hold(&game)); + assert(game.held==original && game.active.type==preview.type && game.active.rotation==0); + random=game.random;preview=game.next; + assert(!q_hold(&game));assert(memcmp(&random,&game.random,sizeof(random))==0); + assert(q_drop(&game));assert(!game.hold_used); + held=game.held;original=game.active.type;preview=game.next;random=game.random; + assert(q_hold(&game)); + assert(game.active.type==held && game.active.rotation==0 && game.held==original); + assert(memcmp(&preview,&game.next,sizeof(preview))==0); + assert(memcmp(&random,&game.random,sizeof(random))==0); + assert(!q_hold(&game)); +} + +static void randomness(void) +{ + QRandom a,b; + QOptions options=defaults; + QGame other; + unsigned i,j,x,y;unsigned selected[7]={0};Q16 lo,hi; + q_random_init(&a,1); + assert(q_random_next(&a)==270369UL); + assert(q_random_next(&a)==67634689UL); + assert(q_random_next(&a)==2647435461UL); + q_random_init(&a,0);q_random_init(&b,0); + for(i=0;i<100;++i)assert(q_weighted(&a)==q_weighted(&b)); + q_random_init(&a,1234567); + for(i=0;i<20000;++i)++selected[q_weighted(&a)]; + lo=hi=selected[0]; + for(i=0;i<7;++i){if(selected[i]hi)hi=selected[i];} + assert(hi-lo<20); + /* Fixed count vector: underrepresented types must be much likelier. */ + memset(selected,0,sizeof(selected));q_random_init(&a,0x12345678UL); + for(i=0;i<20000;++i){for(j=0;j<7;++j)a.counts[j]=0;a.counts[0]=10;++selected[q_weighted(&a)];} + assert(selected[0]>0 && selected[0]<100); + for(i=1;i<7;++i)assert(selected[i]>2500); + for(i=0;i<32;++i) for(j=0;j<=16;++j) { + options.seed=i;options.difficulty=(int)j-1; + q_start(&game,&options);q_start(&other,&options); + assert(memcmp(&game.board,&other.board,sizeof(game.board))==0); + assert(game.active.type==other.active.type && game.next.type==other.next.type); + for(y=0;y<20;++y){unsigned count=0;for(x=0;x<10;++x){assert(game.board.cells[y][x]<=7);count+=game.board.cells[y][x]!=0;}assert(count<10);} + } +} + +static void difficult(void) +{ + static const int empty_metric[7]={-20,-20,-20,-25,-25,-20,-20}; + QBoard b={{{0}}},before; + QRandom a,c; + QChoice choice,other; + unsigned i; + before=b; + for(i=0;i<7;++i)assert(q_best_metric(&b,i)==empty_metric[i]); + assert(memcmp(&b,&before,sizeof(b))==0); + for(i=0;i<10;++i)if(i<3||i>6)b.cells[19][i]=1; + before=b; + assert(q_best_metric(&b,5)==5000); + assert(memcmp(&b,&before,sizeof(b))==0); + q_random_init(&a,47);q_random_init(&c,47); + choice=q_difficult(&b,&a);other=q_difficult(&b,&c); + assert(choice.type<7 && choice.rotation<4); + assert(choice.type==other.type && choice.rotation==other.rotation); + assert(memcmp(&b,&before,sizeof(b))==0); + memset(&b,1,sizeof(b)); + for(i=0;i<7;++i)assert(q_best_metric(&b,i)==-30000L); +} + +int main(void) +{ + pieces();rotation_kicks();movement_and_lock();simultaneous_rows(); + scoring();scoring_through_drop();hold();randomness();difficult(); + printf("PASS: 28 states, all kicks, bounds/top-out, compaction, %u score fixtures plus actual-drop scoring, gravity, hold, RNG/prefill, difficult metrics\n",(unsigned)(sizeof(score_cases)/sizeof(score_cases[0]))); + return 0; +} diff --git a/tests/store_test.c b/tests/store_test.c new file mode 100644 index 0000000..6e87af3 --- /dev/null +++ b/tests/store_test.c @@ -0,0 +1,46 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#include +#include +#include +#include "store.h" +static unsigned char disks[2][35][256],backup[2][35][256],present[2],saved_present[2]; +static int write_count,fail_after=-1,read_only; +static Q8 open_file(Q8 s,Q8 write){assert(s<2);if(!present[s]){if(!write)return Q_STORE_MISSING;if(read_only)return Q_STORE_IO;present[s]=1;}return 0;} +static Q8 read_file(Q8 s,Q8 n,Q8 *p){assert(s<2&&n<35);memcpy(p,disks[s][n],256);return 0;} +static Q8 write_file(Q8 s,Q8 n,const Q8 *p){assert(s<2&&n<35);if(read_only)return Q_STORE_IO;if(write_count++==fail_after){memcpy(disks[s][n],p,127);return Q_STORE_IO;}memcpy(disks[s][n],p,256);return 0;} +static Q8 close_file(Q8 s){assert(s<2);return 0;} +static const QStoreIO ops={open_file,read_file,write_file,close_file}; +static QPreferences prefs,loaded; +static QScore table[10],restored[10]; +static void reload(void){q_preferences_default(&loaded);assert(q_store_load(&ops,&loaded)==0);} +static void recoverable_writes(void){int n;Q8 status; + memset(disks,0,sizeof(disks));memset(present,0,sizeof(present));q_preferences_default(&prefs);reload(); + memset(table,0,sizeof(table));assert(q_score_insert(table,100,"AAA",Q_MODERN));assert(!q_store_save(&prefs,0,table,0)); + memcpy(backup,disks,sizeof(disks));memcpy(saved_present,present,sizeof(present)); + for(n=0;n<=36;++n){ + memcpy(disks,backup,sizeof(disks));memcpy(present,saved_present,sizeof(present));fail_after=-1;reload(); + assert(!q_store_scores(0,table));assert(q_score_insert(table,200,"BBB",Q_CLASSIC));prefs.sound=0;write_count=0;fail_after=n; + status=q_store_save(&prefs,0,table,0);fail_after=-1; + q_preferences_default(&loaded);q_store_load(&ops,&loaded);assert(!q_store_scores(0,restored)); + if(n<36){assert(status);assert(loaded.sound==1&&restored[0].score==100);}else{assert(!status);assert(!loaded.sound&&restored[0].score==200);} + } + read_only=1;memcpy(backup,disks,sizeof(disks));prefs.sound=1;assert(q_store_save(&prefs,-1,0,1));assert(!memcmp(backup,disks,sizeof(disks)));read_only=0; +} +static void categories_and_ties(void){unsigned cat,i;Q8 result; + memset(disks,0,sizeof(disks));memset(present,0,sizeof(present));q_preferences_default(&prefs);reload();prefs.game.seed=0xDEADBEEFUL;prefs.custom_seed=1;prefs.game.difficulty=15; + for(cat=0;cat<34;++cat){ + memset(table,0,sizeof(table));assert(q_score_insert(table,40000+cat,"AAA",Q_MODERN));assert(q_score_insert(table,40000+cat,"BBB",Q_CLASSIC)); + for(i=0;i<9;++i)q_score_insert(table,10000-i,"CCC",Q_MODERN); + assert(!q_store_save(&prefs,(signed char)cat,table,0)); + } + reload();assert(loaded.game.seed==0xDEADBEEFUL&&loaded.custom_seed&&loaded.game.difficulty==15); + for(cat=0;cat<34;++cat){assert(!q_store_scores(cat,restored));assert(restored[0].score==40000+cat&&restored[0].initials[0]=='A'&&restored[1].initials[0]=='B');assert(restored[1].rule==Q_CLASSIC);for(i=1;i<10;++i)assert(restored[i-1].score>=restored[i].score);} + /* The most recent slot is 1 after 34 commits. Corrupt it, recover slot 0. */ + disks[1][0][12]^=1;q_preferences_default(&loaded);result=q_store_load(&ops,&loaded);assert(result==Q_STORE_RECOVERED); + assert(!q_store_scores(0,restored)&&restored[0].score==40000); + prefs.game.scoring=Q_CLASSIC;assert(!q_store_save(&prefs,-1,0,1));reload(); + for(cat=0;cat<34;++cat){assert(!q_store_scores(cat,restored));for(i=0;i<10;++i)assert(!restored[i].score);} + assert(q_score_category(-1,0)==0&&q_score_category(15,1)==33); + assert(q_store_crc((const Q8 *)"123456789",9)==0x29B1); +} +int main(void){recoverable_writes();categories_and_ties();puts("PASS: disk codec, all 34 score categories, stable ties/rule markers, 32-bit values, CRC, read-only reset, every torn-write boundary and recovery");return 0;} diff --git a/tests/video_test.c b/tests/video_test.c new file mode 100644 index 0000000..655e405 --- /dev/null +++ b/tests/video_test.c @@ -0,0 +1,68 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ +#include +#include +#include +#include "video.h" +#include "coco3_video.h" +#include "8-bit-wide-font.h" +static Q8 screen[192][320],colors[16][3]; +byte isCoCo3=1; +void rgb(void){} +void paletteRGB(byte i,byte r,byte g,byte b){assert(i<16);colors[i][0]=r;colors[i][1]=g;colors[i][2]=b;} +byte hscreen(byte mode){assert(mode<=2);memset(screen,0,sizeof(screen));return 1;} +void enableInterrupts(void){} +void resetPalette(byte reset){(void)reset;} +void width(byte cols){(void)cols;} +void setHighSpeed(byte speed){(void)speed;} +word getTimer(void){return 0;} +byte hset(word x,word y,byte color){assert(x<320&&y<192);screen[y][x]=color;return 1;} +byte c3_fill(word x,byte y,word w,byte h,byte color){word col;byte row;assert(x+w<=320&&y+h<=192);for(row=0;row>((col&1)?0:4))&15;return 1;} +static void check_letter(char c) +{ + char s[2];Q8 row,col,expected;int code=c; + s[0]=c;s[1]=0; + /* Render at the last legal cell to cover both screen boundaries. */ + memset(screen,11,sizeof(screen));video_text(31,23,s); + if(code>='a'&&code<='z')code-=32; + for(row=0;row<8;++row)for(col=0;col<8;++col){ + expected=0; + if(code!=32&&row<7&&(eightBitWideFont[code-32][row]&(0x80>>col)))expected=8; + assert(screen[184+row][280+col]==expected); + } + assert(screen[183][280]==11&&screen[191][288]==11); +} +static void write_ppm(const char *path) +{ + FILE *f=fopen(path,"wb");Q16 x,y;Q8 c,channel; + assert(f);fprintf(f,"P6\n320 192\n255\n"); + for(y=0;y<192;++y)for(x=0;x<320;++x){c=screen[y][x];for(channel=0;channel<3;++channel)fputc(colors[c][channel]*85,f);} + assert(!fclose(f)); +} +int main(int argc,char **argv) +{ + const char *p;Q8 x,y,expected,c; + static const Q8 expected_palette[11][3]={ + {0,0,0},{3,0,0},{0,3,0},{0,1,3},{2,2,2},{3,3,0}, + {2,0,3},{3,1,0},{3,3,3},{0,0,1},{1,1,1} + }; + assert(video_open(1)); + assert(!memcmp(colors,expected_palette,sizeof(expected_palette))); + for(p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+.:/>< ?^()&";*p;++p)check_letter(*p); + video_style(1,0);memset(screen,0,sizeof(screen)); + for(c=1;c<=7;++c){ + video_cell(0,0,c); + for(y=0;y<8;++y)for(x=0;x<8;++x){expected=(x==0||x==7||y==0||y==7)?10:c;assert(screen[y][32+x]==expected);} + } + assert(colors[10][0]==1&&colors[10][1]==1&&colors[10][2]==1); + assert(colors[0][0]==0&&colors[0][1]==0&&colors[0][2]==0); + video_style(0,0);video_cell(0,0,1);assert(screen[0][32]==1); + video_style(2,0);video_cell(0,0,1);assert(screen[0][32]==8&&screen[7][39]==1); + video_style(1,0);video_clear(); + video_text(1,1,"QUADRAPASSEL FOR COCO");video_text(1,4,"SCORE 0123456789"); + video_text(1,7,"LEVEL 1 LINES 0");video_text(1,10,"HOLD NEXT SETTINGS"); + video_text(1,13,"MW O0 I1 BRH CCW");video_text(5,21,"(c) 2026 Brian Holman"); + for(x=0;x<7;++x)video_cell(x*32,136,x+1); + if(argc>1)write_ppm(argv[1]); + puts("PASS: font matches Pierre's original row bytes, lowercase mapping, cell boundaries, dark-gray Modern borders, Plain/Clean styles and black background");return 0; +} diff --git a/third_party/cardgame-font/8-bit-wide-font.c b/third_party/cardgame-font/8-bit-wide-font.c new file mode 100644 index 0000000..6eba614 --- /dev/null +++ b/third_party/cardgame-font/8-bit-wide-font.c @@ -0,0 +1,81 @@ +/* 8-bit-wide-font.c - 8x8 font for the Color Computer + + By Pierre Sarrazin . + This file is in the public domain. + + Does not include glyphs from 94 to 127 (i.e., no lower case letters). + Size in memory: 434 bytes. + In the 8x8 grid, the two left-most columns are always empty, i.e., + the two highest bits in each byte are 0. +*/ + +#include "8-bit-wide-font.h" + + +const unsigned char eightBitWideFont[65][7] = { +{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }, // ( 32, 0x20) +{ 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x00, 0x0C, }, // ! ( 33, 0x21) +{ 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, }, // " ( 34, 0x22) +{ 0x1E, 0x1E, 0x1E, 0x3F, 0x1E, 0x1E, 0x1E, }, // # ( 35, 0x23) +{ 0x0C, 0x1E, 0x30, 0x3F, 0x03, 0x1E, 0x0C, }, // $ ( 36, 0x24) +{ 0x33, 0x33, 0x06, 0x0C, 0x18, 0x33, 0x33, }, // % ( 37, 0x25) +{ 0x1C, 0x36, 0x30, 0x18, 0x3C, 0x36, 0x1B, }, // & ( 38, 0x26) +{ 0x0C, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, }, // ' ( 39, 0x27) +{ 0x03, 0x06, 0x0C, 0x0C, 0x0C, 0x06, 0x03, }, // ( ( 40, 0x28) +{ 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x18, 0x30, }, // ) ( 41, 0x29) +{ 0x00, 0x0C, 0x1E, 0x3F, 0x1E, 0x0C, 0x00, }, // * ( 42, 0x2A) +{ 0x00, 0x0C, 0x0C, 0x3F, 0x0C, 0x0C, 0x00, }, // + ( 43, 0x2B) +{ 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x18, }, // , ( 44, 0x2C) +{ 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, }, // - ( 45, 0x2D) +{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, }, // . ( 46, 0x2E) +{ 0x03, 0x03, 0x06, 0x0C, 0x18, 0x30, 0x30, }, // / ( 47, 0x2F) +{ 0x1E, 0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, }, // 0 ( 48, 0x30) +{ 0x1C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, }, // 1 ( 49, 0x31) +{ 0x1E, 0x33, 0x03, 0x06, 0x0C, 0x18, 0x3F, }, // 2 ( 50, 0x32) +{ 0x1E, 0x33, 0x03, 0x0E, 0x03, 0x33, 0x1E, }, // 3 ( 51, 0x33) +{ 0x33, 0x33, 0x33, 0x3F, 0x03, 0x03, 0x03, }, // 4 ( 52, 0x34) +{ 0x3F, 0x30, 0x30, 0x3E, 0x03, 0x03, 0x3E, }, // 5 ( 53, 0x35) +{ 0x1E, 0x33, 0x30, 0x3E, 0x33, 0x33, 0x1E, }, // 6 ( 54, 0x36) +{ 0x3F, 0x03, 0x03, 0x06, 0x0C, 0x0C, 0x0C, }, // 7 ( 55, 0x37) +{ 0x1E, 0x33, 0x33, 0x1E, 0x33, 0x33, 0x1E, }, // 8 ( 56, 0x38) +{ 0x1E, 0x33, 0x33, 0x1F, 0x03, 0x33, 0x1E, }, // 9 ( 57, 0x39) +{ 0x00, 0x0C, 0x0C, 0x00, 0x0C, 0x0C, 0x00, }, // : ( 58, 0x3A) +{ 0x00, 0x0C, 0x0C, 0x00, 0x0C, 0x0C, 0x18, }, // ; ( 59, 0x3B) +{ 0x03, 0x06, 0x0C, 0x18, 0x0C, 0x06, 0x03, }, // < ( 60, 0x3C) +{ 0x00, 0x00, 0x3F, 0x00, 0x3F, 0x00, 0x00, }, // = ( 61, 0x3D) +{ 0x30, 0x18, 0x0C, 0x06, 0x0C, 0x18, 0x30, }, // > ( 62, 0x3E) +{ 0x1E, 0x33, 0x03, 0x06, 0x0C, 0x00, 0x0C, }, // ? ( 63, 0x3F) +{ 0x1E, 0x33, 0x03, 0x1F, 0x33, 0x33, 0x1E, }, // @ ( 64, 0x40) +{ 0x1E, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x33, }, // A ( 65, 0x41) +{ 0x3E, 0x33, 0x33, 0x3E, 0x33, 0x33, 0x3E, }, // B ( 66, 0x42) +{ 0x1E, 0x33, 0x30, 0x30, 0x30, 0x33, 0x1E, }, // C ( 67, 0x43) +{ 0x3E, 0x33, 0x33, 0x33, 0x33, 0x33, 0x3E, }, // D ( 68, 0x44) +{ 0x3F, 0x30, 0x30, 0x3C, 0x30, 0x30, 0x3F, }, // E ( 69, 0x45) +{ 0x3F, 0x30, 0x30, 0x3C, 0x30, 0x30, 0x30, }, // F ( 70, 0x46) +{ 0x1F, 0x30, 0x30, 0x33, 0x33, 0x33, 0x1F, }, // G ( 71, 0x47) +{ 0x33, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x33, }, // H ( 72, 0x48) +{ 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, }, // I ( 73, 0x49) +{ 0x03, 0x03, 0x03, 0x03, 0x03, 0x33, 0x1E, }, // J ( 74, 0x4A) +{ 0x33, 0x33, 0x36, 0x3C, 0x36, 0x33, 0x33, }, // K ( 75, 0x4B) +{ 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x3F, }, // L ( 76, 0x4C) +{ 0x33, 0x3F, 0x3F, 0x3F, 0x33, 0x33, 0x33, }, // M ( 77, 0x4D) +{ 0x33, 0x33, 0x3B, 0x3F, 0x37, 0x33, 0x33, }, // N ( 78, 0x4E) +{ 0x1E, 0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, }, // O ( 79, 0x4F) +{ 0x3E, 0x33, 0x33, 0x3E, 0x30, 0x30, 0x30, }, // P ( 80, 0x50) +{ 0x1E, 0x33, 0x33, 0x33, 0x33, 0x36, 0x1F, }, // Q ( 81, 0x51) +{ 0x3E, 0x33, 0x33, 0x3E, 0x3C, 0x36, 0x33, }, // R ( 82, 0x52) +{ 0x1E, 0x33, 0x30, 0x0C, 0x03, 0x33, 0x1E, }, // S ( 83, 0x53) +{ 0x3F, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, }, // T ( 84, 0x54) +{ 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, }, // U ( 85, 0x55) +{ 0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, 0x0C, }, // V ( 86, 0x56) +{ 0x33, 0x33, 0x33, 0x3F, 0x3F, 0x3F, 0x33, }, // W ( 87, 0x57) +{ 0x33, 0x33, 0x1E, 0x0C, 0x1E, 0x33, 0x33, }, // X ( 88, 0x58) +{ 0x33, 0x33, 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, }, // Y ( 89, 0x59) +{ 0x3F, 0x03, 0x06, 0x0C, 0x18, 0x30, 0x3F, }, // Z ( 90, 0x5A) +{ 0x0F, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0F, }, // [ ( 91, 0x5B) +{ 0x30, 0x30, 0x18, 0x0C, 0x06, 0x03, 0x03, }, // \ ( 92, 0x5C) +{ 0x3C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x3C, }, // ] ( 93, 0x5D) +{ 0x0C, 0x1E, 0x3F, 0x0C, 0x0C, 0x0C, 0x0C, }, // ^ ( 94, 0x5E) +{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, }, // _ ( 95, 0x5F) +{ 0x30, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, }, // ` ( 96, 0x60) +}; diff --git a/third_party/cardgame-font/8-bit-wide-font.h b/third_party/cardgame-font/8-bit-wide-font.h new file mode 100644 index 0000000..b945fb3 --- /dev/null +++ b/third_party/cardgame-font/8-bit-wide-font.h @@ -0,0 +1,12 @@ +/* 8-bit-wide-font.h - 8x8 font for the Color Computer + + By Pierre Sarrazin . + This file is in the public domain. +*/ + +#ifndef _8_bit_wide_font_h +#define _8_bit_wide_font_h + +extern const unsigned char eightBitWideFont[65][7]; + +#endif /* _8_bit_wide_font_h */ diff --git a/third_party/cardgame-font/README.md b/third_party/cardgame-font/README.md new file mode 100644 index 0000000..faffd79 --- /dev/null +++ b/third_party/cardgame-font/README.md @@ -0,0 +1,11 @@ +# Pierre Sarrazin's bitmap font + +Unmodified font-only source files from the permitted local CardGame 0.1.15 +reference, by Pierre Sarrazin . Both files explicitly state +that they are in the public domain. The original notices are retained. + +The complete snapshot is kept as an independent rendering-test reference. +The game's pierre_font.h contains the supported letters, digits and punctuation +with unchanged row bytes, split between code/constants and existing static data +space to respect the CoCo 3 memory bounds. The game does not build or copy the +CardGame assembly drawing routine. See manifest.json for observed source hashes. diff --git a/third_party/cardgame-font/manifest.json b/third_party/cardgame-font/manifest.json new file mode 100644 index 0000000..556b288 --- /dev/null +++ b/third_party/cardgame-font/manifest.json @@ -0,0 +1,9 @@ +{ + "upstream": "Pierre Sarrazin CardGame 0.1.15", + "source_url": "http://sarrazip.com/dev/cardgame-0.1.15.tar.gz", + "license": "Public domain, per original file headers", + "files": { + "8-bit-wide-font.c": "2d58b3d966785d9fb8c34e9410ae62ded698fc7327987ae2d170fefcdb8feae3", + "8-bit-wide-font.h": "1dc3a31c5dc77481e3c63cbb233eb5861def8a1977b34d911f6e6099092acfd0" + } +} diff --git a/tools/build_ui.pl b/tools/build_ui.pl new file mode 100644 index 0000000..99c5a51 --- /dev/null +++ b/tools/build_ui.pl @@ -0,0 +1,23 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# Build bounded, independently checked 512-byte menu text pages. +use strict; +use warnings; +my ($source,$target)=@ARGV; +open my $in,'<',$source or die "$source: $!"; +my @pages=map { [] } 0..11; +while(<$in>){chomp;next if /^#/ || /^$/;my ($scene,$id,$text)=split /\t/,$_,3; + die "invalid text record" unless defined($text) && $scene=~/^\d+$/ && $scene<12 && $id=~/^\d+$/ && $id>0 && $id<256 && $text=~/^[ -~]*$/; + push @{$pages[$scene]},[$id,$text]; +} +close $in; +open my $out,'>:raw',$target or die "$target: $!"; +for my $scene (0..11){ + my @entries=@{$pages[$scene]};my $offset=8+3*@entries; + my $head=pack('a4CCCC','QPTX',$scene,scalar(@entries),1,0);my $strings=''; + for(@entries){$head.=pack('Cn',$_->[0],$offset);$strings.=$_->[1]."\0";$offset+=length($_->[1])+1;} + die "menu page exceeds 510 bytes" if $offset>510; + my $data=$head.$strings.("\0" x (510-$offset));my $crc=0xFFFF; + for my $byte(unpack('C*',$data)){$crc^=$byte<<8;for(1..8){$crc=(($crc&0x8000)?(($crc<<1)^0x1021):($crc<<1))&65535;}} + print {$out} $data,pack('n',$crc); +} +close $out or die "$target: $!"; diff --git a/tools/check_audio.py b/tools/check_audio.py new file mode 100644 index 0000000..80ab696 --- /dev/null +++ b/tools/check_audio.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-or-later +"""Check direct MCP PCM16 WAV captures for digital silence or a bounded effect.""" +import argparse +import array +import json +import sys +import wave + + +def measure(path, tail_ms=500): + with wave.open(str(path), 'rb') as wav: + if wav.getsampwidth() != 2 or wav.getcomptype() != 'NONE': + raise ValueError('Expected uncompressed PCM16 WAV') + channels = wav.getnchannels() + rate = wav.getframerate() + frames = wav.getnframes() + samples = array.array('h', wav.readframes(frames)) + if sys.byteorder != 'little': + samples.byteswap() + if not frames or channels < 1 or len(samples) != frames * channels: + raise ValueError('Empty or incomplete WAV') + separate = [samples[channel::channels] for channel in range(channels)] + tail_frames = min(frames, max(1, rate * tail_ms // 1000)) + return { + 'sample_rate': rate, + 'channels': channels, + 'sample_frames': frames, + 'peak_per_channel': [max(abs(n) for n in channel) for channel in separate], + 'changing_edges_per_channel': [ + sum(channel[i] != channel[i - 1] for i in range(1, frames)) + for channel in separate + ], + 'nonzero_frames': sum( + any(samples[i * channels + channel] for channel in range(channels)) + for i in range(frames) + ), + 'tail_ms': tail_ms, + 'tail_peak': max(abs(n) for n in samples[-tail_frames * channels:]), + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('wav') + parser.add_argument('--expect', choices=('silent', 'effect'), required=True) + parser.add_argument('--tail-ms', type=int, default=500) + args = parser.parse_args() + if args.tail_ms <= 0: + parser.error('--tail-ms must be positive') + result = measure(args.wav, args.tail_ms) + if args.expect == 'silent': + passed = result['nonzero_frames'] == 0 + else: + passed = (result['nonzero_frames'] > 0 + and max(result['changing_edges_per_channel']) >= 2 + and result['tail_peak'] == 0) + print(json.dumps({'passed': passed, 'expect': args.expect, **result})) + return 0 if passed else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/check_memory.pl b/tools/check_memory.pl new file mode 100644 index 0000000..058727c --- /dev/null +++ b/tools/check_memory.pl @@ -0,0 +1,20 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# CMOC --limit checks program_end (data end for split layouts). Check ALL ranges. +use strict; +use warnings; +open my $map,'<',$ARGV[0] or die "$ARGV[0]: $!"; +my ($code_end,$data_end)=(0,0); +while(<$map>){ + next unless /^Section: (\S+) \([^)]*\) load at ([0-9A-F]+), length ([0-9A-F]+)/; + my ($section,$start,$length)=($1,hex($2),hex($3));next unless $length; + my $end=$start+$length; + if($section eq 'bss'||$section eq 'rwdata'){ + die "Static data outside 0E00..13FF" if $start<0x0E00||$end>0x1400; + $data_end=$end if $end>$data_end; + }else{ + die "Code/read-only data outside 1400..7AFF ($section ends at ".sprintf('%04X',$end).")" if $start<0x1400||$end>0x7B00; + $code_end=$end if $end>$code_end; + } +} +die "Missing link-map sections" unless $code_end&&$data_end; +printf "Memory bounds: code/const end %04X; static data end %04X; stack reserve 1024 bytes.\n",$code_end,$data_end; diff --git a/tools/test_components.py b/tools/test_components.py new file mode 100644 index 0000000..afcd4c0 --- /dev/null +++ b/tools/test_components.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-or-later +"""Host-only input/persistence regression suites; CoCo qualification is separate.""" +import subprocess +from pathlib import Path +root=Path(__file__).resolve().parents[1] +out=root/'test-output/components' +out.mkdir(parents=True,exist_ok=True) +for name in ['input','store']: + exe=out/(name+'_test') + subprocess.run(['clang','-std=c89','-Wall','-Wextra','-Werror','-pedantic', + '-fsanitize=address,undefined','-DQUAD_HOST','-I'+str(root/'src/game'), + str(root/'tests'/(name+'_test.c')),str(root/'src/game'/(name+'.c')), + '-o',str(exe)],check=True) + subprocess.run([str(exe)],check=True) diff --git a/tools/test_rules.py b/tools/test_rules.py new file mode 100644 index 0000000..2c8f826 --- /dev/null +++ b/tools/test_rules.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-or-later +"""Host regression tests against the repository's authoritative JSON fixtures. +These complement, and never claim to replace, CMOC/CoCo execution. +""" +import json +import math +import subprocess +from pathlib import Path +root = Path(__file__).resolve().parents[1] +out = root / 'test-output' / 'rules' +out.mkdir(parents=True, exist_ok=True) +pieces = json.loads((root / 'docs/reference/pieces.json').read_text())['pieces'] +cases = json.loads((root / 'docs/reference/scoring.json').read_text())['cases'] +lines = ['/* Generated from committed specification fixtures for this test only. */', + 'static const Q16 reference_masks[7][4] = {'] +for piece in pieces: + masks = [] + for rotation in piece['rotations']: + mask = int(''.join(rotation['rows']).replace('.', '0').replace('#', '1'), 2) + assert mask == int(rotation['mask_hex'], 16) + masks.append('0x%04X' % mask) + lines.append('{' + ','.join(masks) + '},') +lines += ['};', 'typedef struct { int rule,difficulty; Q32 prior; int rows,bottom,level; Q32 points; } ScoreCase;', + 'static const ScoreCase score_cases[] = {'] +for c in cases: + lines.append('{%d,%d,%dUL,%d,%d,%d,%dUL},' % ( + c['rule'] == 'Classic', c['difficulty'], c['prior_lines'], c['rows_cleared'], + c['includes_bottom'], c['expected_level'], c['expected_delta'])) +lines += ['};', 'static const Q16 reference_gravity[100] = {', + ','.join(str(math.floor(80 + 800 * .75 ** i + .5)) for i in range(100)), '};'] +(out / 'reference_cases.h').write_text('\n'.join(lines) + '\n') +subprocess.run(['clang', '-std=c89', '-Wall', '-Wextra', '-Werror', '-pedantic', + '-fsanitize=address,undefined', '-g', '-DQUAD_HOST', + '-I'+str(root/'src/game'), '-I'+str(out), + str(root/'tests/rules_test.c'), str(root/'src/game/rules.c'), + '-o', str(out/'rules_test')], check=True) +subprocess.run([str(out/'rules_test')], check=True) diff --git a/tools/test_video.py b/tools/test_video.py new file mode 100644 index 0000000..6daa73e --- /dev/null +++ b/tools/test_video.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-or-later +"""Compare the real C renderer with the unmodified upstream public-domain font.""" +import subprocess +from pathlib import Path +root=Path(__file__).resolve().parents[1] +out=root/'test-output/font' +out.mkdir(parents=True,exist_ok=True) +exe=out/'video_test' +subprocess.run(['clang','-std=c99','-Wall','-Wextra','-Werror','-pedantic', + '-fsanitize=address,undefined','-DQUAD_HOST', + *['-I'+str(root/p) for p in ['tests/include','src/game','src/platform','third_party/cardgame-font']], + *[str(root/p) for p in ['tests/video_test.c','src/platform/video.c','src/game/rules.c','third_party/cardgame-font/8-bit-wide-font.c']], + '-o',str(exe)],check=True) +subprocess.run([str(exe),str(out/'font-and-borders.ppm')],check=True) diff --git a/vccplus-project.json b/vccplus-project.json new file mode 100644 index 0000000..288ac20 --- /dev/null +++ b/vccplus-project.json @@ -0,0 +1,108 @@ +{ + "binary": "QUAD.bin", + "buildTarget": "disk", + "cleanTarget": "clean", + "configurations": [ + { + "makeArguments": [], + "name": "Debug" + }, + { + "makeArguments": [ + "VCC_CONFIGURATION=Release" + ], + "name": "Release" + }, + { + "name": "Probe", + "makeArguments": [ + "VCC_CONFIGURATION=Release", + "VCC_PROBE=1" + ] + } + ], + "diskImage": "Quadrapassel.DSK", + "diskTarget": "disk", + "entrySource": "main.c", + "jobs": 4, + "launchCommands": [ + "DOS" + ], + "launchMode": "disk", + "makefile": "Makefile", + "makefileSettings": { + "compilerOptions": [ + "--no-relocate", + "--switch=jump" + ], + "defines": [], + "diskBootMode": "program", + "diskFiles": [ + "generated/WORDS.DAT", + "generated/QPTEXT.DAT" + ], + "diskImage": "Quadrapassel.DSK", + "executable": "QUAD.bin", + "generatedResources": [ + { + "command": "$(PERL) src/APIProbe/tools/build-data.pl src/APIProbe/assets/words.txt generated/word-count.c generated/WORDS.DAT", + "inputs": [ + "src/APIProbe/tools/build-data.pl", + "src/APIProbe/assets/words.txt" + ], + "outputs": [ + "generated/word-count.c", + "generated/WORDS.DAT" + ] + }, + { + "command": "$(PERL) tools/build_ui.pl assets/ui-text.tsv generated/QPTEXT.DAT", + "inputs": [ + "assets/ui-text.tsv", + "tools/build_ui.pl" + ], + "outputs": [ + "generated/QPTEXT.DAT" + ] + } + ], + "includePaths": [ + "src/game", + "src/platform", + "src/APIProbe/include" + ], + "libraries": [ + "cardgame", + "bsound", + "decbfile" + ], + "libraryPaths": [], + "libraryProjects": [], + "linkerOptions": [ + "--data=0E00", + "--limit=7B00", + "--stack-space=1024", + "--no-relocate" + ], + "origin": "1400", + "releaseOptimization": "-O2", + "sources": [ + "main.c", + "src/game/rules.c", + "src/game/input.c", + "src/platform/coco3_video.c", + "src/platform/video.c", + "src/game/store.c", + "src/platform/disk_store.c" + ], + "stackSpace": 1024 + }, + "outputDirectories": [ + "obj", + "generated", + "test-output", + "build", + "docs/screenshots", + "local-media-backups" + ] +}