Improved Animation Retargeting for Human
This commit is contained in:
parent
bfe4865a99
commit
22b8fce11e
5 changed files with 209 additions and 19 deletions
|
|
@ -2,19 +2,54 @@
|
|||
// mesh-editor <Canvas>. Renders the target skinned scene (loaded from the rigged
|
||||
// GLB) and drives it with an AnimationMixer. Shown in Auto Rig mode while an
|
||||
// animation is selected, in place of the static EditorMesh.
|
||||
//
|
||||
// Auto-align to floor is a ONE-TIME offset (`floorOffset`): the whole rig is
|
||||
// lifted by a constant so its rest pose sits on the grid. It is NOT a per-frame
|
||||
// foot lock — animations keep their natural motion (jumps leave the ground,
|
||||
// crouches lower), driven by the retargeted hip-position track.
|
||||
//
|
||||
// Expand/Contract arms is a live post-mixer additive rotation on the upper-arm
|
||||
// bones about the spread axis (cross of the arm direction and world up), so it
|
||||
// raises/lowers the arms sideways regardless of the rig's bone orientation.
|
||||
import { useEffect, useMemo, useRef } from 'react'
|
||||
import { useFrame } from '@react-three/fiber'
|
||||
import * as THREE from 'three'
|
||||
|
||||
export default function AnimatedMeshPreview({ object, mixerRoot, clip, playing = true, timeScale = 1, yOffset = 0 }) {
|
||||
const _p0 = new THREE.Vector3()
|
||||
const _p1 = new THREE.Vector3()
|
||||
const _dir = new THREE.Vector3()
|
||||
const _axis = new THREE.Vector3()
|
||||
const _up = new THREE.Vector3(0, 1, 0)
|
||||
const _delta = new THREE.Quaternion()
|
||||
const _bw = new THREE.Quaternion()
|
||||
const _pq = new THREE.Quaternion()
|
||||
|
||||
export default function AnimatedMeshPreview({
|
||||
object, mixerRoot, clip, playing = true, timeScale = 1,
|
||||
alignFloor = true, floorOffset = 0, armExtension = 0, armTargets = null,
|
||||
}) {
|
||||
const mixerRef = useRef(null)
|
||||
const actionRef = useRef(null)
|
||||
const groupRef = useRef(null)
|
||||
|
||||
// Retargeted clips use ".bones[name]" track paths, which the mixer can only
|
||||
// resolve against a node that has a `.skeleton` — i.e. the SkinnedMesh, not the
|
||||
// wrapping scene. Render the whole scene but drive the SkinnedMesh.
|
||||
const root = mixerRoot || object
|
||||
const mixer = useMemo(() => (root ? new THREE.AnimationMixer(root) : null), [root])
|
||||
|
||||
// Upper-arm bones (+ their child, for the arm-direction) for the arm control.
|
||||
const armBones = useMemo(() => {
|
||||
const skeleton = mixerRoot?.skeleton
|
||||
if (!skeleton || !armTargets) return []
|
||||
const names = [...(armTargets.left || []), ...(armTargets.right || [])]
|
||||
return names.map(n => {
|
||||
const bone = skeleton.getBoneByName(n)
|
||||
if (!bone) return null
|
||||
return { bone, child: bone.children.find(c => c.isBone) || null }
|
||||
}).filter(Boolean)
|
||||
}, [mixerRoot, armTargets])
|
||||
|
||||
useEffect(() => {
|
||||
mixerRef.current = mixer
|
||||
return () => {
|
||||
|
|
@ -23,28 +58,20 @@ export default function AnimatedMeshPreview({ object, mixerRoot, clip, playing =
|
|||
}
|
||||
}, [mixer, root])
|
||||
|
||||
// (Re)bind the action whenever the clip changes.
|
||||
useEffect(() => {
|
||||
const m = mixerRef.current
|
||||
if (!m) return undefined
|
||||
m.stopAllAction()
|
||||
if (!clip) {
|
||||
actionRef.current = null
|
||||
return undefined
|
||||
}
|
||||
if (!clip) { actionRef.current = null; return undefined }
|
||||
const action = m.clipAction(clip)
|
||||
action.reset()
|
||||
action.setLoop(THREE.LoopRepeat, Infinity)
|
||||
action.clampWhenFinished = false
|
||||
action.play()
|
||||
actionRef.current = action
|
||||
return () => {
|
||||
action.stop()
|
||||
m.uncacheAction(clip)
|
||||
}
|
||||
return () => { action.stop(); m.uncacheAction(clip) }
|
||||
}, [clip])
|
||||
|
||||
// Keep play/pause + speed in sync without rebinding the action.
|
||||
useEffect(() => {
|
||||
const action = actionRef.current
|
||||
if (action) action.paused = !playing
|
||||
|
|
@ -54,12 +81,36 @@ export default function AnimatedMeshPreview({ object, mixerRoot, clip, playing =
|
|||
}, [timeScale])
|
||||
|
||||
useFrame((_, delta) => {
|
||||
mixerRef.current?.update(delta)
|
||||
const m = mixerRef.current
|
||||
if (m) m.update(delta)
|
||||
|
||||
// Additive arm expand/contract: rotate each upper arm about the axis
|
||||
// perpendicular to the arm and world-up, so positive spreads the arms outward
|
||||
// and negative tucks them in — independent of the rig's bone orientation.
|
||||
const angle = armExtension / 100
|
||||
if (angle && armBones.length) {
|
||||
groupRef.current?.updateMatrixWorld(true)
|
||||
for (const { bone, child } of armBones) {
|
||||
if (!child) continue
|
||||
bone.getWorldPosition(_p0)
|
||||
child.getWorldPosition(_p1)
|
||||
_dir.subVectors(_p1, _p0)
|
||||
if (_dir.lengthSq() < 1e-10) continue
|
||||
_axis.crossVectors(_dir.normalize(), _up)
|
||||
if (_axis.lengthSq() < 1e-10) continue
|
||||
_axis.normalize()
|
||||
_delta.setFromAxisAngle(_axis, angle)
|
||||
bone.getWorldQuaternion(_bw)
|
||||
bone.parent.getWorldQuaternion(_pq).invert()
|
||||
bone.quaternion.copy(_pq.multiply(_delta.multiply(_bw))).normalize()
|
||||
bone.updateMatrixWorld(true)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if (!object) return null
|
||||
return (
|
||||
<group position={[0, yOffset, 0]}>
|
||||
<group ref={groupRef} position={[0, alignFloor ? floorOffset : 0, 0]}>
|
||||
<primitive object={object} />
|
||||
</group>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -238,6 +238,31 @@ export default function SkeletonPanel({ skeleton, selectedBone, onSelectBone, an
|
|||
</span>
|
||||
<span>Auto-align to floor</span>
|
||||
</button>
|
||||
|
||||
{animation?.canAdjustArms && (
|
||||
<div className="mesh-editor-anim__arms">
|
||||
<div className="mesh-editor-anim__arms-head">
|
||||
<span className="mesh-editor-panel__hint">Expand / Contract arms</span>
|
||||
<button
|
||||
type="button"
|
||||
className="mesh-editor-anim__arms-reset"
|
||||
onClick={() => animation.onArmExtensionChange(0)}
|
||||
title="Reset arm spread"
|
||||
>
|
||||
<span className="material-symbols-outlined">restart_alt</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="mesh-editor-anim__arms-row">
|
||||
<input
|
||||
type="range" min="-100" max="100" step="1"
|
||||
value={animation.armExtension}
|
||||
onChange={e => animation.onArmExtensionChange(Number(e.target.value))}
|
||||
/>
|
||||
<span className="mesh-editor-anim__arms-val">{animation.armExtension}%</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mesh-editor-layers-panel__header">
|
||||
<span className="mesh-editor-layers-panel__title">Animations</span>
|
||||
<span className="mesh-editor-panel__hint">{animation?.clips?.length || 0}</span>
|
||||
|
|
|
|||
|
|
@ -668,6 +668,58 @@
|
|||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.mesh-editor-anim__arms {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
padding: 0.5rem 0.6rem;
|
||||
border: 1px solid var(--outline-variant, #2a2a30);
|
||||
border-radius: 8px;
|
||||
background: var(--surface, #141418);
|
||||
}
|
||||
|
||||
.mesh-editor-anim__arms-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.mesh-editor-anim__arms-reset {
|
||||
display: inline-flex;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--on-surface-variant);
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.mesh-editor-anim__arms-reset:hover {
|
||||
color: #8ff5ff;
|
||||
}
|
||||
|
||||
.mesh-editor-anim__arms-reset .material-symbols-outlined {
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
|
||||
.mesh-editor-anim__arms-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.mesh-editor-anim__arms-row input[type="range"] {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.mesh-editor-anim__arms-val {
|
||||
font-size: 0.75rem;
|
||||
color: var(--on-surface);
|
||||
min-width: 38px;
|
||||
text-align: right;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.mesh-editor-anim__list {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
|
|
|
|||
|
|
@ -155,7 +155,7 @@ import SkeletonOverlay from '../components/meshEditor/SkeletonOverlay'
|
|||
import SkeletonPanel from '../components/meshEditor/SkeletonPanel'
|
||||
import AnimatedMeshPreview from '../components/meshEditor/AnimatedMeshPreview'
|
||||
import BoneMappingModal from '../components/meshEditor/BoneMappingModal'
|
||||
import { loadReferenceScene, loadTargetScene, autoMapBones, retargetAnimationClip, getReference } from '../utils/animationLibrary'
|
||||
import { loadReferenceScene, loadTargetScene, autoMapBones, retargetAnimationClip, findUpperArmTargets, getReference } from '../utils/animationLibrary'
|
||||
import OptimizeToolsPanel from '../components/meshEditor/OptimizeToolsPanel'
|
||||
import { autoUv as runAutoUvService, autoRetopo as runAutoRetopoService, optimizeMesh as runOptimizeService, repairMesh as runRepairService, autoRig as runAutoRigService, ensureDesktopService } from '../utils/meshTools'
|
||||
|
||||
|
|
@ -465,6 +465,8 @@ export default function MeshEditorPage() {
|
|||
const [animRetargeting, setAnimRetargeting] = useState(null) // clip name currently retargeting
|
||||
const [animPreview, setAnimPreview] = useState(null) // { scene, skinnedMesh, clip, floorOffset }
|
||||
const [animAlignFloor, setAnimAlignFloor] = useState(true) // sit the animated mesh on the grid
|
||||
const [animArmExtension, setAnimArmExtension] = useState(0) // Expand/Contract arms (%)
|
||||
const [animArmTargets, setAnimArmTargets] = useState(null) // { left:[], right:[] } upper-arm target bones
|
||||
const animSourceRef = useRef(null) // loaded reference: { scene, skinnedMesh, boneNames, clips, hipName }
|
||||
const animTargetRef = useRef(null) // loaded target skinned mesh: { scene, skinnedMesh, boneNames }
|
||||
// The rigged GLB blob returned by the service, kept for Save-as-version / download.
|
||||
|
|
@ -1969,6 +1971,8 @@ export default function MeshEditorPage() {
|
|||
setSelectedAnimation(null)
|
||||
setAnimPreview(null)
|
||||
setAnimError(null)
|
||||
setAnimArmTargets(null)
|
||||
setAnimArmExtension(0)
|
||||
animSourceRef.current = null
|
||||
animTargetRef.current = null
|
||||
setAutoRigResult(null)
|
||||
|
|
@ -4119,6 +4123,8 @@ export default function MeshEditorPage() {
|
|||
setAnimClips([])
|
||||
setSelectedAnimation(null)
|
||||
setAnimPreview(null)
|
||||
setAnimArmTargets(null)
|
||||
setAnimArmExtension(0)
|
||||
|
||||
const t = stats?.tool || {}
|
||||
const rows = []
|
||||
|
|
@ -4243,6 +4249,7 @@ export default function MeshEditorPage() {
|
|||
|
||||
const handleSaveBoneMapping = useCallback((mapping) => {
|
||||
setAnimMapping(mapping)
|
||||
setAnimArmTargets(findUpperArmTargets(mapping))
|
||||
setShowBoneMapping(false)
|
||||
const clips = animSourceRef.current?.clips || []
|
||||
setAnimClips(clips.map(c => ({ name: c.name })))
|
||||
|
|
@ -4301,8 +4308,12 @@ export default function MeshEditorPage() {
|
|||
error: animError,
|
||||
alignFloor: animAlignFloor,
|
||||
onToggleAlignFloor: () => setAnimAlignFloor(v => !v),
|
||||
armExtension: animArmExtension,
|
||||
onArmExtensionChange: setAnimArmExtension,
|
||||
canAdjustArms: !!(animArmTargets && (animArmTargets.left.length || animArmTargets.right.length)),
|
||||
}), [animReferenceId, handleSelectAnimReference, handleOpenBoneMapping, animMapping, animClips,
|
||||
selectedAnimation, handleSelectAnimation, animRetargeting, animLoading, animError, animAlignFloor])
|
||||
selectedAnimation, handleSelectAnimation, animRetargeting, animLoading, animError, animAlignFloor,
|
||||
animArmExtension, animArmTargets])
|
||||
|
||||
// On-demand watertight check for the Auto Retopo panel. The position-welded
|
||||
// edge scan can take a moment on dense meshes, so it runs behind a button with
|
||||
|
|
@ -6679,7 +6690,10 @@ export default function MeshEditorPage() {
|
|||
object={animPreview.scene}
|
||||
mixerRoot={animPreview.skinnedMesh}
|
||||
clip={animPreview.clip}
|
||||
yOffset={animAlignFloor ? animPreview.floorOffset : 0}
|
||||
alignFloor={animAlignFloor}
|
||||
floorOffset={animPreview.floorOffset}
|
||||
armExtension={animArmExtension}
|
||||
armTargets={animArmTargets}
|
||||
/>
|
||||
) : (activeMenu === 'texturing' || activeMenu === 'painting' || activeMenu === 'projection' || activeMenu === 'optimize') && texturableMesh?.root && displayTextureRef.current && (activeMenu !== 'texturing' || maskTextureRef.current) ? (
|
||||
<TexturedMesh
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@
|
|||
// 2. map the source bones to the user's mesh bones (auto + manual),
|
||||
// 3. retarget each clip from the source skeleton to the target skeleton with
|
||||
// three's SkeletonUtils.retargetClip, then play it on the target SkinnedMesh.
|
||||
import { AnimationClip, AnimationMixer, Box3, Quaternion, QuaternionKeyframeTrack } from 'three'
|
||||
import { AnimationClip, AnimationMixer, Box3, Matrix4, Quaternion, QuaternionKeyframeTrack, Vector3, VectorKeyframeTrack } from 'three'
|
||||
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
|
||||
import { resourceUrl } from '../config'
|
||||
|
||||
|
|
@ -118,8 +118,10 @@ export async function loadTargetScene({ riggedBuffer, modelUrl }) {
|
|||
if (!skinnedMesh) throw new Error('The current mesh is not skinned (no bones to animate).')
|
||||
skinnedMesh.skeleton.pose()
|
||||
gltf.scene.updateMatrixWorld(true)
|
||||
// Bind-pose floor offset: how far to lift the scene so its lowest point sits
|
||||
// on y=0 (the grid). Used by the "Auto-align to floor" toggle.
|
||||
// One-time "auto-align to floor" offset: how far to lift the rest pose so its
|
||||
// lowest point sits on y=0 (the grid). Applied as a constant during playback —
|
||||
// NOT a per-frame foot lock — so animations keep their natural motion (jumps
|
||||
// leave the ground, crouches lower, etc.).
|
||||
const box = new Box3().setFromObject(gltf.scene)
|
||||
const floorOffset = Number.isFinite(box.min.y) ? -box.min.y : 0
|
||||
return {
|
||||
|
|
@ -288,6 +290,12 @@ export function retargetAnimationClip({
|
|||
const targetBones = []
|
||||
targetScene.traverse(o => { if (o.isBone) targetBones.push(o) })
|
||||
|
||||
// Hip bone (drives vertical body motion): the target bone mapped from the
|
||||
// source's hip. Its position IS retargeted (scaled) so crouches/pushups lower
|
||||
// the body and the feet stay planted — everything else is rotation-only.
|
||||
const sourceHipName = detectHipBone(sourceSkeleton.bones.map(b => b.name))
|
||||
const hipTargetName = Object.keys(mapping).find(t => mapping[t] === sourceHipName) || null
|
||||
|
||||
// Capture bind-pose world quaternions for both rigs.
|
||||
sourceSkeleton.pose(); sourceScene.updateMatrixWorld(true)
|
||||
targetSkinnedMesh.skeleton.pose(); targetScene.updateMatrixWorld(true)
|
||||
|
|
@ -296,6 +304,18 @@ export function retargetAnimationClip({
|
|||
const tgtBindWorld = new Map()
|
||||
targetBones.forEach(b => tgtBindWorld.set(b.name, b.getWorldQuaternion(new Quaternion())))
|
||||
|
||||
// Hip position bind state + size scale (target hip height / source hip height),
|
||||
// so the source's hip translation maps to the target's proportions.
|
||||
const srcHipBone = sourceByName.get(sourceHipName) || null
|
||||
const hipTargetBone = hipTargetName ? targetBones.find(b => b.name === hipTargetName) : null
|
||||
const srcHipBindPos = srcHipBone ? srcHipBone.getWorldPosition(new Vector3()) : null
|
||||
const tgtHipBindPos = hipTargetBone ? hipTargetBone.getWorldPosition(new Vector3()) : null
|
||||
const hipParentBindInv = hipTargetBone ? new Matrix4().copy(hipTargetBone.parent.matrixWorld).invert() : null
|
||||
let hipScale = 1
|
||||
if (srcHipBindPos && tgtHipBindPos && Math.abs(srcHipBindPos.y) > 1e-6) {
|
||||
hipScale = tgtHipBindPos.y / srcHipBindPos.y
|
||||
}
|
||||
|
||||
// Only target bones that map to an existing source bone get animated.
|
||||
const mapped = targetBones.filter(b => mapping[b.name] && sourceByName.has(mapping[b.name]))
|
||||
|
||||
|
|
@ -304,11 +324,13 @@ export function retargetAnimationClip({
|
|||
const dt = frameCount > 1 ? duration / (frameCount - 1) : 0
|
||||
const times = new Float32Array(frameCount)
|
||||
const values = new Map(mapped.map(b => [b.name, new Float32Array(frameCount * 4)]))
|
||||
const hipPosValues = hipTargetBone ? new Float32Array(frameCount * 3) : null
|
||||
|
||||
const mixer = new AnimationMixer(sourceScene)
|
||||
mixer.clipAction(clip).play()
|
||||
|
||||
const sAnimW = new Quaternion(), deltaW = new Quaternion(), desiredW = new Quaternion(), parentWInv = new Quaternion(), local = new Quaternion()
|
||||
const sHipAnim = new Vector3(), hipWorld = new Vector3(), hipLocal = new Vector3()
|
||||
|
||||
for (let f = 0; f < frameCount; f++) {
|
||||
const t = f * dt
|
||||
|
|
@ -321,6 +343,14 @@ export function retargetAnimationClip({
|
|||
targetSkinnedMesh.skeleton.pose()
|
||||
targetScene.updateMatrixWorld(true)
|
||||
for (const tb of mapped) {
|
||||
// Hip position: bind + scaled source-hip delta, converted to hip-local.
|
||||
if (tb === hipTargetBone) {
|
||||
srcHipBone.getWorldPosition(sHipAnim)
|
||||
hipWorld.subVectors(sHipAnim, srcHipBindPos).multiplyScalar(hipScale).add(tgtHipBindPos)
|
||||
hipLocal.copy(hipWorld).applyMatrix4(hipParentBindInv)
|
||||
tb.position.copy(hipLocal)
|
||||
hipLocal.toArray(hipPosValues, f * 3)
|
||||
}
|
||||
const sName = mapping[tb.name]
|
||||
sourceByName.get(sName).getWorldQuaternion(sAnimW)
|
||||
deltaW.multiplyQuaternions(sAnimW, srcBindWorldInv.get(sName))
|
||||
|
|
@ -341,5 +371,23 @@ export function retargetAnimationClip({
|
|||
|
||||
const tracks = mapped.map(tb =>
|
||||
new QuaternionKeyframeTrack(`.bones[${tb.name}].quaternion`, times, values.get(tb.name)))
|
||||
if (hipTargetBone && hipPosValues) {
|
||||
tracks.push(new VectorKeyframeTrack(`.bones[${hipTargetBone.name}].position`, times, hipPosValues))
|
||||
}
|
||||
return new AnimationClip(clip.name, duration, tracks)
|
||||
}
|
||||
|
||||
// Target bones that correspond to the left/right UPPER ARM (for the
|
||||
// Expand/Contract Arms control). Derived from the saved mapping: the source
|
||||
// upper-arm bones are `upperarm_l` / `upperarm_r` (humanoid references).
|
||||
export function findUpperArmTargets(mapping) {
|
||||
const left = []
|
||||
const right = []
|
||||
for (const [target, source] of Object.entries(mapping || {})) {
|
||||
const s = String(source).toLowerCase()
|
||||
if (!s.includes('upperarm') && !(s.includes('arm') && !s.includes('fore') && !s.includes('lower') && !s.includes('hand'))) continue
|
||||
if (/_l$|left|lupperarm|upperarml/.test(s) || s.endsWith('l')) left.push(target)
|
||||
else if (/_r$|right|rupperarm|upperarmr/.test(s) || s.endsWith('r')) right.push(target)
|
||||
}
|
||||
return { left, right }
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue