UNPKG

@spearwolf/twopoint5d

Version:

Create 2.5D realtime graphics and pixelart with WebGL and three.js

98 lines 3.36 kB
import { TextureAtlas } from './TextureAtlas.js'; import { TextureCoords } from './TextureCoords.js'; const rand = (max) => (Math.random() * max) | 0; export class TileSet { constructor(...args) { this.tileCount = 0; this.firstFrameId = -1; this.#createTextureCoords = () => { const { width: baseWidth, height: baseHeight } = this.baseCoords; const { padding, margin, spacing, tileCountLimit } = this; const tileOuterWidth = this.tileWidth + (padding << 1); const tileOuterHeight = this.tileHeight + (padding << 1); let x = margin; let y = margin; let tileCount = 0; while (tileCount < tileCountLimit) { const coords = new TextureCoords(this.baseCoords, x + padding, y + padding, this.tileWidth, this.tileHeight); const frameId = this.atlas.add(coords); if (this.firstFrameId === -1) { this.firstFrameId = frameId; } ++tileCount; if (tileCount === tileCountLimit) { break; } const xOffsetNext = tileOuterWidth + spacing; if (x + xOffsetNext + tileOuterWidth + margin <= baseWidth) { x += xOffsetNext; } else { x = margin; y += tileOuterHeight + spacing; if (y + tileOuterHeight + margin > baseHeight) { break; } } } this.tileCount = tileCount; }; if (args[0] instanceof TextureAtlas) { const [atlas, baseCoords, options] = args; this.atlas = atlas; this.baseCoords = baseCoords; this.options = options; } else { this.atlas = new TextureAtlas(); const [baseCoords, options] = args; this.baseCoords = baseCoords; this.options = options; } this.#createTextureCoords(); } get tileWidth() { return this.options?.tileWidth ?? this.baseCoords.width; } get tileHeight() { return this.options?.tileHeight ?? this.baseCoords.height; } get firstId() { return this.options?.firstId ?? 1; } get lastId() { return this.firstId + this.tileCount - 1; } get lastFrameId() { return this.firstFrameId + this.tileCount - 1; } get tileCountLimit() { return this.options?.tileCount ?? Infinity; } get margin() { return this.options?.margin ?? 0; } get padding() { return this.options?.padding ?? 0; } get spacing() { return this.options?.spacing ?? 0; } frameId(tileId) { return ((((tileId - this.firstId) % this.tileCount) + this.tileCount) % this.tileCount) + this.firstFrameId; } randomTileId() { return this.firstId + rand(this.tileCount); } randomFrameId() { return this.firstFrameId + rand(this.tileCount); } frame(tileId) { return this.atlas.get(this.frameId(tileId)); } randomFrame() { return this.atlas.get(this.randomFrameId()); } #createTextureCoords; } //# sourceMappingURL=TileSet.js.map