Capítulo 806 de 859

Chapter 806: Cleanup (Manual)

Core Idea

Three.js cannot automatically free GPU memory; geometries, materials and textures must be disposed manually, and a small tracker class can automate discovering and disposing everything a loaded model allocated.

Key Concepts

  • dispose(): the method that frees GPU-side memory for a geometry, material, or texture — required because WebGL gives JavaScript no automatic GC hook for GPU resources.
  • ResourceTracker: a custom helper class that records resources as they're created (or discovered) and disposes them all at once.
  • Object3D walking: for loaded models, a tracker needs to recursively walk resource.geometry, resource.material (which may be an array), and resource.children to find everything to free.
  • Texture discovery in materials: textures can hide in ordinary material properties or in shader uniforms, both need to be checked when tracking a material.
  • Track-time vs. dispose-time decisions: tracking what was loaded (at track time) is more flexible than trying to infer what to free later, especially once objects like a tool get parented onto a loaded character.

Code Examples

class ResourceTracker {
  constructor() {
    this.resources = new Set();
  }
  track(resource) {
    if (!resource) return resource;
    if (Array.isArray(resource)) {
      resource.forEach((r) => this.track(r));
      return resource;
    }
    if (resource.dispose || resource instanceof THREE.Object3D) {
      this.resources.add(resource);
    }
    if (resource instanceof THREE.Object3D) {
      this.track(resource.geometry);
      this.track(resource.material);
      this.track(resource.children);
    }
    return resource;
  }
  // dispose() iterates this.resources and calls .dispose() / removes from parent
}
  • What it demonstrates: a reusable tracker that recursively discovers geometries, materials and children of a loaded Object3D for later bulk disposal.

Key Takeaways

  1. Three.js does not garbage-collect GPU resources; call dispose() yourself on textures, geometries and materials.
  2. A tracker class that records resources at creation/load time makes bulk disposal much less tedious than manual bookkeeping.
  3. Loaded models need a recursive walk (geometry, material, children, and any textures hiding in material properties or shader uniforms) since loaders return only a plain Object3D hierarchy.
  4. Decide explicitly whether objects added to a loaded hierarchy afterward (e.g. a tool in a character's hand) should be disposed together with it.

Connects To

  • GLTFLoader: the typical source of the multi-resource object hierarchies this pattern targets.
  • Material / Geometry / Texture reference chapters: each exposes the dispose() method this pattern relies on.