Skip to content
1        10        20        30        40        50        60        70        80        90        100       110       120       1301import {2	AnimationClip,3	AnimationMixer,4	Matrix4,5	Quaternion,6	QuaternionKeyframeTrack,7	SkeletonHelper,8	Vector3,9	VectorKeyframeTrack10} from 'three';1112/**13 * @module SkeletonUtils14 * @three_import import * as SkeletonUtils from 'three/addons/utils/SkeletonUtils.js';15 */1617function getBoneName( bone, options ) {1819	if ( options.getBoneName !== undefined ) {2021		return options.getBoneName( bone );2223	}2425	return options.names[ bone.name ];2627}2829/**30 * Retargets the skeleton from the given source to the target.31 *32 * Both `target` and `source` can be a 3D object with a skeleton property (e.g. a skinned mesh)33 * or a {@link Skeleton} directly.34 *35 * @param {Object3D|Skeleton} target - The target object.36 * @param {Object3D|Skeleton} source - The source object.37 * @param {module:SkeletonUtils~RetargetOptions} options - The options.38 */39function retarget( target, source, options = {} ) {4041	const quat = new Quaternion(),42		scale = new Vector3(),43		relativeMatrix = new Matrix4(),44		globalMatrix = new Matrix4();4546	options.preserveBoneMatrix = options.preserveBoneMatrix !== undefined ? options.preserveBoneMatrix : true;47	options.preserveBonePositions = options.preserveBonePositions !== undefined ? options.preserveBonePositions : true;48	options.useTargetMatrix = options.useTargetMatrix !== undefined ? options.useTargetMatrix : false;49	options.hip = options.hip !== undefined ? options.hip : 'hip';50	options.hipInfluence = options.hipInfluence !== undefined ? options.hipInfluence : new Vector3( 1, 1, 1 );51	options.scale = options.scale !== undefined ? options.scale : 1;52	options.names = options.names || {};5354	const sourceBones = source.isObject3D ? source.skeleton.bones : getBones( source ),55		bones = target.isObject3D ? target.skeleton.bones : getBones( target );5657	let bone, name, boneTo,58		bonesPosition;5960	// reset bones6162	if ( target.isObject3D ) {6364		target.skeleton.pose();6566	} else {6768		options.useTargetMatrix = true;69		options.preserveBoneMatrix = false;7071	}7273	if ( options.preserveBonePositions ) {7475		bonesPosition = [];7677		for ( let i = 0; i < bones.length; i ++ ) {7879			bonesPosition.push( bones[ i ].position.clone() );8081		}8283	}8485	if ( options.preserveBoneMatrix ) {8687		// reset matrix8889		target.updateMatrixWorld();9091		target.matrixWorld.identity();9293		// reset children matrix9495		for ( let i = 0; i < target.children.length; ++ i ) {9697			target.children[ i ].updateMatrixWorld( true );9899		}100101	}102103	for ( let i = 0; i < bones.length; ++ i ) {104105		bone = bones[ i ];106		name = getBoneName( bone, options );107108		boneTo = getBoneByName( name, sourceBones );109110		globalMatrix.copy( bone.matrixWorld );111112		if ( boneTo ) {113114			boneTo.updateMatrixWorld();115116			if ( options.useTargetMatrix ) {117118				relativeMatrix.copy( boneTo.matrixWorld );119120			} else {121122				relativeMatrix.copy( target.matrixWorld ).invert();123				relativeMatrix.multiply( boneTo.matrixWorld );124125			}126127			// ignore scale to extract rotation128129			scale.setFromMatrixScale( relativeMatrix );130			relativeMatrix.scale( scale.set( 1 / scale.x, 1 / scale.y, 1 / scale.z ) );131132			// apply to global matrix133134			globalMatrix.makeRotationFromQuaternion( quat.setFromRotationMatrix( relativeMatrix ) );135136			if ( target.isObject3D ) {137138				if ( options.localOffsets ) {139140					if ( options.localOffsets[ bone.name ] ) {141142						globalMatrix.multiply( options.localOffsets[ bone.name ] );143144					}145146				}147148			}149150			globalMatrix.copyPosition( relativeMatrix );151152		}153154		if ( name === options.hip ) {155156			globalMatrix.elements[ 12 ] *= options.scale * options.hipInfluence.x;157			globalMatrix.elements[ 13 ] *= options.scale * options.hipInfluence.y;158			globalMatrix.elements[ 14 ] *= options.scale * options.hipInfluence.z;159160			if ( options.hipPosition !== undefined ) {161162				globalMatrix.elements[ 12 ] += options.hipPosition.x * options.scale;163				globalMatrix.elements[ 13 ] += options.hipPosition.y * options.scale;164				globalMatrix.elements[ 14 ] += options.hipPosition.z * options.scale;165166			}167168		}169170		if ( bone.parent ) {171172			bone.matrix.copy( bone.parent.matrixWorld ).invert();173			bone.matrix.multiply( globalMatrix );174175		} else {176177			bone.matrix.copy( globalMatrix );178179		}180181		bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );182183		bone.updateMatrixWorld();184185	}186187	if ( options.preserveBonePositions ) {188189		for ( let i = 0; i < bones.length; ++ i ) {190191			bone = bones[ i ];192			name = getBoneName( bone, options ) || bone.name;193194			if ( name !== options.hip ) {195196				bone.position.copy( bonesPosition[ i ] );197198			}199200		}201202	}203204	if ( options.preserveBoneMatrix ) {205206		// restore matrix207208		target.updateMatrixWorld( true );209210	}211212}213214/**215 * Retargets the animation clip of the source to the target 3D object.216 *217 * The `source` can be a 3D object with a skeleton property (e.g. a skinned mesh)218 * or a {@link Skeleton} directly.219 *220 * @param {Object3D} target - The target 3D object. Must have a `skeleton` property.221 * @param {Object3D|Skeleton} source - The source object.222 * @param {AnimationClip} clip - The animation clip.223 * @param {module:SkeletonUtils~RetargetOptions} options - The options.224 * @return {AnimationClip} The retargeted animation clip.225 */226function retargetClip( target, source, clip, options = {} ) {227228	options.useFirstFramePosition = options.useFirstFramePosition !== undefined ? options.useFirstFramePosition : false;229230	// Calculate the fps from the source clip based on the track with the most frames, unless fps is already provided.231	options.fps = options.fps !== undefined ? options.fps : ( Math.max( ...clip.tracks.map( track => track.times.length ) ) / clip.duration );232	options.names = options.names || [];233234	if ( ! source.isObject3D ) {235236		source = getHelperFromSkeleton( source );237238	}239240	const numFrames = Math.round( clip.duration * ( options.fps / 1000 ) * 1000 ),241		delta = clip.duration / ( numFrames - 1 ),242		convertedTracks = [],243		mixer = new AnimationMixer( source ),244		bones = getBones( target.skeleton ),245		boneDatas = [];246247	let positionOffset,248		bone, boneTo, boneData,249		name;250251	mixer.clipAction( clip ).play();252253	// trim254255	let start = 0, end = numFrames;256257	if ( options.trim !== undefined ) {258259		start = Math.round( options.trim[ 0 ] * options.fps );260		end = Math.min( Math.round( options.trim[ 1 ] * options.fps ), numFrames ) - start;261262		mixer.update( options.trim[ 0 ] );263264	} else {265266		mixer.update( 0 );267268	}269270	source.updateMatrixWorld();271272	//273274	for ( let frame = 0; frame < end; ++ frame ) {275276		const time = frame * delta;277278		retarget( target, source, options );279280		for ( let j = 0; j < bones.length; ++ j ) {281282			bone = bones[ j ];283			name = getBoneName( bone, options ) || bone.name;284			boneTo = getBoneByName( name, source.skeleton );285286			if ( boneTo ) {287288				boneData = boneDatas[ j ] = boneDatas[ j ] || { bone: bone };289290				if ( options.hip === name ) {291292					if ( ! boneData.pos ) {293294						boneData.pos = {295							times: new Float32Array( end ),296							values: new Float32Array( end * 3 )297						};298299					}300301					if ( options.useFirstFramePosition ) {302303						if ( frame === 0 ) {304305							positionOffset = bone.position.clone();306307						}308309						bone.position.sub( positionOffset );310311					}312313					boneData.pos.times[ frame ] = time;314315					bone.position.toArray( boneData.pos.values, frame * 3 );316317				}318319				if ( ! boneData.quat ) {320321					boneData.quat = {322						times: new Float32Array( end ),323						values: new Float32Array( end * 4 )324					};325326				}327328				boneData.quat.times[ frame ] = time;329330				bone.quaternion.toArray( boneData.quat.values, frame * 4 );331332			}333334		}335336		if ( frame === end - 2 ) {337338			// last mixer update before final loop iteration339			// make sure we do not go over or equal to clip duration340			mixer.update( delta - 0.0000001 );341342		} else {343344			mixer.update( delta );345346		}347348		source.updateMatrixWorld();349350	}351352	for ( let i = 0; i < boneDatas.length; ++ i ) {353354		boneData = boneDatas[ i ];355356		if ( boneData ) {357358			if ( boneData.pos ) {359360				convertedTracks.push( new VectorKeyframeTrack(361					'.bones[' + boneData.bone.name + '].position',362					boneData.pos.times,363					boneData.pos.values364				) );365366			}367368			convertedTracks.push( new QuaternionKeyframeTrack(369				'.bones[' + boneData.bone.name + '].quaternion',370				boneData.quat.times,371				boneData.quat.values372			) );373374		}375376	}377378	mixer.uncacheAction( clip );379380	return new AnimationClip( clip.name, - 1, convertedTracks );381382}383384/**385 * Clones the given 3D object and its descendants, ensuring that any `SkinnedMesh` instances are386 * correctly associated with their bones. Bones are also cloned, and must be descendants of the387 * object passed to this method. Other data, like geometries and materials, are reused by reference.388 *389 * @param {Object3D} source - The 3D object to clone.390 * @return {Object3D} The cloned 3D object.391 */392function clone( source ) {393394	const sourceLookup = new Map();395	const cloneLookup = new Map();396397	const clone = source.clone();398399	parallelTraverse( source, clone, function ( sourceNode, clonedNode ) {400401		sourceLookup.set( clonedNode, sourceNode );402		cloneLookup.set( sourceNode, clonedNode );403404	} );405406	clone.traverse( function ( node ) {407408		if ( ! node.isSkinnedMesh ) return;409410		const clonedMesh = node;411		const sourceMesh = sourceLookup.get( node );412		const sourceBones = sourceMesh.skeleton.bones;413414		clonedMesh.skeleton = sourceMesh.skeleton.clone();415		clonedMesh.bindMatrix.copy( sourceMesh.bindMatrix );416417		clonedMesh.skeleton.bones = sourceBones.map( function ( bone ) {418419			return cloneLookup.get( bone );420421		} );422423		clonedMesh.bind( clonedMesh.skeleton, clonedMesh.bindMatrix );424425	} );426427	return clone;428429}430431// internal helper432433function getBoneByName( name, skeleton ) {434435	for ( let i = 0, bones = getBones( skeleton ); i < bones.length; i ++ ) {436437		if ( name === bones[ i ].name )438439			return bones[ i ];440441	}442443}444445function getBones( skeleton ) {446447	return Array.isArray( skeleton ) ? skeleton : skeleton.bones;448449}450451452function getHelperFromSkeleton( skeleton ) {453454	const source = new SkeletonHelper( skeleton.bones[ 0 ] );455	source.skeleton = skeleton;456457	return source;458459}460461function parallelTraverse( a, b, callback ) {462463	callback( a, b );464465	for ( let i = 0; i < a.children.length; i ++ ) {466467		parallelTraverse( a.children[ i ], b.children[ i ], callback );468469	}470471}472473/**474 * Retarget options of `SkeletonUtils`.475 *476 * @typedef {Object} module:SkeletonUtils~RetargetOptions477 * @property {boolean} [useFirstFramePosition=false] - Whether to use the position of the first frame or not.478 * @property {number} [fps] - The FPS of the clip.479 * @property {Object<string,string>} [names] - A dictionary for mapping target to source bone names.480 * @property {function(string):string} [getBoneName] - A function for mapping bone names. Alternative to `names`.481 * @property {Array<number>} [trim] - Whether to trim the clip or not. If set the array should hold two values for the start and end.482 * @property {boolean} [preserveBoneMatrix=true] - Whether to preserve bone matrices or not.483 * @property {boolean} [preserveBonePositions=true] - Whether to preserve bone positions or not.484 * @property {boolean} [useTargetMatrix=false] - Whether to use the target matrix or not.485 * @property {string} [hip='hip'] - The name of the source's hip bone.486 * @property {Vector3} [hipInfluence=(1,1,1)] - The hip influence.487 * @property {number} [scale=1] - The scale.488 * @property {Object<string,Matrix4>} [localOffsets] - Per-bone local offset matrices, keyed by bone name.489 * @property {Vector3} [hipPosition] - An additional position offset applied to the hip bone.490 **/491492export {493	retarget,494	retargetClip,495	clone,496};