Dynamically change GPUComputationRenderer variables textures

Hello!

On my way to explore this example in order to better understand GPUComputationRenderer, I wanted to save the starting position of each “bird” in order to retrieve it in the shader.

Basically, I duplicated the “position” variable texture and added it to GPUComputationRenderer on init, just like in the example:

startPositionVariable = gpuCompute.addVariable('textureStartPosition', document.getElementById('fragmentShaderStartPosition').textContent, dtStartPosition);
...
gpuCompute.setVariableDependencies(startPositionVariable, [startPositionVariable, positionVariable, velocityVariable]);

The only difference is that, in the Fragment Shader, I don’t change the value of vec3 selfStartPosition = texture2D(textureStartPosition, uv).xyz;. I only use it to attract each bird towards its starting position (instead of the center, like in the example).

Everything is working fine for now, but I need to be able to modify this variable texture during runtime. Basically, when I click, I want to randomize this starting position so each bird will be attracted to a new specific position.

So my question is: since these variables are only initialized once, how can I update the value of one of them dynamically? (or is it even possible?).

I figured that calling gpuCompute.addVariable() again was not the solution, obviously, but I didn’t find any way to update them inside GPUComputationRenderer's code.

Any idea? Thank you in advance!

PS: Again, I didn’t send any live snippet because my implementation is more messy than the example, but if I wasn’t clear enough I can get time to simplify and share it.

The uniforms value needs to be assigned directly.
After assignment, you need to call the doRenderTarget function to apply changes.

const dtStartPosition: THREE.DataTexture = gpuCompute.createTexture();
const positions: Array<THREE.Vector3> = [...];
positions.forEach((p: THREE.Vector3, i: number) => {
    const k = i * 4;
    dtStartPosition.image.data[k + 0] = p.x;
    dtStartPosition.image.data[k + 1] = p.y;
    dtStartPosition.image.data[k + 2] = p.z;
    dtStartPosition.image.data[k + 3] = i;
});
startPositionVariable.material.uniforms.textureStartPosition.value = dtStartPosition;
gpuCompute.doRenderTarget(startPositionVariable.material, startPositionVariable.renderTargets[0]);

You may not have read this thread because it’s been so long since you posted, but I’d share it in case it might be useful to others.

1 Like