简体   繁体   中英

THREE.js webGL garbage collection

We have an app that uses THREE.js to render 3D images of body meshes. We have an object called MeshViewer that encapsulates the rendering functionality; during the initialize method, we set

this.renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true })

We wrote a script to test that this.renderer wasn't being deallocated.

<script>
    var count = 0;
    function loop () {
        if (count >= 25) { 
            return; 
        }
        else {
            count++;
            var viewer = new MeshViewer(
                'mesh_viewer',
                's3_assets/textured_mean_scape_female.obj',
                []
            );

            viewer.cleanup();

            setTimeout(function () {
                loop();
            }, 500);
        }
    }
    loop();
</script>

In this case, 'mesh_viewer' is the id of the DOM element we want to embed the viewer in. Our cleanup method sets

this.renderer = null

Cleanup works, in the sense that if we don't perform cleanup, we get an error that too many active WebGL contexts exist, and we can't create anymore, and if we do clean up, we don't get that error.

My question is, why does this fail when viewer.cleanup is called right before loop in setTimeout, and pass when cleanup is called outside and before setTimeout? (This may be a JavaScript question more than a THREE.js/WebGL question.)

It's probably related to the way a browser executes javascript and other stuff in a single thread .

If you put viewer.cleanup(); before setTimeout , either a browser's internal function or a THREE defered function will find time to actually free the renderer before the call to loop(); .

Else viewer.cleanup(); and loop() will be called consecutively with no time in between for anything else to happen.

note: I didn't do any test to confirm that


Also a suggestion: maybe you should put your THREE.WebGLRenderer instance into a singleton and reuse it instead of releasing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM