使用Three.js与CSG实现两个圆柱体相减时遇异常求助
问题描述
尝试用Three.js结合ThreeCSG执行简单的CSG相减运算(外层圆柱体减去内层圆柱体),但渲染结果异常。以webgl_buffergeometry_indexed.html为模板,同时试过THREE-CSGMesh库也无效。使用Firefox 110.0,后续需复杂CSG操作,排除挤压成型方案。
问题代码
import * as THREE from 'three'; window.THREE=THREE; import * as THREECSG from './lib/THREECSG/threeCSG.js'; ... function init() { camera = new THREE.PerspectiveCamera( 27, window.innerWidth / window.innerHeight, 1, 3500 ); camera.position.z = 64; scene = new THREE.Scene(); scene.background = new THREE.Color( 0x050505 ); const light = new THREE.HemisphereLight(); scene.add( light ); const cylinder = new THREE.CylinderGeometry( 5, 5, 1, 40 ); const hole = new THREE.CylinderGeometry( 3, 3, 3, 40 ); const material = new THREE.MeshPhongMaterial({color: 0xFF0000}); var cylInMesh = new THREE.Mesh( hole, new THREE.MeshNormalMaterial()); var cylOutMesh = new THREE.Mesh( cylinder, new THREE.MeshNormalMaterial()); cylInMesh.geometry.computeFaceNormals(); cylInMesh.geometry.computeVertexNormals(); var cylIn_bsp = new ThreeBSP( cylInMesh ); cylOutMesh.geometry.computeFaceNormals(); cylOutMesh.geometry.computeVertexNormals(); var cylOut_bsp = new ThreeBSP( cylOutMesh); var resultBSP = cylOut_bsp.subtract(cylIn_bsp); mesh = resultBSP.toMesh(material); mesh.geometry.computeVertexNormals(); scene.add(mesh); renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); }
解决方案
- 修正几何体尺寸匹配:外层圆柱体高度为1,内层为3,内层完全穿透外层的极端相交情况易导致CSG计算出错。将两个圆柱体高度设为一致(比如都设为3),确保相交区域为规则环形。
- 修正命名空间引用:代码导入的是
THREECSG,但实例化用的是ThreeBSP,需改为new THREECSG.ThreeBSP(...),否则会因找不到构造函数引发异常。 - 统一几何体类型:
webgl_buffergeometry_indexed示例使用BufferGeometry,部分旧版CSG库仅支持已废弃的Geometry。可将几何体转换为兼容格式,或使用支持BufferGeometry的现代CSG库。 - 确保法线方向一致:CSG运算依赖面法线判断内外,运算前需确保两个模型的面法线方向统一。可调用
geometry.scale(1,1,1)强制更新法线,或创建几何体时设置clockwise参数保持方向一致。 - 更新CSG库版本:旧版ThreeCSG与新版Three.js(r150+)存在兼容性问题,建议使用维护中的CSG库,比如对新版Three.js支持更好的实现。
内容的提问来源于stack exchange,提问作者JoseleMG
相关产品推荐
相关产品推荐

