56 lines
1.5 KiB
JavaScript
56 lines
1.5 KiB
JavaScript
import {Canvas, Container, Sprite} from '@avocado/graphics';
|
|
import {Rectangle, Vector} from '@avocado/math';
|
|
|
|
export class TilesRenderer {
|
|
|
|
constructor(tiles, tileset) {
|
|
this.tiles = tiles;
|
|
this.tileset = tileset;
|
|
}
|
|
|
|
renderChunk(renderer, rectangle) {
|
|
// No rectangle? Render all.
|
|
if (!rectangle) {
|
|
rectangle = Rectangle.compose([0, 0], this.tiles.size);
|
|
}
|
|
const slice = this.tiles.slice(rectangle);
|
|
if (!slice) {
|
|
return undefined;
|
|
}
|
|
// Precalcs.
|
|
const size = Rectangle.size(rectangle);
|
|
const tileSize = this.tileset.tileSize;
|
|
const rowWidth = size[0] * tileSize[0];
|
|
// Render all tiles.
|
|
const container = new Container();
|
|
const position = [0, 0];
|
|
for (let i = 0; i < slice.length; ++i) {
|
|
const index = slice[i];
|
|
// Lookup subimage.
|
|
const subimage = this.tileset.subimage(index);
|
|
if (subimage) {
|
|
const sprite = new Sprite(subimage);
|
|
sprite.anchor = [0, 0];
|
|
sprite.position = position;
|
|
container.addChild(sprite);
|
|
}
|
|
// Only adds, please.
|
|
position[0] += tileSize[0];
|
|
if (rowWidth === position[0]) {
|
|
position[0] = 0;
|
|
position[1] += tileSize[1];
|
|
}
|
|
}
|
|
// Blit to canvas.
|
|
const canvasSize = Vector.mul(size, tileSize);
|
|
const canvas = new Canvas(canvasSize);
|
|
canvas.render(container, renderer);
|
|
container.destroy();
|
|
// Convert to image and return.
|
|
const image = canvas.toImage();
|
|
canvas.destroy();
|
|
return image;
|
|
}
|
|
|
|
}
|