Skip to content

Instantly share code, notes, and snippets.

@kishalmi
Created January 16, 2014 09:42
Show Gist options
  • Save kishalmi/8452247 to your computer and use it in GitHub Desktop.
Save kishalmi/8452247 to your computer and use it in GitHub Desktop.
three.js - split a (loaded) model into mesh parts by material index
/**
* split a (loaded) model into mesh parts by material index
* @param {THREE.Geometry} geometry
* @param {Array<THREE.Material>} materials
* @returns {Array<THREE.Mesh>}
*/
var splitByMaterial = function(geometry,materials) {
var parts = [],
geo, vMap, iMat,
addPart = function() {
var mat = materials[iMat];
mat.side = THREE.DoubleSide;
parts.push(new THREE.Mesh(geo,mat));
};
geometry.faces.forEach(function(face) {
if( face.materialIndex != iMat ) {
if( iMat !== undefined )
addPart();
geo = new THREE.Geometry();
vMap = {};
iMat = face.materialIndex;
}
var f = face.clone();
['a','b','c'].forEach(function(p) {
var iv = face[p];
if( !vMap.hasOwnProperty(iv) )
vMap[iv] = geo.vertices.push(geometry.vertices[iv]) - 1;
f[p] = vMap[iv];
});
geo.faces.push(f);
});
addPart();
return parts;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment