2019-03-25 20:26:37 -05:00
|
|
|
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];
|
|
|
|
const sprite = new Sprite(this.tileset.subimages[index]);
|
|
|
|
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);
|
2019-03-25 20:27:07 -05:00
|
|
|
canvas.render(container, renderer);
|
2019-03-25 20:26:37 -05:00
|
|
|
container.destroy();
|
|
|
|
// Convert to image and return.
|
|
|
|
const image = canvas.toImage();
|
|
|
|
canvas.destroy();
|
|
|
|
return image;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|