74 lines
2.1 KiB
TypeScript
74 lines
2.1 KiB
TypeScript
import Renderer from './renderer/Renderer';
|
|
|
|
export type TileCoords = [number, number, number, number];
|
|
|
|
export class TileViewBuilder {
|
|
private static pushTile(buf: number[], coords: TileCoords): void {
|
|
const [x1, y1, x2, y2] = coords;
|
|
|
|
buf.push(x1); buf.push(y1);
|
|
buf.push(x2); buf.push(y1);
|
|
buf.push(x1); buf.push(y2);
|
|
|
|
buf.push(x1); buf.push(y2);
|
|
buf.push(x2); buf.push(y1);
|
|
buf.push(x2); buf.push(y2);
|
|
}
|
|
|
|
private readonly vertexData: number[] = [];
|
|
private readonly textureData: number[] = [];
|
|
|
|
constructor(private readonly r: Renderer, private readonly texture: WebGLTexture) {}
|
|
|
|
public addTile(vertexCoords: TileCoords, texCoords: TileCoords): void {
|
|
TileViewBuilder.pushTile(this.vertexData, vertexCoords);
|
|
TileViewBuilder.pushTile(this.textureData, texCoords);
|
|
}
|
|
|
|
public build(): TileView {
|
|
return new TileView(this.r, this.texture, this.vertexData, this.textureData);
|
|
}
|
|
}
|
|
|
|
export class TileView {
|
|
private readonly vertexCount: number;
|
|
private readonly vertexBuffer: WebGLBuffer;
|
|
private readonly textureBuffer: WebGLBuffer;
|
|
|
|
constructor(
|
|
private readonly r: Renderer,
|
|
private readonly texture: WebGLTexture,
|
|
vertexData: number[],
|
|
textureData: number[],
|
|
) {
|
|
const gl = r.getContext();
|
|
|
|
this.vertexBuffer = r.createBuffer();
|
|
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
|
|
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexData), gl.STATIC_DRAW);
|
|
|
|
this.textureBuffer = r.createBuffer();
|
|
gl.bindBuffer(gl.ARRAY_BUFFER, this.textureBuffer);
|
|
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureData), gl.STATIC_DRAW);
|
|
|
|
this.vertexCount = vertexData.length / 2;
|
|
}
|
|
|
|
public render(): void {
|
|
const gl = this.r.getContext();
|
|
|
|
gl.clear(gl.COLOR_BUFFER_BIT);
|
|
|
|
gl.activeTexture(gl.TEXTURE0);
|
|
gl.bindTexture(gl.TEXTURE_2D, this.texture);
|
|
gl.uniform1i(this.r.getSamplerLoc(), 0);
|
|
|
|
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
|
|
gl.vertexAttribPointer(this.r.getVertexPosLoc(), 2, gl.FLOAT, false, 0, 0);
|
|
|
|
gl.bindBuffer(gl.ARRAY_BUFFER, this.textureBuffer);
|
|
gl.vertexAttribPointer(this.r.getTextureCoordLoc(), 2, gl.FLOAT, false, 0, 0);
|
|
|
|
gl.drawArrays(gl.TRIANGLES, 0, this.vertexCount);
|
|
}
|
|
}
|