summaryrefslogtreecommitdiffstats
path: root/src/view/renderer/Renderer.ts
blob: 344bccf5876a3a606720ef8c6725b5eb4028fcf9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { mat4, vec2 } from 'gl-matrix';

import Shaders from './Shaders';

export default class Renderer {
	private readonly gl: WebGLRenderingContext;
	private readonly shaders: Shaders;

	private readonly center: vec2 = vec2.create();
	private readonly translation: vec2 = vec2.create();
	private readonly viewport: mat4 = mat4.create();

	constructor(private readonly canvas: HTMLCanvasElement) {
		this.gl = this.mkContext();

		this.shaders = new Shaders(this.gl);

		this.gl.clearColor(0.0, 0.0, 0.0, 1.0);

		this.gl.enable(this.gl.BLEND);
		this.gl.blendFunc(this.gl.ONE, this.gl.ONE_MINUS_SRC_ALPHA);
		this.gl.pixelStorei(this.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);

		this.setSize();
	}

	public createBuffer(): WebGLBuffer {
		const ret = this.gl.createBuffer();
		if (!ret)
			throw new Error('unable to create buffer');

		return ret;
	}

	public getContext(): WebGLRenderingContext {
		return this.gl;
	}

	public getVertexPosLoc(): number {
		return this.shaders.vertexPosLoc;
	}

	public getTextureCoordLoc(): number {
		return this.shaders.textureCoordLoc;
	}

	public getSamplerLoc(): WebGLUniformLocation {
		return this.shaders.samplerLoc;
	}

	public setCenter(v: vec2|number[]) {
		vec2.copy(this.center, v);
	}

	public setTranslation(v: vec2|number[]) {
		vec2.sub(this.translation, v, this.center);
		this.gl.uniform2fv(this.shaders.translateLoc, this.translation);
	}

	public clear(): void {
		this.gl.clear(this.gl.COLOR_BUFFER_BIT);

		this.setTranslation([0, 0]);
	}

	private mkContext(): WebGLRenderingContext {
		const gl = (
			this.canvas.getContext('webgl') || this.canvas.getContext('experimental-webgl')
		);
		if (!gl)
			throw new Error('unable to initialize WebGL context');

		return gl;
	}

	private setSize(): void {
		const w = this.canvas.width;
		const h = this.canvas.height;

		this.gl.viewport(0, 0, w, h);
		this.clear();

		mat4.identity(this.viewport);
		mat4.scale(this.viewport, this.viewport, [2 * 64 / w, -2 * 64 / h, 1.0]);
		this.gl.uniformMatrix4fv(this.shaders.viewportLoc, false, this.viewport);
	}
}