Three.js 工业场景性能优化合集|大批量管线、InstancedMesh 实例化、合并 Geometry、显存释放

前言

工业组态很容易遇到性能问题:

  • 几十上百根 Tube 管线,几十个阀门、仪表,FPS 掉到 20 以下
  • 页面反复打开关闭,内存越用越高,最终浏览器崩溃
  • 同一种阀门 / 仪表大量重复渲染,每个单独 Mesh,DrawCall 爆炸
  • 忘记释放几何体、材质、贴图,dispose 写不全
  • 盲目合并几何体,导致拾取、变色、告警功能废掉

先记住核心结论:工业场景优化两大主线:降低 DrawCall + 合理释放 GPU 资源 。

常用手段:合并 Geometry、InstancedMesh 实例化、视锥剔除、简化模型、规范 dispose。

取舍原则:

✅ 完全一样、状态统一、不需要单独变色:InstancedMesh

✅ 多段管线,不需要单独交互:BufferGeometryUtils 合并

❌ 需要单独 hover、单独告警变色:不能合并,不能实例化

一、基础概念:DrawCall

每一个 Mesh,默认一次 DrawCall。

  • 100 个独立 Mesh = 100 次 DrawCall
  • InstancedMesh:1 个 DrawCall 渲染成千上万个相同模型
  • 合并 Geometry:多个 Mesh 拼成一个,1 次 DrawCall

GPU 更怕大量 DrawCall,而不是三角面数量。

二、InstancedMesh 实例化(大量重复阀门、测点、仪表首选)

场景:同一个阀门模型,在场景里几十上百个,只是位置、旋转不一样,大部分时候状态统一。

限制:实例化后,不能单独修改每个实例的材质颜色(可以用 instanceColor 单独控制每个实例颜色,支持告警变色)。

示例代码(InstancedMesh + 独立颜色)

复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>InstancedMesh 阀门实例化</title>
<style>*{margin:0;padding:0}canvas{display:block}</style>
</head>
<body>
<script type="importmap">
{
  "imports": {
    "three": "https://unpkg.com/three@0.160.0/build/three.module.js",
    "three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
  }
}
</script>
<script type="module">
import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'

const scene = new THREE.Scene()
scene.background = new THREE.Color(0xf4f4f4)
const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 500)
camera.position.set(14,12,14)
const renderer = new THREE.WebGLRenderer({antialias:true})
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.outputColorSpace = THREE.SRGBColorSpace
document.body.appendChild(renderer.domElement)
const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true

const ambient = new THREE.AmbientLight(0xffffff,0.4)
const dirLight = new THREE.DirectionalLight(0xffffff,0.7)
dirLight.position.set(6,12,6)
scene.add(ambient,dirLight)
scene.add(new THREE.GridHelper(30,30))

// 基础几何体,用一个立方体代替阀门,实际项目替换为GLTF解析后的基础geometry
const geo = new THREE.BoxGeometry(0.6,0.6,0.6)
const mat = new THREE.MeshStandardMaterial({
  color:0x2288cc,
  metalness:0.3,
  roughness:0.6,
  vertexColors:true // 开启顶点色,支持每个实例独立颜色
})

// 实例数量
const count = 80
const instancedMesh = new THREE.InstancedMesh(geo, mat, count)
const matrix = new THREE.Matrix4()
const color = new THREE.Color()
// 随机位置
for(let i=0;i<count;i++){
  matrix.setPosition(
    (Math.random()-0.5)*20,
    0.3,
    (Math.random()-0.5)*20
  )
  instancedMesh.setMatrixAt(i, matrix)
  // 初始化全部正常蓝色
  color.set(0x2288cc)
  instancedMesh.setColorAt(i, color)
}
instancedMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage)
instancedMesh.instanceColor.setUsage(THREE.DynamicDrawUsage)
scene.add(instancedMesh)

// 设置第10个实例告警红色
function setErrorById(index){
  color.set(0xff2222)
  instancedMesh.setColorAt(index, color)
  instancedMesh.instanceColor.needsUpdate = true
}
setErrorById(10)

// 射线拾取实例:获取命中的实例下标
const raycaster = new THREE.Raycaster()
const pointer = new THREE.Vector2()
renderer.domElement.addEventListener('click', (e)=>{
  const rect = renderer.domElement.getBoundingClientRect()
  pointer.x = ((e.clientX - rect.left)/rect.width)*2 -1
  pointer.y = -((e.clientY - rect.top)/rect.height)*2 +1
  raycaster.setFromCamera(pointer, camera)
  const intersects = raycaster.intersectObject(instancedMesh)
  if(intersects.length>0){
    const instanceId = intersects[0].instanceId
    console.log('点击实例下标:', instanceId)
    setErrorById(instanceId)
  }
})

function animate(){
  requestAnimationFrame(animate)
  controls.update()
  renderer.render(scene,camera)
}
animate()
window.addEventListener('resize',()=>{
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()
  renderer.setSize(window.innerWidth, window.innerHeight)
})
</script>
</body>
</html>

✅ 优点:80 个阀门只占用 1 次 DrawCall,性能提升巨大

⚠️ 限制:

  • 模型必须是同一个几何体
  • 独立颜色依靠instanceColor,不能每个实例用完全不同材质
  • 拾取需要读取instanceId,业务数据自己维护一个映射表 instanceId -> deviceId

GLTF 模型配合 InstancedMesh 做法:加载 GLTF,取出里面 Mesh 的 geometry,作为实例几何体。

三、BufferGeometryUtils 合并几何体(管线批量合并)

场景:大量简单管线,不需要单独 hover、单独告警,只作为背景管网。

一旦合并,就是一个 Mesh,无法单独拾取其中一根管道。

复制代码
import { BufferGeometryUtils } from 'three/addons/utils/BufferGeometryUtils.js'

const geoList = []
// 循环生成多根管线geometry,push进数组
geoList.push(tubeGeo1)
geoList.push(tubeGeo2)
geoList.push(tubeGeo3)
const mergedGeo = BufferGeometryUtils.mergeGeometries(geoList)
const pipeMesh = new THREE.Mesh(mergedGeo, pipeMat)
scene.add(pipeMesh)

适用:静态背景管网、预埋管线,无交互。

交互管线(要 hover、告警变色)绝对不能合并。

四、显存释放规范(Vue 路由切换内存泄漏重点)

很多项目路由切走,场景对象还留在 GPU 显存,内存持续上涨。

释放顺序:Mesh → Geometry → Material → Texture

注意:共享材质不要重复 dispose,多个 Mesh 共用同一个材质,只 dispose 一次。

封装通用释放函数:

复制代码
function disposeMesh(obj) {
  if(!obj) return
  obj.traverse(child=>{
    if(child.isMesh) {
      if(child.geometry) {
        child.geometry.dispose()
      }
      if(child.material) {
        if(Array.isArray(child.material)) {
          child.material.forEach(mat=>disposeMaterial(mat))
        } else {
          disposeMaterial(child.material)
        }
      }
    }
  })
}
function disposeMaterial(mat) {
  if(!mat) return
  // 释放贴图
  if(mat.map) mat.map.dispose()
  if(mat.normalMap) mat.normalMap.dispose()
  if(mat.emissiveMap) mat.emissiveMap.dispose()
  mat.dispose()
}

Vue 组件 onUnmounted 里面调用:

复制代码
onUnmounted(()=>{
  cancelAnimationFrame(animateId)
  disposeMesh(scene)
  renderer.dispose()
})

❌ 常见错误:只做scene.remove(mesh),不 dispose,GPU 显存不会释放!

五、视锥剔除、LOD、模型减面

  1. 视锥剔除(默认开启)
    相机看不到的物体自动跳过渲染,但是如果物体包围盒很大,会失效。
    给管线、模型正确计算包围盒:geo.computeBoundingBox()

  2. LOD 多细节层次
    远距离用低面数模型,近距离加载高模。适合大型泵站、罐体。

    const lod = new THREE.LOD()
    lod.addLevel(highMesh, 0, 15)
    lod.addLevel(lowMesh, 15, 100)
    scene.add(lod)

  3. GLTF 模型减面
    Blender 减面,阀门、仪表控制面数:单个构件尽量 3k 三角面以内,大型设备 10k 以内。
    冗余倒角、细小螺纹全部删掉,组态里看不见。

六、渲染器、阴影、贴图优化

  1. 阴影:工业场景尽量少开阴影,阴影开销极高;只关键设备开阴影,其余关闭

    renderer.shadowMap.enabled = false

  2. 贴图规范:贴图尺寸统一 2 的幂次,最大 2048,不要 4k 贴图;优先用 jpg,透明贴图用 png,压缩贴图

  3. 抗锯齿:大屏静态场景开启;构件极多的时候,可以关闭 antialias 换 FXAA 后处理

七、射线拾取性能优化(前面拾取章节补充)

  1. 先判断包围盒,再做精细求交,减少三角面计算

    const box = new THREE.Box3().setFromObject(mesh)
    if(raycaster.ray.intersectsBox(box)){
    // 再intersectObjects
    }

  2. 拾取过滤:维护一个业务构件数组,只遍历业务构件,不要遍历整个 scene.children

    const businessObjects = [pipe1, valve1, valve2]
    const intersects = raycaster.intersectObjects(businessObjects, true)

  3. mousemove 节流,一帧只执行一次拾取(前面已经讲过)

八、工业场景的分层渲染方案(推荐架构)

  1. 静态背景管网:Geometry 合并,无交互,低 DrawCall
  2. 需要交互的管道:独立 Mesh,支持 hover、告警变色(TubeGeometry)
  3. 大量重复阀门测点:InstancedMesh,instanceColor 控制告警颜色
  4. 特殊大型设备(泵、罐体):独立 GLTF 高模,单独控制
  5. 标注 Sprite/CSS2D:少量使用,大量标签会卡顿

九、踩坑清单

  1. InstancedMesh 想单独修改材质:不行,只能 instanceColor
  2. 合并 Geometry 之后,拾取只能拿到整体,无法区分单根管道
  3. dispose 重复调用:同一个材质多次 dispose 会报错,增加标记判断是否已释放
  4. DynamicDrawUsage:实例矩阵、颜色频繁更新,必须设置 usage 为 DynamicDrawUsage
  5. 大量 Shader 流光:Shader 本身开销可控,但是几百根管线同时开流光,GPU 压力上涨,非工作状态关闭流光
  6. 不要一个设备一个 scene、一个 renderer!整个项目尽量单渲染器、单场景,多组件共享场景,否则资源爆炸

十、性能排查工具

  • Three.js 自带 Stats:看 FPS
  • Chrome 开发者工具 → Performance:看帧耗时
  • Chrome WebGL Inspector:看 DrawCall 数量、显存占用
相关推荐
AAA修煤气灶刘哥39 分钟前
权重已经读进缓存了,7B 模型怎么还要等 43 秒?
人工智能·性能优化·阿里巴巴
Sakura_j_h_1 小时前
TypeScript 7.0 换 Go 编译器后,我先在 6.0 清完默认值
javascript·golang·typescript·vite·前端工程化·tsc
用户298698530141 小时前
在 React 中实现 Excel 与 TXT 格式互转的前端方案
javascript·react.js·excel
步峰代理-盾山1 小时前
R语言爬虫实战:使用httr与XML解析网页数据并进行统计分析
xml·开发语言·爬虫·r语言·网络爬虫
map_3d_vis2 小时前
百度地图地图类型切换:普通地图、卫星图、混合图
前端·javascript·地图·百度地图
sharemylove11 小时前
Java集合框架全面详解
java·开发语言·经验分享·笔记·学习
郝学胜-神的一滴15 小时前
Effective Python 条款43:自定义容器类
开发语言·windows·python·pandas·scikit-learn·pyqt
FYKJ_201016 小时前
springboot贫困生认定管理系统59009-计算机毕业设计、课程设计
java·javascript·vue.js·spring boot·后端·django·课程设计
kyriewen16 小时前
我测了 5 种关页上报,两种老写法一条都没发出去
前端·javascript·程序员