aboutsummaryrefslogtreecommitdiff
path: root/web/pw-visualizer/src/webgl/shader.ts
blob: 942c4c21b816846d7151128f4f22d774f3a7c988 (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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import type { Dictionary } from './util';

function error(msg: string) {
  console.error(msg);
}

const defaultShaderType = [
  "VERTEX_SHADER",
  "FRAGMENT_SHADER"
];

/// Create Shader from Source string
function loadShader(
  gl: WebGLRenderingContext,
  shaderSource: string,
  shaderType: number,
  opt_errorCallback: any,
): WebGLShader {
  var errFn = opt_errorCallback || error;
  // Create the shader object
  var shader = gl.createShader(shaderType);

  // Load the shader source
  gl.shaderSource(shader, shaderSource);

  // Compile the shader
  gl.compileShader(shader);

  // Check the compile status
  var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  if (!compiled) {
    // Something went wrong during compilation; get the error
    var lastError = gl.getShaderInfoLog(shader);
    errFn("*** Error compiling shader '" + shader + "':" + lastError);
    gl.deleteShader(shader);
    return null;
  }

  return shader;
}

/// Actually Create Program with Shader's
function createProgram(
  gl: WebGLRenderingContext,
  shaders: WebGLShader[],
  opt_attribs: string[],
  opt_locations: number[],
  opt_errorCallback: any,
): WebGLProgram {
  var errFn = opt_errorCallback || error;
  var program = gl.createProgram();
  shaders.forEach(function (shader) {
    gl.attachShader(program, shader);
  });
  if (opt_attribs) {
    opt_attribs.forEach(function (attrib, ndx) {
      gl.bindAttribLocation(
        program,
        opt_locations ? opt_locations[ndx] : ndx,
        attrib);
    });
  }
  gl.linkProgram(program);

  // Check the link status
  var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  if (!linked) {
    // something went wrong with the link
    var lastError = gl.getProgramInfoLog(program);
    errFn("Error in program linking:" + lastError);

    gl.deleteProgram(program);
    return null;
  }
  return program;
}

export class ShaderFactory {
  frag_source: string;
  vert_source: string;

  static async create_factory(frag_url: string, vert_url: string): Promise<ShaderFactory> {
    const sources = await Promise.all([
      fetch(frag_url).then((r) => r.text()),
      fetch(vert_url).then((r) => r.text()),
    ]);

    return new ShaderFactory(sources[0], sources[1]);
  }

  constructor(frag_source: string, vert_source: string ) {
    this.frag_source = frag_source;
    this.vert_source = vert_source;
  }

  create_shader(
    gl: WebGLRenderingContext,
    context?: Dictionary<string>,
    opt_attribs?: string[],
    opt_locations?: number[],
    opt_errorCallback?: any,
  ): Shader {
    let vert = this.vert_source.slice();
    let frag = this.frag_source.slice();
    for (let key in context) {
      vert = vert.replace(new RegExp("\\$" + key, 'g'), context[key]);
      frag = frag.replace(new RegExp("\\$" + key, 'g'), context[key]);
    }

    const shaders = [
      loadShader(gl, vert, gl.VERTEX_SHADER, opt_errorCallback),
      loadShader(gl, frag, gl.FRAGMENT_SHADER, opt_errorCallback),
    ];

    return new Shader(createProgram(gl, shaders, opt_attribs, opt_locations, opt_errorCallback));
  }
}

export class Shader {
  shader: WebGLProgram;
  uniformCache: Dictionary<WebGLUniformLocation>;
  attribCache: Dictionary<number>;

  static async createProgramFromUrls(
    gl: WebGLRenderingContext,
    vert_url: string,
    frag_url: string,
    context?: Dictionary<string>,
    opt_attribs?: string[],
    opt_locations?: number[],
    opt_errorCallback?: any,
  ): Promise<Shader> {
    const sources = (await Promise.all([
      fetch(vert_url).then((r) => r.text()),
      fetch(frag_url).then((r) => r.text()),
    ])).map(x => {
      for (let key in context) {
        x = x.replace(new RegExp("\\$" + key, 'g'), context[key]);
      }
      return x;
    });

    const shaders = [
      loadShader(gl, sources[0], 35633, opt_errorCallback),
      loadShader(gl, sources[1], 35632, opt_errorCallback),
    ];
    return new Shader(createProgram(gl, shaders, opt_attribs, opt_locations, opt_errorCallback));
  }

  constructor(shader: WebGLProgram) {
    this.shader = shader;
    this.uniformCache = {};
    this.attribCache = {};
  }

  bind(gl: WebGLRenderingContext) {
    gl.useProgram(this.shader);
  }

  // Different locations have different types :/
  getUniformLocation(gl: WebGLRenderingContext, name: string): WebGLUniformLocation {
    if (this.uniformCache[name] === undefined) {
      this.uniformCache[name] = gl.getUniformLocation(this.shader, name);
    }

    return this.uniformCache[name];
  }

  getAttribLocation(gl: WebGLRenderingContext, name: string): number {
    if (this.attribCache[name] === undefined) {
      this.attribCache[name] = gl.getAttribLocation(this.shader, name);
    }

    return this.attribCache[name];
  }

  uniform<T extends Uniform>(
    gl: WebGLRenderingContext,
    name: string,
    uniform: T,
  ) {
    this.bind(gl);
    const location = this.getUniformLocation(gl, name);
    if (location < 0) {
      console.error("No location found with name " + name);
    }

    uniform.setUniform(gl, location);
  }

  clear(gl: WebGLRenderingContext) {
    gl.deleteProgram(this.shader);
  }
}

export interface Uniform {
  setUniform(gl: WebGLRenderingContext, location: WebGLUniformLocation): void;
}

export class Uniform2fv implements Uniform {
  data: number[] | Float32Array;
  constructor(data: number[] | Float32Array) {
    this.data = data;
  }

  setUniform(gl: WebGLRenderingContext, location: WebGLUniformLocation) {
    gl.uniform2fv(location, this.data);
  }
}

export class Uniform3fv implements Uniform {
  data: number[] | Float32Array;
  constructor(data: number[] | Float32Array) {
    this.data = data;
  }

  setUniform(gl: WebGLRenderingContext, location: WebGLUniformLocation) {
    gl.uniform3fv(location, this.data);
  }
}

export class Uniform3f implements Uniform {
  x: number;
  y: number;
  z: number;

  constructor(x: number, y: number, z: number) {
    this.x = x;
    this.y = y;
    this.z = z;
  }

  setUniform(gl: WebGLRenderingContext, location: WebGLUniformLocation) {
    gl.uniform3f(location, this.x ,this.y, this.z);
  }
}

export class Uniform1iv implements Uniform {
  data: number[] | Int32List;
  constructor(data: number[] | Int32List) {
    this.data = data;
  }

  setUniform(gl: WebGLRenderingContext, location: WebGLUniformLocation) {
    gl.uniform1iv(location, this.data);
  }
}

export class Uniform1i implements Uniform {
  texture: number;

  constructor(texture: number) {
    this.texture = texture;
  }

  setUniform(gl: WebGLRenderingContext, location: WebGLUniformLocation) {
    gl.uniform1i(location, this.texture);
  }
}

export class Uniform1f implements Uniform {
  texture: number;

  constructor(texture: number) {
    this.texture = texture;
  }

  setUniform(gl: WebGLRenderingContext, location: WebGLUniformLocation) {
    gl.uniform1f(location, this.texture);
  }
}

export class Uniform2f implements Uniform {
  x: number;
  y: number;

  constructor(xy: number[]) {
    this.x = xy[0];
    this.y = xy[1];
  }

  setUniform(gl: WebGLRenderingContext, location: WebGLUniformLocation) {
    gl.uniform2f(location, this.x, this.y);
  }
}

export class Uniform4f implements Uniform {
  v0: number;
  v1: number;
  v2: number;
  v3: number;

  constructor(xyzw: number[]) {
    this.v0 = xyzw[0];
    this.v1 = xyzw[1];
    this.v2 = xyzw[2];
    this.v3 = xyzw[3];
  }

  setUniform(gl: WebGLRenderingContext, location: WebGLUniformLocation) {
    gl.uniform4f(location, this.v0, this.v1, this.v2, this.v3);
  }
}

export class UniformMatrix3fv implements Uniform {
  data: number[] | Float32Array;
  constructor(data: number[] | Float32Array) {
    this.data = data;
  }

  setUniform(gl: WebGLRenderingContext, location: WebGLUniformLocation) {
    gl.uniformMatrix3fv(location, false, this.data);
  }
}

export class UniformBool implements Uniform {
  data: </