This post is related to LinesMesh no longer disposes shaderMaterial by default — causes memory leak in BoundingBoxGizmo as well as the resulting PR.
While the linked post/PR actually revert the behavior to fix a memory leak (which is good), I stumbled upon an issue in the original implementation.
If you actually supply an external material to the LinesMesh
using the constructor, it will by default dispose of the material when disposing the LinesMesh
. I would argue that supplying a material from outside means you may want to reuse the material elsewhere and handle ownership / disposal yourself.
This is complicated by the fact that the disposal can be disabled when actually calling dispose
on the LinesMesh
using the parameter doNotDisposeMaterial
. However you won’t be able to specify this parameter when the mesh is retrieved through other mechanisms that give you the object as a Mesh
or AbstractMesh
. It is also confusing that dispose
already has a disposeMaterialAndTextures
parameter (which is false by default!) but the linesmesh disposal provides an additional parameter called doNotDisposeMaterial
which works the opposite way. So what if you don’t specify either? The defaults would say:
disposeMaterialAndTextures = false
→ Do not dispose the material
doNotDisposeMaterial = false
→ Do dispose the material
I was thinking about opening a PR as suggested by @sebavan but I know far too little about the implications of making a change in this area.
I would however suggest two changes to fix / improve this behavior:
- Remember if material has been externally supplied and act accordingly.
It is possible to detect whetherdispose
has been called with an explicit value fordoNotDisposeMaterial
or if it is simplyundefined
. Ifundefined
, only dispose self-created materials. If an explicit value has been given, use this to decide. - Optional: Remove the third parameter and just consider
disposeMaterialAndTextures
. In this case, theLinesMesh
should still always dispose of self-created materials to prevent memory leaks but you can opt-in to dispose of any externally supplied materials as well by setting this parameter to true.
Here is a playground to get a better understanding of our issue:
We currently create a few line systems which share the same external material and give them a tag. Once its time to remove all the line systems we retrieve them by tag and dispose them. It is not possible to keep the material alive unless you cast back to the LinesMesh
and specify the appropriate parameter.