Skip to content

Instantly share code, notes, and snippets.

@manthrax
Created August 8, 2023 08:07
Show Gist options
  • Save manthrax/c2cc117b98c00f539a054699b8eb14e4 to your computer and use it in GitHub Desktop.
Save manthrax/c2cc117b98c00f539a054699b8eb14e4 to your computer and use it in GitHub Desktop.
Combine skinnedmeshes in threejs
import * as SkeletonUtils from 'threeModules/utils/SkeletonUtils.js';
import * as BufferGeometryUtils from 'threeModules/utils/BufferGeometryUtils.js';
function CrushAnimatedObject(root){
//Make a clone of the root.. to work with..
let ud = root.userData;
root.userData={}
let nroot = SkeletonUtils.clone(root);
root.userData = nroot.userData = ud;
//Find all the skinned meshes
let meshes = []
nroot.traverse(e=>e&&e.isMesh&&meshes.push(e));
//Find all the materials
let matmap = new Map()
meshes.forEach(m=>matmap.set(m.material,m.material))
let mats = Array.from(matmap.values())
console.log(mats);
let texmap = new Map()
let mapTypes = new Map();
mats.forEach(m=>{
for(let k in m){
if(!(k.endsWith('Map')||(k=='map')))continue;
if(m[k]){
texmap.set(m[k],m[k]);
mapTypes.set(k,k);
}
}
})
mapTypes = Array.from(mapTypes.values())
let textures=Array.from(texmap.values())
//Make sure all the meshes have the same morphTargetsRelative setting.. or merging will fail..
meshes.forEach(m=>{
// m.geometry.morphTargetAttributes={}
m.geometry.morphTargetsRelative = false;
})
//Merge all the geometries into a single geometry....
let geoms = meshes.map(e=>e.geometry)
let mergedGeometry = BufferGeometryUtils.mergeBufferGeometries( geoms,true );
let smesh = new THREE.SkinnedMesh(mergedGeometry,meshes.map(e=>e.material));
//copy the skeleton to the new SkinnedMesh...
smesh.skeleton = meshes[0].skeleton;
meshes.forEach(m=>m.parent.remove(m)) //Remove the original meshes
nroot.add(smesh); //Add the newly generated merged mesh...
nroot.userData = ud; //copy the userdata from the original root
return nroot;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment