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
|
import { loadImages, mkTexture } from 'util/image';
import { mapValues, nextPowerOf2 } from '../util';
import { TileCoords } from './tile';
import MapState from '../model/state/MapState';
import MapView from './MapView';
import Renderer from './renderer/Renderer';
export interface TileMap {
texture: WebGLTexture;
tiles: Map<string, TileCoords>;
}
function loadTiles(tiles: Map<string, string>): Promise<Map<string, HTMLImageElement>> {
return loadImages(mapValues((t) => `resources/sprite/tile/${t}.png`, tiles));
}
function mkTileMap(
gl: WebGLRenderingContext,
tiles: Map<string, HTMLImageElement>,
): TileMap {
const tileSize = 32;
const canvasDim = nextPowerOf2(Math.sqrt(tiles.size));
const canvasSize = canvasDim * tileSize;
const canvas = document.createElement('canvas');
canvas.width = canvas.height = canvasSize;
let x = 0, y = 0;
const map: Map<string, TileCoords> = new Map();
const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
for (const [k, tile] of tiles) {
ctx.drawImage(tile, x * tileSize, y * tileSize);
map.set(k, [x / canvasDim, y / canvasDim, (x + 1) / canvasDim, (y + 1) / canvasDim]);
x++;
if (x === canvasDim) {
x = 0;
y++;
}
}
return {
texture: mkTexture(gl, canvas),
tiles: map,
};
}
export async function loadMap(r: Renderer, map: MapState): Promise<MapView> {
const tiles = await loadTiles(map.data.tiles);
const tileMap = mkTileMap(r.getContext(), tiles);
return new MapView(r, map, tileMap);
}
|