I've encountered an issue with three.js and instancing, similar to what others have experienced. The objects are randomly clipped and disappear from the camera view. Examples can be found here.
- Mesh suddenly disappears in three.js. Clipping?
- Three.js buffergeometry disappears after moving camera too close
Some suggested workarounds involve setting
my_instanced_object.frustumCulled = false;
However, this leads to rendering every object per frame, causing a significant drop in framerate with a large number of objects.
What are the alternatives to achieve proper frustum culling while using instancing?
Below is the code I'm using:
var geometry = new THREE.InstancedBufferGeometry();
geometry.maxInstancedCount = all_meshes_data.length;
geometry.addAttribute( 'position', mesh.geometry.attributes.position );
geometry.addAttribute( 'normal', mesh.geometry.attributes.normal );
geometry.addAttribute( 'uv', mesh.geometry.attributes.uv );
var offsets = new THREE.InstancedBufferAttribute( new Float32Array( all_meshes_data.length * 3 ), 3, 1 );
for ( var i = 0, ul = all_meshes_data.length; i < ul; i++ ) { // Populate all instancing positions (where to spawn instances)
offsets.setXYZ( i, all_meshes_data[i].x, all_meshes_data[i].y, all_meshes_data[i].z );
}
geometry.addAttribute( 'offset', offsets );
var instanceMaterial = new THREE.RawShaderMaterial( {
vertexShader: document.getElementById( 'vertexShader' ).textContent,
fragmentShader: document.getElementById( 'fragmentShader' ).textContent,
transparent: true
} );
geometry.computeVertexNormals();
geometry.boundingSphere = new THREE.Sphere( new THREE.Vector3(), 50 ); // Not working, it works just for a 0;0;0 world positioned mesh that is the 'base' of all of the instanced ones
var instanced_mesh = new THREE.Mesh( geometry, instanceMaterial );
//instanced_mesh.frustumCulled = false; // Works, but the scene becomes very slow (rendering everything even if not in sight)
scene.add( instanced_mesh );