是否可以为每个`InstancedBufferGeometry`实例设置不同的顶点颜色?

时间:2017-04-09 12:06:33

标签: javascript three.js

我想知道是否可以为每个InstancedBufferGeometry实例设置不同的顶点颜色。

const xRes = 3;
const yRes = 2;
const numVertices = xRes * yRes;
geometry = new THREE.InstancedBufferGeometry();
geometry.copy(new THREE.PlaneBufferGeometry(3, 2, xRes, yRes));

const particleCount = 500;

const vertexColorArray = new Float32Array(particleCount * numVertices * 3);
for (let i = 0; i < particleCount * numVertices * 3; i++) {
    vertexColorArray[i] = Math.random();
}
const colors = new THREE.BufferAttribute(vertexColorArray, 3);
geometry.addAttribute("vertexColor", colors);

在这种情况下,所有实例共享相同的顶点颜色,当我执行const colors = new THREE.InstancedBufferAttribute(vertexColorArray, 3, 1);时,每个实例都有一个单独的颜色,但不是每个顶点。

着色器看起来像这样:

<script id="vshader" type="x-shader/x-vertex">
    precision highp float;
    uniform mat4 modelViewMatrix;
    uniform mat4 projectionMatrix;
    uniform float time;

    attribute vec3 position;
    attribute vec3 translate;
    attribute vec3 vertexColor;

    varying vec3 vVertexColor;

    void main() {
        vec4 mvPosition = modelViewMatrix * vec4(translate, 1.0);
        vec3 trTime = vec3(
            translate.x + time,
            translate.y + time, 
            translate.z + time
        );
        float scale = 1.0;
        scale = scale * 10.0 + 10.0;
        mvPosition.xyz += position * scale;
        vVertexColor = vertexColor;
        gl_Position = projectionMatrix * mvPosition;
    }
</script>
<script id="fshader" type="x-shader/x-fragment">
    precision highp float;
    varying vec3 vVertexColor;

    void main() {
        gl_FragColor = vec4(vVertexColor, 1);
    }
</script>

1 个答案:

答案 0 :(得分:2)

您想知道,在使用InstancedBufferGeoemtry时,是否可以让每个实例的每个顶点都有不同的顶点颜色。

是的,这是可能的。

一种方法是以编程方式计算着色器中的颜色,或者通过基于几何顶点ID和实例ID的查找表来计算颜色:

geometry.addAttribute( 'vertexID', new THREE.BufferAttribute( vertexIDs, 1 ) );

geometry.addAttribute( 'instanceID', new THREE.InstancedBufferAttribute( instanceIDs, 1 ) );

因此,在着色器中,您可以访问原始几何体的顶点ID,并且还可以访问实例的ID。从这两个值中,您可以为每个实例的每个顶点唯一地设置着色器中的颜色。

three.js r.84