Finally got some time to play with shaders, but got stuck in one moment. I want to pass the vertices to a shader and make some gpgpu on it.
Gpgpu is working fine I guess because i see few pixels and one in the center being pushed to the side as i put in code just for testing.
Now i want to pass the sphere vertices. Here are the steps I am taking. Please point out errors :-)
edit: fiddle added - click here
1) Creating geometry, and passing it to 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) Save it in data texture
posTexture[2] = new THREE.DataTexture(a, 16, 16, THREE.RGBAFormat, THREE.FloatType);
3) Set the 'Set scene' (it should pass the datatexture 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) Set the shaders.
<script type="x-shader/x-vertex" id="setVert">
// switch on 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) Animate it!!! start sets the SetShader to save the data and output a WebGLRenderTarget to next shaders: one responsible for doing calculations and giving back a texture with coordinates, next one for displaying
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);
}
col
is undefined). Another, an RGBA texture is Unsigned Normalized; you generally do not want to spit vertex positions directly into this kind of a texture because you will lose any coordinate that is < 0. Assuming it stores clip-space vertex positions, where w = 1.0, then you want to multiply by 0.5 and add 0.5 before writing the position togl_FragColor
for output to the texture.