Home Reference Source

viewer/ssquad.js

  1. /**
  2. * A Screen-space quadrangle used for deferred rendering. Currently only used for
  3. * Order Independent Transparency which is hard-coded here in the constructor.
  4. *
  5. * @class SSQuad
  6. */
  7. export class SSQuad {
  8.  
  9. constructor(gl) {
  10. this.gl = gl;
  11.  
  12. let vao = this.vao = gl.createVertexArray();
  13. gl.bindVertexArray(vao);
  14.  
  15. let positionBuffer = gl.createBuffer();
  16. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  17. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  18. -1., +1., -1., -1., +1., -1.,
  19. -1., +1., +1., -1., +1., +1.
  20. ]), gl.STATIC_DRAW);
  21. gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
  22. gl.enableVertexAttribArray(0);
  23.  
  24. let vs_source = `#version 300 es
  25. layout(location=0) in vec4 vertexPosition;
  26. out vec2 uv;
  27. void main() {
  28. gl_Position = vertexPosition;
  29. uv = (vertexPosition.xy + 1.) / 2.;
  30. }`;
  31.  
  32. let fs_source = `#version 300 es
  33. precision highp float;
  34. uniform sampler2D colorAccumulate;
  35. uniform sampler2D alphaAccumulate;
  36. in vec2 uv;
  37. out vec4 fragColor;
  38. void main() {
  39. float a = texture(alphaAccumulate, uv).r;
  40. vec4 accum = texture(colorAccumulate, uv);
  41. // pssst I'm just doing random stuff here
  42. fragColor = vec4(pow(accum.rgb / a, vec3(0.75, 0.75, 0.75)), clamp(accum.a, 0., 1.));
  43. }`;
  44.  
  45. let vs = gl.createShader(gl.VERTEX_SHADER);
  46. gl.shaderSource(vs, vs_source);
  47. gl.compileShader(vs);
  48. if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) {
  49. console.error(gl.getShaderInfoLog(vs));
  50. }
  51. let fs = gl.createShader(gl.FRAGMENT_SHADER);
  52. gl.shaderSource(fs, fs_source);
  53. gl.compileShader(fs);
  54. if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) {
  55. console.error(gl.getShaderInfoLog(fs));
  56. }
  57. let p = this.program = gl.createProgram();
  58. gl.attachShader(p, vs);
  59. gl.attachShader(p, fs);
  60. gl.linkProgram(p);
  61. if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {
  62. console.error(gl.getProgramInfoLog(p));
  63. }
  64.  
  65. this.colorLocation = gl.getUniformLocation(p, "colorAccumulate");
  66. this.alphaLocation = gl.getUniformLocation(p, "alphaAccumulate");
  67. }
  68.  
  69. draw(...args) {
  70. let gl = this.gl;
  71.  
  72. gl.disable(gl.DEPTH_TEST);
  73.  
  74. gl.activeTexture(gl.TEXTURE1);
  75. gl.bindTexture(gl.TEXTURE_2D, args[0]);
  76. gl.activeTexture(gl.TEXTURE2);
  77. gl.bindTexture(gl.TEXTURE_2D, args[1]);
  78.  
  79. gl.useProgram(this.program);
  80. gl.uniform1i(this.colorLocation, 1);
  81. gl.uniform1i(this.alphaLocation, 2);
  82.  
  83. gl.bindVertexArray(this.vao);
  84. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  85. gl.drawArrays(gl.TRIANGLES, 0, 6);
  86. gl.bindVertexArray(null);
  87. }
  88. }