From 446a05283259e0fb5a90d9631be27f88718c5c39 Mon Sep 17 00:00:00 2001 From: fef Date: Wed, 26 Oct 2022 22:09:22 +0200 Subject: [PATCH] sprite: add resolution, optimize matches() --- dist/palette.json | 1 + src/sprite.ts | 43 +++++++++++++++++++++++++++++++------------ 2 files changed, 32 insertions(+), 12 deletions(-) diff --git a/dist/palette.json b/dist/palette.json index 30e82b0..2029190 100644 --- a/dist/palette.json +++ b/dist/palette.json @@ -1,6 +1,7 @@ { "baseurl": "/sprites", "sections": 4, + "resolution": 128, "sprites": [ { "url": "/01.png", diff --git a/src/sprite.ts b/src/sprite.ts index 30d5d37..6b7faf7 100644 --- a/src/sprite.ts +++ b/src/sprite.ts @@ -42,6 +42,8 @@ export interface IPaletteData { * (as in the four edges of a quadratic tile). */ sections: number, + /** horizontal and vertical resolution of all sprites, in pixels */ + resolution: number, /** Array of all tile prototypes. */ sprites: ISpriteData[], } @@ -66,19 +68,33 @@ export class Sprite { .catch(e => console.error(e)); } - public matches(ownDir: Direction, other: Sprite): boolean { - if (other.sections !== this.sections) { + public matches(ownEdge: Direction, other: Sprite, otherEdge: Direction): boolean { + const sections = this.sections; + if (other.sections !== sections) { return false; } - const ownStart = ownDir * this.sections; + const getStart = (edge: Direction) => { + let start = edge * sections; + if (edge >= 2) { + start += sections - 1; + } + return start; + }; + let ownPos = getStart(ownEdge); + let otherPos = getStart(otherEdge); - const otherDir: Direction = (ownDir + 2) % 4; - const otherStart = otherDir * other.sections; + const ownDir = ownEdge < 2 ? 1 : -1; + const otherDir = otherEdge < 2 ? 1 : -1; + for (let n = 0; n < sections; n++) { + if (this.edges[ownPos] !== other.edges[otherPos]) { + return false; + } + ownPos += ownDir; + otherPos += otherDir; + } - let ownEdge = this.edges.slice(ownStart, ownStart + this.sections); - let otherEdge = other.edges.slice(otherStart, otherStart + other.sections); - return !ownEdge.some((v, i) => otherEdge[other.sections - i - 1] !== v); + return true; } /** @@ -126,20 +142,23 @@ export const enum Direction { export class Palette { private readonly sections: number; public readonly sprites: Sprite[]; + public readonly resolution: number; public constructor(proto: IPaletteData) { this.sections = proto.sections; - const tiles = []; - for (let tile of proto.sprites) { - tiles.push(new Sprite(proto.sections, proto.baseurl, tile)); + const sprites = []; + for (let s of proto.sprites) { + sprites.push(new Sprite(proto.sections, proto.baseurl, s)); } - this.sprites = tiles; + this.sprites = sprites; + this.resolution = proto.resolution; } } const PALETTE_SCHEMA: JSONSchema = { baseurl: "string", sections: "number", + resolution: "number", sprites: [{ url: "string", edges: ["number"],