| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- import * as THREE from 'three';
- export default class ResourceTracker {
- constructor() {
- this.resources = new Set();
- }
- track(resource) {
- if (!resource) {
- return resource;
- }
- // handle children and when material is an array of materials or
- // uniform is array of textures
- if (Array.isArray(resource)) {
- resource.forEach((resource) => this.track(resource));
- return resource;
- }
- if (resource.dispose || resource instanceof THREE.Object3D) {
- this.resources.add(resource);
- }
- if (resource instanceof THREE.Object3D) {
- this.track(resource.geometry);
- this.track(resource.material);
- this.track(resource.children);
- } else if (resource instanceof THREE.Material) {
- // We have to check if there are any textures on the material
- for (const value of Object.values(resource)) {
- if (value instanceof THREE.Texture) {
- this.track(value);
- }
- }
- // We also have to check if any uniforms reference textures or arrays of textures
- if (resource.uniforms) {
- for (const value of Object.values(resource.uniforms)) {
- if (value) {
- const uniformValue = value.value;
- if (uniformValue instanceof THREE.Texture || Array.isArray(uniformValue)) {
- this.track(uniformValue);
- }
- }
- }
- }
- }
- return resource;
- }
- untrack(resource) {
- resource = undefined;
- this.resources.delete(resource);
- }
- dispose() {
- for (const resource of this.resources) {
- try {
- if (resource instanceof THREE.Object3D) {
- if (resource.parent) {
- resource.parent.remove(resource);
- }
- }
- if (resource.dispose) {
- resource.dispose();
- }
- this.untrack(resource);
- } catch (error) {
- console.log('资源删除失败------>', resource);
- }
- }
- console.log('this.resources--------------->', this.resources);
- this.resources.clear();
- }
- doDispose(obj) {
- if (obj !== null) {
- for (var i = 0; i < obj.children.length; i++) {
- doDispose(obj.children[i]);
- }
- if (obj.geometry) {
- obj.geometry.dispose();
- obj.geometry = undefined;
- }
- if (obj.material) {
- if (obj.material.materials) {
- for (i = 0; i < obj.material.materials.length; i++) {
- obj.material.materials[i].dispose();
- }
- } else {
- obj.material.dispose();
- }
- obj.material = undefined;
- }
- if (obj.texture) {
- obj.texture.dispose();
- obj.texture = undefined;
- }
- }
- obj = undefined;
- }
- }
|