javascriptwebglwebgl2

WebGL does not like Index 255 with indexed drawing


Here is a minimal WebGL test program that creates an index buffer with a single uint8 value of 255. It should draw a red square of a size of 64px, it does not (the index value is not really important for the draw).

Somehow WebGL ignores Elements with an index of 255 although it fits in the unsigned byte range. Use 254 or some other value and the red square appears as expected.

Is this a bug of WebGL or intended behaviour? I couldn't find anything about it.

<canvas width="800" height="600"></canvas>
<script>
let canvas = document.querySelector("canvas");
let gl = canvas.getContext("webgl2");
let vert = gl.createShader(gl.VERTEX_SHADER);
let frag = gl.createShader(gl.FRAGMENT_SHADER);
let prog = gl.createProgram();
let index_buf = gl.createBuffer();

gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buf);

gl.bufferData(
    gl.ELEMENT_ARRAY_BUFFER, new Uint8Array([255]), gl.STATIC_DRAW
);

gl.shaderSource(vert, `#version 300 es
    void main()
    {
        gl_Position = vec4(0,0,0,1);
        gl_PointSize = 64.0;
    }
`);

gl.shaderSource(frag, `#version 300 es
    precision highp float;
    out vec4 color;
    void main()
    {
        color = vec4(1,0,0,1);
    }
`);

gl.compileShader(vert);
gl.compileShader(frag);
gl.attachShader(prog, vert);
gl.attachShader(prog, frag);
gl.linkProgram(prog);
gl.clearColor(0, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.useProgram(prog);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buf);
gl.drawElements(gl.POINTS, 1, gl.UNSIGNED_BYTE, 0);
</script>

Solution

  • See WebGL 2.0 Specification - PRIMITIVE_RESTART_FIXED_INDEX is always enabled:

    The PRIMITIVE_RESTART_FIXED_INDEX context state, controlled with Enable/Disable in OpenGL ES 3.0, is not supported in WebGL 2.0. Instead, WebGL 2.0 behaves as though this state were always enabled. This is a compatibility difference compared to WebGL 1.0.

    When drawElements, drawElementsInstanced, or drawRangeElements processes an index, if the index's value is the maximum for the data type (255 for UNSIGNED_BYTE indices, 65535 for UNSIGNED_SHORT, or 4294967295 for UNSIGNED_INT), ...

    Therefore, if the index type is UNSIGNED_BYTE, index 255 is the primitive restart index and cannot be used for indexing vertices.