Sprite-Sheet-Check
Misst ein Blatt mit Einzelbildern einer Animation und meldet, was damit im Spiel schiefgehen wird: ein Hintergrund, der gemalt und nicht durchsichtig ist, Einzelbilder, die sich nicht gleichmäßig schneiden lassen, eine zerschnittene Figur, Füße, die nicht auf einer Linie stehen, ein Körper, der seitwärts springt, und eine Schleife, die ruckt. Jeder Fund nennt die Einzelbilder und die Pixelzeilen, um die es geht.


Wann du das brauchst
Bevor ein Sprite-Sheet in dein Spiel kommt, vor allem eines aus einem Bildgenerator, und nach jeder Reparatur noch einmal. Deine KI lässt es auf der echten Datei laufen und zeigt dir den Bericht, du bekommst also gemessene Zeilen und Zahlen und keine Meinung darüber, wie das Bild aussieht. Ob die Animation gut aussieht, kann es dir nicht sagen: Ein Gang kann jede Prüfung bestehen und trotzdem steif wirken, und das beurteilen deine Augen.
Das sagst du deiner KI
Prüf mein Sprite-Sheet mit dem Sprite-Sheet-Check von Spielerando und lies die Datei mit dem Rezept PNG-Pixel von Spielerando. Jedes Einzelbild soll 32 mal 32 Pixel groß sein. Zeig mir den Bericht Wort für Wort, behebe, was er gefunden hat, lass ihn noch einmal laufen und zeig mir auch den zweiten Bericht.
Der Code, von https://spielerando.com/de/recipes/sprite-sheet-check (TypeScript, tested):
```ts
/* Sprite sheet check: measures a sheet of animation frames instead of looking at it. It finds what
makes a sprite fall apart in a game: a background that is painted and not see-through, frames
that cannot be cut evenly, a figure cut in two, feet that are not on one line, a body that jumps
sideways, a loop that jerks, soft edges and too many colours for pixel art.
Usage:
const report = checkSpriteSheet(sheet, { frameWidth: 32, frameHeight: 32 });
console.log(report.text); // every finding, with the frames it is about
report.ok; // true when nothing was found
report.frames[2].footLine; // the numbers behind it, for each frame
`sheet` is the picture as pixels: { width, height, data } with four numbers a pixel (red, green,
blue, opacity). A canvas gives you that with getImageData, and the PNG pixels recipe reads it
from a file. Say how the sheet is cut with `frameWidth` and `frameHeight`, or with `columns`
and `rows`.
To fix the most common finding, feet on different lines:
const frames = alignFeet(cutFrames(sheet, { frameWidth: 32, frameHeight: 32 }));
const fixed = joinFrames(frames, 4); // a new sheet, four frames a row
Frames and rows count from 1, as a person counts: frame 1 is top left, row 1 is a frame's top
row. Empty frames at the end of the sheet are left out, because sheets are often not full.
What it cannot tell you: whether the animation looks good. A walk can pass every check and
still look stiff. That part is for your eyes.
SPDX-License-Identifier: MIT
Copyright (c) 2026 Spielerando, https://spielerando.com */
export const DEFAULTS = {
/** "pixel" for pixel art, "painted" for soft drawings: only pixel art is held to hard edges and few colours. */
style: "pixel",
/** "loop" for an animation that repeats, "once" for one that ends. */
plays: "loop",
/** How many pixels the foot line of a frame may be off. */
footTolerance: 0,
/** How many pixels the middle of the drawing may move sideways from frame to frame. */
driftTolerance: 2,
/** The most colours a pixel art sheet may use. */
maxColors: 32,
/** How many times bigger than the biggest step inside the animation the step from the last frame back to the first may be. */
loopJump: 1.5,
};
export type SheetSettings = Partial<typeof DEFAULTS>;
/** A picture as a canvas holds it: four numbers a pixel (red, green, blue, opacity), row by row. */
export interface Pixels {
width: number;
height: number;
data: Uint8ClampedArray;
}
/** How the sheet is cut: the size of a frame, or how many frames there are across and down. */
export interface SheetLayout {
frameWidth?: number;
frameHeight?: number;
columns?: number;
rows?: number;
}
export type FindingKind =
| "uneven-cut"
| "no-transparency"
| "painted-checkerboard"
| "soft-edges"
| "too-many-colors"
| "empty-frame"
| "cut-through"
| "foot-line"
| "drift"
| "new-colors"
| "loop-jump"
| "doubled-frame";
export interface Finding {
kind: FindingKind;
/** The frames it is about, counting from 1. */
frames: number[];
message: string;
}
export interface FrameInfo {
/** Counting from 1, row by row. */
frame: number;
empty: boolean;
/** The box around what is drawn, inside the frame, counting from 1. */
left: number;
right: number;
top: number;
/** The lowest row with something drawn in it: where the feet are. */
footLine: number;
/** The middle of the drawing from left to right, in pixels from the frame's left edge. */
middle: number;
/** How many pixels are drawn. */
pixels: number;
colors: number;
}
export interface SheetReport {
ok: boolean;
frameWidth: number;
frameHeight: number;
columns: number;
rows: number;
/** How many real pixels wide one pixel of the art is: 1, or more for a sheet that was scaled up. */
pixelSize: number;
frames: FrameInfo[];
findings: Finding[];
/** The report in words, to show as it is. */
text: string;
}
const hex = (r: number, g: number, b: number) => "#" + [r, g, b].map((v) => v.toString(16).padStart(2, "0")).join("");
const list = (numbers: number[]) => (numbers.length === 1 ? `${numbers[0]}` : `${numbers.slice(0, -1).join(", ")} and ${numbers[numbers.length - 1]}`);
const plural = (n: number, one: string, many = one + "s") => `${n} ${n === 1 ? one : many}`;
function grid(sheet: Pixels, layout: SheetLayout): { frameWidth: number; frameHeight: number; columns: number; rows: number; problem?: string } {
let frameWidth = layout.frameWidth ?? 0;
let frameHeight = layout.frameHeight ?? 0;
if (!frameWidth && layout.columns) frameWidth = sheet.width / layout.columns;
// without a height or a count of rows, the sheet is one row of frames
if (!frameHeight) frameHeight = layout.rows ? sheet.height / layout.rows : sheet.height;
if (!frameWidth) throw new Error("Say how the sheet is cut: give frameWidth and frameHeight, or columns and rows.");
if (frameWidth < 1 || frameHeight < 1) throw new Error(`A frame of ${frameWidth} by ${frameHeight} pixels cannot be cut.`);
const problems: string[] = [];
if (!Number.isInteger(frameWidth) || sheet.width % frameWidth !== 0) {
const across = Number.isInteger(frameWidth) ? `frames ${frameWidth} wide leave ${sheet.width % frameWidth} over` : `${layout.columns} frames across would each be ${Math.round(frameWidth * 100) / 100} pixels wide`;
problems.push(`the sheet is ${sheet.width} pixels wide and ${across}`);
}
if (!Number.isInteger(frameHeight) || sheet.height % frameHeight !== 0) {
const down = Number.isInteger(frameHeight) ? `frames ${frameHeight} high leave ${sheet.height % frameHeight} over` : `${layout.rows} rows would each be ${Math.round(frameHeight * 100) / 100} pixels high`;
problems.push(`the sheet is ${sheet.height} pixels high and ${down}`);
}
frameWidth = Math.floor(frameWidth);
frameHeight = Math.floor(frameHeight);
return { frameWidth, frameHeight, columns: Math.floor(sheet.width / frameWidth), rows: Math.floor(sheet.height / frameHeight), problem: problems.join(", and ") || undefined };
}
/** The frames of a sheet as pictures of their own, row by row, without the empty ones at the end. */
export function cutFrames(sheet: Pixels, layout: SheetLayout): Pixels[] {
const { frameWidth, frameHeight, columns, rows } = grid(sheet, layout);
const frames: Pixels[] = [];
for (let r = 0; r < rows; r++) {
for (let c = 0; c < columns; c++) {
const data = new Uint8ClampedArray(frameWidth * frameHeight * 4);
for (let y = 0; y < frameHeight; y++) {
const from = ((r * frameHeight + y) * sheet.width + c * frameWidth) * 4;
data.set(sheet.data.subarray(from, from + frameWidth * 4), y * frameWidth * 4);
}
frames.push({ width: frameWidth, height: frameHeight, data });
}
}
while (frames.length > 0 && isEmpty(frames[frames.length - 1])) frames.pop();
return frames;
}
function isEmpty(frame: Pixels): boolean {
for (let i = 3; i < frame.data.length; i += 4) if (frame.data[i] !== 0) return false;
return true;
}
/** Frames put side by side into one sheet, `columns` a row. */
export function joinFrames(frames: Pixels[], columns: number = frames.length): Pixels {
if (frames.length === 0) throw new Error("There are no frames to join.");
const { width: w, height: h } = frames[0];
for (const [i, frame] of frames.entries()) if (frame.width !== w || frame.height !== h) throw new Error(`Frame ${i + 1} is ${frame.width} by ${frame.height} pixels, frame 1 is ${w} by ${h}.`);
const rows = Math.ceil(frames.length / columns);
const sheet: Pixels = { width: w * columns, height: h * rows, data: new Uint8ClampedArray(w * columns * h * rows * 4) };
frames.forEach((frame, i) => {
const left = (i % columns) * w;
const top = Math.floor(i / columns) * h;
for (let y = 0; y < h; y++) sheet.data.set(frame.data.subarray(y * w * 4, (y + 1) * w * 4), ((top + y) * sheet.width + left) * 4);
});
return sheet;
}
function measure(frame: Pixels, index: number): FrameInfo {
let left = frame.width;
let right = -1;
let top = frame.height;
let bottom = -1;
let pixels = 0;
let sum = 0;
const colors = new Set<number>();
for (let y = 0; y < frame.height; y++) {
for (let x = 0; x < frame.width; x++) {
const i = (y * frame.width + x) * 4;
if (frame.data[i + 3] === 0) continue;
pixels++;
sum += x + 0.5;
if (x < left) left = x;
if (x > right) right = x;
if (y < top) top = y;
if (y > bottom) bottom = y;
colors.add((frame.data[i] << 16) | (frame.data[i + 1] << 8) | frame.data[i + 2]);
}
}
if (pixels === 0) return { frame: index + 1, empty: true, left: 0, right: 0, top: 0, footLine: 0, middle: 0, pixels: 0, colors: 0 };
return { frame: index + 1, empty: false, left: left + 1, right: right + 1, top: top + 1, footLine: bottom + 1, middle: Math.round((sum / pixels) * 100) / 100, pixels, colors: colors.size };
}
/** The frames moved down, never stretched, until every one stands on the lowest foot line among them. */
export function alignFeet(frames: Pixels[]): Pixels[] {
const infos = frames.map(measure);
const line = Math.max(0, ...infos.filter((f) => !f.empty).map((f) => f.footLine));
return frames.map((frame, i) => {
const shift = infos[i].empty ? 0 : line - infos[i].footLine;
const data = new Uint8ClampedArray(frame.data.length);
data.set(frame.data.subarray(0, (frame.height - shift) * frame.width * 4), shift * frame.width * 4);
return { width: frame.width, height: frame.height, data };
});
}
/** How many real pixels one pixel of the art takes: the biggest block size at which every block is one colour. */
export function pixelSizeOf(picture: Pixels): number {
const same = (a: number, b: number) => picture.data[a] === picture.data[b] && picture.data[a + 1] === picture.data[b + 1] && picture.data[a + 2] === picture.data[b + 2] && picture.data[a + 3] === picture.data[b + 3];
for (let size = Math.min(picture.width, picture.height, 64); size > 1; size--) {
if (picture.width % size !== 0 || picture.height % size !== 0) continue;
let blocks = true;
for (let y = 0; y < picture.height && blocks; y++) {
for (let x = 0; x < picture.width; x++) {
if (!same((y * picture.width + x) * 4, ((y - (y % size)) * picture.width + x - (x % size)) * 4)) {
blocks = false;
break;
}
}
}
if (blocks) return size;
}
return 1;
}
/** How many pixels differ between two frames of one size. */
function difference(a: Pixels, b: Pixels): number {
let n = 0;
for (let i = 0; i < a.data.length; i += 4) {
const clearA = a.data[i + 3] === 0;
const clearB = b.data[i + 3] === 0;
if (clearA && clearB) continue;
if (clearA !== clearB || a.data[i] !== b.data[i] || a.data[i + 1] !== b.data[i + 1] || a.data[i + 2] !== b.data[i + 2] || a.data[i + 3] !== b.data[i + 3]) n++;
}
return n;
}
/** What the outermost pixels of the sheet are painted with, when nothing in it is see-through. */
function background(sheet: Pixels): Finding {
const counts = new Map<number, number>();
let total = 0;
const see = (x: number, y: number) => {
const i = (y * sheet.width + x) * 4;
const key = (sheet.data[i] << 16) | (sheet.data[i + 1] << 8) | sheet.data[i + 2];
counts.set(key, (counts.get(key) ?? 0) + 1);
total++;
};
for (let x = 0; x < sheet.width; x++) {
see(x, 0);
see(x, sheet.height - 1);
}
for (let y = 1; y < sheet.height - 1; y++) {
see(0, y);
see(sheet.width - 1, y);
}
const sorted = [...counts].sort((a, b) => b[1] - a[1]);
const name = (key: number) => hex(key >> 16, (key >> 8) & 255, key & 255);
const grey = (key: number) => Math.max(key >> 16, (key >> 8) & 255, key & 255) - Math.min(key >> 16, (key >> 8) & 255, key & 255) <= 12 && (key & 255) >= 140;
const [first, second] = sorted;
// a figure may touch the edge, so the two greys need not be all of it: a fifth each and most of it together
if (second && grey(first[0]) && grey(second[0]) && second[1] >= total * 0.2 && first[1] + second[1] >= total * 0.6) {
return { kind: "painted-checkerboard", frames: [], message: `No pixel is see-through, and the sheet's edge is two greys in turn (${name(first[0])} and ${name(second[0])}): the checkerboard that means "see-through" in image programs was painted into the picture.` };
}
const share = Math.round((first[1] / total) * 100);
const edge = share < 50 ? `has ${counts.size} colours and none of them fills half of it` : `is ${share === 100 ? "all" : `${share} percent`} ${name(first[0])}`;
return { kind: "no-transparency", frames: [], message: `No pixel is see-through. The sheet's edge ${edge}: the background is painted, and in a game every frame shows up as a box.` };
}
/** Measures a sheet of frames and reports what will go wrong with it in a game. */
export function checkSpriteSheet(sheet: Pixels, layout: SheetLayout, settings: SheetSettings = {}): SheetReport {
const { style = DEFAULTS.style, plays = DEFAULTS.plays, footTolerance = DEFAULTS.footTolerance, driftTolerance = DEFAULTS.driftTolerance, maxColors = DEFAULTS.maxColors, loopJump = DEFAULTS.loopJump } = settings;
if (sheet.data.length !== sheet.width * sheet.height * 4) throw new Error(`A sheet of ${sheet.width} by ${sheet.height} pixels needs ${sheet.width * sheet.height * 4} numbers, and there are ${sheet.data.length}.`);
const { frameWidth, frameHeight, columns, rows, problem } = grid(sheet, layout);
const findings: Finding[] = [];
if (problem) findings.push({ kind: "uneven-cut", frames: [], message: `The sheet cannot be cut into equal frames: ${problem}. Cut like this, every frame after the first is shifted.` });
let clear = 0;
let soft = 0;
const allColors = new Set<number>();
for (let i = 0; i < sheet.data.length; i += 4) {
const a = sheet.data[i + 3];
if (a === 0) clear++;
else {
if (a !== 255) soft++;
allColors.add((sheet.data[i] << 16) | (sheet.data[i + 1] << 8) | sheet.data[i + 2]);
}
}
if (clear === 0) findings.push(background(sheet));
if (style === "pixel") {
if (soft > 0) findings.push({ kind: "soft-edges", frames: [], message: `${plural(soft, "pixel is", "pixels are")} partly see-through. Pixel art has hard edges; soft ones show as a pale rim around the figure.` });
if (allColors.size > maxColors) findings.push({ kind: "too-many-colors", frames: [], message: `The sheet uses ${allColors.size} colours, and the limit is ${maxColors}. Pixel art is drawn with a few fixed colours; thousands mean it is a soft picture made to look like pixel art.` });
}
const pictures = cutFrames(sheet, { frameWidth, frameHeight });
const frames = pictures.map(measure);
const drawn = frames.filter((f) => !f.empty);
const empty = frames.filter((f) => f.empty).map((f) => f.frame);
if (empty.length > 0) findings.push({ kind: "empty-frame", frames: empty, message: `${empty.length === 1 ? "Frame" : "Frames"} ${list(empty)} ${empty.length === 1 ? "is" : "are"} empty in the middle of the animation: the figure blinks out for a moment.` });
// a drawing that runs across the cut between two frames of a row
for (let i = 0; i + 1 < pictures.length; i++) {
if ((i + 1) % columns === 0) continue;
let touching = 0;
for (let y = 0; y < frameHeight; y++) {
if (pictures[i].data[(y * frameWidth + frameWidth - 1) * 4 + 3] !== 0 && pictures[i + 1].data[y * frameWidth * 4 + 3] !== 0) touching++;
}
if (touching > 0 && clear > 0) findings.push({ kind: "cut-through", frames: [i + 1, i + 2], message: `The drawing runs across the cut between frames ${i + 1} and ${i + 2}, in ${plural(touching, "row")}: one figure is cut in two, or two figures touch.` });
}
if (drawn.length > 1 && clear > 0) {
// the foot line most frames share is the ground; the others are off it
const usual = (values: number[]) => {
const counts = new Map<number, number>();
for (const v of values) counts.set(v, (counts.get(v) ?? 0) + 1);
return [...counts].sort((a, b) => b[1] - a[1] || b[0] - a[0])[0][0];
};
const ground = usual(drawn.map((f) => f.footLine));
const off = drawn.filter((f) => Math.abs(f.footLine - ground) > footTolerance);
if (off.length > 0) {
findings.push({ kind: "foot-line", frames: off.map((f) => f.frame), message: `The feet are not on one line: ${off.map((f) => `frame ${f.frame} stands on row ${f.footLine}`).join(", ")}, the ${off.length === drawn.length - 1 ? "other" : "others"} on row ${ground}. The figure bobs up and down while it plays.` });
}
const middles = drawn.map((f) => f.middle).sort((a, b) => a - b);
const median = middles[Math.floor((middles.length - 1) / 2)];
const adrift = drawn.filter((f) => Math.abs(f.middle - median) > driftTolerance);
if (adrift.length > 0) {
findings.push({ kind: "drift", frames: adrift.map((f) => f.frame), message: `The figure does not stay in place: ${adrift.map((f) => `in frame ${f.frame} its middle is ${Math.abs(Math.round((f.middle - median) * 10) / 10)} pixels to the ${f.middle < median ? "left" : "right"}`).join(", ")}. It jitters sideways while it plays.` });
}
}
if (style === "pixel" && drawn.length > 2 && clear > 0 && allColors.size <= maxColors) {
// colours only one frame has: a hat that changes colour for one step
const users = new Map<number, Set<number>>();
pictures.forEach((picture, f) => {
for (let i = 0; i < picture.data.length; i += 4) {
if (picture.data[i + 3] === 0) continue;
const key = (picture.data[i] << 16) | (picture.data[i + 1] << 8) | picture.data[i + 2];
if (!users.has(key)) users.set(key, new Set());
users.get(key)!.add(f);
}
});
for (const [f] of pictures.entries()) {
const own = [...users].filter(([, where]) => where.size === 1 && where.has(f)).map(([key]) => hex(key >> 16, (key >> 8) & 255, key & 255));
if (own.length > 0) findings.push({ kind: "new-colors", frames: [f + 1], message: `Frame ${f + 1} has ${plural(own.length, "colour")} no other frame has (${own.slice(0, 4).join(", ")}${own.length > 4 ? ", …" : ""}). If that is not an effect you wanted, something about the figure changes for that one frame.` });
}
}
if (plays === "loop" && pictures.length > 2 && empty.length === 0) {
const steps = pictures.slice(1).map((picture, i) => difference(pictures[i], picture));
const biggest = Math.max(...steps);
const back = difference(pictures[pictures.length - 1], pictures[0]);
if (back === 0) {
findings.push({ kind: "doubled-frame", frames: [1, pictures.length], message: `The last frame, ${pictures.length}, is the same picture as the first. Played as a loop that picture shows twice in a row and the motion stalls for a moment: leave the last frame out.` });
} else if (biggest > 0 && back > biggest * loopJump) {
findings.push({ kind: "loop-jump", frames: [pictures.length, 1], message: `The loop does not close: going from the last frame back to the first changes ${plural(back, "pixel")}, and the biggest step inside the animation changes ${biggest}. The figure jerks each time the animation starts over.` });
}
}
const pixelSize = pixelSizeOf(sheet);
const head = [
`Sheet of ${sheet.width} by ${sheet.height} pixels: ${plural(pictures.length, "frame")} of ${frameWidth} by ${frameHeight}${pixelSize > 1 ? `, scaled up ${pixelSize} times (the art itself is ${frameWidth / pixelSize} by ${frameHeight / pixelSize})` : ""}.`,
`See-through pixels: ${clear}. Partly see-through: ${soft}. Colours: ${allColors.size}.`,
findings.length === 0 ? "No problems found." : `Found ${plural(findings.length, "problem")}.`,
];
return { ok: findings.length === 0, frameWidth, frameHeight, columns, rows, pixelSize, frames, findings, text: [...head, ...findings.map((f) => `${f.kind}: ${f.message}`)].join("\n") };
}
```
Prüf mein Sprite-Sheet mit dem Sprite-Sheet-Check von Spielerando und lies die Datei mit dem Rezept PNG-Pixel von Spielerando. Jedes Einzelbild soll 32 mal 32 Pixel groß sein. Zeig mir den Bericht Wort für Wort, behebe, was er gefunden hat, lass ihn noch einmal laufen und zeig mir auch den zweiten Bericht.Einstellungen
- style (pixel): Ob das Blatt Pixel Art ist oder eine weiche, gemalte Zeichnung. Nur Pixel Art muss harte Kanten und wenige Farben haben, also gib für alles andere painted an.
- plays (loop): Ob die Animation sich wiederholt oder einmal abläuft. Nur eine Schleife wird auf einen Ruck zwischen letztem und erstem Bild geprüft, also gib once für einen Sprung oder einen Sturz an.
- footTolerance (0): Um wie viele Pixel die unterste gezeichnete Zeile eines Einzelbilds von den anderen abweichen darf. Erhöhe das für eine Figur, die den Boden verlassen soll.
- driftTolerance (2): Um wie viele Pixel die Mitte der Zeichnung von Bild zu Bild seitwärts wandern darf. Ein Gang verschiebt sie ein wenig, wenn die Beine ausgreifen, ein Ausfallschritt stark.
- maxColors (32): Wie viele Farben ein Pixel-Art-Blatt höchstens haben darf. Ein weiches Bild, das nur wie Pixel Art aussieht, hat Tausende.
- loopJump (1.5): Wievielmal größer als die größte Änderung innerhalb der Animation die Änderung vom letzten Einzelbild zurück zum ersten sein darf.
Der Code
Getestetes TypeScript ohne fremde Teile. Kopier es in dein Spiel oder gib es deiner KI zusammen mit dem Text oben.
/* Sprite sheet check: measures a sheet of animation frames instead of looking at it. It finds what
makes a sprite fall apart in a game: a background that is painted and not see-through, frames
that cannot be cut evenly, a figure cut in two, feet that are not on one line, a body that jumps
sideways, a loop that jerks, soft edges and too many colours for pixel art.
Usage:
const report = checkSpriteSheet(sheet, { frameWidth: 32, frameHeight: 32 });
console.log(report.text); // every finding, with the frames it is about
report.ok; // true when nothing was found
report.frames[2].footLine; // the numbers behind it, for each frame
`sheet` is the picture as pixels: { width, height, data } with four numbers a pixel (red, green,
blue, opacity). A canvas gives you that with getImageData, and the PNG pixels recipe reads it
from a file. Say how the sheet is cut with `frameWidth` and `frameHeight`, or with `columns`
and `rows`.
To fix the most common finding, feet on different lines:
const frames = alignFeet(cutFrames(sheet, { frameWidth: 32, frameHeight: 32 }));
const fixed = joinFrames(frames, 4); // a new sheet, four frames a row
Frames and rows count from 1, as a person counts: frame 1 is top left, row 1 is a frame's top
row. Empty frames at the end of the sheet are left out, because sheets are often not full.
What it cannot tell you: whether the animation looks good. A walk can pass every check and
still look stiff. That part is for your eyes.
SPDX-License-Identifier: MIT
Copyright (c) 2026 Spielerando, https://spielerando.com */
export const DEFAULTS = {
/** "pixel" for pixel art, "painted" for soft drawings: only pixel art is held to hard edges and few colours. */
style: "pixel",
/** "loop" for an animation that repeats, "once" for one that ends. */
plays: "loop",
/** How many pixels the foot line of a frame may be off. */
footTolerance: 0,
/** How many pixels the middle of the drawing may move sideways from frame to frame. */
driftTolerance: 2,
/** The most colours a pixel art sheet may use. */
maxColors: 32,
/** How many times bigger than the biggest step inside the animation the step from the last frame back to the first may be. */
loopJump: 1.5,
};
export type SheetSettings = Partial<typeof DEFAULTS>;
/** A picture as a canvas holds it: four numbers a pixel (red, green, blue, opacity), row by row. */
export interface Pixels {
width: number;
height: number;
data: Uint8ClampedArray;
}
/** How the sheet is cut: the size of a frame, or how many frames there are across and down. */
export interface SheetLayout {
frameWidth?: number;
frameHeight?: number;
columns?: number;
rows?: number;
}
export type FindingKind =
| "uneven-cut"
| "no-transparency"
| "painted-checkerboard"
| "soft-edges"
| "too-many-colors"
| "empty-frame"
| "cut-through"
| "foot-line"
| "drift"
| "new-colors"
| "loop-jump"
| "doubled-frame";
export interface Finding {
kind: FindingKind;
/** The frames it is about, counting from 1. */
frames: number[];
message: string;
}
export interface FrameInfo {
/** Counting from 1, row by row. */
frame: number;
empty: boolean;
/** The box around what is drawn, inside the frame, counting from 1. */
left: number;
right: number;
top: number;
/** The lowest row with something drawn in it: where the feet are. */
footLine: number;
/** The middle of the drawing from left to right, in pixels from the frame's left edge. */
middle: number;
/** How many pixels are drawn. */
pixels: number;
colors: number;
}
export interface SheetReport {
ok: boolean;
frameWidth: number;
frameHeight: number;
columns: number;
rows: number;
/** How many real pixels wide one pixel of the art is: 1, or more for a sheet that was scaled up. */
pixelSize: number;
frames: FrameInfo[];
findings: Finding[];
/** The report in words, to show as it is. */
text: string;
}
const hex = (r: number, g: number, b: number) => "#" + [r, g, b].map((v) => v.toString(16).padStart(2, "0")).join("");
const list = (numbers: number[]) => (numbers.length === 1 ? `${numbers[0]}` : `${numbers.slice(0, -1).join(", ")} and ${numbers[numbers.length - 1]}`);
const plural = (n: number, one: string, many = one + "s") => `${n} ${n === 1 ? one : many}`;
function grid(sheet: Pixels, layout: SheetLayout): { frameWidth: number; frameHeight: number; columns: number; rows: number; problem?: string } {
let frameWidth = layout.frameWidth ?? 0;
let frameHeight = layout.frameHeight ?? 0;
if (!frameWidth && layout.columns) frameWidth = sheet.width / layout.columns;
// without a height or a count of rows, the sheet is one row of frames
if (!frameHeight) frameHeight = layout.rows ? sheet.height / layout.rows : sheet.height;
if (!frameWidth) throw new Error("Say how the sheet is cut: give frameWidth and frameHeight, or columns and rows.");
if (frameWidth < 1 || frameHeight < 1) throw new Error(`A frame of ${frameWidth} by ${frameHeight} pixels cannot be cut.`);
const problems: string[] = [];
if (!Number.isInteger(frameWidth) || sheet.width % frameWidth !== 0) {
const across = Number.isInteger(frameWidth) ? `frames ${frameWidth} wide leave ${sheet.width % frameWidth} over` : `${layout.columns} frames across would each be ${Math.round(frameWidth * 100) / 100} pixels wide`;
problems.push(`the sheet is ${sheet.width} pixels wide and ${across}`);
}
if (!Number.isInteger(frameHeight) || sheet.height % frameHeight !== 0) {
const down = Number.isInteger(frameHeight) ? `frames ${frameHeight} high leave ${sheet.height % frameHeight} over` : `${layout.rows} rows would each be ${Math.round(frameHeight * 100) / 100} pixels high`;
problems.push(`the sheet is ${sheet.height} pixels high and ${down}`);
}
frameWidth = Math.floor(frameWidth);
frameHeight = Math.floor(frameHeight);
return { frameWidth, frameHeight, columns: Math.floor(sheet.width / frameWidth), rows: Math.floor(sheet.height / frameHeight), problem: problems.join(", and ") || undefined };
}
/** The frames of a sheet as pictures of their own, row by row, without the empty ones at the end. */
export function cutFrames(sheet: Pixels, layout: SheetLayout): Pixels[] {
const { frameWidth, frameHeight, columns, rows } = grid(sheet, layout);
const frames: Pixels[] = [];
for (let r = 0; r < rows; r++) {
for (let c = 0; c < columns; c++) {
const data = new Uint8ClampedArray(frameWidth * frameHeight * 4);
for (let y = 0; y < frameHeight; y++) {
const from = ((r * frameHeight + y) * sheet.width + c * frameWidth) * 4;
data.set(sheet.data.subarray(from, from + frameWidth * 4), y * frameWidth * 4);
}
frames.push({ width: frameWidth, height: frameHeight, data });
}
}
while (frames.length > 0 && isEmpty(frames[frames.length - 1])) frames.pop();
return frames;
}
function isEmpty(frame: Pixels): boolean {
for (let i = 3; i < frame.data.length; i += 4) if (frame.data[i] !== 0) return false;
return true;
}
/** Frames put side by side into one sheet, `columns` a row. */
export function joinFrames(frames: Pixels[], columns: number = frames.length): Pixels {
if (frames.length === 0) throw new Error("There are no frames to join.");
const { width: w, height: h } = frames[0];
for (const [i, frame] of frames.entries()) if (frame.width !== w || frame.height !== h) throw new Error(`Frame ${i + 1} is ${frame.width} by ${frame.height} pixels, frame 1 is ${w} by ${h}.`);
const rows = Math.ceil(frames.length / columns);
const sheet: Pixels = { width: w * columns, height: h * rows, data: new Uint8ClampedArray(w * columns * h * rows * 4) };
frames.forEach((frame, i) => {
const left = (i % columns) * w;
const top = Math.floor(i / columns) * h;
for (let y = 0; y < h; y++) sheet.data.set(frame.data.subarray(y * w * 4, (y + 1) * w * 4), ((top + y) * sheet.width + left) * 4);
});
return sheet;
}
function measure(frame: Pixels, index: number): FrameInfo {
let left = frame.width;
let right = -1;
let top = frame.height;
let bottom = -1;
let pixels = 0;
let sum = 0;
const colors = new Set<number>();
for (let y = 0; y < frame.height; y++) {
for (let x = 0; x < frame.width; x++) {
const i = (y * frame.width + x) * 4;
if (frame.data[i + 3] === 0) continue;
pixels++;
sum += x + 0.5;
if (x < left) left = x;
if (x > right) right = x;
if (y < top) top = y;
if (y > bottom) bottom = y;
colors.add((frame.data[i] << 16) | (frame.data[i + 1] << 8) | frame.data[i + 2]);
}
}
if (pixels === 0) return { frame: index + 1, empty: true, left: 0, right: 0, top: 0, footLine: 0, middle: 0, pixels: 0, colors: 0 };
return { frame: index + 1, empty: false, left: left + 1, right: right + 1, top: top + 1, footLine: bottom + 1, middle: Math.round((sum / pixels) * 100) / 100, pixels, colors: colors.size };
}
/** The frames moved down, never stretched, until every one stands on the lowest foot line among them. */
export function alignFeet(frames: Pixels[]): Pixels[] {
const infos = frames.map(measure);
const line = Math.max(0, ...infos.filter((f) => !f.empty).map((f) => f.footLine));
return frames.map((frame, i) => {
const shift = infos[i].empty ? 0 : line - infos[i].footLine;
const data = new Uint8ClampedArray(frame.data.length);
data.set(frame.data.subarray(0, (frame.height - shift) * frame.width * 4), shift * frame.width * 4);
return { width: frame.width, height: frame.height, data };
});
}
/** How many real pixels one pixel of the art takes: the biggest block size at which every block is one colour. */
export function pixelSizeOf(picture: Pixels): number {
const same = (a: number, b: number) => picture.data[a] === picture.data[b] && picture.data[a + 1] === picture.data[b + 1] && picture.data[a + 2] === picture.data[b + 2] && picture.data[a + 3] === picture.data[b + 3];
for (let size = Math.min(picture.width, picture.height, 64); size > 1; size--) {
if (picture.width % size !== 0 || picture.height % size !== 0) continue;
let blocks = true;
for (let y = 0; y < picture.height && blocks; y++) {
for (let x = 0; x < picture.width; x++) {
if (!same((y * picture.width + x) * 4, ((y - (y % size)) * picture.width + x - (x % size)) * 4)) {
blocks = false;
break;
}
}
}
if (blocks) return size;
}
return 1;
}
/** How many pixels differ between two frames of one size. */
function difference(a: Pixels, b: Pixels): number {
let n = 0;
for (let i = 0; i < a.data.length; i += 4) {
const clearA = a.data[i + 3] === 0;
const clearB = b.data[i + 3] === 0;
if (clearA && clearB) continue;
if (clearA !== clearB || a.data[i] !== b.data[i] || a.data[i + 1] !== b.data[i + 1] || a.data[i + 2] !== b.data[i + 2] || a.data[i + 3] !== b.data[i + 3]) n++;
}
return n;
}
/** What the outermost pixels of the sheet are painted with, when nothing in it is see-through. */
function background(sheet: Pixels): Finding {
const counts = new Map<number, number>();
let total = 0;
const see = (x: number, y: number) => {
const i = (y * sheet.width + x) * 4;
const key = (sheet.data[i] << 16) | (sheet.data[i + 1] << 8) | sheet.data[i + 2];
counts.set(key, (counts.get(key) ?? 0) + 1);
total++;
};
for (let x = 0; x < sheet.width; x++) {
see(x, 0);
see(x, sheet.height - 1);
}
for (let y = 1; y < sheet.height - 1; y++) {
see(0, y);
see(sheet.width - 1, y);
}
const sorted = [...counts].sort((a, b) => b[1] - a[1]);
const name = (key: number) => hex(key >> 16, (key >> 8) & 255, key & 255);
const grey = (key: number) => Math.max(key >> 16, (key >> 8) & 255, key & 255) - Math.min(key >> 16, (key >> 8) & 255, key & 255) <= 12 && (key & 255) >= 140;
const [first, second] = sorted;
// a figure may touch the edge, so the two greys need not be all of it: a fifth each and most of it together
if (second && grey(first[0]) && grey(second[0]) && second[1] >= total * 0.2 && first[1] + second[1] >= total * 0.6) {
return { kind: "painted-checkerboard", frames: [], message: `No pixel is see-through, and the sheet's edge is two greys in turn (${name(first[0])} and ${name(second[0])}): the checkerboard that means "see-through" in image programs was painted into the picture.` };
}
const share = Math.round((first[1] / total) * 100);
const edge = share < 50 ? `has ${counts.size} colours and none of them fills half of it` : `is ${share === 100 ? "all" : `${share} percent`} ${name(first[0])}`;
return { kind: "no-transparency", frames: [], message: `No pixel is see-through. The sheet's edge ${edge}: the background is painted, and in a game every frame shows up as a box.` };
}
/** Measures a sheet of frames and reports what will go wrong with it in a game. */
export function checkSpriteSheet(sheet: Pixels, layout: SheetLayout, settings: SheetSettings = {}): SheetReport {
const { style = DEFAULTS.style, plays = DEFAULTS.plays, footTolerance = DEFAULTS.footTolerance, driftTolerance = DEFAULTS.driftTolerance, maxColors = DEFAULTS.maxColors, loopJump = DEFAULTS.loopJump } = settings;
if (sheet.data.length !== sheet.width * sheet.height * 4) throw new Error(`A sheet of ${sheet.width} by ${sheet.height} pixels needs ${sheet.width * sheet.height * 4} numbers, and there are ${sheet.data.length}.`);
const { frameWidth, frameHeight, columns, rows, problem } = grid(sheet, layout);
const findings: Finding[] = [];
if (problem) findings.push({ kind: "uneven-cut", frames: [], message: `The sheet cannot be cut into equal frames: ${problem}. Cut like this, every frame after the first is shifted.` });
let clear = 0;
let soft = 0;
const allColors = new Set<number>();
for (let i = 0; i < sheet.data.length; i += 4) {
const a = sheet.data[i + 3];
if (a === 0) clear++;
else {
if (a !== 255) soft++;
allColors.add((sheet.data[i] << 16) | (sheet.data[i + 1] << 8) | sheet.data[i + 2]);
}
}
if (clear === 0) findings.push(background(sheet));
if (style === "pixel") {
if (soft > 0) findings.push({ kind: "soft-edges", frames: [], message: `${plural(soft, "pixel is", "pixels are")} partly see-through. Pixel art has hard edges; soft ones show as a pale rim around the figure.` });
if (allColors.size > maxColors) findings.push({ kind: "too-many-colors", frames: [], message: `The sheet uses ${allColors.size} colours, and the limit is ${maxColors}. Pixel art is drawn with a few fixed colours; thousands mean it is a soft picture made to look like pixel art.` });
}
const pictures = cutFrames(sheet, { frameWidth, frameHeight });
const frames = pictures.map(measure);
const drawn = frames.filter((f) => !f.empty);
const empty = frames.filter((f) => f.empty).map((f) => f.frame);
if (empty.length > 0) findings.push({ kind: "empty-frame", frames: empty, message: `${empty.length === 1 ? "Frame" : "Frames"} ${list(empty)} ${empty.length === 1 ? "is" : "are"} empty in the middle of the animation: the figure blinks out for a moment.` });
// a drawing that runs across the cut between two frames of a row
for (let i = 0; i + 1 < pictures.length; i++) {
if ((i + 1) % columns === 0) continue;
let touching = 0;
for (let y = 0; y < frameHeight; y++) {
if (pictures[i].data[(y * frameWidth + frameWidth - 1) * 4 + 3] !== 0 && pictures[i + 1].data[y * frameWidth * 4 + 3] !== 0) touching++;
}
if (touching > 0 && clear > 0) findings.push({ kind: "cut-through", frames: [i + 1, i + 2], message: `The drawing runs across the cut between frames ${i + 1} and ${i + 2}, in ${plural(touching, "row")}: one figure is cut in two, or two figures touch.` });
}
if (drawn.length > 1 && clear > 0) {
// the foot line most frames share is the ground; the others are off it
const usual = (values: number[]) => {
const counts = new Map<number, number>();
for (const v of values) counts.set(v, (counts.get(v) ?? 0) + 1);
return [...counts].sort((a, b) => b[1] - a[1] || b[0] - a[0])[0][0];
};
const ground = usual(drawn.map((f) => f.footLine));
const off = drawn.filter((f) => Math.abs(f.footLine - ground) > footTolerance);
if (off.length > 0) {
findings.push({ kind: "foot-line", frames: off.map((f) => f.frame), message: `The feet are not on one line: ${off.map((f) => `frame ${f.frame} stands on row ${f.footLine}`).join(", ")}, the ${off.length === drawn.length - 1 ? "other" : "others"} on row ${ground}. The figure bobs up and down while it plays.` });
}
const middles = drawn.map((f) => f.middle).sort((a, b) => a - b);
const median = middles[Math.floor((middles.length - 1) / 2)];
const adrift = drawn.filter((f) => Math.abs(f.middle - median) > driftTolerance);
if (adrift.length > 0) {
findings.push({ kind: "drift", frames: adrift.map((f) => f.frame), message: `The figure does not stay in place: ${adrift.map((f) => `in frame ${f.frame} its middle is ${Math.abs(Math.round((f.middle - median) * 10) / 10)} pixels to the ${f.middle < median ? "left" : "right"}`).join(", ")}. It jitters sideways while it plays.` });
}
}
if (style === "pixel" && drawn.length > 2 && clear > 0 && allColors.size <= maxColors) {
// colours only one frame has: a hat that changes colour for one step
const users = new Map<number, Set<number>>();
pictures.forEach((picture, f) => {
for (let i = 0; i < picture.data.length; i += 4) {
if (picture.data[i + 3] === 0) continue;
const key = (picture.data[i] << 16) | (picture.data[i + 1] << 8) | picture.data[i + 2];
if (!users.has(key)) users.set(key, new Set());
users.get(key)!.add(f);
}
});
for (const [f] of pictures.entries()) {
const own = [...users].filter(([, where]) => where.size === 1 && where.has(f)).map(([key]) => hex(key >> 16, (key >> 8) & 255, key & 255));
if (own.length > 0) findings.push({ kind: "new-colors", frames: [f + 1], message: `Frame ${f + 1} has ${plural(own.length, "colour")} no other frame has (${own.slice(0, 4).join(", ")}${own.length > 4 ? ", …" : ""}). If that is not an effect you wanted, something about the figure changes for that one frame.` });
}
}
if (plays === "loop" && pictures.length > 2 && empty.length === 0) {
const steps = pictures.slice(1).map((picture, i) => difference(pictures[i], picture));
const biggest = Math.max(...steps);
const back = difference(pictures[pictures.length - 1], pictures[0]);
if (back === 0) {
findings.push({ kind: "doubled-frame", frames: [1, pictures.length], message: `The last frame, ${pictures.length}, is the same picture as the first. Played as a loop that picture shows twice in a row and the motion stalls for a moment: leave the last frame out.` });
} else if (biggest > 0 && back > biggest * loopJump) {
findings.push({ kind: "loop-jump", frames: [pictures.length, 1], message: `The loop does not close: going from the last frame back to the first changes ${plural(back, "pixel")}, and the biggest step inside the animation changes ${biggest}. The figure jerks each time the animation starts over.` });
}
}
const pixelSize = pixelSizeOf(sheet);
const head = [
`Sheet of ${sheet.width} by ${sheet.height} pixels: ${plural(pictures.length, "frame")} of ${frameWidth} by ${frameHeight}${pixelSize > 1 ? `, scaled up ${pixelSize} times (the art itself is ${frameWidth / pixelSize} by ${frameHeight / pixelSize})` : ""}.`,
`See-through pixels: ${clear}. Partly see-through: ${soft}. Colours: ${allColors.size}.`,
findings.length === 0 ? "No problems found." : `Found ${plural(findings.length, "problem")}.`,
];
return { ok: findings.length === 0, frameWidth, frameHeight, columns, rows, pixelSize, frames, findings, text: [...head, ...findings.map((f) => `${f.kind}: ${f.message}`)].join("\n") };
}
Die Tests, die dieser Code besteht
import assert from "node:assert/strict";
import test from "node:test";
import { DEFAULTS, type Pixels, alignFeet, checkSpriteSheet, cutFrames, joinFrames, pixelSizeOf } from "./code.ts";
/* A clean four-frame walk passes with nothing found. Then each mistake is planted on its own, and
the check has to name exactly that mistake and the frames it is in. */
const COLORS: Record<string, number[]> = { h: [0xf2, 0xc9, 0xa0, 255], b: [0x2f, 0x62, 0xf0, 255], l: [0x1f, 0x21, 0x42, 255], r: [0xc2, 0x41, 0x2d, 255], "~": [0xf2, 0xc9, 0xa0, 128] };
/** A frame from rows of letters; a dot is see-through. */
function draw(rows: string[]): Pixels {
const width = rows[0].length;
const data = new Uint8ClampedArray(width * rows.length * 4);
rows.forEach((row, y) => {
assert.equal(row.length, width, `row ${y + 1} of a test frame`);
[...row].forEach((letter, x) => {
if (letter !== ".") data.set(COLORS[letter], (y * width + x) * 4);
});
});
return { width, height: rows.length, data };
}
const HEAD = ["....hhhh....", "....hhhh....", "....hhhh....", "...bbbbbb..."];
const STRIDE = ["...ll..ll...", "..ll....ll..", "..ll....ll.."];
const PASSING = ["....llll....", "....llll....", "....llll...."];
const WALK = [
[...HEAD, "...bbbbbb...", "..hbbbbbb...", "...bbbbbb...", ...STRIDE],
[...HEAD, "...bbbbbb...", "...bbbbbb...", "...bbbbbb...", ...PASSING],
[...HEAD, "...bbbbbb...", "...bbbbbbh..", "...bbbbbb...", ...STRIDE],
[...HEAD, "...bbbbbb...", "...bbbbbb...", "...bbbbbb...", ...PASSING],
];
const FRAME = { frameWidth: 12, frameHeight: 10 };
const walk = () => WALK.map(draw);
const sheetOf = (frames: Pixels[]) => joinFrames(frames, frames.length);
const kinds = (sheet: Pixels, settings = {}, layout: object = FRAME) => checkSpriteSheet(sheet, layout, settings).findings.map((f) => f.kind);
/** A frame with its drawing moved; what leaves the frame is lost, as in a badly cut sheet. */
function moved(frame: Pixels, dx: number, dy: number): Pixels {
const data = new Uint8ClampedArray(frame.data.length);
for (let y = 0; y < frame.height; y++) {
for (let x = 0; x < frame.width; x++) {
const fx = x - dx;
const fy = y - dy;
if (fx < 0 || fy < 0 || fx >= frame.width || fy >= frame.height) continue;
data.set(frame.data.subarray((fy * frame.width + fx) * 4, (fy * frame.width + fx) * 4 + 4), (y * frame.width + x) * 4);
}
}
return { width: frame.width, height: frame.height, data };
}
/** The sheet with every see-through pixel painted by `paint`. */
function painted(sheet: Pixels, paint: (x: number, y: number) => number[]): Pixels {
const data = sheet.data.slice();
for (let y = 0; y < sheet.height; y++) {
for (let x = 0; x < sheet.width; x++) {
const i = (y * sheet.width + x) * 4;
if (data[i + 3] === 0) data.set(paint(x, y), i);
}
}
return { width: sheet.width, height: sheet.height, data };
}
test("a clean walk passes, and the report gives the numbers it measured", () => {
const report = checkSpriteSheet(sheetOf(walk()), FRAME);
assert.equal(report.ok, true, report.text);
assert.equal(report.text, "Sheet of 48 by 10 pixels: 4 frames of 12 by 10.\nSee-through pixels: 286. Partly see-through: 0. Colours: 3.\nNo problems found.");
// 480 pixels in all; the frames draw 49, 48, 49 and 48 of them
assert.equal(480 - report.frames.reduce((sum, f) => sum + f.pixels, 0), 286);
assert.deepEqual([report.frameWidth, report.frameHeight, report.columns, report.rows, report.pixelSize], [12, 10, 4, 1, 1]);
assert.deepEqual(report.frames[1], { frame: 2, empty: false, left: 4, right: 9, top: 1, footLine: 10, middle: 6, pixels: 48, colors: 3 });
assert.deepEqual(report.frames.map((f) => f.footLine), [10, 10, 10, 10]);
// the hand of frame 1 pulls its middle a little to the left, far less than the tolerance
assert.deepEqual(report.frames.map((f) => f.middle), [5.93, 6, 6.07, 6]);
});
test("the same sheet can be described by its columns and rows", () => {
const sheet = sheetOf(walk());
assert.deepEqual(checkSpriteSheet(sheet, { columns: 4 }).frames, checkSpriteSheet(sheet, FRAME).frames);
assert.deepEqual(checkSpriteSheet(joinFrames(walk(), 2), { columns: 2, rows: 2 }).frames, checkSpriteSheet(sheet, FRAME).frames);
assert.throws(() => checkSpriteSheet(sheet, {}), /Say how the sheet is cut/);
assert.throws(() => checkSpriteSheet({ width: 4, height: 4, data: new Uint8ClampedArray(60) }, { columns: 1 }), /needs 64 numbers, and there are 60/);
});
test("planted: a background painted white is not see-through", () => {
const report = checkSpriteSheet(painted(sheetOf(walk()), () => [255, 255, 255, 255]), FRAME);
assert.deepEqual(report.findings.map((f) => f.kind), ["no-transparency"]);
// the edge is 112 pixels long; heads touch it at the top and feet at the bottom, in 32 of them
assert.match(report.text, /No pixel is see-through\. The sheet's edge is 71 percent #ffffff/);
// a background that is a picture of its own: no colour fills half of the edge
const scenery = checkSpriteSheet(painted(sheetOf(walk()), (x, y) => [x * 5, y * 20, 90, 255]), FRAME, { style: "painted" });
assert.deepEqual(scenery.findings.map((f) => f.kind), ["no-transparency"]);
assert.match(scenery.text, /The sheet's edge has 82 colours and none of them fills half of it/);
const box = draw(["hhhh", "h..h", "hhhh"]);
assert.match(checkSpriteSheet(painted(box, () => [0, 0, 0, 255]), { columns: 1 }).text, /No pixel is see-through\. The sheet's edge is all #f2c9a0/);
});
test("planted: a checkerboard painted in is named as one", () => {
const board = painted(sheetOf(walk()), (x, y) => ((x >> 1) + (y >> 1)) % 2 ? [204, 204, 204, 255] : [255, 255, 255, 255]);
const report = checkSpriteSheet(board, FRAME);
assert.deepEqual(report.findings.map((f) => f.kind), ["painted-checkerboard"]);
assert.match(report.text, /two greys in turn \(#(ffffff|cccccc) and #(ffffff|cccccc)\)/);
// a floor of two strong colours is a painted background, but not a checkerboard of greys
const floor = painted(sheetOf(walk()), (x) => (x % 2 ? [30, 120, 60, 255] : [40, 140, 70, 255]));
assert.deepEqual(kinds(floor), ["no-transparency"]);
});
test("planted: one frame stands two pixels too high", () => {
const frames = walk();
frames[2] = moved(frames[2], 0, -2);
const report = checkSpriteSheet(sheetOf(frames), FRAME);
assert.deepEqual(report.findings.map((f) => [f.kind, f.frames]), [["foot-line", [3]]]);
assert.match(report.text, /frame 3 stands on row 8, the others on row 10/);
// one pixel off is still found, unless one pixel is allowed
frames[2] = moved(walk()[2], 0, -1);
assert.deepEqual(kinds(sheetOf(frames)), ["foot-line"]);
assert.deepEqual(kinds(sheetOf(frames), { footTolerance: 1 }), []);
});
test("planted: one frame sits three pixels to the right", () => {
const frames = walk();
frames[1] = moved(frames[1], 3, 0);
const report = checkSpriteSheet(sheetOf(frames), FRAME);
assert.deepEqual(report.findings.map((f) => [f.kind, f.frames]), [["drift", [2]]]);
assert.match(report.text, /in frame 2 its middle is 3 pixels to the right/);
assert.deepEqual(kinds(sheetOf(frames), { driftTolerance: 3 }), []);
frames[1] = moved(walk()[1], -3, 0);
// measured from the middle most frames have, which is frame 1's here: 5.93, not 6
assert.match(checkSpriteSheet(sheetOf(frames), FRAME).text, /in frame 2 its middle is 2\.9 pixels to the left/);
});
test("planted: a sheet that cannot be cut into equal frames", () => {
const sheet = sheetOf(walk());
const wider: Pixels = { width: 50, height: 10, data: new Uint8ClampedArray(50 * 10 * 4) };
for (let y = 0; y < 10; y++) wider.data.set(sheet.data.subarray(y * 48 * 4, (y + 1) * 48 * 4), y * 50 * 4);
const report = checkSpriteSheet(wider, FRAME);
assert.deepEqual(report.findings.map((f) => f.kind), ["uneven-cut"]);
assert.match(report.text, /the sheet is 50 pixels wide and frames 12 wide leave 2 over/);
assert.match(checkSpriteSheet(sheet, { columns: 5 }).text, /48 pixels wide and 5 frames across would each be 9\.6 pixels wide/);
assert.match(checkSpriteSheet(sheet, { frameWidth: 12, frameHeight: 4 }).text, /10 pixels high and frames 4 high leave 2 over/);
});
test("planted: a figure drawn across the cut between two frames", () => {
const frames = walk();
frames[1] = moved(frames[1], 5, 0);
frames[2] = moved(frames[2], -4, 0);
const report = checkSpriteSheet(sheetOf(frames), FRAME, { driftTolerance: 99 });
assert.deepEqual(report.findings.map((f) => [f.kind, f.frames]), [["cut-through", [2, 3]]]);
// frame 2 fills its last column from top to bottom; frame 3 fills its first in the top 8 rows, down to the hip
assert.match(report.text, /across the cut between frames 2 and 3, in 8 rows/);
// the last frame of a row and the first of the next do not touch
const twoRows = joinFrames([frames[0], frames[1], frames[2], frames[3]], 2);
assert.deepEqual(kinds(twoRows, { driftTolerance: 99 }, { columns: 2, rows: 2 }), []);
});
test("planted: soft edges and too many colours, which only pixel art is held to", () => {
const frames = walk();
frames[0] = draw([...HEAD.slice(0, 3), "..~bbbbbb...", "...bbbbbb...", "..hbbbbbb...", "...bbbbbb...", ...STRIDE]);
const soft = checkSpriteSheet(sheetOf(frames), FRAME);
assert.deepEqual(soft.findings.map((f) => f.kind), ["soft-edges"]);
assert.match(soft.text, /1 pixel is partly see-through/);
assert.deepEqual(kinds(sheetOf(frames), { style: "painted" }), []);
const noisy = sheetOf(walk());
let n = 0;
for (let i = 0; i < noisy.data.length; i += 4) if (noisy.data[i + 3] !== 0) noisy.data[i + 1] = n++ % 40;
const many = checkSpriteSheet(noisy, FRAME);
assert.deepEqual(many.findings.map((f) => f.kind), ["too-many-colors"]);
assert.match(many.text, /The sheet uses 120 colours, and the limit is 32/);
assert.deepEqual(kinds(noisy, { style: "painted" }), []);
assert.deepEqual(kinds(noisy, { maxColors: 120 }).filter((k) => k === "too-many-colors"), []);
});
test("planted: one frame has a colour no other frame has", () => {
const frames = walk();
frames[2] = draw([...WALK[2].slice(0, 3).map((row) => row.replace(/h/g, "r")), ...WALK[2].slice(3)]);
const report = checkSpriteSheet(sheetOf(frames), FRAME);
assert.deepEqual(report.findings.map((f) => [f.kind, f.frames]), [["new-colors", [3]]]);
assert.match(report.text, /Frame 3 has 1 colour no other frame has \(#c2412d\)/);
});
test("planted: a last frame that repeats the first makes a loop stall", () => {
const frames = [...walk(), draw(WALK[0])];
const report = checkSpriteSheet(sheetOf(frames), FRAME);
assert.deepEqual(report.findings.map((f) => [f.kind, f.frames]), [["doubled-frame", [1, 5]]]);
assert.deepEqual(kinds(sheetOf(frames), { plays: "once" }), []);
});
test("planted: an animation that does not come back to its start jerks as a loop", () => {
// a flag that rises six pixels a frame and never comes down
const flag = (height: number) => draw(Array.from({ length: 10 }, (_, y) => (y >= 9 - height ? ".....bbbbbb." : "............").replace(/^\.(.*)$/, (_, rest) => (y === 9 ? "l" : ".") + rest)));
const frames = [1, 2, 3, 4].map(flag);
const report = checkSpriteSheet(sheetOf(frames), FRAME, { driftTolerance: 99 });
assert.deepEqual(report.findings.map((f) => [f.kind, f.frames]), [["loop-jump", [4, 1]]]);
assert.match(report.text, /back to the first changes 18 pixels, and the biggest step inside the animation changes 6/);
assert.deepEqual(kinds(sheetOf(frames), { plays: "once", driftTolerance: 99 }), []);
assert.deepEqual(kinds(sheetOf(frames), { loopJump: 3, driftTolerance: 99 }), []);
// the walk comes back: its last step is as big as the others
assert.equal(DEFAULTS.loopJump, 1.5);
assert.deepEqual(kinds(sheetOf(walk())), []);
});
test("planted: an empty frame in the middle; empty frames at the end are left out", () => {
const blank = draw(Array.from({ length: 10 }, () => "............"));
const report = checkSpriteSheet(sheetOf([walk()[0], walk()[1], blank, walk()[3]]), FRAME);
assert.deepEqual(report.findings.map((f) => [f.kind, f.frames]), [["empty-frame", [3]]]);
const padded = checkSpriteSheet(sheetOf([...walk(), blank, blank]), FRAME);
assert.equal(padded.ok, true, padded.text);
assert.equal(padded.frames.length, 4);
assert.equal(padded.columns, 6);
});
test("alignFeet moves frames down onto one line without changing a pixel of them", () => {
// the walk with three rows of room above the heads
const room = ["............", "............", "............"];
const tall = () => WALK.map((rows) => draw([...room, ...rows]));
const frames = tall();
frames[0] = moved(frames[0], 0, -3);
frames[2] = moved(frames[2], 0, -1);
const layout = { frameWidth: 12, frameHeight: 13 };
const before = checkSpriteSheet(sheetOf(frames), layout);
assert.deepEqual(before.findings.map((f) => [f.kind, f.frames]), [["foot-line", [1, 3]]]);
assert.match(before.text, /frame 1 stands on row 10, frame 3 stands on row 12, the others on row 13/);
const fixed = alignFeet(frames);
assert.deepEqual(fixed, tall(), "every frame is back where the clean walk has it");
assert.equal(checkSpriteSheet(sheetOf(fixed), layout).ok, true);
// frames that already stand on one line are not touched
assert.deepEqual(alignFeet(walk()), walk());
});
test("cutting a sheet and joining the frames gives the sheet back", () => {
const sheet = joinFrames(walk(), 2);
assert.deepEqual([sheet.width, sheet.height], [24, 20]);
const frames = cutFrames(sheet, { columns: 2, rows: 2 });
assert.deepEqual(frames, walk());
assert.deepEqual(joinFrames(frames, 2), sheet);
assert.throws(() => joinFrames([walk()[0], draw(["hh"])]), /Frame 2 is 2 by 1 pixels, frame 1 is 12 by 10/);
assert.throws(() => joinFrames([]), /no frames/);
});
test("a sheet that was scaled up is measured in real pixels, and the report says by how much", () => {
const small = sheetOf(walk());
const big: Pixels = { width: small.width * 4, height: small.height * 4, data: new Uint8ClampedArray(small.data.length * 16) };
for (let y = 0; y < big.height; y++) {
for (let x = 0; x < big.width; x++) big.data.set(small.data.subarray(((y >> 2) * small.width + (x >> 2)) * 4, ((y >> 2) * small.width + (x >> 2)) * 4 + 4), (y * big.width + x) * 4);
}
assert.equal(pixelSizeOf(small), 1);
assert.equal(pixelSizeOf(big), 4);
const report = checkSpriteSheet(big, { frameWidth: 48, frameHeight: 40 });
assert.equal(report.ok, true, report.text);
assert.match(report.text, /4 frames of 48 by 40, scaled up 4 times \(the art itself is 12 by 10\)/);
assert.deepEqual(report.frames.map((f) => f.footLine), [40, 40, 40, 40]);
// one pixel out of place and it is no longer a clean scale
big.data.set([1, 2, 3, 255], 0);
assert.equal(pixelSizeOf(big), 1);
});
Häufige Fragen
warum zittert mein sprite beim laufen
Die Einzelbilder passen nicht aufeinander. Entweder stehen die Füße von Bild zu Bild auf anderen Zeilen, oder die Figur steht in manchen ein paar Pixel weiter links oder rechts. Der Check nennt diese Einzelbilder, und seine Fuß-Korrektur schiebt sie auf eine Linie, ohne etwas zu verzerren.
wie prüfe ich ein sprite sheet von einer ki
Miss die Datei selbst. Der Check zählt die durchsichtigen Pixel, schneidet das Blatt in Einzelbilder und vergleicht Fußlinie, Mitte und Farben jedes Einzelbilds, dann listet er auf, was nicht zusammenpasst.
warum stockt meine laufanimation in der schleife
Oft ist das letzte Einzelbild dasselbe Bild wie das erste, dann erscheint dieses Bild zweimal hintereinander, oder das letzte liegt weit vom ersten entfernt und die Figur ruckt zurück. Der Check meldet beides und sagt, wie viele Pixel sich bei diesem Schritt ändern.
War diese Seite hilfreich?
Nächster Schritt
- Oder: Pixel Art aus Text
- Oder: Pixel Art drehen