Search code examples
webglwebgl2opengl-es-3.0

Migrating to WebGL2 shaders from WebGL


I am currently migrating some WebGL code to make use of WebGL2 shaders. I have altered the shaders to the es 300 syntax and systematically redacted the 3D engine business logic code to the point where I have only a sequence of calls to the API, yet I am unable to see any output in the renderer. I am not receiving any shader compilation errors and the clear viewport is clearing fine, however I do not see any geometry output from the draw.

My question is: Are there alternative WebGL2 calls that I must implement in order to render geometry that has been ported from WebGL?

GL20.gl = GL20.createContext('ex3-root')
let gl = GL20.gl
gl = WebGLDebugUtils.makeDebugContext(gl, onGLError)

let vShader = gl.createShader(GL20.gl.VERTEX_SHADER)
gl.shaderSource(vShader, 
`#version 300 es

in vec3 a_position;
out vec4 outPosition;

void main() {
    outPosition = vec4(a_position, 1.0);
}`
)
gl.compileShader(vShader)

let fShader = gl.createShader(gl.FRAGMENT_SHADER)
gl.shaderSource(fShader, 
`#version 300 es
precision highp float;

out vec4 outColor;

void main() {
    outColor = vec4(1.0, 0.0, 1.0, 1.0);
}`
)
gl.compileShader(fShader)

let program = gl.createProgram()
gl.attachShader(program, vShader)
gl.attachShader(program, fShader)
gl.linkProgram(program)

if(!gl.getProgramParameter( program, gl.LINK_STATUS) ) {
    let info = gl.getProgramInfoLog(program)
    throw 'Could not compile WebGL program. \n' + info
}
gl.useProgram(program)

let vBufferPointer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vBufferPointer)
gl.bufferData(gl.ARRAY_BUFFER, 
    new Float32Array([-0.3, -0.3, 0.5,
                       0.3, -0.3, 0.5,
                       0.3,  0.3, 0.5,
                      -0.3,  0.3, 0.5]),
    gl.STATIC_DRAW)

let iBufferPointer = gl.createBuffer()
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, iBufferPointer)
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, 
    new Uint16Array([0, 1, 2,
                     0, 2, 3]),
    gl.STATIC_DRAW)

let positionAttributeLocation = gl.getAttribLocation(program, "a_position")
gl.vertexAttribPointer(positionAttributeLocation, 3, gl.FLOAT, false, 12, 0)
gl.enableVertexAttribArray(positionAttributeLocation)

gl.viewport(0, 0, gl.canvas.width, gl.canvas.height)
gl.clearColor(0.6, 0.7, 0.8, 1.0)
gl.enable(gl.DEPTH_TEST)
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0)

gl.bindBuffer(gl.ARRAY_BUFFER, null)
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null)

Solution

  • In the vertex shader you must use gl_Position to output the vertex position.