Search code examples
opengl-eswebglwebgl2

WebGL 2.0 Occlusion Query


I want to render a big scene(a modeled city) using WebGL, and I think occlusion culling is a good way to optimize the performance.

And I know WebGL 2.0 has a new feature called 'Query Objects' to get the occlusion information. But every time I use gl.getQueryParameter(query, gl.QUERY_RESULT), I got the same result 1.

And I wrote a demo here to explain the problem:

    var query = gl.createQuery();
    gl.beginQuery(gl.ANY_SAMPLES_PASSED, query);
    gl.drawArrays(gl.TRIANGLES,0,n);
    gl.endQuery(gl.ANY_SAMPLES_PASSED);

    var tick = function(){
        if(!gl.getQueryParameter(query,gl.QUERY_RESULT_AVAILABLE)){
            requestAnimationFrame(tick);
            return;
        }
        var result = gl.getQueryParameter(query,gl.QUERY_RESULT);
        console.log(Number(result));
        gl.deleteQuery(query);
    };

    tick();

and here are my vertex information that the sceond triangle is obscured by the first triangle.

    var vertexData = new Float32Array([
            0.0,0.5,0.0,        //first triangle
            -0.5,-0.5,0.0,
            0.5,-0.5,0.0,

            0.0,0.5,-0.5,       //second triangle
            -0.5,-0.5,-0.5,
            0.5,-0.5,-0.5
    ]);

and the result is always 1.

What's the result '1' stands for?

In addition, how could I do occlusion culling using WebGL 2.0? Is there any helpful samples?


Solution

  • Occlusion queries and occlusion culling are NOT the same thing.

    Basic object culling can be (and should be) done entirely on the CPU (e.g. frustum checks on object bounding boxes, portal visibility, octrees, etc) far more effectively than on the GPU because the application can exploit scene level knowledge the graphics driver simply doesn't have.

    On the GPU occlusion culling is most easily provided by rendering opaque objects using a front-to-back render order (again, game engine will usually crudely sort object batches), and using the depth test to cull obscured things.

    Occlusion queries are a very specialized tool that are useful for a small number of visual effects (e.g. lens flare), but far too difficult to pipeline for any aggressive culling within a single frame.