This commit is contained in:
TrèsAbhi committed 2026-05-12 18:08:02 -05:00
1 parent 100c7391fb
commit 2f745a16d1
1 file changed
+34 -51
+34 -51
View File
@@ -1,62 +1,45 @@
import { useLoader } from "@react-three/fiber"; import { useLoader, type ObjectMap } from "@react-three/fiber";
import { useEffect } from "react"; import { useEffect } from "react";
import { Cache } from "three"; import { Cache, Group, Mesh, MeshStandardMaterial, Object3D } from "three";
import { GLTFLoader } from "three-stdlib"; import { GLTFLoader, type GLTF } from "three-stdlib";
export function useDispose(gltf: any, path: string) { export function useDispose(gltf: GLTF & ObjectMap, path: string) {
useEffect(() => { useEffect(() => {
return () => { return () => {
const disposedGeometries = new Set<string>(); gltf.scene.traverse((object) => {
const disposedMaterials = new Set<string>(); if (object instanceof Mesh) {
const disposedTextures = new Set<string>(); if (object.material instanceof MeshStandardMaterial) {
const maps = [
object.material.map,
object.material.aoMap,
object.material.envMap,
object.material.bumpMap,
object.material.alphaMap,
object.material.lightMap,
object.material.normalMap,
object.material.emissiveMap,
object.material.roughnessMap,
object.material.metalnessMap,
object.material.displacementMap,
];
gltf.scene.traverse((obj: any) => { for (const map of maps) {
if (obj.geometry) { if (!map) continue;
const geometry = obj.geometry;
if (!disposedGeometries.has(geometry.uuid)) { map.source.data.close();
disposedGeometries.add(geometry.uuid); map.dispose();
geometry.dispose();
}
}
if (obj.material) {
const materials = Array.isArray(obj.material)
? obj.material
: [obj.material];
for (const material of materials) {
if (!disposedMaterials.has(material.uuid)) {
disposedMaterials.add(material.uuid);
for (const key in material) {
const value = material[key];
if (
value &&
value.isTexture &&
!disposedTextures.has(value.uuid)
) {
disposedTextures.add(value.uuid);
}
}
for (const key in material) {
const value = material[key];
if (value && value.isTexture) {
value.source.data.close();
value.dispose();
}
}
material.dispose();
} }
}
}
if (obj.skeleton) { object.material.dispose();
obj.skeleton.dispose?.(); } else {
throw new TypeError(
`Unexpected material type: ${object.material.type}`,
);
}
} else if (object instanceof Group || object instanceof Object3D) {
// traverse will get children
} else {
throw new TypeError(`Unexpected object type: ${object}`);
} }
}); });