Thomas Bedrnik
Thomas Bedrnik

Reputation: 147

Is it possible to store shader vertex positions in a texture with Three.js?

I am working on a looped 3D starfield in Three.js with a moving camera, but doing this on the CPU is bad for my framerate. It would be great if this would somehow be able to be done by the vertex shader.

This is the javascript code for what I would like to do in the shader:

SW.Starfield = function ( position, scene ) {
    var scale = 10000;
    var particleCount = 2000;
    var x, y, z;
    var particles;

    var material = new THREE.ParticleBasicMaterial( { sizeAttenuation: false, size: 1, color: '#FFFFFF' } );
    var geometry = new THREE.Geometry();

    for ( var i=0; i <= particleCount; i++ ) {
        do {
            x = Math.random() * scale - scale/2 + position.x;
            y = Math.random() * scale - scale/2 + position.y;
            z = Math.random() * scale - scale/2 + position.z;
        } while (new THREE.Vector3( x, y, z ).length()> scale/2);

        geometry.vertices.push( new THREE.Vector3( x, y, z ) );
    }

    particles = new THREE.ParticleSystem( geometry, material );
    particles.dynamic = true;
    particles.position = position;
    particles.sortParticles = true;
    scene.add( particles );

    this.update = function( shipPos ) {
        for ( i=0; i <= particleCount; i++ ) {
            var particleVec = new THREE.Vector3().copy( particles.geometry.vertices[ i ] );
            var shipVec = new THREE.Vector3().copy( shipPos );

            if ( shipVec.sub(particleVec).length() >= scale/2 ) {
                particles.geometry.vertices[ i ].add(shipVec.multiplyScalar(2.0));
            }
        }
    }
}

If I understand it correctly, I would have to store the position of the stars somwhow in a texture to make this work in a shader, because I don't think that you can calculate the new positions of the stars only from their initial positions with an equation in this case. If you look at the update function, it should be clear what I mean.

Is there a way to do this in Three.js? I know that it is possible to store the color. Perhaps I could encode the position as a color, but a position can have much higher values than colors can have and also negative values.

Upvotes: 1

Views: 950

Answers (1)

WestLangley
WestLangley

Reputation: 104833

Google GPGPU and three.js.

There are several examples on the net. Most of them are old.

Here is a recent one:

http://jabtunes.com/labs/3d/gpuflocking/webgl_gpgpu_flocking3.html

three.js r.56dev.

Upvotes: 2

Related Questions