| 1 | import test from "node:test"; |
| 2 | import assert from "node:assert/strict"; |
| 3 | import { CHUNK_SIZE } from "../../shared/protocol/constants.js"; |
| 4 | |
| 5 | /** Mirrors WorldView.#chunkRebuildScore for unit tests. */ |
| 6 | function chunkRebuildScore ({ |
| 7 | chunkX, |
| 8 | chunkY, |
| 9 | playerChunkX, |
| 10 | playerChunkY, |
| 11 | moveDx, |
| 12 | moveDy, |
| 13 | mode = "urgent" |
| 14 | }) |
| 15 | { |
| 16 | const dx = chunkX - playerChunkX; |
| 17 | const dy = chunkY - playerChunkY; |
| 18 | const dist = Math.abs(dx) + Math.abs(dy); |
| 19 | let ahead = 0; |
| 20 | if (moveDx !== 0 || moveDy !== 0) |
| 21 | { ahead = dx * moveDx + dy * moveDy; } |
| 22 | if (mode === "idle") |
| 23 | { |
| 24 | return -dist * 10 + (ahead > 0 ? -ahead * 2 : Math.max(ahead, 0)); |
| 25 | } |
| 26 | return dist * 10 - Math.max(0, ahead) * 3; |
| 27 | } |
| 28 | |
| 29 | test("urgent chunk rebuild prefers nearby chunks ahead of movement", () => |
| 30 | { |
| 31 | const playerChunkX = 5; |
| 32 | const playerChunkY = 5; |
| 33 | const ahead = chunkRebuildScore({ |
| 34 | chunkX: 6, |
| 35 | chunkY: 5, |
| 36 | playerChunkX, |
| 37 | playerChunkY, |
| 38 | moveDx: 1, |
| 39 | moveDy: 0, |
| 40 | mode: "urgent" |
| 41 | }); |
| 42 | const behind = chunkRebuildScore({ |
| 43 | chunkX: 4, |
| 44 | chunkY: 5, |
| 45 | playerChunkX, |
| 46 | playerChunkY, |
| 47 | moveDx: 1, |
| 48 | moveDy: 0, |
| 49 | mode: "urgent" |
| 50 | }); |
| 51 | assert.ok(ahead < behind, "chunk in walk direction should outrank chunk behind"); |
| 52 | }); |
| 53 | |
| 54 | test("idle prefetch prefers far chunks ahead of movement", () => |
| 55 | { |
| 56 | const playerChunkX = 5; |
| 57 | const playerChunkY = 5; |
| 58 | const farAhead = chunkRebuildScore({ |
| 59 | chunkX: 7, |
| 60 | chunkY: 5, |
| 61 | playerChunkX, |
| 62 | playerChunkY, |
| 63 | moveDx: 1, |
| 64 | moveDy: 0, |
| 65 | mode: "idle" |
| 66 | }); |
| 67 | const nearBehind = chunkRebuildScore({ |
| 68 | chunkX: 4, |
| 69 | chunkY: 5, |
| 70 | playerChunkX, |
| 71 | playerChunkY, |
| 72 | moveDx: 1, |
| 73 | moveDy: 0, |
| 74 | mode: "idle" |
| 75 | }); |
| 76 | assert.ok(farAhead < nearBehind, "idle should target far-ahead chunks before near-behind"); |
| 77 | }); |
| 78 | |
| 79 | test("player chunk coords align with CHUNK_SIZE", () => |
| 80 | { |
| 81 | assert.equal(Math.floor((5 * CHUNK_SIZE) / CHUNK_SIZE), 5); |
| 82 | }); |