MapLoader: use square tile texture rather than long Nx1 rectangle
By placing the tiles in a square texture, the dimensions are bounded by the square root of the dimension in the old solution. This way we can fit a significantly higher number of tiles into it without using up all the accuracy of the coordinates.
This commit is contained in:
parent
bc6d79b088
commit
4b680776a3
3 changed files with 55 additions and 38 deletions
|
@ -4,6 +4,11 @@ import MapState from '../model/state/MapState';
|
|||
import MapView from './MapView';
|
||||
import Renderer from './renderer/Renderer';
|
||||
|
||||
export interface TileMap {
|
||||
texture: WebGLTexture;
|
||||
tiles: Map<string, [number, number, number, number]>;
|
||||
}
|
||||
|
||||
function loadImage(url: string): Promise<HTMLImageElement> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
|
@ -36,27 +41,42 @@ function mkTexture(gl: WebGLRenderingContext, src: HTMLCanvasElement|HTMLImageEl
|
|||
return texture;
|
||||
}
|
||||
|
||||
function mkTileTexture(gl: WebGLRenderingContext, tiles: Map<string, HTMLImageElement>):
|
||||
[WebGLTexture, Map<string, number>] {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = nextPowerOf2(tiles.size) * MapView.tileSize;
|
||||
canvas.height = MapView.tileSize;
|
||||
function mkTileMap(
|
||||
gl: WebGLRenderingContext,
|
||||
tiles: Map<string, HTMLImageElement>,
|
||||
): TileMap {
|
||||
const tileSize = MapView.tileSize;
|
||||
|
||||
let i = 0;
|
||||
const ret: Map<string, number> = new Map();
|
||||
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, [number, number, number, number]> = new Map();
|
||||
const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
|
||||
|
||||
for (const [k, tile] of tiles) {
|
||||
ctx.drawImage(tile, i * MapView.tileSize, 0);
|
||||
ret.set(k, i++);
|
||||
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 [mkTexture(gl, canvas), ret];
|
||||
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 [tileTexture, tileMap] = mkTileTexture(r.getContext(), tiles);
|
||||
const tileMap = mkTileMap(r.getContext(), tiles);
|
||||
|
||||
return new MapView(r, map, tileTexture, tileMap);
|
||||
return new MapView(r, map, tileMap);
|
||||
}
|
||||
|
|
Reference in a new issue