Library posted here:
…
Hi, I have been working on an extension to InstancedMesh
for a couple of days now.
InstancedMesh2
I have created my own InstancedMesh2
class that extends InstancedMesh
, which manages an array of InstancedEntity
, itself a class that is similar to Object3D
that allows you to manage the position, scale, rotation and visibility.
Visibility is managed by swapping the element you wish to hide with the last one in instanceMatrix array, and decreasing the count by 1.
This allows the hidden element not to actually be rendered.
This approach uses more memory but:
- it simplifies object transformations
- it allows hiding all instances that are not in the camera frustum (I am working on this with good results, using a custom octree and other optimisations, even if i want to try BVH)
- it allows the easy creation of an
InstancedLOD
(which I am working on, also with good results)
I tried using an InstancedMesh2 with a count of 2kk, using low poly geometry.
In a favourable scenario, with static objects and camera, thanks to the frustum control, it was possible to hide 85% of the instances. Frustum check needs to be done after each camera transformation (still considering static objects).
How to use it
const monkeys = new InstancedMesh2(geometry, material, count, {
behaviour: CullingDynamic,
onInstanceCreation: (obj, index) => {
obj.position.random();
obj.scale.setScalar(2);
obj.quaternion.random();
}
});
scene.add(monkeys);
// How to handle instances
monkeys.instances[0].visible = false;
monkeys.instances[1].rotateOnWorldAxis(xAxis, Math.PI);
monkeys.instances[1].updateMatrix();
monkeys.instances[2].position.x += 10;
monkeys.instances[2].scale.multiplyScalar(2);
monkeys.instances[2].updateMatrix();
Live Example (no frustum check)
I will make all my work public and usable by anyone, as packages with only three.js as peer dependency, and would love to receive advice.
I thank @DolphinIQ for the advice
Currently a similar version without visibility management, but with interaction events is already available in my three.ez library.
In future posts I will explain how I plan to optimise visibility management according to the frustum of the camera and perhaps how I would like to manage InstancedLOD
.
Update:
Last example (1 million instances + frustum culling)
https://stackblitz.com/edit/three-ez-instancedmesh2-cullingstatic-1kk-forest?file=src%2Fmain.ts