使用三个js更改合并网格上的材质颜色

时间:2013-05-06 14:09:32

标签: three.js opengl-es-2.0 webgl

是否可以与合并多个网格时使用的缓冲区进行交互以更改所选单个网格上的颜色?

使用网格集合很容易做到这一点但是有多种不同材质的合并网格呢?

3 个答案:

答案 0 :(得分:2)

@hgates,你的最后评论对我很有帮助,我几天都在寻找同样的事情!

  

好的我在每个面上设置一个颜色,并设置为真正的vertexColor   材料,解决问题! :)

我在这里写下我使用的整个概念,以便为处于相同情况的人添加正确的答案:

// Define a main Geometry used for the final mesh
var mainGeometry = new THREE.Geometry();

// Create a Geometry, a Material and a Mesh shared by all the shapes you want to merge together (here I did 1000 cubes)
var cubeGeometry = new THREE.CubeGeometry( 1, 1, 1 );
var cubeMaterial = new THREE.MeshBasicMaterial({vertexColors: true});
var cubeMesh = new THREE.Mesh( cubeGeometry );

var i = 0;

for ( i; i<1000; i++ ) {

    // I set the color to the material for each of my cubes individually, which is just random here
    cubeMaterial.color.setHex(Math.random() * 0xffffff);

    // For each face of the cube, I assign the color
    for ( var j = 0; j < cubeGeometry.faces.length; j ++ ) {
        cubeGeometry.faces[ j ].color = cubeMaterial.color;
}

    // Each cube is merged to the mainGeometry
    THREE.GeometryUtils.merge(mainGeometry, cubeMesh);
 }

 // Then I create my final mesh, composed of the mainGeometry and the cubeMaterial
 var finalMesh = new THREE.Mesh( mainGeometry, cubeMaterial );
 scene.add( finalMesh );

希望它会对我有所帮助! :)

答案 1 :(得分:1)

取决于您对“改变颜色”的意思。请注意,合并后,网格就像任何其他非合并网格一样。

如果您指的是顶点颜色,则可能会迭代这些面并根据材质索引确定要更改颜色的顶点。

如果您的意思是为材料本身设置颜色,请确保它是可能的。合并网格仍然可以使用与普通网格相同的多种材质 - 在MeshFaceMaterial中,但是如果要合并自己,则需要为每个几何体传递材质索引偏移参数。

答案 2 :(得分:1)

this.meshMaterials.push(new THREE.MeshBasicMaterial(
    {color:0x00ff00 * Math.random(), side:THREE.DoubleSide}));

for ( var face in geometry.faces ) {
  geometry.faces[face].materialIndex = this.meshMaterials.length-1;
}

var mesh = new THREE.Mesh(geometry);

THREE.GeometryUtils.merge(this.globalMesh, mesh);
var mesh = new THREE.Mesh(this.globalMesh, new THREE.MeshFaceMaterial(this.meshMaterials));

对于那些需要榜样的人来说,就像魅力一样!这会创建多个额外的缓冲区(索引和顶点数据),并且多个drawElements也会调用:(,我在使用webgl inpector检查绘制调用,之后添加MeshFaceMaterial:75调用opengl api ,以60fps轻松运行, 之后:3490调用opengl api fps下降约20%45-50 fps,这意味着每个网格调用drawElements,我们松开合并网格的上下文,我在这里错过了什么?我想要在同一个缓冲区上共享不同的材料