So I found yet another memory leak in my application today (I swear everytime I optimize something I break something else) - I need just general brainstorming and or approval as to whether what I am doing will work or not, or how to go about doing something of the sort in a better manner.
The memory leak I am seeing is on instanced meshes, specifically sourceMesh._visibleInstances – When I freezeActiveMeshes, the object constantly gets added to on every render without clearing out the previous renderIds, so it begins to grow and grow and grow (until unfreeze is called, then it clears out). – I do however unfreeze everytime a mesh is added, and or when a mesh is enabled/disabled, so even with the memory leak it seems to be faster than without the behavior.
The behavior in question is as follows: (I call this method after initializing scene).
Object.defineProperty(BABYLON.Scene.prototype, "$$initializeFreezeCallbacks", {
value() {
this.onNewMeshAddedObservable.add(function(mesh) {
if(this._activeMeshesFrozen) {
this.unfreezeActiveMeshes();
}
console.log('new mesh added to scene', mesh.name);
mesh.$$onSetEnabledObservable.add(function(val){
if(val === true && mesh._scene._activeMeshesFrozen) {
mesh._scene.unfreezeActiveMeshes();
}
}, undefined, undefined, mesh);
mesh.onDisposeObservable.add(function(val){
if(mesh._scene._activeMeshesFrozen) {
mesh._scene.unfreezeActiveMeshes();
mesh._scene.$$scheduleFreeze();
}
}, undefined, undefined, mesh);
}, undefined, undefined, this);
this.onAfterRenderObservable.add(function() {
if(this.$$freeze_scheduled || !this._activeMeshesFrozen && this._activeParticleSystems.length === 0) {
this.freezeActiveMeshes();
this.$$freeze_scheduled = false;
}
}, undefined, undefined, this);
}
});
So the idea is, when a mesh is enabled, disabled, unfreeze once per frame, but always freeze after rendering, unless particles are flying around (I could probably do better if there is a particle.onDispose method I could tap into but haven’t dug into that yet and don’t think there is).
Initially I had a super bad memory leak (consistently drops 1 fps per second until <5fps) when I would freezeActiveMeshes, that I fixed by overwriting/commenting out the following line in renderingGroup render method (don’t think it’s related, because commenting back in doesn’t fix the underlying issue,but for what it’s worth)
// if (renderSprites) {
// this._renderSprites();
// }
So my question is, do you see anything wrong with what I am doing above. If not, do you happen to have any ideas as to what could be causing sourceMesh._visibleInstances to pile up like this?