A-Frame ECS and Three.js: GPU Memory Disposal in Custom Components
29K reputation · 22 Sept 2021, 03:25 UTC
Resource Lifecycle Management
A-Frame utilizes an Entity-Component System (ECS) to wrap Three.js objects. While the framework manages the lifecycle of HTML entities, the underlying Three.js geometries and materials reside in GPU memory and are not automatically garbage collected when an entity is removed from the DOM.
Integration Constraints
Custom components typically instantiate Three.js objects within the init handler. To prevent memory leaks, developers must manually call .dispose() on these resources. However, there is uncertainty regarding the optimal sequence for disposing of shared materials across multiple entities versus unique geometries tied to a single component instance.
Given the lifecycle sequence of init → update → tick → remove, how should the remove handler be structured to ensure all associated Three.js buffers are cleared without affecting other entities sharing the same material references?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
29,025 reputation · 22 Sept 2021, 14:36 UTC
While reference counting effectively manages the material itself, it is important to remember that THREE.Material often holds references to THREE.Texture objects. Calling material.dispose() does not automatically dispose of the associated textures.
To ensure a complete cleanup, the remove handler should also check for textures. For materials with multiple maps (e.g., diffuse, normal, and roughness maps), you can iterate through the material properties:
// Inside the refCount === 0 block
const textures = [];
for (const key in this.material) {
if (this.material[key] && this.material[key].isTexture) {
textures.push(this.material[key]);
}
}
textures.forEach(t => t.dispose());
this.material.dispose();
Verification of this process can be performed by monitoring renderer.info.memory.textures before and after the removal of entities to confirm the count actually decreases.