xiangpei
2024-09-03 16eb67ab6b103663d30cad9ba74360f982e131cb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { Scene, GridHelper, AxesHelper } from 'three';
import Stats from "three/examples/jsm/libs/stats.module";
 
import World from "./world/world";
import Camera from "./camera";
import Renderer from "./renderer";
import CSSRenderer from './cssRenderer';
 
// 工具类
import Sizes from "./utils/sizes";
import Time from "./utils/time";
 
export default class Experience {
  constructor(canvas) {
    this.canvas = canvas;
    this.container = canvas.parentElement;
    this.sizes = new Sizes(this.canvas);
    this.time = new Time();
    this.scene = new Scene();
    this.camera = new Camera(this);
    this.renderer = new Renderer(this);
    this.cssRenderer = new CSSRenderer(this);
    this.world = new World(this);
 
    // const size = 100;
    // const divisions = 100;
 
    // const gridHelper = new GridHelper(size, divisions);
    // this.scene.add(gridHelper);
 
    // this.stats = new Stats();
    // document.querySelector('.map-container').appendChild(this.stats.dom);
 
 
 
    // 帧
    this.time.on('tick', () => {
      this.update();
    });
  }
 
  update() {
    this.camera.update();
    this.world.update();
    this.renderer.update();
    this.cssRenderer.update();
    // this.stats.update();
  }
 
  /**
   * 销毁场景
   */
  destroy() {
    this.disposeObject();
    this.resetObject();
  }
 
  disposeObject() {
    this.time.destroy();
    this.world.destroy();
    this.camera.destroy();
    this.renderer.destroy();
    this.cssRenderer.destroy();
    this.scene.traverse((child) => {
      if (child.material) {
        // 可能存在材质为数组的情况
        if (child.material instanceof Array) {
          child.material.forEach((item) => item.dispose());
        } else {
          child.material.dispose();
          if (child.material.map) {
            child.material.map.dispose();
          }
        }
      }
      if (child.geometry) {
        child.geometry.dispose();
        child.geometry.attributes = null; // 这些属性包括position, normal, uv等等
      }
      child = null;
    });
  }
 
  resetObject() {
    this.world = null;
    this.camera = null;
    this.renderer = null;
    this.cssRenderer = null;
    this.scene = null;
    this.canvas = null;
    this.container = null;
    this.time = null;
    this.sizes = null;
  }
}