Quellcode durchsuchen

M4.1: terrain all over the world (random mix per world, bridges)

Region generator with a per-world terrain mix: jittered seeds on a grid,
noisy nearest-seed regions, smoothing, thin-water removal, shores and
trees; the road grid crosses water on new bridge tiles. The scroll
rebuild skips cells whose tile is already drawn, keeping rebuilds within
8 frames with textured terrain everywhere (chunk cutoffs 224/234).
check-world checks the new rules over N VICE runs; check-keys and
check-scroll allow for the slower start-up. Spec R1.5/R1.6, M4, MT4.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
main
Daniel Covington vor 2 Tagen
Ursprung
Commit
75b9f4677d
11 geänderte Dateien mit 980 neuen und 212 gelöschten Zeilen
  1. +32
    -0
      docs/manual-tests.md
  2. +12
    -0
      docs/milestones.md
  3. +8
    -5
      docs/spec.md
  4. +8
    -0
      docs/verification-status.md
  5. +54
    -6
      project.json
  6. +62
    -7
      src/scroll.inc
  7. +9
    -0
      src/tiles.inc
  8. +563
    -144
      src/world.inc
  9. +1
    -1
      tools/check-keys.ps1
  10. +5
    -5
      tools/check-scroll.ps1
  11. +226
    -44
      tools/check-world.ps1

+ 32
- 0
docs/manual-tests.md Datei anzeigen

@@ -233,6 +233,38 @@ Expected:

Verifies: R6 (and the R1 view size)

## M4 - Terrain all over the world

### MT4.1: Terrain everywhere, a different mix per world (c64)

Setup: VICE x64sc, NTSC (-ntsc), pepto-pal palette (tools/run.ps1 selects it), warp off.
Start: `pwsh -File tools/run.ps1 -Target c64`

Automated first: `pwsh -File tools/check-world.ps1 -Runs 10` should end with
`[PASS] the terrain mix varies between worlds ...` and `[PASS] 10 world(s) checked.`
(add `-ShowMap` to print each world as a character map: `.` land, `g` grass, `T` trees,
`#` stone, `~` water, roads `-` `|` with `+` crossings, bridges `=` `!` with `*` crossings).

Steps:
1. Wait for the map (the generating message shows for about 4 seconds). Look at the first view.
2. Scroll over the whole world: right to the edge, down, left, and up again.
3. Tap SPACE five or six times, waiting for each new map, and compare the first views.
4. In one world, scroll along a road that crosses a lake, and watch the dots near water and stone for a minute.
5. Scroll left, right, up and down across busy terrain.

Expected:
- Every view shows a mixture of terrain: open light brown land, green meadows with trees, grey rock
outcrops and blue lakes with shores, spread over the whole world, not one big lake or a few patches.
- Each new world has a different mix: some clearly wetter, rockier or greener than others.
- Black roads (two across, two down) run the full width and height of the world; where one crosses
water it continues as a bridge (black over blue), with no gap.
- No colour clash, no stray pixels at shores, bridges or crossings.
- Dots walk on land, grass, trees, roads and bridges, and never step onto water or stone.
- Scrolling stays smooth over textured terrain (no regular stutter at each cell step). A short
hesitation when a scroll starts from rest is acceptable, as before.

Verifies: R1 (R1.2-R1.6), R2.3, R5.1

## Real hardware

Optional for this release. Use these steps when hardware is available.


+ 12
- 0
docs/milestones.md Datei anzeigen

@@ -56,3 +56,15 @@ Requirements: R5, R6, R3, R2
| M3.4 | Check that people stay aligned with the terrain over long scrolling runs; measure the frame budget with a border-colour timing bar. | R2, R3, R5, R6 | People stay aligned with terrain over long runs; budget measured | Manual tests MT3.2, MT3.3 and MT3.4 |

Manual verification: see docs/manual-tests.md section M3.

## M4 - Terrain all over the world

Goal: Lakes, meadows with trees, rocky outcrops and open land are spread over the whole world, in a different mix for each world, with roads crossing water on bridges.

Requirements: R1, R2, R5

| Task | Description | Requirements | Buildable outcome | Completion check |
|---|---|---|---|---|
| M4.1 | Region generator: each world rolls its own terrain mix; jittered seeds on a grid give every class areas all over the world, shaped by noisy distances, smoothing and removal of thin water; shores from the neighbours; trees on grass. Roads stay a grid of two rows and two columns and become bridges over water. The scroll rebuild skips cells whose tile is already drawn, to keep the 8-frame rebuild with textured terrain everywhere. | R1, R2, R5 | Varied terrain in every view; SPACE gives a different mix | `pwsh -File tools/check-world.ps1 -Runs 10`, `tools/check-scroll.ps1 -Long`; manual test MT4.1 |

Manual verification: see docs/manual-tests.md section M4.

+ 8
- 5
docs/spec.md Datei anzeigen

@@ -8,6 +8,7 @@ Changes approved by the user since then:
- 2026-12-03: R3 reworded for scrolling: while a scroll rebuild runs, people are drawn in the shown buffer during vertical blank; drawing people relative to the view moved from M3.4 to M3.3.
- 2026-12-03: A4 status recorded from the M3.4 measurement as partly met; the user accepted the occasional one-frame scroll pause.
- 2026-12-03: Background (land, border and status area) changed from brown (colour 9) to light brown: C64 colour 8 (named orange), which VICE's pepto-pal palette (measured from PAL C64s) shows as light brown; tools/run.ps1 starts VICE with that palette (new assumption A8). Tree trunks stay colour 9.
- 2026-12-03: Terrain all over the world ("the different land spaces need to be all over the map, not just here and there"): R1 reworded; new criteria R1.5 (every view shows at least three terrain kinds) and R1.6 (each world rolls its own random terrain mix). Roads stay a grid and cross water on bridges. New milestone M4.

## Summary

@@ -71,13 +72,15 @@ Each criterion is observable. Criteria IDs (for example R1.2) are referenced by

### R1 - Generated 2x2-screen world (must)

At start-up the program generates a world of 2x2 screens (80x50 cells of 4x8 multicolour pixels) from a seed. The generator decides the layout, shapes and counts of features; every world contains light brown land, grey stone, green grass and trees, blue water and black roads that connect to each other. The view shows a 40x20-cell window of it in multicolour bitmap mode, above the status area (R6).
At start-up the program generates a world of 2x2 screens (80x50 cells of 4x8 multicolour pixels) from a seed. Terrain covers the whole world: lakes, meadows with trees, rocky outcrops and open light brown land are spread all over it, not gathered in a few places. Each world rolls its own mix of the four terrain kinds (land, grass and trees, water, stone), so one world may be wet and another rocky. A grid of black roads (two across, two down) connects to each other and crosses water on bridges. The view shows a 40x20-cell window of it in multicolour bitmap mode, above the status area (R6).

Acceptance criteria:
- [R1.1] After autostart in VICE (x64sc, NTSC) the map view appears within 15 seconds
- [R1.2] Scrolling across the whole world shows all five terrain colours: light brown, grey, green, blue and black
- [R1.3] Roads are continuous black lines that connect to each other
- [R1.3] Roads are continuous black lines that connect to each other; where a road crosses water it is a bridge
- [R1.4] No colour clash: every 4x8 cell shows only its intended colours
- [R1.5] Every 40x20-cell view of the world shows at least three of the four terrain kinds (land, grass and trees, water, stone), each covering at least 8 cells
- [R1.6] Different worlds have different terrain mixes: over several SPACE presses, some worlds are visibly wetter, rockier or greener than others

Capabilities: smooth-animation

@@ -148,9 +151,9 @@ Capabilities: raster-interrupts
| Persistence (save/load) | None. Maps and seeds are not saved. | practical default |
| File formats | None. A single PRG. | practical default |
| Peripherals | Keyboard only. No disk access after loading, no joystick. | practical default |
| Timing and memory budgets | NTSC: 60 Hz, 17,095 cycles per frame (263 lines x 65 cycles, the NTSC VIC-II 6567R8 that x64sc emulates). Per frame: fine-scroll update, one slice of the hidden-buffer rebuild (about 7,600 bytes of bitmap and screen RAM, 20 map rows plus one partial row, spread over 8 frames), and restoring and redrawing visible people; together under one frame. World data about 4 KB; two bitmap buffers with their screen RAM about 18 KB. World generation may take several seconds. | practical default |
| Timing and memory budgets | NTSC: 60 Hz, 17,095 cycles per frame (263 lines x 65 cycles, the NTSC VIC-II 6567R8 that x64sc emulates). Per frame: fine-scroll update, one slice of the hidden-buffer rebuild (about 7,600 bytes of bitmap and screen RAM, 20 map rows plus one partial row, spread over 8 frames), and restoring and redrawing visible people; together under one frame. World data about 4 KB; two bitmap buffers with their screen RAM about 18 KB. World generation may take several seconds (since M4.1 about 4 seconds, behind the generating message; the map is ready about 7 seconds after power-on). | practical default |
| Memory layout | Buffer A in VIC bank 1 and buffer B in VIC bank 2, each with its own 8 KB bitmap and 1 KB screen RAM; flipping switches bank bits in $DD00 during vertical blank. Each bank also holds a 1 KB status text screen (bank + $0400) and a 2 KB copy of the upper-case ROM font (bank + $0800), at the same offsets so a flip still changes only $DD00. Colour RAM is shared and constant (light red), which is also the status text colour. | practical default |
| Rebuild source | The hidden buffer is rebuilt from the tile world, never copied from the visible buffer, so people's dots are never copied into the new view. | practical default |
| Rebuild source | The hidden buffer is rebuilt from the tile world, never copied from the visible buffer, so people's dots are never copied into the new view. Since M4.1 the rebuild first puts back the bytes under the buffer's own people and then skips every cell whose tile is already drawn there (most cells, as terrain comes in areas), so textured terrain everywhere still rebuilds within 8 frames. | practical default |
| Seed | The seed comes from the CIA timer at start-up and at each SPACE press. It is not shown or saved in the first release. | practical default |

## Required capabilities
@@ -166,7 +169,7 @@ Capabilities: raster-interrupts
| A1 | Light red (C64 colour 10) stands in for tan, as the C64 has no tan. | confirmed |
| A2 | The map generator keeps every 4x8 cell to at most two of grey, green, blue and black (besides the light brown background). Where three would meet, for example a road along a shoreline next to grass, it changes the least-represented colour in that cell. | default |
| A3 | Each buffer has its own bitmap and screen RAM in a separate VIC bank (banks 1 and 2), flipped via $DD00 in vertical blank; colour RAM is shared and constant. | unverified |
| A4 | Rebuilding the hidden buffer from tile patterns (about 7,600 bytes) can be spread over 8 frames alongside the people update within the NTSC frame budget, which allows 1 pixel per frame scrolling. | partly met (measured 2026-12-03 in VICE x64sc NTSC, accepted by the user): most rebuilds take 7-8 frames; about 6% take 9-10 when many people are in view, pausing the scroll for one frame (1.7% of scrolling frames); not noticeable in use |
| A4 | Rebuilding the hidden buffer from tile patterns (about 7,600 bytes) can be spread over 8 frames alongside the people update within the NTSC frame budget, which allows 1 pixel per frame scrolling. | partly met (measured 2026-12-03 in VICE x64sc NTSC, accepted by the user): since M4.1 the rebuild skips cells already drawn; in the long tour 99% of rebuilds take 6-8 frames, 13 of 1,928 take 9 or more, pausing the scroll for one frame in 0.8% of scrolling frames (M3.4, before terrain everywhere: 1.7%); not noticeable in use |
| A5 | The smoke test cannot read a bitmap. The program writes a status mirror ("LAND MAP 64", "MAP READY") into the unused text screen at $0400 once the first view is shown; the smoke test checks that text, and the VICE screenshot shows the map. | default |
| A6 | The catalog has no bitmap-graphics capability. Multicolour bitmap mode and VIC bank switching are documented in Mapping the Commodore 64 (53265 $D011, 53270 $D016, 53272 $D018, 56576 $DD00); a catalog update is proposed separately. | unverified |
| A7 | Switching from the fine-scrolled multicolour bitmap to fixed text (and back at the top of the frame) with raster interrupts gives a steady split in VICE x64sc NTSC with no bad-line glitches at the boundary, whatever the map's vertical fine-scroll value. | unverified |


+ 8
- 0
docs/verification-status.md Datei anzeigen

@@ -18,9 +18,17 @@ manual = `pending`, `confirmed by user (<date>)`, `problem reported (<date>): <n
| M3.2 Split screen: raster interrupts switch to text below a 20-row map and back at the top of the frame; status text screen and ROM font copy in both banks; status lines with the people-in-view count. | passed (2026-12-03, `pwsh -File tools/build.ps1`; `pwsh -File tools/smoke.ps1` incl. status text in both banks; `pwsh -File tools/check-world.ps1`; `pwsh -File tools/check-people.ps1`; `pwsh -File tools/check-keys.ps1`; `pwsh -File tools/check-split.ps1`: 955 splits in 955 frames, writes start at 210:55-61, digits right in every frame) | confirmed by user (2026-12-03) |
| M3.3 Fine scroll via $D016/$D011 in the 38-column, 20-row map area; rebuild the hidden buffer from tiles over 8 frames and flip on wrap; stop at world edges; show the view position in the status area; draw people relative to the view (in the shown buffer during vertical blank while a rebuild runs). | passed (2026-12-03, `pwsh -File tools/build.ps1`; `pwsh -File tools/smoke.ps1`; `pwsh -File tools/check-world.ps1`; `pwsh -File tools/check-people.ps1`: 2,127 frames, 0 missed, update done by line 36; `pwsh -File tools/check-keys.ps1`: 8 of 8; `pwsh -File tools/check-split.ps1`: 964 splits in 964 frames, all y-scroll values 0-7, starts 210:55-64, digits right after 240 of 240 status updates; `pwsh -File tools/check-scroll.ps1`: 3 of 3 scenarios, edges reached and held, 1-5 stall frames per scenario, both buffers byte-exact at the end) | confirmed by user (2026-12-03), after the fix for the reported tear ("the top of the screen tears a little when I go left or right") |
| M3.4 Check that people stay aligned with the terrain over long scrolling runs; measure the frame budget with a border-colour timing bar. | passed (2026-12-03, `pwsh -File tools/build.ps1`; `pwsh -File tools/smoke.ps1`; `pwsh -File tools/check-world.ps1`; `pwsh -File tools/check-people.ps1`: 2,130 frames, update done by line 21; `pwsh -File tools/check-keys.ps1`: 8 of 8; `pwsh -File tools/check-split.ps1`: 962 splits, digits 241/241; `pwsh -File tools/check-scroll.ps1 -Long`: 4 of 4, tour 23,195 frames (about 6.4 minutes NTSC) with 21 stops byte-exact, people update done by line 45 at the latest; timing build `--asm-define TIMING_BAR` built and screenshot in VICE) | confirmed by user (2026-12-03), with the light brown background (colour 8, pepto-pal palette); dots visible |
| M4.1 Region generator: each world rolls its own terrain mix; jittered seeds on a grid give every class areas all over the world, shaped by noisy distances, smoothing and removal of thin water; shores from the neighbours; trees on grass. Roads stay a grid of two rows and two columns and become bridges over water. The scroll rebuild skips cells whose tile is already drawn, to keep the 8-frame rebuild with textured terrain everywhere. | passed (2026-12-03, `pwsh -File tools/build.ps1` (4,647 bytes); `pwsh -File tools/smoke.ps1`; `pwsh -File tools/check-world.ps1 -Runs 10`: 10 of 10 worlds, every 40x20 view with 3+ terrain kinds, map ready 7.1-7.3 s after power-on (generation 4.0-4.1 s), mix spread land 14 / grass-trees 8 / water 13 / stone 16 percentage points; `pwsh -File tools/check-people.ps1`: 1,919 frames, 0 missed, update done by line 20; `pwsh -File tools/check-keys.ps1`: 8 of 8; `pwsh -File tools/check-split.ps1`: 734 splits, digits right after 183 of 183 updates; `pwsh -File tools/check-scroll.ps1 -Long`: 4 of 4, tour 22,966 frames with 21 stops byte-exact, 116 stall frames in 15,216 moving frames) | pending |

## Notes

- 2026-12-03 (M4.1, spec change approved by the user: terrain all over the world, random mix per world, roads as a grid with bridges):
- Generator (src/world.inc): per-world class weights and tree threshold; 8x5 jittered seeds on 10x10-cell squares (a class never repeats the previous two seeds; every class appears at least once); each cell takes the nearest seed among the 2x2 nearest squares (distance max + min/2 + noise 0-3); two smoothing passes; thin water removed; shores from the four neighbours; trees on grass; roads as two rows and two columns, bridge tiles (BRIDGE_H, BRIDGE_V, BRIDGE_X; src/tiles.inc) over water. Generation takes about 4 s behind the generating message (the 3x3 seed search took about 6 s and looked the same).
- tools/check-world.ps1 rewritten for the new rules (R1.3-R1.6): tile IDs, all classes present, exactly the road grid with crossings, bridges beside water, no one-cell-thin water, shores matching their neighbours, every 40x20 view with 3+ classes of 8+ cells, map ready within 15 s; -Runs N checks N VICE runs and the spread of the mix. Its first version wrongly required a bridge wherever a road had water on both sides; a road on a one-cell land causeway between lakes is correct, so the rule is now "a bridge has water beside it".
- Problem found and fixed: with textured terrain on 57% of cells the scroll rebuild took 9-10 frames (check-scroll edges: 146 stall frames, failing). src/scroll.inc now restores the hidden buffer's people bytes at rebuild start and skips cells whose tile is already drawn there (compared against the buffer's old origin; buffers that were incomplete, or after a new world, are drawn in full). Rebuilds now take 6-8 frames. The 8 extra cycles per drawn cell made one chunk overrun the frame (one missed frame in a check run), so the chunk cutoffs moved from lines 228/238 to 224/234; afterwards the main loop finished by line 248 at the latest and no frame was missed.
- tools/check-keys.ps1 and tools/check-scroll.ps1: cycle limits raised by 6M cycles for the slower start-up (they failed with 0 frames logged). check-scroll now names the first missed frame.
- The knowledge system was available: entries 3723-3726 recorded.

- 2026-12-03 (colour change, approved by the user): During M3.4 manual testing the user found the background orange ("should be light brown"). The C64 has no light brown; from rendered VICE comparisons the user chose C64 colour 8 shown with VICE's pepto-pal palette (light brown). src/main.s COL_BACKGROUND = 8 (background, border, status area); tree trunks stay colour 9; project.json emulator args select the palette for tools/run.ps1 and tools/smoke.ps1. Checks after the change: `pwsh -File tools/build.ps1`, `tools/smoke.ps1`, `tools/check-world.ps1`, `tools/check-people.ps1`, `tools/check-keys.ps1`, `tools/check-split.ps1`, `tools/check-scroll.ps1` all exit 0 (2026-12-03); the smoke screenshot shows the light brown background. Observation: the light red dots have less contrast on light brown than on brown. The M3.4 manual tests (MT3.2, MT3.3, MT3.4) stay pending with the new colour.

- 2026-12-03 (M3.4): Frame budget measured with tools/check-scroll.ps1 (CPU clock at frame_start, people_moved, frame_done, interrupt entry/exit, start_rebuild, rebuild_ready), all in VICE x64sc NTSC:


+ 54
- 6
project.json Datei anzeigen

@@ -71,13 +71,15 @@
"requirements": [
{
"title": "Generated 2x2-screen world",
"text": "At start-up the program generates a world of 2x2 screens (80x50 cells of 4x8 multicolour pixels) from a seed. The generator decides the layout, shapes and counts of features; every world contains light brown land, grey stone, green grass and trees, blue water and black roads that connect to each other. The view shows a 40x20-cell window of it in multicolour bitmap mode, above the status area (R6).",
"text": "At start-up the program generates a world of 2x2 screens (80x50 cells of 4x8 multicolour pixels) from a seed. Terrain covers the whole world: lakes, meadows with trees, rocky outcrops and open light brown land are spread all over it, not gathered in a few places. Each world rolls its own mix of the four terrain kinds (land, grass and trees, water, stone), so one world may be wet and another rocky. A grid of black roads (two across, two down) connects to each other and crosses water on bridges. The view shows a 40x20-cell window of it in multicolour bitmap mode, above the status area (R6).",
"priority": "must",
"acceptance": [
"After autostart in VICE (x64sc, NTSC) the map view appears within 15 seconds",
"Scrolling across the whole world shows all five terrain colours: light brown, grey, green, blue and black",
"Roads are continuous black lines that connect to each other",
"No colour clash: every 4x8 cell shows only its intended colours"
"Roads are continuous black lines that connect to each other; where a road crosses water it is a bridge",
"No colour clash: every 4x8 cell shows only its intended colours",
"Every 40x20-cell view of the world shows at least three of the four terrain kinds (land, grass and trees, water, stone), each covering at least 8 cells",
"Different worlds have different terrain mixes: over several SPACE presses, some worlds are visibly wetter, rockier or greener than others"
],
"id": "R1",
"capabilities": [
@@ -164,7 +166,7 @@
"source": "user"
},
"budgets": {
"value": "NTSC: 60 Hz, 17,095 cycles per frame (263 lines x 65 cycles, the NTSC VIC-II 6567R8 that x64sc emulates). Per frame: fine-scroll update, one slice of the hidden-buffer rebuild (about 7,600 bytes of bitmap and screen RAM, 20 map rows plus one partial row, spread over 8 frames), and restoring and redrawing visible people; together under one frame. World data about 4 KB; two bitmap buffers with their screen RAM about 18 KB. World generation may take several seconds.",
"value": "NTSC: 60 Hz, 17,095 cycles per frame (263 lines x 65 cycles, the NTSC VIC-II 6567R8 that x64sc emulates). Per frame: fine-scroll update, one slice of the hidden-buffer rebuild (about 7,600 bytes of bitmap and screen RAM, 20 map rows plus one partial row, spread over 8 frames), and restoring and redrawing visible people; together under one frame. World data about 4 KB; two bitmap buffers with their screen RAM about 18 KB. World generation may take several seconds (since M4.1 about 4 seconds, behind the generating message; the map is ready about 7 seconds after power-on).",
"source": "default"
},
"sound": {
@@ -195,7 +197,7 @@
},
{
"topic": "Rebuild source",
"value": "The hidden buffer is rebuilt from the tile world, never copied from the visible buffer, so people's dots are never copied into the new view.",
"value": "The hidden buffer is rebuilt from the tile world, never copied from the visible buffer, so people's dots are never copied into the new view. Since M4.1 the rebuild first puts back the bytes under the buffer's own people and then skips every cell whose tile is already drawn there (most cells, as terrain comes in areas), so textured terrain everywhere still rebuilds within 8 frames.",
"source": "default"
},
{
@@ -229,7 +231,7 @@
{
"id": "A4",
"text": "Rebuilding the hidden buffer from tile patterns (about 7,600 bytes) can be spread over 8 frames alongside the people update within the NTSC frame budget, which allows 1 pixel per frame scrolling.",
"status": "partly met (measured 2026-12-03 in VICE x64sc NTSC, accepted by the user): most rebuilds take 7-8 frames; about 6% take 9-10 when many people are in view, pausing the scroll for one frame (1.7% of scrolling frames); not noticeable in use"
"status": "partly met (measured 2026-12-03 in VICE x64sc NTSC, accepted by the user): since M4.1 the rebuild skips cells already drawn; in the long tour 99% of rebuilds take 6-8 frames, 13 of 1,928 take 9 or more, pausing the scroll for one frame in 0.8% of scrolling frames (M3.4, before terrain everywhere: 1.7%); not noticeable in use"
},
{
"id": "A5",
@@ -581,6 +583,52 @@
]
}
]
},
{
"id": "M4",
"title": "Terrain all over the world",
"goal": "Lakes, meadows with trees, rocky outcrops and open land are spread over the whole world, in a different mix for each world, with roads crossing water on bridges.",
"tasks": [
{
"id": "M4.1",
"text": "Region generator: each world rolls its own terrain mix; jittered seeds on a grid give every class areas all over the world, shaped by noisy distances, smoothing and removal of thin water; shores from the neighbours; trees on grass. Roads stay a grid of two rows and two columns and become bridges over water. The scroll rebuild skips cells whose tile is already drawn, to keep the 8-frame rebuild with textured terrain everywhere.",
"requirements": [
"R1",
"R2",
"R5"
],
"outcome": "Varied terrain in every view; SPACE gives a different mix",
"check": "pwsh -File tools/check-world.ps1 -Runs 10; tools/check-scroll.ps1 -Long; manual test MT4.1"
}
],
"manualTests": [
{
"id": "MT4.1",
"title": "Terrain everywhere, a different mix per world",
"target": "c64",
"setup": "VICE x64sc, NTSC (-ntsc), pepto-pal palette (tools/run.ps1 selects it), warp off.",
"steps": [
"Wait for the map and look at the first view.",
"Scroll over the whole world.",
"Tap SPACE five or six times and compare the first views.",
"Scroll along a road that crosses a lake; watch the dots near water and stone for a minute.",
"Scroll in every direction across busy terrain."
],
"expected": [
"Every view mixes land, meadows with trees, rock and lakes with shores, spread over the whole world",
"Each new world has a different mix",
"Two roads across and two down run the whole world and cross water on bridges, with no gaps",
"No colour clash or stray pixels",
"Dots never step onto water or stone",
"Scrolling stays smooth over textured terrain"
],
"requirements": [
"R1",
"R2",
"R5"
]
}
]
}
],
"destination": "C:\\Development\\Commodore\\Foundry Projects\\land-map-64",


+ 62
- 7
src/scroll.inc Datei anzeigen

@@ -16,8 +16,11 @@
MAX_VIEW_CX = 42 ; vx 336 = 80 * 8 - 304 visible hires pixels
MAX_VIEW_CY = 30
MAX_VIEW_FY = 4 ; vy 244 = 50 * 8 - 156 visible lines
CHUNK8_CUTOFF = 228 ; start an 8-cell chunk only before this line
CHUNK4_CUTOFF = 238 ; and a 4-cell chunk only before this one
; A chunk of drawn cells must end before line 251, where the main loop waits
; for the next frame (worst case: 8 patterned cells, a new row and a bitmap
; page change, about 23 lines).
CHUNK8_CUTOFF = 224 ; start an 8-cell chunk only before this line
CHUNK4_CUTOFF = 234 ; and a 4-cell chunk only before this one
; Zero page for the rebuild's inner loop ($40-$4F: BASIC's area, unused here).
rb_col = $40
rb_count = $41
@@ -46,8 +49,11 @@ reset_view:
jsr build_buffer_now
jmp set_scroll_regs

; X = buffer. Rebuild it for (rb_tx, rb_ty) without a time limit.
; X = buffer. Rebuild it for (rb_tx, rb_ty) without a time limit. Every
; cell is drawn: the buffer may hold another world's tiles.
build_buffer_now:
lda #0
sta buf_ready,x
jsr start_rebuild
@chunk: ldy #MAP_COLS_DRAWN
jsr rebuild_chunk
@@ -56,11 +62,26 @@ build_buffer_now:
beq @chunk
rts

; X = buffer. Begin rebuilding it for origin (rb_tx, rb_ty). Its saved
; people bytes are dropped: every row is redrawn from the tiles.
; X = buffer. Begin rebuilding it for origin (rb_tx, rb_ty). If the buffer
; is complete, its people's saved bytes are put back first: it then holds
; the clean map for its old origin, and the rebuild skips every cell whose
; tile is already there. Otherwise every cell is redrawn and the saved
; bytes are dropped.
start_rebuild:
stx rb_buf
lda rb_tx
lda buf_ready,x
sta rb_diff
beq @fresh
lda buf_cx,x
sta rb_old_cx
lda buf_cy,x
sta rb_old_cy
lda buf_rows,x
sta rb_old_rows
stx people_buf
jsr restore_people
ldx rb_buf
@fresh: lda rb_tx
sta buf_cx,x
lda rb_ty
sta buf_cy,x
@@ -400,6 +421,27 @@ rebuild_chunk:
lda world_row_high,y
adc #0
sta rb_src+2
lda rb_diff ; tiles already in this buffer row, if known
beq @no_old
lda rb_row
cmp rb_old_rows
bcs @no_old
adc rb_old_cy ; carry is clear
tay
lda world_row_low,y
clc
adc rb_old_cx
sta rb_old+1
lda world_row_high,y
adc #0
sta rb_old+2
jmp @screen
@no_old:
lda #<no_old_tiles
sta rb_old+1
lda #>no_old_tiles
sta rb_old+2
@screen:
ldy rb_row
lda screen_row_low,y
sta rb_scr+1
@@ -422,6 +464,9 @@ rebuild_chunk:
rb_cell:
ldy rb_col
rb_src: ldx $FFFF,y ; X = tile
txa
rb_old: cmp $FFFF,y ; already drawn in this cell: skip it
beq rb_advance
lda tile_colors,x
rb_scr: sta $FFFF,y
ldy rb_boff
@@ -442,7 +487,7 @@ rb_pattern:
.endrepeat
rb_advance:
inc rb_col
tya
lda rb_boff
clc
adc #8
sta rb_boff
@@ -494,6 +539,12 @@ screen_row_high:
.byte >(40 * row)
.endrepeat
buffer_screen_high: .byte >SCREEN_A, >SCREEN_B
; Compared with the tiles of a row whose old contents are unknown: no tile
; ID is $FF, so every cell of that row is drawn.
no_old_tiles:
.repeat MAP_COLS_DRAWN
.byte $FF
.endrepeat
tile_times8:
.repeat TILE_COUNT, t
.byte t * 8
@@ -524,4 +575,8 @@ lock_frames: .res 1
rb_tx: .res 1
rb_ty: .res 1
rb_buf: .res 1
rb_diff: .res 1 ; 1: the buffer held the clean map for rb_old_cx/cy
rb_old_cx: .res 1
rb_old_cy: .res 1
rb_old_rows: .res 1
rb_row: .res 1

+ 9
- 0
src/tiles.inc Datei anzeigen

@@ -22,6 +22,9 @@
ROAD_SE
ROAD_SW
ROAD_X
BRIDGE_H
BRIDGE_V
BRIDGE_X
TILE_COUNT
.endenum

@@ -47,6 +50,9 @@ tile_patterns:
.byte $00,$00,$00,$15,$15,$14,$14,$14 ; south-east bend
.byte $00,$00,$00,$54,$54,$14,$14,$14 ; south-west bend
.byte $14,$14,$14,$55,$55,$14,$14,$14 ; crossing
.byte $55,$55,$55,$AA,$AA,$55,$55,$55 ; east-west bridge: water %01, road %10
.byte $69,$69,$69,$69,$69,$69,$69,$69 ; north-south bridge
.byte $69,$69,$69,$AA,$AA,$69,$69,$69 ; bridge crossing
.assert * - tile_patterns = TILE_COUNT * 8, error, "Tile bitmap table size"
.assert TILE_COUNT <= 32, error, "Tile bitmap offsets must fit in X"

@@ -73,4 +79,7 @@ tile_colors:
.repeat 7
.byte $09
.endrepeat
.repeat 3
.byte $60
.endrepeat
.assert * - tile_colors = TILE_COUNT, error, "Tile colour table size"

+ 563
- 144
src/world.inc Datei anzeigen

@@ -1,11 +1,44 @@
; One tile ID per 4x8 multicolour cell, in row-major order.
;
; Generator (M4.1): terrain all over the world, with a different mix per world.
; 1. Roll the world's mix: a weight for each terrain class (land, grass and
; trees, water, stone) and a tree density.
; 2. Place 40 seed points on a jittered 8x5 grid of 10x10-cell squares, so
; seeds cover the whole world. Each seed gets a class drawn from the
; weights, never the same as either of the two seeds before it in its row,
; so any three neighbouring seeds in a row have three different classes.
; Every class is then forced to appear at least once.
; 3. Every cell takes the class of its nearest seed (searching the 2x2 seed
; squares nearest the cell), with a little noise so region edges are ragged.
; 4. Two smoothing passes: a cell takes a class shared by 3 of its 4
; neighbours. This removes single-cell spikes.
; 5. Water clean-up, repeated until nothing changes: a water cell with land on
; both sides (north and south, or west and east) becomes its neighbour's
; class. No water strip is one cell thin, so the 9 shore tiles always fit.
; Outside the world counts as water.
; 6. Final tiles: water cells get the shore tile for their open sides, grass
; cells become trees at the world's tree density.
; 7. Two east-west and two north-south roads cross the whole world; over
; water they become bridges.
WORLD_WIDTH = 80
WORLD_HEIGHT = 50
SECTOR_WIDTH = WORLD_WIDTH / 2
SECTOR_WIDTH = WORLD_WIDTH / 2 ; quarters of the world, used to spread people
SECTOR_HEIGHT = WORLD_HEIGHT / 2
SEED_COLS = 8
SEED_ROWS = 5
SEED_SIZE = 10 ; cells per seed square
SEED_COUNT = SEED_COLS * SEED_ROWS
CLASS_COUNT = 4
NO_CLASS = $FF
MAX_CLEANUP_PASSES = 12
CIA1_TIMER_A = $DC04
world_ptr = bmp ; generator runs before bitmap drawing

; Zero page for the generator ($50-$55; BASIC and the KERNAL interrupt are off).
row_n = $50 ; row above the current one (or the water row)
row_c = $52 ; current row
row_s = $54 ; row below the current one (or the water row)

.export world_tiles, generate_world

.segment "CODE"
@@ -38,63 +71,17 @@ generate_world:
lda seed_low
sta last_seed_low
stx last_seed_high
ldx #0
@clear_row:
jsr point_world_row
lda #LAND
ldy #WORLD_WIDTH-1
@clear_cell:
sta (world_ptr),y
dey
bpl @clear_cell
inx
cpx #WORLD_HEIGHT
bne @clear_row

lda #0
sta sector
@terrain:
ldx sector
lda sector_left,x
sta origin_x
lda sector_top,x
sta origin_y
jsr random_byte
and #1
sta water_side

ldx water_side
lda #WATER
ldy #2
jsr stamp_patch
lda water_side
eor #1
tax
lda #GRASS
ldy #2
jsr stamp_patch
ldx water_side
lda #STONE
ldy #17
jsr stamp_patch
jsr random_byte
and #1
beq @next_sector
lda water_side
eor #1
tax
lda #GRASS
ldy #17
jsr stamp_patch
@next_sector:
inc sector
lda sector
cmp #4
bne @terrain
jsr roll_mix
jsr place_seeds
jsr assign_cells
jsr smooth_pass
jsr smooth_pass
jsr clean_water
jsr finish_tiles

; Lay down two east-west trunks and two north-south trunks.
; The trunks are in the gaps between patches, so no tile has to mix
; road and shoreline pixels. Every intersection becomes a crossing.
; Roads: two east-west and two north-south trunks, as before. They now
; run through terrain and become bridges over water.
jsr random_byte
and #3
clc
@@ -104,10 +91,9 @@ generate_world:
jsr random_byte
and #3
clc
adc #SECTOR_HEIGHT+10
adc #WORLD_HEIGHT/2+10
tax
jsr draw_horizontal_road

jsr random_byte
and #7
clc
@@ -117,106 +103,451 @@ generate_world:
jsr random_byte
and #7
clc
adc #SECTOR_WIDTH+16
adc #WORLD_WIDTH/2+16
tay
jmp draw_vertical_road

; A = terrain type, X = side within sector, Y = base row within sector.
; Patch bounds are exclusive on the right and bottom.
stamp_patch:
sta patch_type
; ---------------------------------------------------------------- 1. mix
; Weights 6-59 per class (sum at most 236, so one random byte can pick), and a
; tree threshold of 24-151 out of 256 for grass cells.
roll_mix:
ldx #CLASS_COUNT-1
@weight:
jsr random_byte
and #3
and #31
sta mix_tmp
jsr random_byte
and #15
clc
adc plot_left,x
adc origin_x
sta patch_left
adc mix_tmp
sta mix_tmp
jsr random_byte
and #3
and #7
clc
adc mix_tmp
adc #6
adc patch_left
sta patch_right
sta class_weight,x
dex
bpl @weight
jsr random_byte
and #1
sty patch_top
and #127
clc
adc patch_top
adc origin_y
sta patch_top
adc #24
sta tree_threshold
ldx #0 ; noise for ragged region edges
@noise: jsr random_byte
sta noise_table,x
inx
bne @noise
rts

; ---------------------------------------------------------------- 2. seeds
place_seeds:
ldx #0 ; X = seed index
lda #0
sta seed_row
@row: lda #0
sta seed_col
lda #NO_CLASS
sta prev1
sta prev2
@col: jsr seed_jitter ; x = col * 10 + 2..7
clc
ldy seed_col
adc times10,y
sta seed_x,x
jsr seed_jitter ; y = row * 10 + 2..7
clc
ldy seed_row
adc times10,y
sta seed_y,x
jsr pick_class ; not prev1, not prev2
sta seed_class,x
ldy prev1
sty prev2
sta prev1
inx
inc seed_col
lda seed_col
cmp #SEED_COLS
bne @col
inc seed_row
lda seed_row
cmp #SEED_ROWS
bne @row

; Every class must appear: give a missing class to a random seed. A
; missing class cannot repeat a neighbour, so the row rule still holds.
@check: lda #0
ldx #CLASS_COUNT-1
@clear: sta class_seen,x
dex
bpl @clear
ldx #SEED_COUNT-1
@mark: ldy seed_class,x
lda #1
sta class_seen,y
dex
bpl @mark
ldy #CLASS_COUNT-1
@find: lda class_seen,y
beq @missing
dey
bpl @find
rts
@missing:
jsr random_byte
and #63
cmp #SEED_COUNT
bcs @missing
tax
tya
sta seed_class,x
jmp @check

; A = 2..7 (triangular), preserves X and Y.
seed_jitter:
jsr random_byte
and #3
sta mix_tmp
jsr random_byte
and #1
clc
adc mix_tmp
sta mix_tmp
jsr random_byte
and #1
clc
adc #4
adc patch_top
sta patch_bottom
adc mix_tmp
adc #2
rts

@row: jsr point_world_row
lda #3
cpx patch_top
bne @bottom_edge
; A = a class drawn from class_weight, never prev1 or prev2. Preserves X.
pick_class:
stx pick_save_x
lda #0 ; total weight of the allowed classes
ldx #CLASS_COUNT-1
@sum: cpx prev1
beq @skip
cpx prev2
beq @skip
clc
adc class_weight,x
@skip: dex
bpl @sum
sta pick_total
@draw: jsr random_byte
cmp pick_total
bcs @draw
ldx #0
@walk: cpx prev1
beq @next
cpx prev2
beq @next
cmp class_weight,x
bcc @found
sec
sbc class_weight,x
@next: inx
bne @walk ; always ends at @found
@found: txa
ldx pick_save_x
rts

; ---------------------------------------------------------------- 3. cells
; Each cell takes the class of the nearest seed among the 2x2 seed squares
; nearest it. Distance = max(dx,dy) + min(dx,dy)/2 + noise 0-3.
assign_cells:
lda #0
sta cell_y
@row: ldx cell_y
jsr point_world_row
ldy cell_y ; search the 2x2 seed squares nearest the cell
lda near_square_y,y
sta sy_lo
clc
adc #2
sta sy_hi
lda #0
beq @row_index
@bottom_edge:
sta cell_x
@cell: jsr random_byte
sta noise_base
lda #$FF
sta best_dist
ldy cell_x
lda near_square_x,y
sta sx_lo
clc
adc #2
sta sx_hi
lda sy_lo
sta sy
@srow: ldy sy
lda times8,y
clc
adc sx_lo
tax ; X = seed index
lda sx_lo
sta sx
@seed: lda cell_x ; dx = |cell_x - seed_x|
sec
sbc seed_x,x
bcs @dxpos
eor #$FF
adc #1
@dxpos: sta dx
lda cell_y ; dy = |cell_y - seed_y|
sec
sbc seed_y,x
bcs @dypos
eor #$FF
adc #1
@dypos: cmp dx ; A = dy
bcc @dysmall
; dy >= dx: max dy, min dx
sta dist
lda dx
jmp @half
@dysmall:
ldy dx ; dy < dx: max dx, min dy
sty dist
@half: lsr
clc
adc dist
sta dist
txa ; noise from the per-world table
clc
adc noise_base
tay
lda noise_table,y
and #3
clc
adc dist
cmp best_dist
bcs @farther
sta best_dist
lda seed_class,x
sta best_class
@farther:
inx
cpx patch_bottom
bne @middle
lda #6
@middle:
dex
@row_index:
sta shore_row
ldy patch_left
@cell: lda patch_type
inc sx
lda sx
cmp sx_hi
bcc @seed
inc sy
lda sy
cmp sy_hi
bcc @srow

ldy best_class ; store the class's tile ID
lda class_tile,y
ldy cell_x
sta (world_ptr),y
inc cell_x
lda cell_x
cmp #WORLD_WIDTH
beq @row_done
jmp @cell ; loop body is too long for a branch
@row_done:
inc cell_y
lda cell_y
cmp #WORLD_HEIGHT
beq @done
jmp @row
@done: rts

; ---------------------------------------------------------------- 4. smoothing
; Interior cells take a class that 3 of their 4 neighbours share.
smooth_pass:
ldx #1
@row: stx cell_y
jsr point_three_rows
ldy #1
@cell: lda (row_n),y ; north = south, plus west or east?
cmp (row_s),y
bne @try_we
sta candidate
dey
lda (row_c),y ; west
iny
cmp candidate
beq @take
iny
lda (row_c),y ; east
dey
cmp candidate
beq @take
@try_we:
dey ; west = east, plus north or south?
lda (row_c),y
iny
sta candidate
iny
lda (row_c),y
dey
cmp candidate
bne @next
lda (row_n),y
cmp candidate
beq @take
lda (row_s),y
cmp candidate
bne @next
@take: lda candidate
sta (row_c),y
@next: iny
cpy #WORLD_WIDTH-1
bne @cell
ldx cell_y
inx
cpx #WORLD_HEIGHT-1
bne @row
rts

; ---------------------------------------------------------------- 5. water
; Repeat until stable: a water cell with non-water on both sides of an axis
; takes that neighbour's class. Outside the world counts as water.
clean_water:
lda #MAX_CLEANUP_PASSES
sta passes_left
@pass: lda #0
sta changed
ldx #0
@row: stx cell_y
jsr point_three_rows
ldy #0
@cell: lda (row_c),y
cmp #WATER
beq @water
bne @next
lda (row_n),y ; north and south both not water?
cmp #WATER
beq @check_we
lda (row_s),y
cmp #WATER
beq @check_we
lda (row_n),y
jmp @replace
@check_we:
cpy #0 ; west (outside counts as water)
beq @next
cpy #WORLD_WIDTH-1 ; east (outside counts as water)
beq @next
dey
lda (row_c),y
iny
cmp #WATER
beq @next
iny
lda (row_c),y
dey
cmp #WATER
beq @next
dey
lda (row_c),y
iny
@replace:
sta (row_c),y
lda #1
sta changed
@next: iny
cpy #WORLD_WIDTH
bne @cell
ldx cell_y
inx
cpx #WORLD_HEIGHT
bne @row
lda changed
beq @done
dec passes_left
bne @pass
@done: rts

; ---------------------------------------------------------------- 6. tiles
; Water cells get their shore tile, grass cells may become trees. Water tests
; use the water family (WATER..WATER_SE), since converted cells are shore tiles.
finish_tiles:
ldx #0
@row: stx cell_y
jsr point_three_rows
ldy #0
@cell: lda (row_c),y
cmp #GRASS
bne @store
cpy patch_left
beq @store ; guarantee grass even for a dense grove
bne @water
jsr random_byte
and #3
bne @grass
cmp tree_threshold
bcs @next
lda #TREE
jmp @store
@grass: lda #GRASS
jmp @store
@water:
; Select the west, middle or east tile for this shore row.
lda shore_row
cpy patch_left
beq @shore
sta (row_c),y
bne @next
@water: cmp #WATER
bne @next
lda #1 ; row part: 0 north shore, 1 middle, 2 south
sta shore_part
lda (row_n),y
jsr is_water
bcs @north_ok
lda #0
sta shore_part
beq @cols
@north_ok:
lda (row_s),y
jsr is_water
bcs @cols
lda #2
sta shore_part
@cols: ldx shore_part ; tile index = row part * 3 + column part
lda times3,x
sta shore_part
cpy #0 ; west shore? (outside counts as water)
beq @east
dey
lda (row_c),y
iny
jsr is_water
bcs @east
jmp @store ; column part 0
@east: inc shore_part ; column part 1 (middle)
cpy #WORLD_WIDTH-1
beq @store
iny
cpy patch_right ; carry is set only for the east edge
lda (row_c),y
dey
adc #1 ; middles add 1, east edge adds 2
@shore:
stx patch_row
tax
jsr is_water
bcs @store
inc shore_part ; column part 2 (east shore)
@store: ldx shore_part
lda shore_tiles,x
ldx patch_row
@store: sta (world_ptr),y
iny
cpy patch_right
sta (row_c),y
@next: iny
cpy #WORLD_WIDTH
bne @cell
ldx cell_y
inx
cpx patch_bottom
cpx #WORLD_HEIGHT
bne @row
lda patch_type
cmp #GRASS
bne @done
ldy patch_left
iny
lda #TREE ; guarantee a tree in every grass patch
sta (world_ptr),y
@done: rts
rts

; Carry set if tile A is water or a shore tile. Preserves X and Y.
is_water:
sec
sbc #WATER
cmp #WATER_SE - WATER + 1
bcs @no
sec
rts
@no: clc
rts

; ---------------------------------------------------------------- 7. roads
draw_horizontal_road:
jsr point_world_row
ldy #WORLD_WIDTH-1
@cell: lda (world_ptr),y
jsr is_water
lda #ROAD_H
@cell: sta (world_ptr),y
bcc @store
lda #BRIDGE_H
@store: sta (world_ptr),y
dey
bpl @cell
rts
@@ -226,17 +557,25 @@ draw_vertical_road:
@row: jsr point_world_row
lda (world_ptr),y
cmp #ROAD_H
bne @straight
bne @bridge_h
lda #ROAD_X
bne @store
@straight:
@bridge_h:
cmp #BRIDGE_H
bne @plain
lda #BRIDGE_X
bne @store
@plain: jsr is_water
lda #ROAD_V
bcc @store
lda #BRIDGE_V
@store: sta (world_ptr),y
inx
cpx #WORLD_HEIGHT
bne @row
rts

; ---------------------------------------------------------------- helpers
; X = world row. Preserves X and Y.
point_world_row:
lda world_row_low,x
@@ -245,6 +584,33 @@ point_world_row:
sta world_ptr+1
rts

; X = world row. row_c = that row, row_n/row_s = the rows above and below, or
; the all-water row outside the world. Preserves X and Y.
point_three_rows:
lda world_row_low,x
sta row_c
lda world_row_high,x
sta row_c+1
lda #<water_row
sta row_n
sta row_s
lda #>water_row
sta row_n+1
sta row_s+1
cpx #0
beq @below
lda world_row_low-1,x
sta row_n
lda world_row_high-1,x
sta row_n+1
@below: cpx #WORLD_HEIGHT-1
beq @done
lda world_row_low+1,x
sta row_s
lda world_row_high+1,x
sta row_s+1
@done: rts

; 16-bit right-shifting Galois LFSR, polynomial mask $B400.
; Return a mix of both state bytes in A. Preserves X and Y.
random_byte:
@@ -261,11 +627,44 @@ random_byte:
.segment "RODATA"
sector_left: .byte 0, SECTOR_WIDTH, 0, SECTOR_WIDTH
sector_top: .byte 0, 0, SECTOR_HEIGHT, SECTOR_HEIGHT
plot_left: .byte 2, 25
class_tile: .byte LAND, GRASS, WATER, STONE
shore_tiles:
.byte WATER_NW, WATER_N, WATER_NE
.byte WATER_W, WATER, WATER_E
.byte WATER_SW, WATER_S, WATER_SE
times3: .byte 0, 3, 6
times8:
.repeat SEED_ROWS, r
.byte r * SEED_COLS
.endrepeat
times10:
.repeat SEED_COLS, c
.byte c * SEED_SIZE
.endrepeat
; First of the two seed squares nearest a cell on each axis: the square the
; cell is in and the neighbour on the side of the cell's half, clipped.
near_square_x:
.repeat WORLD_WIDTH, col
.if col < SEED_SIZE / 2
.byte 0
.elseif (col - SEED_SIZE / 2) / SEED_SIZE > SEED_COLS - 2
.byte SEED_COLS - 2
.else
.byte (col - SEED_SIZE / 2) / SEED_SIZE
.endif
.endrepeat
near_square_y:
.repeat WORLD_HEIGHT, row
.if row < SEED_SIZE / 2
.byte 0
.elseif (row - SEED_SIZE / 2) / SEED_SIZE > SEED_ROWS - 2
.byte SEED_ROWS - 2
.else
.byte (row - SEED_SIZE / 2) / SEED_SIZE
.endif
.endrepeat
water_row:
.res WORLD_WIDTH, WATER
world_row_low:
.repeat WORLD_HEIGHT, row
.byte <(world_tiles + WORLD_WIDTH * row)
@@ -276,20 +675,40 @@ world_row_high:
.endrepeat

.segment "BSS"
seed_low: .res 1
seed_high: .res 1
last_seed_low: .res 1
seed_low: .res 1
seed_high: .res 1
last_seed_low: .res 1
last_seed_high: .res 1
sector: .res 1
origin_x: .res 1
origin_y: .res 1
water_side: .res 1
patch_type: .res 1
patch_left: .res 1
patch_right: .res 1
patch_top: .res 1
patch_bottom: .res 1
patch_row: .res 1
shore_row: .res 1
world_tiles: .res WORLD_WIDTH * WORLD_HEIGHT
class_weight: .res CLASS_COUNT
class_seen: .res CLASS_COUNT
tree_threshold: .res 1
mix_tmp: .res 1
pick_total: .res 1
pick_save_x: .res 1
prev1: .res 1
prev2: .res 1
seed_row: .res 1
seed_col: .res 1
seed_x: .res SEED_COUNT
seed_y: .res SEED_COUNT
seed_class: .res SEED_COUNT
cell_x: .res 1
cell_y: .res 1
sx: .res 1
sy: .res 1
sx_lo: .res 1
sx_hi: .res 1
sy_lo: .res 1
sy_hi: .res 1
dx: .res 1
dist: .res 1
best_dist: .res 1
best_class: .res 1
noise_base: .res 1
candidate: .res 1
changed: .res 1
passes_left: .res 1
shore_part: .res 1
noise_table: .res 256
world_tiles: .res WORLD_WIDTH * WORLD_HEIGHT
.assert * <= SCREEN_A, lderror, "World must fit below VIC bank 1"

+ 1
- 1
tools/check-keys.ps1 Datei anzeigen

@@ -89,7 +89,7 @@ foreach ($sc in $scenarios) {
Set-Content -LiteralPath (Join-Path $dir 'monitor.txt') -Value $mon
Set-Content -LiteralPath (Join-Path $dir 'vicerc') -Value ''

$cycles = if ($sc.space) { 20000000 } else { 6000000 }
$cycles = if ($sc.space) { 26000000 } else { 12000000 }
$vargs = @('-config', 'vicerc', '-default', '-sounddev', 'dummy', '-warp', '-minimized') + (Get-VideoArgs $target)
$vargs += @('-limitcycles', [string]$cycles, '-moncommands', 'monitor.txt', '-autostartprgmode', '1', '-autostart', (Get-AutostartFile $target))
$quoted = $vargs | ForEach-Object { if ($_ -match '[\s"]') { '"' + $_ + '"' } else { $_ } }


+ 5
- 5
tools/check-scroll.ps1 Datei anzeigen

@@ -119,19 +119,19 @@ function View([int]$cx, [int]$fx, [int]$cy, [int]$fy) {
$c
}
$scenarios = @(
@{ name = 'edges'; cycles = 30000000; phases = @(
@{ name = 'edges'; cycles = 36000000; phases = @(
@{ cursor = $NONE; lshift = $NONE; until = (Frame 30) }
@{ cursor = $RIGHT_DOWN; lshift = $NONE; until = (View 42 0 30 4) } # vx 336, vy 244
@{ cursor = $RIGHT_DOWN; lshift = $NONE; until = (Frame 0); edge = $true }
@{ cursor = $RIGHT_DOWN; lshift = $SHIFT; until = (View 0 0 0 0) }
@{ cursor = $RIGHT_DOWN; lshift = $SHIFT; until = (Frame 128); edge = $true }
@{ cursor = $NONE; lshift = $NONE }) }
@{ name = 'middle'; cycles = 12000000; phases = @(
@{ name = 'middle'; cycles = 18000000; phases = @(
@{ cursor = $NONE; lshift = $NONE; until = (Frame 30) }
@{ cursor = $DOWN; lshift = $NONE; until = (View -1 0 12 3) } # vy 99
@{ cursor = $RIGHTK; lshift = $NONE; until = (View 16 5 -1 0) } # vx 133
@{ cursor = $NONE; lshift = $NONE }) }
@{ name = 'reverse'; cycles = 12000000; phases = @(
@{ name = 'reverse'; cycles = 18000000; phases = @(
@{ cursor = $NONE; lshift = $NONE; until = (Frame 30) }
@{ cursor = $RIGHTK; lshift = $NONE; until = (View 9 0 -1 0) } # just stepped into cell 9
@{ cursor = $RIGHTK; lshift = $SHIFT; until = (View 3 2 -1 0) }
@@ -319,7 +319,7 @@ foreach ($sc in $scenarios) {
$p = $frames[$i - 1]
$dx = $vx - $p.vx; $dy = $vy - $p.vy
if ($dx -ne 0 -or $dy -ne 0) { $steps++ }
if ($f.clock - $p.clock -gt 1.5 * 17095) { $late++ }
if ($f.clock - $p.clock -gt 1.5 * 17095) { if ($late -eq 0) { $firstLate = "first at frame $i, phase $($f.phase), view ($vx,$vy) from ($($p.vx),$($p.vy))" }; $late++ }
# The keys read after people_moved in frame i-1 (that frame's phase) give frame i's step.
$k = $sc.phases[[Math]::Min($p.phase, $lastPhase)]
$bits = [Convert]::ToByte($k.cursor, 16)
@@ -339,7 +339,7 @@ foreach ($sc in $scenarios) {
if ($vx -lt $minAfterMaxVx) { $minAfterMaxVx = $vx }
if ($vy -lt $minAfterMaxVy) { $minAfterMaxVy = $vy }
}
if ($late -gt 0) { $failures.Add("the main loop missed $late frame(s)") }
if ($late -gt 0) { $failures.Add("the main loop missed $late frame(s), $firstLate") }
if ($phaseFrames[$lastPhase] -lt 10) { $failures.Add("reached the last phase for only $($phaseFrames[$lastPhase]) frame(s) (frames per phase: $($phaseFrames -join ', '))") }
if ($sc.name -eq 'edges') {
if ($maxVx -ne 336 -or $maxVy -ne 244) { $failures.Add("did not reach the bottom-right edge (max vx $maxVx, vy $maxVy)") }


+ 226
- 44
tools/check-world.ps1 Datei anzeigen

@@ -1,59 +1,241 @@
<# Verifies the generated C64 tile world captured by tools/smoke.ps1. #>
<#
.SYNOPSIS
Verifies generated Land Map 64 worlds (R1).
.DESCRIPTION
Without -Runs: checks the world captured by tools/smoke.ps1 (build/smoke/c64/world.bin).
With -Runs N: runs the program headless in VICE N times (VICE randomises the autostart
delay, so the timer seed and the world differ per run), captures each world at
smoke_ready, and checks every one. With 5 or more worlds it also checks that the
terrain mix differs between worlds (R1.6).

Checks per world:
- 80x50 tile IDs, all known (src/tiles.inc order)
- every terrain type present: land, grass, trees, stone, water (R1.2)
- roads: exactly two full east-west rows and two full north-south columns, crossings
where they meet, no road tile anywhere else; every bridge has water beside it (R1.3)
- water: no strip one cell thin, and every water cell has the shore tile its
neighbours call for (outside the world and bridges count as water) (R1.4)
- spread: every 40x20-cell view contains at least three of land, grass and trees,
water and stone, with at least 8 cells each (R1.5)
- with -Runs: the map is ready (smoke_ready) within 15 seconds of NTSC time after
autostart (R1.1); also reports how long generation took (generate_world to smoke_ready)
Exit 0 when every world passes, 1 on a failure, 2 when a tool is missing.
#>
[CmdletBinding()]
param(
[string]$Path = (Join-Path $PSScriptRoot '../build/smoke/c64/world.bin'),
[switch]$ShowMap
[string]$Path,
[int]$Runs = 0,
[switch]$ShowMap,
[switch]$NoBuild,
[int]$TimeoutSeconds = 120
)

$ErrorActionPreference = 'Stop'
$width = 80
$height = 50
$tiles = [IO.File]::ReadAllBytes((Resolve-Path -LiteralPath $Path).Path)
if ($tiles.Length -ne $width * $height) {
throw "Expected an 80x50 tile map, got $($tiles.Length) bytes."
}
. (Join-Path $PSScriptRoot 'lib.ps1')

$width = 80; $height = 50
# Tile IDs from src/tiles.inc.
$LAND = 0; $GRASS = 1; $TREE = 2; $STONE = 3; $WATER = 4
$WATER_N = 5; $WATER_S = 6; $WATER_W = 7; $WATER_E = 8
$WATER_NW = 9; $WATER_NE = 10; $WATER_SW = 11; $WATER_SE = 12
$ROAD_H = 13; $ROAD_V = 14; $ROAD_X = 19; $BRIDGE_H = 20; $BRIDGE_V = 21; $BRIDGE_X = 22
$TILE_COUNT = 23
$glyphs = '.gT#~~~~~~~~~-|+++++=!*'
# Shore tile by [row part][column part]: row 0 = open to the north, 2 = open to the south.
$shore = @(@($WATER_NW, $WATER_N, $WATER_NE), @($WATER_W, $WATER, $WATER_E), @($WATER_SW, $WATER_S, $WATER_SE))
$NTSC_HZ = 1022727
$maxCycles = 15 * $NTSC_HZ

# Tile IDs from src/tiles.inc. M1.2 uses straight roads and four-way crossings.
$roadH = 13
$roadV = 14
$roadCross = 19
$glyphs = '.gT#~~~~~~~~~-|+++++'
$counts = [int[]]::new($glyphs.Length)
foreach ($tile in $tiles) {
if ($tile -ge $glyphs.Length) { throw "Invalid terrain tile ID $tile." }
$counts[$tile]++
function Test-WaterFamily([int]$t) { $t -ge $WATER -and $t -le $WATER_SE }
function Test-Bridge([int]$t) { $t -ge $BRIDGE_H -and $t -le $BRIDGE_X }

# Class of a tile for the spread check: 0 land, 1 grass/trees, 2 water, 3 stone, -1 road/bridge.
function Get-TileClass([int]$t) {
if ($t -eq $LAND) { 0 } elseif ($t -eq $GRASS -or $t -eq $TREE) { 1 }
elseif (Test-WaterFamily $t) { 2 } elseif ($t -eq $STONE) { 3 } else { -1 }
}
foreach ($tile in 0..12) {
if ($counts[$tile] -eq 0) { throw "Missing terrain tile ID $tile." }

function Test-World([byte[]]$tiles, [string]$name) {
$fail = [System.Collections.Generic.List[string]]::new()
if ($tiles.Length -ne $width * $height) { $fail.Add("expected 4000 bytes, got $($tiles.Length)"); return @{ failures = $fail } }
$at = { param($x, $y) $tiles[$y * $width + $x] }

# Tile IDs and terrain types present.
$counts = [int[]]::new(256)
foreach ($t in $tiles) { $counts[$t]++ }
for ($t = $TILE_COUNT; $t -lt 256; $t++) { if ($counts[$t]) { $fail.Add("unknown tile ID $t ($($counts[$t]) cells)") } }
$waterCells = 0; for ($t = $WATER; $t -le $WATER_SE; $t++) { $waterCells += $counts[$t] }
foreach ($p in @(@('land', $counts[$LAND]), @('grass', $counts[$GRASS]), @('trees', $counts[$TREE]), @('stone', $counts[$STONE]), @('water', $waterCells))) {
if ($p[1] -eq 0) { $fail.Add("no $($p[0]) anywhere") }
}

# Roads.
$hSet = @($ROAD_H, $BRIDGE_H, $ROAD_X, $BRIDGE_X); $vSet = @($ROAD_V, $BRIDGE_V, $ROAD_X, $BRIDGE_X)
$roadRows = @(0..($height - 1) | Where-Object { $y = $_; @(0..($width - 1) | Where-Object { (& $at $_ $y) -notin $hSet }).Count -eq 0 })
$roadCols = @(0..($width - 1) | Where-Object { $x = $_; @(0..($height - 1) | Where-Object { (& $at $x $_) -notin $vSet }).Count -eq 0 })
if ($roadRows.Count -ne 2) { $fail.Add("expected 2 full east-west roads, found $($roadRows.Count)") }
if ($roadCols.Count -ne 2) { $fail.Add("expected 2 full north-south roads, found $($roadCols.Count)") }
for ($y = 0; $y -lt $height; $y++) {
for ($x = 0; $x -lt $width; $x++) {
$t = & $at $x $y
$onH = $y -in $roadRows; $onV = $x -in $roadCols
$isRoad = $t -ge $ROAD_H
if ($onH -and $onV) { if ($t -notin @($ROAD_X, $BRIDGE_X)) { $fail.Add("crossing at ($x,$y) is tile $t") } }
elseif (-not ($onH -or $onV) -and $isRoad) { $fail.Add("road tile $t off the road grid at ($x,$y)") }
}
}

# Water: neighbours count as water if water family, bridge, or outside the world.
$isWet = { param($x, $y)
if ($x -lt 0 -or $y -lt 0 -or $x -ge $width -or $y -ge $height) { return $true }
$t = & $at $x $y; (Test-WaterFamily $t) -or (Test-Bridge $t) }
for ($y = 0; $y -lt $height; $y++) {
for ($x = 0; $x -lt $width; $x++) {
$t = & $at $x $y
if (Test-WaterFamily $t) {
$n = & $isWet $x ($y - 1); $s = & $isWet $x ($y + 1); $w = & $isWet ($x - 1) $y; $e = & $isWet ($x + 1) $y
if (-not $n -and -not $s) { $fail.Add("water one cell thin (north-south) at ($x,$y)"); continue }
if (-not $w -and -not $e) { $fail.Add("water one cell thin (west-east) at ($x,$y)"); continue }
$r = if (-not $n) { 0 } elseif (-not $s) { 2 } else { 1 }
$c = if (-not $w) { 0 } elseif (-not $e) { 2 } else { 1 }
if ($t -ne $shore[$r][$c]) { $fail.Add("water at ($x,$y) is tile $t, its neighbours call for $($shore[$r][$c])") }
} elseif ($t -eq $BRIDGE_H -and -not ((& $isWet $x ($y - 1)) -or (& $isWet $x ($y + 1)))) {
$fail.Add("bridge at ($x,$y) has no water north or south of it")
} elseif ($t -eq $BRIDGE_V -and -not ((& $isWet ($x - 1) $y) -or (& $isWet ($x + 1) $y))) {
$fail.Add("bridge at ($x,$y) has no water west or east of it")
}
}
}

# Spread: prefix sums per class, then every 40x20 window.
$sum = 0..3 | ForEach-Object { , ([int[]]::new(($width + 1) * ($height + 1))) }
for ($y = 0; $y -lt $height; $y++) {
for ($x = 0; $x -lt $width; $x++) {
$k = Get-TileClass (& $at $x $y)
for ($c = 0; $c -lt 4; $c++) {
$v = if ($k -eq $c) { 1 } else { 0 }
$i = ($y + 1) * ($width + 1) + ($x + 1)
$sum[$c][$i] = $v + $sum[$c][$i - 1] + $sum[$c][$i - ($width + 1)] - $sum[$c][$i - ($width + 1) - 1]
}
}
}
$worst = 4; $worstAt = ''
for ($y = 0; $y -le $height - 20; $y++) {
for ($x = 0; $x -le $width - 40; $x++) {
$present = 0
for ($c = 0; $c -lt 4; $c++) {
$a = $sum[$c]; $W = $width + 1
$n = $a[($y + 20) * $W + $x + 40] - $a[$y * $W + $x + 40] - $a[($y + 20) * $W + $x] + $a[$y * $W + $x]
if ($n -ge 8) { $present++ }
}
if ($present -lt $worst) { $worst = $present; $worstAt = "($x,$y)" }
}
}
if ($worst -lt 3) { $fail.Add("the 40x20 view at $worstAt has only $worst terrain types with 8+ cells") }

$total = 0; $share = 0..3 | ForEach-Object { $sum[$_][$height * ($width + 1) + $width] }
foreach ($v in $share) { $total += $v }
@{ failures = $fail; share = @($share | ForEach-Object { [math]::Round(100 * $_ / $total) }); worstView = $worst }
}

# Find the road columns and rows from their endpoints on the world edges.
$roadColumns = @(0..($width - 1) | Where-Object { $tiles[$_] -eq $roadV })
$roadRows = @(0..($height - 1) | Where-Object { $tiles[($_ * $width)] -eq $roadH })
if ($roadColumns.Count -ne 2 -or $roadRows.Count -ne 2) {
throw "Expected two east-west and two north-south roads."
function Show-World([byte[]]$tiles) {
for ($y = 0; $y -lt $height; $y++) {
-join ($tiles[($y * $width)..($y * $width + $width - 1)] | ForEach-Object { if ($_ -lt $glyphs.Length) { $glyphs[$_] } else { '?' } })
}
}

for ($y = 0; $y -lt $height; $y++) {
for ($x = 0; $x -lt $width; $x++) {
$tile = $tiles[$y * $width + $x]
$horizontal = $y -in $roadRows
$vertical = $x -in $roadColumns
if ($horizontal -or $vertical) {
$expected = if ($horizontal -and $vertical) { $roadCross }
elseif ($horizontal) { $roadH }
else { $roadV }
if ($tile -ne $expected) {
throw "Broken road at ($x,$y): expected tile $expected, got $tile."
# ---------------------------------------------------------------- collect worlds
$worlds = [System.Collections.Generic.List[hashtable]]::new()
if ($Runs -le 0) {
if (-not $Path) { $Path = Join-Path $PSScriptRoot '../build/smoke/c64/world.bin' }
$worlds.Add(@{ name = 'smoke world'; tiles = [IO.File]::ReadAllBytes((Resolve-Path -LiteralPath $Path).Path); cycles = $null })
} else {
try {
$project = Get-ProjectConfig
$target = Get-ProjectTargets $project 'c64'
if (-not $NoBuild) { Invoke-TargetBuild $project $target @{} }
$emu = Get-ToolPath $project $target.emulator.binary
} catch [MissingToolException] {
Write-Host $_.Exception.Message -ForegroundColor Yellow
exit 2
}
$labels = @{}
foreach ($line in Get-Content -LiteralPath (Get-RepoPath $target.build.labels)) {
$parts = $line -split '\s+'
if ($parts.Count -ge 3) { $labels[$parts[2].TrimStart('.')] = [Convert]::ToInt32($parts[1], 16) }
}
$root = Get-RepoPath 'build/check-world'
if (Test-Path -LiteralPath $root) { Remove-Item -LiteralPath $root -Recurse -Force }
for ($run = 1; $run -le $Runs; $run++) {
$dir = Join-Path $root "run$run"
New-Item -ItemType Directory -Force -Path $dir | Out-Null
$mon = @('logname "monitor.log"', 'log on',
('trace exec ${0:x4}' -f $labels.smoke_ready),
('command 1 "bsave \"world.bin\" 0 {0:x4} {1:x4}"' -f $labels.world_tiles, ($labels.world_tiles + $width * $height - 1)),
('trace exec ${0:x4}' -f $labels.generate_world))
$n = 2
# No key may reach the program: keys typed on the PC while VICE has focus would.
foreach ($row in 'key_row_cursor', 'key_row_lshift', 'key_row_rshift', 'key_row_space') {
$n++; $mon += ('trace exec ${0:x4}' -f $labels[$row]); $mon += ('command {0} "r a = ff"' -f $n)
}
Set-Content -LiteralPath (Join-Path $dir 'monitor.txt') -Value $mon
Set-Content -LiteralPath (Join-Path $dir 'vicerc') -Value ''
$vargs = @('-config', 'vicerc', '-default', '-sounddev', 'dummy', '-warp', '-minimized') + (Get-VideoArgs $target)
$vargs += @('-limitcycles', [string]($maxCycles + 2000000), '-moncommands', 'monitor.txt', '-autostartprgmode', '1', '-autostart', (Get-AutostartFile $target))
$quoted = $vargs | ForEach-Object { if ($_ -match '[\s"]') { '"' + $_ + '"' } else { $_ } }
$p = Start-Process -FilePath $emu -ArgumentList $quoted -WorkingDirectory $dir -PassThru `
-RedirectStandardOutput (Join-Path $dir 'vice.log') -RedirectStandardError (Join-Path $dir 'vice.err')
if (-not $p.WaitForExit($TimeoutSeconds * 1000)) { $p.Kill($true); Write-Host "[FAIL] run $run`: VICE did not exit in time." -ForegroundColor Red; exit 1 }
$file = Join-Path $dir 'world.bin'
if (-not (Test-Path -LiteralPath $file)) { Write-Host "[FAIL] run $run`: smoke_ready not reached within 15 s of NTSC time (R1.1)." -ForegroundColor Red; exit 1 }
# The trace's instruction line ends with the CPU clock.
$clock = @{}
foreach ($log in 'monitor.log', 'vice.log') {
$lf = Join-Path $dir $log
if (-not (Test-Path -LiteralPath $lf)) { continue }
$lines = Get-Content -LiteralPath $lf
for ($i = 0; $i -lt $lines.Count; $i++) {
if ($lines[$i] -match '^#([12]) \(Trace\s+exec' -and -not $clock.ContainsKey($Matches[1])) {
$id = $Matches[1]
for ($j = $i + 1; $j -lt [math]::Min($i + 4, $lines.Count); $j++) { if ($lines[$j] -match '^\.C:.*\s(\d+)\s*$') { $clock[$id] = [long]$Matches[1]; break } }
}
}
} elseif ($tile -ge $roadH) {
throw "Disconnected road tile at ($x,$y)."
if ($clock.Count -eq 2) { break }
}
}
if ($ShowMap) {
$start = $y * $width
-join ($tiles[$start..($start + $width - 1)] | ForEach-Object { $glyphs[$_] })
$gen = if ($clock.ContainsKey('1') -and $clock.ContainsKey('2')) { $clock['1'] - $clock['2'] } else { $null }
$worlds.Add(@{ name = "run $run"; tiles = [IO.File]::ReadAllBytes($file); cycles = $clock['1']; genCycles = $gen })
}
}

Write-Output '[PASS] 80x50 world has all terrain types and four connected road crossings.'
# ---------------------------------------------------------------- check
$failed = $false
$shares = [System.Collections.Generic.List[int[]]]::new()
foreach ($w in $worlds) {
$r = Test-World $w.tiles $w.name
$time = if ($null -ne $w.cycles) { ', ready {0:N1} s after power-on' -f ($w.cycles / $NTSC_HZ) } else { '' }
if ($null -ne $w.genCycles) { $time += ' (generation {0:N1} s)' -f ($w.genCycles / $NTSC_HZ) }
if ($null -ne $w.cycles -and $w.cycles -gt $maxCycles) { $r.failures.Add('generation took longer than 15 s (R1.1)') }
$mix = if ($r.share) { 'land {0}% grass/trees {1}% water {2}% stone {3}%' -f $r.share[0], $r.share[1], $r.share[2], $r.share[3] } else { '' }
if ($r.failures.Count) {
$failed = $true
Write-Host "[FAIL] $($w.name): $mix$time" -ForegroundColor Red
$r.failures | Select-Object -First 10 | ForEach-Object { Write-Host " $_" }
if ($r.failures.Count -gt 10) { Write-Host " ... $($r.failures.Count - 10) more" }
} else {
Write-Host "[PASS] $($w.name): $mix; every 40x20 view has $($r.worstView)+ terrain types$time"
$shares.Add([int[]]$r.share)
}
if ($ShowMap) { Show-World $w.tiles }
}
if ($worlds.Count -ge 5 -and -not $failed) {
$names = 'land', 'grass/trees', 'water', 'stone'
$spread = 0..3 | ForEach-Object { $c = $_; $v = $shares | ForEach-Object { $_[$c] }; ($v | Measure-Object -Maximum).Maximum - ($v | Measure-Object -Minimum).Minimum }
$line = (0..3 | ForEach-Object { '{0} {1}' -f $names[$_], $spread[$_] }) -join ', '
if (($spread | Where-Object { $_ -ge 10 }).Count -lt 2) {
Write-Host "[FAIL] the terrain mix hardly varies between worlds (percentage-point spread: $line); R1.6 needs 10+ for at least two types" -ForegroundColor Red
$failed = $true
} else {
Write-Host "[PASS] the terrain mix varies between worlds (percentage-point spread: $line)"
}
}
if ($failed) { exit 1 }
Write-Output "[PASS] $($worlds.Count) world(s) checked."

Laden…
Abbrechen
Speichern

Powered by TurnKey Linux.