Safe shader construction

November 13, 2017 View Source on GitHub

This is a prototype library for contructing and using WebGL shaders safely at runtime.

It contains a representation of the GLSL abstract syntax tree that can be constructed, although in the future this will be done through a domain-specific language to remove the extra verbosity of constructing the tree:

const fragShader = new cgl.Shader(
  new cgl.Function('main', [
    new cgl.Statement(
      new cgl.EqualAssignment(
        new cgl.Reference(glFragColor),
        new cgl.Reference(colour)
      )
    )
  ]), [], [new cgl.VariableDeclaration(colour)]
);

// ...

const pipelineBuilder = new cgl.ShaderPipelineBuilder(vertexShader, fragShader);
const pipeline = pipelineBuilder.build(gl);

Then, type checking is done to ensure that variables passed into and between shaders will work. Variables can be passed easily between Javascript and the shader pipeline without having to create and manage buffers:

pipeline.useProgram();
pipeline.setAttribute('vertexPosition', [
    1.0, 1.0, 0.0, 1.0,
    -1.0, 1.0, 0.0, 1.0,
    1.0, -1.0, 0.0, 1.0,
    -1.0, -1.0, 0.0, 1.0
]);
pipeline.setUniform('colour', [1.0,  1.0,  1.0,  1.0]);
pipeline.setUniform('modelView', modelViewMatrix);
pipeline.setUniform('projection', projectionMatrix);
pipeline.draw(numVertices);