将颜色渐变应用于网格上的 material - three.js

Apply color gradient to material on mesh - three.js

我将一个 STL 文件加载到我的场景中,并将单一颜色应用于 phong material

我想要一种将两种颜色应用到此网格的 material 并在 Z 轴上应用渐变效果的方法,如下例所示。Gradient Vase]1

我觉得我可能必须引入着色器,但我还没有做到这一点 three.js。

如果您希望您的渐变是静态的,您可以使用 .map property. Or you could assign it to the .emissiveMap 属性 向您的 material 添加一个纹理,如果您希望它 "glow" 没有需要灯光。

但是,如果您希望改变渐变,并且始终在 z 轴上淡入淡出,即使在旋转模型或相机之后,您也必须编写自定义着色器,这需要您学习一些教程.您可以查看 this example for how to implement custom shaders in Three.js, and visit https://thebookofshaders.com/ 以更好地理解如何编写简单的渐变着色器。

基于 uvs 的简单渐变着色器:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, 1, 1, 1000);
camera.position.set(13, 25, 38);
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer({
  antialias: true
});
var canvas = renderer.domElement
document.body.appendChild(canvas);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

var geometry = new THREE.CylinderBufferGeometry(2, 5, 20, 32, 1, true);
var material = new THREE.ShaderMaterial({
  uniforms: {
    color1: {
      value: new THREE.Color("red")
    },
    color2: {
      value: new THREE.Color("purple")
    }
  },
  vertexShader: `
    varying vec2 vUv;

    void main() {
      vUv = uv;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
    }
  `,
  fragmentShader: `
    uniform vec3 color1;
    uniform vec3 color2;
  
    varying vec2 vUv;
    
    void main() {
      
      gl_FragColor = vec4(mix(color1, color2, vUv.y), 1.0);
    }
  `,
  wireframe: true
});
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);



render();

function resize(renderer) {
  const canvas = renderer.domElement;
  const width = canvas.clientWidth;
  const height = canvas.clientHeight;
  const needResize = canvas.width !== width || canvas.height !== height;
  if (needResize) {
    renderer.setSize(width, height, false);
  }
  return needResize;
}

function render() {
  if (resize(renderer)) {
    camera.aspect = canvas.clientWidth / canvas.clientHeight;
    camera.updateProjectionMatrix();
  }
  renderer.render(scene, camera);
  requestAnimationFrame(render);
}
html,
body {
  height: 100%;
  margin: 0;
  overflow: hidden;
}

canvas {
  width: 100%;
  height: 100%;
  display;
  block;
}
<script src="https://cdn.jsdelivr.net/npm/three@0.115.0/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.115.0/examples/js/controls/OrbitControls.js"></script>

简单的渐变着色器,基于坐标:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, 1, 1, 1000);
camera.position.set(13, 25, 38);
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer({
  antialias: true
});
var canvas = renderer.domElement
document.body.appendChild(canvas);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

var geometry = new THREE.CylinderBufferGeometry(2, 5, 20, 16, 4, true);
geometry.computeBoundingBox();
var material = new THREE.ShaderMaterial({
  uniforms: {
    color1: {
      value: new THREE.Color("red")
    },
    color2: {
      value: new THREE.Color("purple")
    },
    bboxMin: {
      value: geometry.boundingBox.min
    },
    bboxMax: {
      value: geometry.boundingBox.max
    }
  },
  vertexShader: `
    uniform vec3 bboxMin;
    uniform vec3 bboxMax;
  
    varying vec2 vUv;

    void main() {
      vUv.y = (position.y - bboxMin.y) / (bboxMax.y - bboxMin.y);
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
    }
  `,
  fragmentShader: `
    uniform vec3 color1;
    uniform vec3 color2;
  
    varying vec2 vUv;
    
    void main() {
      
      gl_FragColor = vec4(mix(color1, color2, vUv.y), 1.0);
    }
  `,
  wireframe: true
});
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);



render();

function resize(renderer) {
  const canvas = renderer.domElement;
  const width = canvas.clientWidth;
  const height = canvas.clientHeight;
  const needResize = canvas.width !== width || canvas.height !== height;
  if (needResize) {
    renderer.setSize(width, height, false);
  }
  return needResize;
}

function render() {
  if (resize(renderer)) {
    camera.aspect = canvas.clientWidth / canvas.clientHeight;
    camera.updateProjectionMatrix();
  }
  renderer.render(scene, camera);
  requestAnimationFrame(render);
}
html,
body {
  height: 100%;
  margin: 0;
  overflow: hidden;
}

canvas {
  width: 100%;
  height: 100%;
  display: block;
}
<script src="https://cdn.jsdelivr.net/npm/three@0.115.0/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.115.0/examples/js/controls/OrbitControls.js"></script>

顶点颜色渐变:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, 1, 1, 1000);
camera.position.set(0, 0, 10);
var renderer = new THREE.WebGLRenderer({
  antialias: true
});
var canvas = renderer.domElement
document.body.appendChild(canvas);


var geom = new THREE.TorusKnotGeometry(2.5, .5, 100, 16);

var rev = true;

var cols = [{
  stop: 0,
  color: new THREE.Color(0xf7b000)
}, {
  stop: .25,
  color: new THREE.Color(0xdd0080)
}, {
  stop: .5,
  color: new THREE.Color(0x622b85)
}, {
  stop: .75,
  color: new THREE.Color(0x007dae)
}, {
  stop: 1,
  color: new THREE.Color(0x77c8db)
}];

setGradient(geom, cols, 'z', rev);

function setGradient(geometry, colors, axis, reverse) {

  geometry.computeBoundingBox();

  var bbox = geometry.boundingBox;
  var size = new THREE.Vector3().subVectors(bbox.max, bbox.min);

  var vertexIndices = ['a', 'b', 'c'];
  var face, vertex, normalized = new THREE.Vector3(),
    normalizedAxis = 0;

  for (var c = 0; c < colors.length - 1; c++) {

    var colorDiff = colors[c + 1].stop - colors[c].stop;

    for (var i = 0; i < geometry.faces.length; i++) {
      face = geometry.faces[i];
      for (var v = 0; v < 3; v++) {
        vertex = geometry.vertices[face[vertexIndices[v]]];
        normalizedAxis = normalized.subVectors(vertex, bbox.min).divide(size)[axis];
        if (reverse) {
          normalizedAxis = 1 - normalizedAxis;
        }
        if (normalizedAxis >= colors[c].stop && normalizedAxis <= colors[c + 1].stop) {
          var localNormalizedAxis = (normalizedAxis - colors[c].stop) / colorDiff;
          face.vertexColors[v] = colors[c].color.clone().lerp(colors[c + 1].color, localNormalizedAxis);
        }
      }
    }
  }
}

var mat = new THREE.MeshBasicMaterial({
  vertexColors: THREE.VertexColors,
  wireframe: true
});
var obj = new THREE.Mesh(geom, mat);
scene.add(obj);



render();

function resize(renderer) {
  const canvas = renderer.domElement;
  const width = canvas.clientWidth;
  const height = canvas.clientHeight;
  const needResize = canvas.width !== width || canvas.height !== height;
  if (needResize) {
    renderer.setSize(width, height, false);
  }
  return needResize;
}

function render() {
  if (resize(renderer)) {
    camera.aspect = canvas.clientWidth / canvas.clientHeight;
    camera.updateProjectionMatrix();
  }
  renderer.render(scene, camera);
  obj.rotation.y += .01;
  requestAnimationFrame(render);
}
html,
body {
  height: 100%;
  margin: 0;
  overflow: hidden;
}

canvas {
  width: 100%;
  height: 100%;
  display;
  block;
}
<script src="https://cdn.jsdelivr.net/npm/three@0.115.0/build/three.min.js"></script>

实际上,使用哪种方法取决于您:着色器、顶点颜色、纹理等。

如果您想保留 MeshPhongMaterial 的功能,您可以尝试扩展 material。

这是一个比较宽泛的主题,有几种方法,您可以深入阅读 here

phong materials 着色器中有一行看起来像这样

vec4 diffuseColor = vec4( diffuse, opacity );

因此,在学习了着色器之书或其他一些教程之后,您将了解到可以使用归一化因子(介于 0,1 之间的数字)混合两种颜色。

这意味着您可以将此行更改为类似这样的内容

vec4 diffuseColor = vec4( mix(diffuse, myColor, vec3(myFactor)), opacity);

您可以这样扩展着色器

const myFactor = { value: 0 }
const myColor = {value: new THREE.Color}


myMaterial.onBeforeCompile = shader=>{
  shader.uniforms.myFactor = myFactor
  shader.uniforms.myColor = myColor
  shader.fragmentShader = `
  uniform vec3 myColor;
  uniform float myFactor;
  ${shader.fragmentShader.replace(
    vec4 diffuseColor = vec4( diffuse, opacity );
    vec4 diffuseColor = vec4( mix(diffuse, myColor, vec3(myFactor)), opacity);
  )}
`

现在,当您更改 myFactor.value 时,对象的颜色应该从 myMaterial.color 更改为 myColor.value

现在要真正将其变成渐变,您可以将 myFactor 替换为动态的东西。我喜欢使用紫外线的囚犯解决方案。它完全在 javascript 中完成,并且非常简单地连接到这个着色器中。其他方法可能需要更多的着色器工作。

vec4 diffuseColor = vec4( mix(diffuse, myColor, vec3(vUv.y)), opacity);

现在你可能会遇到的问题 - 如果你调用 new PhongMaterial({color}) 即。如果没有提供任何纹理,着色器将在没有 vUv 的情况下编译。 有很多条件会导致它编译并对你有用,但我不确定它们是否会破坏其他东西:

#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )

所以,添加类似

的东西
myMaterial.defines = {USE_MAP:''} 

可能会使 vUv 变量可用于您的着色器。这样你就可以让 phong material 的所有灯光影响 material,你只需更改基色。