avocado-old/packages/topdown/tiles-renderer.js

56 lines
1.5 KiB
JavaScript
Raw Normal View History

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];
2019-03-25 23:05:22 -05:00
// Lookup subimage.
const subimage = this.tileset.subimage(index);
if (subimage) {
const sprite = new Sprite(subimage);
sprite.anchor = [0, 0];
2019-03-25 23:05:22 -05:00
sprite.position = position;
container.addChild(sprite);
}
2019-03-25 20:26:37 -05:00
// 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;
}
}