Finally found some time to experiment with shaders, but I hit a roadblock. My goal is to pass vertices to a shader and perform general-purpose computing on them.
It seems like the gpgpu functionality is working fine because I can see a few pixels being shifted to the side in the center as I added some test code.
Now, my aim is to pass the vertices of a sphere. Here are the steps I am following. Please let me know if you spot any mistakes :-)
edit: fiddle included - click here
1) Creating geometry and storing it in a data array.
geometry = new THREE.SphereGeometry( 0.2, 15, 15 );
console.log(geometry.vertices.length);
var a = new Float32Array(geometry.vertices.length * 4);
for(var k=0; k<geometry.vertices.length; k++) {
a[ k*4 + 0 ] = geometry.vertices[k].x;
a[ k*4 + 1 ] = geometry.vertices[k].y;
a[ k*4 + 2 ] = geometry.vertices[k].z;
a[ k*4 + 3 ] = 1;
}
2) Saving it in a data texture.
posTexture[2] = new THREE.DataTexture(a, 16, 16, THREE.RGBAFormat, THREE.FloatType);
3) Setting up the 'Set scene' (it should pass the data texture to it once). setUniforms = { posTexture: {type: "t", value: posTexture[2]} };
var setMaterial = new THREE.ShaderMaterial({
uniforms: setUniforms,
vertexShader: document.getElementById('setVert').textContent,
fragmentShader: document.getElementById('setFrag').textContent,
wireframe: true
});
var setPlane = new THREE.Mesh(new THREE.PlaneGeometry(16,16), setMaterial);
setScene.add(setPlane);
4) Defining the shaders.
<script type="x-shader/x-vertex" id="setVert">
// enabling high precision floats
#ifdef GL_ES
precision highp float;
#endif
varying vec2 vUv;
uniform sampler2D posTexture;
void main(){
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
}
</script>
<script type="x-shader/x-fragment" id="setFrag">
#ifdef GL_ES
precision highp float;
#endif
uniform sampler2D posTexture;
varying vec2 vUv;
void main(){
vec3 color = texture2D( posTexture, vUv ).xyz;
gl_FragColor = vec4(col, 1.0);
}
</script>
5) Time to animate!!! The 'start' function initializes the SetShader to store the data and output a WebGLRenderTarget for the next shaders: one for calculations and providing a texture with coordinates, and another for display.
function animate() {
requestAnimationFrame(animate);
renderer.setViewport(0,0,16, 16);
if(buffer == 0) {
buffer = 1;
a = 0;
b = 1;
} else {
buffer = 0;
a = 1;
b = 0;
}
if(start) {
renderer.render(setScene, processCamera, posTexture[a]);
start = false;
}
posUniforms.posTexture.value = posTexture[a];
renderer.render(posScene, processCamera, posTexture[b])
dispUniforms.posTexture.value = posTexture[b];
renderer.setViewport(0,0,dispSize.x, dispSize.y);
renderer.render(scene, camera);
}