Three.js:平滑非索引 BufferGeometry 上的法线

Three.js: Smoothing normals on non indexed BufferGeometry

我正在尝试从非索引 BufferGeometry 开始平滑网格的法线。 This question has been answered before 但是 Three.js api 自那以后发生了很大变化,我无法让它在 r130

上工作

据我了解,我需要先合并顶点以获得索引 BufferGeometry,然后重新计算法线,但这似乎不起作用。

这是一个使用 defaulf 多维数据集的最小示例:

    // Scene
    const scene = new THREE.Scene();
    
    // Geometry
    const boxGeometry = new THREE.BoxGeometry(.7,.7,.7);
    
    // Materials
    const shadedMaterial = new THREE.MeshStandardMaterial();
    shadedMaterial.metalness = 0.4;
    shadedMaterial.roughness = 0.4;
    shadedMaterial.color = new THREE.Color(0xffffff);
    
    // Mesh
    const smoothBoxGeometry=BufferGeometryUtils
    .mergeVertices(new THREE.BufferGeometry().copy(boxGeometry))
    smoothBoxGeometry.computeVertexNormals();
    smoothBoxGeometry.computeBoundingBox();
    smoothBoxGeometry.normalizeNormals();
    
    const box = new THREE.Mesh(smoothBoxGeometry, shadedMaterial);
    scene.add(box);

flat shaded cube instead of expected smooth shaded cube

我错过了什么?

试试看:

let camera, scene, renderer;

let mesh;

init();
animate();

function init() {

  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
  camera.position.z = 4;

  scene = new THREE.Scene();

  const hemiLight = new THREE.HemisphereLight(0xffffff, 0x444444);
  hemiLight.position.set(0, 20, 0);
  scene.add(hemiLight);

  const dirLight = new THREE.DirectionalLight(0xffffff);
  dirLight.position.set(-3, 10, -10);
  scene.add(dirLight);

  let geometry = new THREE.BoxGeometry();
  geometry.deleteAttribute('normal');
  geometry.deleteAttribute('uv');
  geometry = THREE.BufferGeometryUtils.mergeVertices(geometry);
  geometry.computeVertexNormals();
  const material = new THREE.MeshStandardMaterial();

  mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);

  renderer = new THREE.WebGLRenderer({
    antialias: true
  });
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

}

function animate() {

  requestAnimationFrame(animate);

  mesh.rotation.x += 0.01;
  mesh.rotation.y += 0.02;

  renderer.render(scene, camera);

}
body {
      margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three@0.130.1/build/three.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.130.1/examples/js/utils/BufferGeometryUtils.js"></script>

BufferGeometryUtils.mergeVertices() 只有在顶点数据相同的情况下才能执行合并。为确保这一点,有必要删除现有的 normal 和 uv 属性。