美文网首页
threejs 占用内存过高,性能优化篇

threejs 占用内存过高,性能优化篇

作者: 时间煮鱼 | 来源:发表于2023-05-28 22:25 被阅读0次

本文旨在记录,“如有错漏之处,敬请指正

1、模型删除时,释放内存

不仅仅是调用scene.remove(mesh)删除,还需要删除该模型占用的内存,使用dispose()方法,下面是我的写法,网上还有其他很多优秀的写法,百度百度都有

// 优化删除模型
    removeModel(parentGroup, group){
      parentGroup.remove(group);
      if (!this.$isEmpty(group)) {
        group.traverse(child => {
          if (child instanceof THREE.Mesh || child instanceof THREE.Line) {
            this.disposeMaterial(child.material);
            child.geometry.dispose && child.geometry.dispose();
          } else  {
            this.disposeMaterial(child.material);
          }
        });
        group = null;
      }
    },
    // 自己写的材质贴图释放
    disposeMaterial(material) { 
      if (material instanceof THREE.Material) {
        for (const value of Object.values(material)) {
          if (value instanceof THREE.Texture) {
            value.dispose();
          }
        }
        if (material.uniforms) {
          for (const value of Object.values(material.uniforms)) {
            if (value) {
              const uniformValue = value.value;
              if (uniformValue instanceof THREE.Texture) {
                uniformValue.dispose();
              }
              if(Array.isArray(uniformValue)){
                uniformValue.length = 0;
              }
            }
          }
        }
        material.dispose();
      }
    },

2、使用vue的时候,除非必要使用响应式的数据,都不要绑定到data上

比如场景scene,相机camera之类的
可以类似我这么写

let scene = null; // 场景
let camera = null; // 摄像机
let container = null; // 画布
let renderer = null; // 渲染器
let animationFrameId = null; // 记录AnimationFrame
let controls = null; // 控制器
let mouse = null; // 获取鼠标
let rayCaster = null; // 获取射线
let composer = null; // 后期处理
let renderPass = null; // 后期处理 渲染通道
let css3DRenderer = null; // 标签

data() {
    return {
      optionsData: {}, // 接口数据
      optionsSetUp: {}, // 配置数据
    };
  },

3、离开页面记得销毁threejs的很多对象(太多了,如控制器)

将下面的代码放在destoryed中

beforeDestroy() {
    // 销毁内存中的threejs
    this.destroyThreejs();
  },
// 销毁threejs
    destroyThreejs() {
      try {
        cancelAnimationFrame(animationFrameId); // animationFrameId = requestAnimationFrame(this.render);
        renderer.dispose();
        renderer.forceContextLoss();
        renderer.content = null;
        let gl = renderer.domElement.getContext("webgl");
        if (gl && gl.getExtension("WEBGL_lose_context")) {
          gl.getExtension("WEBGL_lose_context").loseContext();
        }
        renderer = null;
        camera = null;
        scene.traverse((child) => {
          if (child.material) {
            child.material.dispose();
          }
          if (child.geometry) {
            child.geometry.dispose();
          }
          child = null;
        });
        scene = null;
      } catch (e) {
        console.error('Failed to destroy threejs', e);
      }
    },

4、查看是不是有哪里代码写错了,一直往场景中添加模型,可以不定时打印下看看场景中有多少模型

// 查看场景中的模型数量
    getSceneModelFaceNum(view) {  // 将scene传进去
      let objects = 0; // 场景模型对象
      let triangles = 0; // 模型面片

      for (let index = 0; index < view.children.length; index++) {
        let object = view.children[index];
        object.traverse(obj => {
          objects ++;
          if (obj instanceof THREE.Mesh || object instanceof THREE.Line) {
              let geometry = obj.geometry;
              if (geometry instanceof THREE.BufferGeometry) {
                if (geometry.index && geometry.index.count) {
                  triangles += geometry.index.count
                } else if (geometry.attributes.position) {
                  const pos = geometry.attributes.position
                  if (pos.count && pos.itemSize) {
                    triangles += Math.round(pos.count / pos.itemSize)
                  }
                }
              }
            }
        });
      }
      console.log('模型对象数量: ' + objects, '模型面片数: ' + triangles);
    },

5、对只用来展示的模型合并,线段合并

代码可查看我以前的文章threejs 引入外部模型(fbx)后,合并模型渲染
threejs 大量线段Line合并(贝塞尔曲线或者直线)
其他想到再补充

相关文章

网友评论

      本文标题:threejs 占用内存过高,性能优化篇

      本文链接:https://www.haomeiwen.com/subject/spodedtx.html