agargaro / instanced-mesh

Enhanced InstancedMesh with frustum culling, fast raycasting (using BVH), sorting, visibility management, LOD and more.
MIT License
122 stars 8 forks source link

Question: Force update instnacedUniforms #37

Open OhBonsai opened 9 hours ago

OhBonsai commented 9 hours ago

HI, @agargaro

Here is my samlpe code. i wana update instanced unifrom perioldly. It seems not working. Is there any explicit update function need to call?


const PeriodUpdateInstances = ()=>{
  const  renderer  = useThree((state) => state.gl)
  const objs = InstancedMesh2(
      renderer, 1000, new PlaneGeometry(1, 1), new RttMaterial(1000)
  )

  objs.createInstances((obj, index)=>{
    obj.setUniform('vTexture', index);
  })
  objs.computeBVH()

  useEffect(()=>{
    const update = ()=>{
      for (let i = 0; i < 1000; i++) {
        objs.instances[i].setUniform('vTexture', Math.random());
      }
    }

    // do updated every 30 seconds
    const intervalId = setInterval(() => {
      update()
    }, 30000)
    return () => clearInterval(intervalId)

  })

  return <primitive object={objs}  />

}
agargaro commented 8 hours ago

Hi! I should add more documentation about this 🤔

To use setUniform you must use a DataTexture. There are utility methods to create and use them and you have to modify the shader (you can use Material.OnBeforeCompile).

Is RttMaterial a your custom material?

Example that use setUniform (see tileMaterial.ts): https://stackblitz.com/edit/three-ezinstancedmesh2-custom-material?file=src%2FtileMaterial.ts,src%2Fmain.ts

Later I will try to write a simpler example and create utility methods also to patch existing materials like yours.

Ps. I see that you don't set the object positions and create a BVH. This might slow down.

agargaro commented 3 hours ago

I have prepared an example where you can set the opacity for each instance: https://stackblitz.com/edit/three-ezinstancedmesh2-opacity-per-instance?file=src%2Fmain.ts

In your case you should do something similar. Lacking utility methods it can be quite complex. I will try to improve these things in future versions.