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
|
import fragmentShaderSrc from './shaders/default.fs';
import vertexShaderSrc from './shaders/default.vs';
export class Shaders {
public readonly viewportLoc: WebGLUniformLocation;
public readonly translateLoc: WebGLUniformLocation;
public readonly vertexPosLoc: number;
public readonly textureCoordLoc: number;
public readonly samplerLoc: WebGLUniformLocation;
constructor(private readonly gl: WebGLRenderingContext) {
const shaderProgram = this.gl.createProgram();
if (!shaderProgram)
throw new Error('Unable to create shader program');
const vertexShader = this.compileShader(this.gl.VERTEX_SHADER, vertexShaderSrc);
const fragmentShader = this.compileShader(this.gl.FRAGMENT_SHADER, fragmentShaderSrc);
this.gl.attachShader(shaderProgram, vertexShader);
this.gl.attachShader(shaderProgram, fragmentShader);
this.gl.linkProgram(shaderProgram);
if (!this.gl.getProgramParameter(shaderProgram, this.gl.LINK_STATUS)) {
const err = this.gl.getProgramInfoLog(shaderProgram);
this.gl.deleteShader(vertexShader);
this.gl.deleteShader(fragmentShader);
this.gl.deleteProgram(shaderProgram);
throw new Error('Unable to link shader: ' + err);
}
this.gl.useProgram(shaderProgram);
this.vertexPosLoc = this.getAttribLocation(shaderProgram, 'aVertexPos');
this.gl.enableVertexAttribArray(this.vertexPosLoc);
this.textureCoordLoc = this.getAttribLocation(shaderProgram, 'aTextureCoord');
this.gl.enableVertexAttribArray(this.textureCoordLoc);
this.viewportLoc = this.getUniformLocation(shaderProgram, 'uViewport');
this.translateLoc = this.getUniformLocation(shaderProgram, 'uTranslate');
this.samplerLoc = this.getUniformLocation(shaderProgram, 'uSampler');
}
private compileShader(type: number, src: string): WebGLShader {
const shader = this.gl.createShader(type);
if (!shader)
throw new Error('Unable to create shader');
this.gl.shaderSource(shader, src);
this.gl.compileShader(shader);
if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) {
const err = this.gl.getShaderInfoLog(shader);
this.gl.deleteShader(shader);
throw new Error('Unable to compile shader: ' + err);
}
return shader;
}
private getAttribLocation(program: WebGLProgram, name: string): number {
const ret = this.gl.getAttribLocation(program, name);
if (ret < 0)
throw new Error("unable to get location of attribute '" + name + "'");
return ret;
}
private getUniformLocation(program: WebGLProgram, name: string): WebGLUniformLocation {
const ret = this.gl.getUniformLocation(program, name);
if (!ret)
throw new Error("unable to get location of uniform '" + name + "'");
return ret;
}
}
|