javascriptthree.jsbuffer-geometry

Set transparency of buffer geometry vertex colors rather than color in threejs


I have a particle cloud I'm making in threejs with buffer geometry, and I am connecting those particles via THREE.LineSegments with a THREE.LineBasicMaterial:

enter image description here

As you can (kind of) see, some of the lines are black or gray - I want to make it so the lines are transparent shades of white.

Here is, I believe, the relevant lines of code:

var material = new THREE.LineBasicMaterial({
    vertexColors: THREE.VertexColors,
    blending: THREE.AdditiveBlending,
    color: 0xffffff,
    transparent: true,
  });

var colors = new Float32Array(segments * 3);

geometry.addAttribute(
    "color",
    new THREE.BufferAttribute(colors, 3).setDynamic(true)
); //will allow us to set the color of the lines between particles in buffer geometry

linesMesh = new THREE.LineSegments(geometry, material);

...

animate(){
  for (var i = 0; i < particleCount; i++) { //loop through particles to make line connections
    for (var j = i + 1; j < particleCount; j++) { //check collision
      var dist = Math.sqrt(dx * dx + dy * dy + dz * dz); //getting particle positions to neighbors
      if (dist < effectController.minDistance) { //make a connection
        var alpha = 1.0 - dist / effectController.minDistance; 
        colors[colorpos++] = alpha;
        
      }
    }
  }
}


Solution

  • Simple Answer

    The default three.js shader implements vertex colors as a vec3 (RGB), so there is no transparency component.

    Search for USE_COLOR in https://github.com/mrdoob/three.js/blob/r118/src/renderers/webgl/WebGLProgram.js (r118) to see this definition.

    Advanced Answer

    You could write your own shader to accept a color attribute as a vec4 instead, adding a transparency component to each color. You will need to look further into how a line-type material uses colors, and how it blends vertex colors along a line. Or, because it's your shader, make it do the blending however you want.