Update Parent Bounding Box On Child Added

I am trying to create a bounding box mesh that updates its bounding box whenever it receives a new child mesh so that the bounding box includes all the children meshes. I am finding this hard to do with the typical observers and functions because onAfterWorldMatrixUpdate will trigger when you call getHierarchyBoundingVectors() causing an infinite loop.

Is there a better way to listen for changes to a node/mesh scene graph hierarchy?

let container = new Mesh(name, scene);
let { min, max } = container.getHierarchyBoundingVectors();
container.setBoundingInfo(new BoundingInfo(min, max));

container.onAfterWorldMatrixUpdateObservable.add((v) => {
  let { min, max } = container.getHierarchyBoundingVectors(); //triggers observable causing infinite loop
  container.setBoundingInfo(new BoundingInfo(min, max));
})

let sphere = new MeshBuilder.CreateSphere()

sphere.setParent(container)

Indeed it seems that it forces computing the world matrix to be sure we are up to date.

image

@Evgeni_Popov can you think of anything ?

You could detect reentrancy like this:

But it won’t work in your case because onAfterWorldMatrixUpdateObservable is called on the container before the parent property of the sphere is updated.

You can delay the execution of onAfterWorldMatrixUpdateObservable to the end of the frame, to let the code that set the parenting run:

2 Likes

Thanks! that works great!

I created a PR to update the bounding box documentation to include this method and these examples.

3 Likes

There is a strange behavior with this approach where if you move the parent mesh the bounding box seems to drift from the child meshes, not sure whats causing this.

getHierarchyBoundingVectors returns the values in word space, while BoundingInfo expects min/max in local space:

2 Likes