File size: 10,683 Bytes
f6f03fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
328
329
330
331
332
333
334
335
336
337
// WebGL post-processing: bloom + chromatic aberration + glitch + grade + grain.
// WebGL1 API for the widest device support (incl. older iOS Safari).

export interface PostParams {
  time: number
  flash: number
  flashColor: [number, number, number]
  aberr: number
  glitch: number
  zoom: number
  shake: [number, number]
  bloom: number
  grain: number
  vignette: number
  scan: number
  /** 0 = normal, 1 = full black-out (used for hard cut to black) */
  black: number
  seed: number
}

const VS = `
attribute vec2 p;
varying vec2 uv;
void main(){ uv = p*0.5+0.5; gl_Position = vec4(p,0.0,1.0); }`

const FS_BRIGHT = `
precision mediump float;
varying vec2 uv;
uniform sampler2D src;
uniform vec2 texel;
void main(){
  vec3 c = vec3(0.0);
  c += texture2D(src, uv + texel*vec2(-1.0,-1.0)).rgb;
  c += texture2D(src, uv + texel*vec2( 1.0,-1.0)).rgb;
  c += texture2D(src, uv + texel*vec2(-1.0, 1.0)).rgb;
  c += texture2D(src, uv + texel*vec2( 1.0, 1.0)).rgb;
  c *= 0.25;
  float l = max(max(c.r,c.g),c.b);
  float k = smoothstep(0.42, 0.95, l);
  gl_FragColor = vec4(c*k, 1.0);
}`

const FS_BLUR = `
precision mediump float;
varying vec2 uv;
uniform sampler2D src;
uniform vec2 dir;
void main(){
  vec3 c = texture2D(src, uv).rgb * 0.227027;
  c += texture2D(src, uv + dir*1.3846).rgb * 0.3162162;
  c += texture2D(src, uv - dir*1.3846).rgb * 0.3162162;
  c += texture2D(src, uv + dir*3.2307).rgb * 0.0702702;
  c += texture2D(src, uv - dir*3.2307).rgb * 0.0702702;
  gl_FragColor = vec4(c, 1.0);
}`

const FS_FINAL = `
precision highp float;
varying vec2 uv;
uniform sampler2D scene;
uniform sampler2D bloomA;
uniform sampler2D bloomB;
uniform vec2 res;
uniform float time;
uniform float flash;
uniform vec3 flashColor;
uniform float aberr;
uniform float glitch;
uniform float zoom;
uniform vec2 shake;
uniform float bloom;
uniform float grain;
uniform float vignette;
uniform float scan;
uniform float black;
uniform float seed;

float h1(float n){ return fract(sin(n*127.1+seed*13.7)*43758.5453); }
float h2(vec2 p){ return fract(sin(dot(p, vec2(12.9898,78.233)) + seed)*43758.5453); }

void main(){
  vec2 q = uv;
  // zoom punch & shake around the centre
  q = (q - 0.5) / zoom + 0.5 + shake;
  // subtle lens barrel
  vec2 cc = q - 0.5;
  q = 0.5 + cc * (1.0 + 0.035*dot(cc,cc));
  // glitch: horizontal block displacement
  if (glitch > 0.001) {
    float row = floor(q.y * 24.0);
    float tt = floor(time * 30.0);
    float r = h1(row + tt*7.0);
    if (r < glitch*0.45) {
      q.x += (h1(row*3.1 + tt) - 0.5) * 0.18 * glitch;
    }
    float big = floor(q.y * 6.0);
    if (h1(big + tt*1.7) < glitch*0.15) q.x = fract(q.x + 0.06);
  }
  float ab = aberr + glitch*0.012;
  vec2 dir = (q - 0.5);
  vec3 col;
  col.r = texture2D(scene, q + dir*ab).r;
  col.g = texture2D(scene, q).g;
  col.b = texture2D(scene, q - dir*ab).b;
  // outside edges -> black
  if (q.x < 0.0 || q.x > 1.0 || q.y < 0.0 || q.y > 1.0) col = vec3(0.0);

  vec3 b = texture2D(bloomA, uv).rgb * 0.8 + texture2D(bloomB, uv).rgb * 1.0;
  col += b * bloom;

  // filmic grade: teal shadows, warm highlights (inspired by the reference palette)
  float l = dot(col, vec3(0.299,0.587,0.114));
  vec3 shadowTint = vec3(0.86, 1.0, 1.10);
  vec3 highTint = vec3(1.08, 0.99, 0.88);
  col *= mix(shadowTint, highTint, smoothstep(0.15, 0.75, l));
  col = mix(vec3(l), col, 1.06);
  // soft shoulder tonemap
  col = col / (1.0 + col*0.18) * 1.14;
  // lifted, slightly teal blacks (filmic look from the reference footage)
  col = col * 0.94 + vec3(0.018, 0.028, 0.036);

  // scanlines + grain
  float s = sin(uv.y * res.y * 3.14159) * 0.5 + 0.5;
  col *= 1.0 - scan * (1.0 - s);
  float g = h2(uv*res + fract(time*61.0)*vec2(91.7, 37.3)) - 0.5;
  col += g * grain;

  // vignette
  vec2 v = uv - 0.5;
  col *= mix(1.0, smoothstep(0.85, 0.2, length(v*vec2(1.0, res.y/res.x*0.9+0.1))), vignette);

  col = mix(col, flashColor, clamp(flash, 0.0, 1.0));
  col *= 1.0 - black;
  gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
}`

interface FBO {
  fb: WebGLFramebuffer
  tex: WebGLTexture
  w: number
  h: number
}

export class Post {
  gl: WebGLRenderingContext
  private progBright: WebGLProgram
  private progBlur: WebGLProgram
  private progFinal: WebGLProgram
  private sceneTex: WebGLTexture
  private buf: WebGLBuffer
  private fA!: FBO
  private fB!: FBO
  private fC!: FBO
  private fD!: FBO
  private W = 0
  private H = 0
  private uni = new Map<WebGLProgram, Map<string, WebGLUniformLocation | null>>()

  static create(canvas: HTMLCanvasElement): Post | null {
    try {
      const gl = canvas.getContext('webgl', {
        preserveDrawingBuffer: true,
        antialias: false,
        premultipliedAlpha: false,
        alpha: false,
      }) as WebGLRenderingContext | null
      if (!gl) return null
      return new Post(gl)
    } catch {
      return null
    }
  }

  constructor(gl: WebGLRenderingContext) {
    this.gl = gl
    this.progBright = this.program(VS, FS_BRIGHT)
    this.progBlur = this.program(VS, FS_BLUR)
    this.progFinal = this.program(VS, FS_FINAL)
    this.buf = gl.createBuffer()!
    gl.bindBuffer(gl.ARRAY_BUFFER, this.buf)
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW)
    this.sceneTex = this.texture()
  }

  private shader(type: number, src: string) {
    const gl = this.gl
    const s = gl.createShader(type)!
    gl.shaderSource(s, src)
    gl.compileShader(s)
    if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s) || 'shader')
    return s
  }
  private program(vs: string, fs: string) {
    const gl = this.gl
    const p = gl.createProgram()!
    gl.attachShader(p, this.shader(gl.VERTEX_SHADER, vs))
    gl.attachShader(p, this.shader(gl.FRAGMENT_SHADER, fs))
    gl.linkProgram(p)
    if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p) || 'link')
    return p
  }
  private u(p: WebGLProgram, name: string) {
    let m = this.uni.get(p)
    if (!m) {
      m = new Map()
      this.uni.set(p, m)
    }
    if (!m.has(name)) m.set(name, this.gl.getUniformLocation(p, name))
    return m.get(name)!
  }
  private texture() {
    const gl = this.gl
    const t = gl.createTexture()!
    gl.bindTexture(gl.TEXTURE_2D, t)
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
    return t
  }
  private fbo(w: number, h: number): FBO {
    const gl = this.gl
    const tex = this.texture()
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null)
    const fb = gl.createFramebuffer()!
    gl.bindFramebuffer(gl.FRAMEBUFFER, fb)
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0)
    gl.bindFramebuffer(gl.FRAMEBUFFER, null)
    return { fb, tex, w, h }
  }
  private freeFbo(f?: FBO) {
    if (!f) return
    this.gl.deleteFramebuffer(f.fb)
    this.gl.deleteTexture(f.tex)
  }

  resize(W: number, H: number) {
    if (W === this.W && H === this.H) return
    this.W = W
    this.H = H
    ;[this.fA, this.fB, this.fC, this.fD].forEach((f) => this.freeFbo(f))
    const qw = Math.max(2, Math.round(W / 4))
    const qh = Math.max(2, Math.round(H / 4))
    const ew = Math.max(2, Math.round(W / 12))
    const eh = Math.max(2, Math.round(H / 12))
    this.fA = this.fbo(qw, qh)
    this.fB = this.fbo(qw, qh)
    this.fC = this.fbo(ew, eh)
    this.fD = this.fbo(ew, eh)
  }

  private draw(p: WebGLProgram) {
    const gl = this.gl
    gl.useProgram(p)
    const loc = gl.getAttribLocation(p, 'p')
    gl.bindBuffer(gl.ARRAY_BUFFER, this.buf)
    gl.enableVertexAttribArray(loc)
    gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0)
    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
  }

  private bindTex(p: WebGLProgram, name: string, tex: WebGLTexture, unit: number) {
    const gl = this.gl
    gl.activeTexture(gl.TEXTURE0 + unit)
    gl.bindTexture(gl.TEXTURE_2D, tex)
    gl.uniform1i(this.u(p, name), unit)
  }

  private blur(src: FBO, tmp: FBO, scale: number) {
    const gl = this.gl
    const p = this.progBlur
    gl.useProgram(p)
    gl.bindFramebuffer(gl.FRAMEBUFFER, tmp.fb)
    gl.viewport(0, 0, tmp.w, tmp.h)
    this.bindTex(p, 'src', src.tex, 0)
    gl.uniform2f(this.u(p, 'dir'), scale / src.w, 0)
    this.draw(p)
    gl.bindFramebuffer(gl.FRAMEBUFFER, src.fb)
    gl.viewport(0, 0, src.w, src.h)
    this.bindTex(p, 'src', tmp.tex, 0)
    gl.uniform2f(this.u(p, 'dir'), 0, scale / src.h)
    this.draw(p)
  }

  private down(src: WebGLTexture, srcW: number, srcH: number, dst: FBO) {
    const gl = this.gl
    const p = this.progBright
    gl.useProgram(p)
    gl.bindFramebuffer(gl.FRAMEBUFFER, dst.fb)
    gl.viewport(0, 0, dst.w, dst.h)
    this.bindTex(p, 'src', src, 0)
    gl.uniform2f(this.u(p, 'texel'), 1.5 / srcW, 1.5 / srcH)
    this.draw(p)
  }

  render(source: HTMLCanvasElement, pp: PostParams) {
    const gl = this.gl
    const W = source.width
    const H = source.height
    this.resize(W, H)
    gl.bindTexture(gl.TEXTURE_2D, this.sceneTex)
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true)
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source)

    // bloom chain
    this.down(this.sceneTex, W, H, this.fA)
    this.blur(this.fA, this.fB, 1.0)
    this.blur(this.fA, this.fB, 2.0)
    this.down(this.fA.tex, this.fA.w, this.fA.h, this.fC)
    this.blur(this.fC, this.fD, 1.0)
    this.blur(this.fC, this.fD, 2.0)

    const p = this.progFinal
    gl.useProgram(p)
    gl.bindFramebuffer(gl.FRAMEBUFFER, null)
    gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight)
    this.bindTex(p, 'scene', this.sceneTex, 0)
    this.bindTex(p, 'bloomA', this.fA.tex, 1)
    this.bindTex(p, 'bloomB', this.fC.tex, 2)
    gl.uniform2f(this.u(p, 'res'), W, H)
    gl.uniform1f(this.u(p, 'time'), pp.time)
    gl.uniform1f(this.u(p, 'flash'), pp.flash)
    gl.uniform3f(this.u(p, 'flashColor'), pp.flashColor[0], pp.flashColor[1], pp.flashColor[2])
    gl.uniform1f(this.u(p, 'aberr'), pp.aberr)
    gl.uniform1f(this.u(p, 'glitch'), pp.glitch)
    gl.uniform1f(this.u(p, 'zoom'), pp.zoom)
    gl.uniform2f(this.u(p, 'shake'), pp.shake[0], pp.shake[1])
    gl.uniform1f(this.u(p, 'bloom'), pp.bloom)
    gl.uniform1f(this.u(p, 'grain'), pp.grain)
    gl.uniform1f(this.u(p, 'vignette'), pp.vignette)
    gl.uniform1f(this.u(p, 'scan'), pp.scan)
    gl.uniform1f(this.u(p, 'black'), pp.black)
    gl.uniform1f(this.u(p, 'seed'), pp.seed)
    this.draw(p)
  }
}