Three.js removes model objects (.remove() and ·dispose() methods)

Clear the main idea

  • The shader contains vertex data and texture.

The dispose () method

  • Please dispose() method by referring to objects such as BufferGeometry or Geometry, Material Material and Texture.
    • Geometry, the dispose ()
    • Texture· Dispose () (Shader and afterdispose two)
    • Material, the dispose ()
    • WebGLRenderer · the dispose ()
    • rendererTarget.dispose()
  • DispatchEvent with type ‘Dispose’ to call EventDispatcher
Dispose () method encapsulation
dispose: function () {
  // A geometry or material object automatically triggers an event called Dispose
  this.dispatchEvent( { type: 'dispose'}); }Copy the code
// Dispose event on WebGLGeometries. Js source code
function get( object, geometry ) {... geometry.addEventListener('dispose', onGeometryDispose ); . }function onGeometryDispose( event ) {...// Call the remove method wrapped by webglattributes.js to remove the vertex bufferattributes.remove( buffergeometry.index ); . }Copy the code
Webglattributes.js encapsulates the remove method to remove the vertex buffer created by Threejs when parsing vertex data from model geometry.
function remove( attribute ) {...if ( data ) {
    // Call gl.deleteBuffer() to remove the vertex buffergl.deleteBuffer( data.buffer ); }... }Copy the code

Self – written texture map release

disposeMaterial(material) { / / empty texture
    if (material instanceof THREE.Material) {
            for (const value of Object.values(material)) {
                    if (value instanceofTHREE.Texture) { value.dispose(); }}if (material.uniforms) {
                    for (const value of Object.values(material.uniforms)) {
                            if (value) {
                                    const uniformValue = value.value;
                                    if (uniformValue instanceof THREE.Texture) {
                                            uniformValue.dispose();
                                    }
                                    if(Array.isArray(uniformValue)){
                                            uniformValue.length = 0; } } } } material.dispose(); }}Copy the code

Determine the number of vertices and tiles in the memery

renderer.info.memory;
Copy the code