-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathgame.test.ts
More file actions
608 lines (569 loc) · 20.2 KB
/
Copy pathgame.test.ts
File metadata and controls
608 lines (569 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
/**
* The game slot nodes fill the contract in @nodetool-ai/protocol/game-assets:
* the fill they stamp on the image must pass `checkSlotFill` against the
* template manifest, and every rejection (wrong sheet size, too few frames,
* a hard edge on an image that must tile) must actually fire.
*/
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { describe, it, expect } from "vitest";
import sharp from "sharp";
import {
SLOT_METADATA_KEY,
checkSlotFill,
gameAssetManifest,
type GameSlotSpec,
type ImageFill,
type SpritesheetFill,
type TilesetFill
} from "@nodetool-ai/protocol";
import {
GAME_NODES,
SeamlessImageNode,
SpriteSheetNode,
TilesetNode
} from "@nodetool-ai/image-nodes";
const manifestPath = fileURLToPath(
new URL(
"../../protocol/fixtures/game-assets/platformer.manifest.json",
import.meta.url
)
);
const manifest = gameAssetManifest.parse(
JSON.parse(readFileSync(manifestPath, "utf8"))
);
function slot(id: string): GameSlotSpec {
const spec = manifest.slots.find((s) => s.id === id);
if (!spec) throw new Error(`fixture has no slot ${id}`);
return spec;
}
async function runNode(
suffix: string,
inputs: Record<string, unknown>,
context?: unknown
): Promise<Record<string, unknown>> {
const Cls = GAME_NODES.find((n) =>
(n as unknown as { nodeType: string }).nodeType.endsWith(suffix)
);
expect([SpriteSheetNode, TilesetNode, SeamlessImageNode]).toContain(Cls);
if (!Cls) throw new Error(`Node ending with "${suffix}" not found`);
const node = new (Cls as unknown as {
new (): {
assign(p: Record<string, unknown>): void;
process(ctx?: unknown): Promise<Record<string, unknown>>;
};
})();
node.assign(inputs);
return node.process(context);
}
/** An RGB PNG image ref whose pixel (x, y) is chosen by `pixel`. */
async function makeImage(
w: number,
h: number,
pixel: (x: number, y: number) => [number, number, number]
): Promise<Record<string, unknown>> {
const pixels = Buffer.alloc(w * h * 3);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const [r, g, b] = pixel(x, y);
pixels.set([r, g, b], (y * w + x) * 3);
}
}
const buf = await sharp(pixels, { raw: { width: w, height: h, channels: 3 } })
.png()
.toBuffer();
return { type: "image", data: buf.toString("base64"), uri: "" };
}
const noise = (x: number, y: number): [number, number, number] => [
(x * 17 + y * 3) % 256,
(x * 5 + y * 23) % 256,
(x * 11 + y * 7) % 256
];
function stamped(result: Record<string, unknown>): unknown {
const output = result.output as { metadata: Record<string, unknown> };
return output.metadata[SLOT_METADATA_KEY];
}
describe("nodetool.game.SpriteSheet", () => {
const player = slot("player");
if (player.kind !== "spritesheet") throw new Error("player is a spritesheet");
it("fills the fixture player slot from a 256x64 sheet", async () => {
const image = await makeImage(256, 64, noise);
const result = await runNode(".SpriteSheet", {
image,
cell_width: 32,
cell_height: 32,
animations: player.animations,
fps: player.fps,
slot_id: player.id
});
const fill = result.fill as SpritesheetFill;
expect(checkSlotFill(player, fill)).toEqual([]);
expect(fill.columns).toBe(8);
expect(fill.rows).toBe(2);
expect(fill.animations).toEqual({
idle: { from: 0, to: 3, fps: 8, loop: true },
run: { from: 4, to: 11, fps: 8, loop: true },
jump: { from: 12, to: 13, fps: 8, loop: false },
hurt: { from: 14, to: 15, fps: 8, loop: false }
});
expect(stamped(result)).toEqual(fill);
});
it("accepts the animations as a JSON string and honours loop overrides", async () => {
const image = await makeImage(256, 64, noise);
const result = await runNode(".SpriteSheet", {
image,
cell_width: 32,
cell_height: 32,
animations: JSON.stringify(player.animations),
loop: { jump: true, idle: false },
fps: 8,
slot_id: player.id
});
const fill = result.fill as SpritesheetFill;
expect(fill.animations.jump.loop).toBe(true);
expect(fill.animations.idle.loop).toBe(false);
expect(fill.animations.hurt.loop).toBe(false);
});
it("checkSlotFill rejects the player fill offered to another slot", async () => {
const image = await makeImage(256, 64, noise);
const result = await runNode(".SpriteSheet", {
image,
cell_width: 32,
cell_height: 32,
animations: player.animations,
fps: 8,
slot_id: "enemy.walker"
});
expect(
checkSlotFill(slot("enemy.walker"), result.fill as SpritesheetFill)
).toEqual(["animation walk missing", "animation die missing"]);
});
it("throws when the sheet is not a multiple of the cell", async () => {
const image = await makeImage(250, 64, noise);
await expect(
runNode(".SpriteSheet", {
image,
cell_width: 32,
cell_height: 32,
animations: player.animations,
fps: 8,
slot_id: player.id
})
).rejects.toThrow(/Sprite Sheet: image 250x64 is not a multiple of cell 32x32/);
});
it("throws when the animations need more frames than the sheet holds", async () => {
const image = await makeImage(128, 64, noise);
await expect(
runNode(".SpriteSheet", {
image,
cell_width: 32,
cell_height: 32,
animations: player.animations,
fps: 8,
slot_id: player.id
})
).rejects.toThrow(/Sprite Sheet: animations need 16 frames, sheet holds 8/);
});
it("throws on an empty animation list and a bad slot id", async () => {
const image = await makeImage(64, 32, noise);
await expect(
runNode(".SpriteSheet", {
image,
cell_width: 32,
cell_height: 32,
animations: {},
fps: 8,
slot_id: "player"
})
).rejects.toThrow(/at least one animation/);
await expect(
runNode(".SpriteSheet", {
image,
cell_width: 32,
cell_height: 32,
animations: { idle: 2 },
fps: 8,
slot_id: "Player"
})
).rejects.toThrow(/Sprite Sheet: fill failed validation/);
});
});
describe("nodetool.game.Tileset", () => {
const ground = slot("tiles.ground");
it("fills the fixture tiles.ground slot from a 64x48 sheet", async () => {
const image = await makeImage(64, 48, noise);
const result = await runNode(".Tileset", {
image,
cell_width: 16,
cell_height: 16,
count: 12,
slot_id: ground.id
});
const fill = result.fill as TilesetFill;
expect(checkSlotFill(ground, fill)).toEqual([]);
expect(fill).toMatchObject({ columns: 4, rows: 3, count: 12 });
expect(stamped(result)).toEqual(fill);
});
it("throws when the count exceeds the grid or the sheet is off-cell", async () => {
await expect(
runNode(".Tileset", {
image: await makeImage(64, 48, noise),
cell_width: 16,
cell_height: 16,
count: 13,
slot_id: ground.id
})
).rejects.toThrow(/Tileset: 13 tiles do not fit 4x3/);
await expect(
runNode(".Tileset", {
image: await makeImage(60, 48, noise),
cell_width: 16,
cell_height: 16,
count: 12,
slot_id: ground.id
})
).rejects.toThrow(/Tileset: image 60x48 is not a multiple of cell 16x16/);
});
});
describe("nodetool.game.SeamlessImage", () => {
it.each([[true, false], [false, true], [true, true]])(
"repairs requested axes x=%s y=%s and preserves the center",
async (checkX, checkY) => {
const image = await makeImage(64, 64, (x, y) => [x * 4, y * 4, 80]);
const result = await runNode(".SeamlessImage", {
image, slot_id: "bg.space", check_x: checkX, check_y: checkY,
repair: true, threshold: 0
});
const output = result.output as { data: Uint8Array; uri: string; asset_id: string | null };
expect(output.uri).toBe("");
expect(output.asset_id).toBeNull();
const { data, info } = await sharp(output.data).ensureAlpha().raw()
.toBuffer({ resolveWithObject: true });
expect([info.width, info.height]).toEqual([64, 64]);
const pixel = (x: number, y: number) => [...data.subarray((y * 64 + x) * 4, (y * 64 + x) * 4 + 4)];
expect(pixel(32, 32)).toEqual([128, 128, 80, 255]);
for (let i = 0; i < 64; i++) {
if (checkX) expect(pixel(0, i)).toEqual(pixel(63, i));
if (checkY) expect(pixel(i, 0)).toEqual(pixel(i, 63));
}
expect(result.fill).toMatchObject({ seamless_x: checkX, seamless_y: checkY });
expect(stamped(result)).toEqual(result.fill);
}
);
it.each([[1, 1], [1, 7], [7, 1], [2, 2], [9, 11], [1920, 1080]])(
"repairs images sized %s by %s",
async (width, height) => {
const image = await makeImage(width, height, (x, y) => [x * 20, y * 20, 50]);
const result = await runNode(".SeamlessImage", {
image, slot_id: "bg.space", check_x: true, check_y: true,
repair: true, threshold: 0
});
expect(result.fill).toMatchObject({ size: [width, height], seamless_x: true, seamless_y: true });
}
);
it("does not alter artwork when neither axis requires tiling", async () => {
const image = await makeImage(16, 16, (x, y) => [x * 10, y * 10, 50]);
const result = await runNode(".SeamlessImage", {
image, slot_id: "title", check_x: false, check_y: false, repair: true
});
const output = result.output as { data: Uint8Array };
expect(Buffer.from(output.data)).toEqual(Buffer.from(image.data as string, "base64"));
});
it("blends transparency without leaking invisible colors into the edge", async () => {
const pixels = Buffer.alloc(16 * 16 * 4);
for (let i = 0; i < 16 * 16; i++) {
pixels.set(i < 128 ? [255, 0, 0, 0] : [0, 0, 255, 255], i * 4);
}
const data = await sharp(pixels, { raw: { width: 16, height: 16, channels: 4 } }).png().toBuffer();
const result = await runNode(".SeamlessImage", {
image: { type: "image", data }, slot_id: "bg.space",
check_x: false, check_y: true, repair: true, threshold: 0
});
const output = result.output as { data: Uint8Array };
const rgba = await sharp(output.data).ensureAlpha().raw().toBuffer();
expect([...rgba.subarray(0, 4)]).toEqual([0, 0, 255, 128]);
expect([...rgba.subarray(15 * 16 * 4, 15 * 16 * 4 + 4)]).toEqual([0, 0, 255, 128]);
});
const bgFar = slot("bg.far");
if (bgFar.kind !== "image") throw new Error("bg.far is an image");
const [w, h] = bgFar.size;
/** Periodic in x (wraps at the edge) and hard-edged in y. */
const tileableX = (x: number, y: number): [number, number, number] => {
const t = (x / w) * Math.PI * 2;
const v = Math.round(127 + 120 * Math.sin(t));
return [v, (v + 40) % 256, y < h / 2 ? 20 : 235];
};
/** A hard seam on x: black left half, white right half. */
const hardEdgeX = (x: number): [number, number, number] =>
x < w / 2 ? [0, 0, 0] : [255, 255, 255];
it("reports seamless_x true for a tileable image and passes the slot", async () => {
const image = await makeImage(w, h, tileableX);
const result = await runNode(".SeamlessImage", {
image,
slot_id: bgFar.id,
check_x: true,
check_y: true,
threshold: 12
});
const fill = result.fill as ImageFill;
expect(fill).toEqual({
kind: "image",
slot_id: "bg.far",
size: [w, h],
seamless_x: true,
seamless_y: false
});
expect(checkSlotFill(bgFar, fill)).toEqual([]);
expect(stamped(result)).toEqual(fill);
});
it("reports seamless_x false for a hard-edged image and fails the slot", async () => {
const image = await makeImage(w, h, hardEdgeX);
const result = await runNode(".SeamlessImage", {
image,
slot_id: bgFar.id,
check_x: true,
check_y: false
});
const fill = result.fill as ImageFill;
expect(fill.seamless_x).toBe(false);
expect(checkSlotFill(bgFar, fill)).toEqual(["not seamless on x"]);
});
it("reports seamless_y true when the rows wrap, independent of x", async () => {
const image = await makeImage(64, 64, (x, y) => [
x < 32 ? 0 : 255,
Math.round(127 + 120 * Math.sin((y / 64) * Math.PI * 2)),
0
]);
const result = await runNode(".SeamlessImage", {
image,
slot_id: "title",
check_x: true,
check_y: true
});
const fill = result.fill as ImageFill;
expect(fill.seamless_x).toBe(false);
expect(fill.seamless_y).toBe(true);
});
it("does not claim an axis it was told not to check", async () => {
const image = await makeImage(64, 64, () => [50, 60, 70]);
const result = await runNode(".SeamlessImage", {
image,
slot_id: "title",
check_x: false,
check_y: false
});
const fill = result.fill as ImageFill;
expect(fill.seamless_x).toBe(false);
expect(fill.seamless_y).toBe(false);
});
it("size mismatch against the slot is caught by checkSlotFill", async () => {
const image = await makeImage(64, 64, tileableX);
const result = await runNode(".SeamlessImage", {
image,
slot_id: bgFar.id,
check_x: true
});
expect(checkSlotFill(bgFar, result.fill as ImageFill)).toContain(
"size 64x64 is not 960x540"
);
});
it("stores the stamped sheet as an asset when the context can create one", async () => {
const player = slot("player");
if (player.kind !== "spritesheet") throw new Error("player is a spritesheet");
const image = await makeImage(256, 64, noise);
const calls: Array<Record<string, unknown>> = [];
const context = {
hasModelInterface: (name: string) => name === "createAsset",
createAsset: async (args: Record<string, unknown>) => {
calls.push(args);
return { id: "asset-player" };
}
};
const result = await runNode(
".SpriteSheet",
{
image,
cell_width: 32,
cell_height: 32,
animations: player.animations,
fps: player.fps,
slot_id: player.id
},
context
);
const output = result.output as { asset_id?: string; uri?: string };
expect(output.asset_id).toBe("asset-player");
expect(output.uri).toBe("asset://asset-player.png");
expect(calls).toHaveLength(1);
expect(calls[0].name).toBe("player.png");
expect(calls[0].contentType).toBe("image/png");
expect(calls[0].content).toBeInstanceOf(Uint8Array);
expect((calls[0].metadata as Record<string, unknown>)[SLOT_METADATA_KEY]).toEqual(result.fill);
});
it("reads a stored asset through the asset resolver, not the temporary store", async () => {
const inline = await makeImage(64, 32, noise);
const png = Buffer.from(inline.data as string, "base64");
const retrieved: string[] = [];
const resolved: string[] = [];
const context = {
resolveAssetBytes: async (uri: string) => {
resolved.push(uri);
return { bytes: new Uint8Array(png), attempts: [] };
},
storage: {
retrieve: async (key: string) => {
retrieved.push(key);
return null;
}
}
};
const result = await runNode(
".Tileset",
{
image: { type: "image", uri: "asset://stored-tiles.png", asset_id: "stored-tiles" },
cell_width: 16,
cell_height: 16,
count: 8,
slot_id: "tiles.ground"
},
context
);
expect(resolved).toEqual(["asset://stored-tiles.png"]);
expect(retrieved).toEqual([]);
const fill = result.fill as TilesetFill;
expect([fill.columns, fill.rows]).toEqual([4, 2]);
});
it("re-encodes a WebP generation as PNG before stamping and storing it", async () => {
const pixels = Buffer.alloc(64 * 32 * 3);
for (let i = 0; i < 64 * 32; i++) {
const [r, g, b] = noise(i % 64, Math.floor(i / 64));
pixels.set([r, g, b], i * 3);
}
const webp = await sharp(pixels, { raw: { width: 64, height: 32, channels: 3 } })
.webp()
.toBuffer();
expect(webp.subarray(8, 12).toString("ascii")).toBe("WEBP");
const calls: Array<Record<string, unknown>> = [];
const context = {
hasModelInterface: (name: string) => name === "createAsset",
createAsset: async (args: Record<string, unknown>) => {
calls.push(args);
return { id: "asset-title" };
}
};
const result = await runNode(
".SeamlessImage",
{
image: { type: "image", data: webp.toString("base64"), uri: "" },
slot_id: "title",
check_x: false,
check_y: false
},
context
);
const output = result.output as { data: Uint8Array; uri: string };
expect(Buffer.from(output.data.subarray(0, 8))).toEqual(PNG_MAGIC);
expect(output.uri).toBe("asset://asset-title.png");
expect(calls[0].name).toBe("title.png");
expect(calls[0].contentType).toBe("image/png");
expect(Buffer.from((calls[0].content as Uint8Array).subarray(0, 8))).toEqual(PNG_MAGIC);
const meta = await sharp(Buffer.from(output.data)).metadata();
expect([meta.format, meta.width, meta.height]).toEqual(["png", 64, 32]);
});
});
describe("a connected game_slot input", () => {
const player = slot("player");
const ground = slot("tiles.ground");
const bg = slot("bg.far");
it("beats stale hand-typed values on SpriteSheet", async () => {
const image = await makeImage(256, 64, noise);
const result = await runNode(".SpriteSheet", {
image,
slot: player,
// Everything below is left over from a different slot and must lose.
cell_width: 16,
cell_height: 16,
animations: { walk: 6, die: 4 },
fps: 24,
slot_id: "enemy.walker"
});
const fill = result.fill as SpritesheetFill;
expect(fill.slot_id).toBe("player");
expect(fill.cell).toEqual([32, 32]);
expect(fill.columns).toBe(8);
expect(fill.rows).toBe(2);
expect(Object.keys(fill.animations)).toEqual(["idle", "run", "jump", "hurt"]);
expect(fill.animations.idle.fps).toBe(8);
expect(checkSlotFill(player, fill)).toEqual([]);
});
it("beats stale hand-typed values on Tileset", async () => {
const image = await makeImage(64, 48, noise);
const result = await runNode(".Tileset", {
image,
slot: ground,
cell_width: 32,
cell_height: 32,
count: 4,
slot_id: "player"
});
const fill = result.fill as TilesetFill;
expect(fill.slot_id).toBe("tiles.ground");
expect(fill.cell).toEqual([16, 16]);
expect(fill.count).toBe(12);
expect(checkSlotFill(ground, fill)).toEqual([]);
});
it("beats stale hand-typed values on SeamlessImage", async () => {
// Seamless on x: column 0 and the last column match.
const image = await makeImage(64, 32, (x, y) =>
x === 63 ? [0, y, 0] : [0, y, 0]
);
const result = await runNode(".SeamlessImage", {
image,
slot: bg,
check_x: false,
check_y: true,
slot_id: "title"
});
const fill = result.fill as ImageFill;
expect(fill.slot_id).toBe("bg.far");
expect(fill.seamless_x).toBe(true);
// check_y was true by hand and false on the slot, so it never ran.
expect(fill.seamless_y).toBe(false);
});
it("leaves the hand-typed values alone when nothing is wired", async () => {
const image = await makeImage(64, 48, noise);
for (const slotValue of [undefined, null, {}, ""]) {
const result = await runNode(".Tileset", {
image,
slot: slotValue,
cell_width: 16,
cell_height: 16,
count: 12,
slot_id: "tiles.ground"
});
expect((result.fill as TilesetFill).slot_id, String(slotValue)).toBe(
"tiles.ground"
);
}
});
it("refuses a slot of the wrong kind rather than ignoring it", async () => {
const image = await makeImage(64, 48, noise);
await expect(
runNode(".Tileset", { image, slot: player })
).rejects.toThrow(/player is a spritesheet slot, not a tileset slot/);
});
it("refuses a malformed slot rather than falling back", async () => {
const image = await makeImage(64, 48, noise);
await expect(
runNode(".Tileset", {
image,
slot: { id: "tiles.ground", kind: "tileset", cell: [16, 16] },
cell_width: 16,
cell_height: 16,
count: 12,
slot_id: "tiles.ground"
})
).rejects.toThrow(/not a game slot spec/);
});
});
const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);