ShaderCompiler.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. /**
  2. * Represents a WebGL shader object and provides a mechanism to load shaders from HTML
  3. * script tags.
  4. */
  5. export default class ShaderCompiler {
  6. /**
  7. * @param {WebGLRenderingContext}gl
  8. * @param {{type: string, source: string}}script
  9. * @return {WebGLShader}
  10. */
  11. static compile (gl, script) {
  12. let shader
  13. // Now figure out what type of shader script we have, based on its MIME type.
  14. if (script.type === 'x-shader/x-fragment') {
  15. shader = gl.createShader(gl.FRAGMENT_SHADER)
  16. } else if (script.type === 'x-shader/x-vertex') {
  17. shader = gl.createShader(gl.VERTEX_SHADER)
  18. } else {
  19. throw new Error('Unknown shader type: ' + script.type)
  20. }
  21. // Send the source to the shader object.
  22. gl.shaderSource(shader, script.source)
  23. // Compile the shader program.
  24. gl.compileShader(shader)
  25. // See if it compiled successfully.
  26. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  27. throw new Error('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(shader))
  28. }
  29. return shader
  30. }
  31. }