import { Renderer } from './renderer/renderer'; import { SpriteCoords, SpriteView, SpriteViewBuilder } from './sprite'; import { loadImage, mkTexture } from './util/image'; import { MapData } from '../model/data/map'; import { nextPowerOf2 } from '../util'; interface Tileset { texture: WebGLTexture; tiles: SpriteCoords[]; } function loadTiles(tiles: string[]): Promise { return Promise.all(tiles.map((t) => loadImage(`resources/sprite/tile/${t}.png`))); } function mkTileset( gl: WebGLRenderingContext, tiles: HTMLImageElement[], ): Tileset { const tileSize = 32; const canvasDim = nextPowerOf2(Math.sqrt(tiles.length)); const canvasSize = canvasDim * tileSize; const canvas = document.createElement('canvas'); canvas.width = canvas.height = canvasSize; let x = 0, y = 0; const tileCoords: SpriteCoords[] = []; const ctx = canvas.getContext('2d') as CanvasRenderingContext2D; for (const tile of tiles) { ctx.drawImage(tile, x * tileSize, y * tileSize); tileCoords.push([x / canvasDim, y / canvasDim, (x + 1) / canvasDim, (y + 1) / canvasDim]); x++; if (x === canvasDim) { x = 0; y++; } } return { texture: mkTexture(gl, canvas), tiles: tileCoords, }; } function addSprite(builder: SpriteViewBuilder, tileset: Tileset, x: number, y: number, tile: number) { if (tile === 0) return; const tilePos = tileset.tiles[tile - 1]; builder.addSprite([x, y, x + 1, y + 1], tilePos); } export async function loadMap(r: Renderer, map: MapData): Promise { const tiles = await loadTiles(map.tiles); const tileset = mkTileset(r.getContext(), tiles); const builder = new SpriteViewBuilder(r, tileset.texture); for (const layer of map.layers) for (let x = 0; x < map.width; x++) for (let y = 0; y < map.height; y++) addSprite(builder, tileset, x, y, layer[y][x]); return builder.build(); }