Skip to content

Import a 3D Model and automatically assign and export animations

TypeScript

WIP still trying to get the bone roll fixed

Scott Petrovic4499248dc00b
diff --git a/src/retarget/BoneAutoMapper.ts b/src/retarget/BoneAutoMapper.ts
index 6f8e99b..d8a7be5 100644
--- a/src/retarget/BoneAutoMapper.ts
+++ b/src/retarget/BoneAutoMapper.ts
@@ -1,4 +1,4 @@
-import { Bone, Group, Object3D, SkinnedMesh } from 'three'
+import { Bone, Group, Object3D, Scene, SkinnedMesh } from 'three'
import { BoneCategoryMapper } from './BoneCategoryMapper'
import { MixamoMapper } from './MixamoMapper'
import { TargetBoneMappingType } from './StepBoneMapping'
@@ -52,7 +52,7 @@ export class BoneAutoMapper {
*/
public static auto_map_bones (
source_armature: Object3D,
- target_skeleton_data: Group,
+ target_skeleton_data: Scene,
target_bone_mapping_type: TargetBoneMappingType
): Map<string, string> {
// mappings: final output mapping of target bone name to source bone name
@@ -163,7 +163,7 @@ export class BoneAutoMapper {
* @param target_skeleton_data - Target skeleton data group
* @returns Map of bone name to parent bone name
*/
- private static extract_target_bone_parent_map (target_skeleton_data: Group): Map<string, string | null> {
+ private static extract_target_bone_parent_map (target_skeleton_data: Scene): Map<string, string | null> {
const parent_map = new Map<string, string | null>()
const processed_bones = new Set<string>()
diff --git a/src/retarget/RetargetAnimationPreview.ts b/src/retarget/RetargetAnimationPreview.ts
index d4b27b5..90bb63f 100644
--- a/src/retarget/RetargetAnimationPreview.ts
+++ b/src/retarget/RetargetAnimationPreview.ts
@@ -1,4 +1,4 @@
-import { AnimationClip, AnimationMixer, type Scene, type SkinnedMesh, VectorKeyframeTrack, QuaternionKeyframeTrack, type AnimationAction, Quaternion, Euler, type Object3D } from 'three'
+import { AnimationClip, AnimationMixer, type Scene, type SkinnedMesh, VectorKeyframeTrack, QuaternionKeyframeTrack, type AnimationAction, Quaternion, Euler, type Object3D, Vector3 } from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { SkeletonType } from '../lib/enums/SkeletonType.ts'
import { AnimationUtility } from '../lib/processes/animations-listing/AnimationUtility.ts'
@@ -268,7 +268,7 @@ export class RetargetAnimationPreview extends EventTarget {
// Apply Mixamo-specific corrections
const target_mapping_type = this.step_bone_mapping.get_target_mapping_template()
if (target_mapping_type === TargetBoneMappingType.Mixamo) {
- this.apply_mixamo_corrections(retargeted_clip)
+ this.apply_bone_rotation_correction(retargeted_clip)
}
console.log(`Retargeted animation: ${source_clip.name} (${new_tracks.length} tracks)`)
@@ -339,12 +339,13 @@ export class RetargetAnimationPreview extends EventTarget {
}
/**
- * Calculate the rotation delta between source and target bones in bind pose
+ * Calculate the bone roll delta between source and target bones in bind pose
+ * Bone roll is the rotation around the bone's primary axis (Y-axis in Three.js)
* @param source_bone_name - Name of the bone in the source skeleton
* @param target_bone_name - Name of the bone in the target skeleton
- * @returns The rotation difference as a quaternion, or null if bones not found
+ * @returns The rotation difference as a quaternion (Y-axis only), or null if bones not found
*/
- private calculate_bone_rotation_delta (source_bone_name: string, target_bone_name: string): Quaternion | null {
+ private calculate_bone_rotation_delta (source_bone_name: string, target_bone_name: string): Quaternion | null {
// Get both skeleton roots
const source_armature = this.step_bone_mapping.get_source_armature()
const target_skeleton_data = this.step_bone_mapping.get_target_skeleton_data()
@@ -365,21 +366,26 @@ export class RetargetAnimationPreview extends EventTarget {
return null
}
- // Get quaternions from bind pose (local rotation)
+ // Local-space bind pose quaternions
const source_quat = new Quaternion().copy(source_bone.quaternion)
const target_quat = new Quaternion().copy(target_bone.quaternion)
- // Calculate delta: target_inverse * source
- const delta_quat = target_quat.clone().invert().multiply(source_quat)
+ // Relative local delta (target -> source)
+ const full_delta_quat = target_quat.clone().invert().multiply(source_quat)
- return delta_quat
+ // Extract only the twist around local Y (bone roll) via swing–twist decomposition
+ const axis_y = new Vector3(0, 1, 0)
+ const v = new Vector3(full_delta_quat.x, full_delta_quat.y, full_delta_quat.z)
+ const proj = axis_y.clone().multiplyScalar(v.dot(axis_y))
+ const twist_y = new Quaternion(proj.x, proj.y, proj.z, full_delta_quat.w).normalize()
+
+ return twist_y
}
/**
- * Apply Mixamo-specific corrections to retargeted animation by calculating rotation deltas
- * between source and target bones in bind pose. Uses actual bone mappings instead of guessing names.
+ * Apply bone rotation correction for fixing bone roll delta between target and source skeleton
*/
- private apply_mixamo_corrections (animation_clip: AnimationClip): void {
+ private apply_bone_rotation_correction (animation_clip: AnimationClip): void {
const bone_mappings = this.step_bone_mapping.get_bone_mapping()
bone_mappings.forEach((source_bone_name, target_bone_name) => {
@@ -388,8 +394,6 @@ export class RetargetAnimationPreview extends EventTarget {
if (delta !== null) {
const delta_euler = new Euler().setFromQuaternion(delta)
- console.log(`Applying Mixamo correction for bone: ${target_bone_name}, delta Euler:`, delta_euler)
-
this.rotate_bone_for_retargeting(animation_clip, [target_bone_name], delta_euler)
} else {
console.log(`Warning: delta is NULL when fixing bone roll. Skipping correction for bone: ${target_bone_name}`)
@@ -399,11 +403,6 @@ export class RetargetAnimationPreview extends EventTarget {
console.log('Applied Mixamo-specific corrections to retargeted animation (dynamically calculated)', animation_clip)
}
- // helps when specifying rotations in degrees with retargeting corrections
- private deg_to_rad (deg: number): number {
- return deg * Math.PI / 180
- }
-
/**
* Parse a track name to extract bone name and property
* Handles various formats like "boneName.property" or ".bones[boneName].property"
diff --git a/src/retarget/StepBoneMapping.ts b/src/retarget/StepBoneMapping.ts
index c6fcc1a..198c826 100644
--- a/src/retarget/StepBoneMapping.ts
+++ b/src/retarget/StepBoneMapping.ts
@@ -163,12 +163,12 @@ export class StepBoneMapping extends EventTarget {
if (this.source_bones_list === null) return
const bone_names = this.get_source_bone_names()
-
+
// Update bone count display
if (this.source_bone_count !== null) {
this.source_bone_count.textContent = `(${bone_names.length})`
}
-
+
if (bone_names.length === 0) {
this.source_bones_list.innerHTML = '<em>No source skeleton loaded</em>'
return
@@ -179,15 +179,15 @@ export class StepBoneMapping extends EventTarget {
const bone_item = document.createElement('div')
bone_item.textContent = name
bone_item.className = 'bone-item bone-item-source'
-
+
// Make the bone draggable (source bones from Mesh2Motion skeleton)
bone_item.draggable = true
bone_item.dataset.boneName = name
-
+
// Add drag event listeners
bone_item.addEventListener('dragstart', this.handle_drag_start.bind(this))
bone_item.addEventListener('dragend', this.handle_drag_end.bind(this))
-
+
this.source_bones_list?.appendChild(bone_item)
})
}
@@ -196,12 +196,12 @@ export class StepBoneMapping extends EventTarget {
if (this.target_bones_list === null) return
const bone_names = this.get_target_bone_names()
-
+
// Update bone count display
if (this.target_bone_count !== null) {
this.target_bone_count.textContent = `(${bone_names.length})`
}
-
+
if (bone_names.length === 0) {
this.target_bones_list.innerHTML = '<em>No target skeleton loaded</em>'
return
@@ -212,18 +212,17 @@ export class StepBoneMapping extends EventTarget {
const bone_item = document.createElement('div')
bone_item.className = 'bone-item bone-item-target'
bone_item.dataset.targetBoneName = name
-
+
// Check if this target bone has a mapping
const mapped_source_bone = this.bone_mapping.get(name)
if (mapped_source_bone !== undefined) {
-
const source_name_span = document.createElement('span')
source_name_span.textContent = mapped_source_bone
source_name_span.className = 'mapping-source-name'
-
+
const target_name_span = document.createElement('span')
target_name_span.textContent = name
-
+
bone_item.appendChild(source_name_span)
bone_item.appendChild(target_name_span)
@@ -240,12 +239,12 @@ export class StepBoneMapping extends EventTarget {
} else {
bone_item.textContent = name
}
-
+
// Make the bone a drop target (target bones from uploaded mesh)
bone_item.addEventListener('dragover', this.handle_drag_over.bind(this))
bone_item.addEventListener('dragleave', this.handle_drag_leave.bind(this))
bone_item.addEventListener('drop', this.handle_drop.bind(this))
-
+
this.target_bones_list?.appendChild(bone_item)
})
}
@@ -254,7 +253,7 @@ export class StepBoneMapping extends EventTarget {
private handle_drag_start (event: DragEvent): void {
const target = event.target as HTMLElement
const bone_name = target.dataset.boneName
-
+
if (bone_name !== undefined && event.dataTransfer !== null) {
event.dataTransfer.effectAllowed = 'copy'
event.dataTransfer.setData('text/plain', bone_name)
@@ -270,7 +269,7 @@ export class StepBoneMapping extends EventTarget {
private handle_drag_over (event: DragEvent): void {
event.preventDefault() // Allow drop
const target = event.target as HTMLElement
-
+
// Visual feedback for drop zone
if (event.dataTransfer !== null) {
event.dataTransfer.dropEffect = 'copy'
@@ -287,20 +286,20 @@ export class StepBoneMapping extends EventTarget {
event.preventDefault()
const target = event.target as HTMLElement
target.classList.remove('drag-over')
-
+
if (event.dataTransfer !== null) {
const source_bone_name = event.dataTransfer.getData('text/plain')
const target_bone_name = target.dataset.targetBoneName
-
+
if (source_bone_name !== '' && target_bone_name !== undefined) {
// Update the mapping
this.bone_mapping.set(target_bone_name, source_bone_name)
console.log(`Mapped: ${target_bone_name} <- ${source_bone_name}`)
-
+
// Update the UI to show the mapping
this.update_target_bones_list()
this.update_clear_button_visibility()
-
+
// Dispatch event to notify of mapping change
this.dispatchEvent(new CustomEvent('bone-mapping-updated', {
detail: {
@@ -308,7 +307,7 @@ export class StepBoneMapping extends EventTarget {
source_bone: source_bone_name
}
}))
-
+
// Dispatch event to notify about mapping state change
this.dispatchEvent(new CustomEvent('bone-mappings-changed'))
}
@@ -386,19 +385,8 @@ export class StepBoneMapping extends EventTarget {
console.log(`Auto-mapped ${auto_mappings.size} bones:`, auto_mappings)
// Update UI
- this.polish_rig_after_bone_mappings()
this.update_target_bones_list()
this.update_clear_button_visibility()
this.dispatchEvent(new CustomEvent('bone-mappings-changed'))
}
-
- // some rig types don't have a root (like mixamo), so we need to rotate
- // certain bones to get the model standing upright after retargeting
- private polish_rig_after_bone_mappings (): void {
- if (this.target_mapping_template === TargetBoneMappingType.Mixamo) {
- console.log('Applying Mixamo rig polish adjustments since there is no root bone')
- // for mixamo rigs, rotate the entire group by -90 degrees on X to get upright
- // TODO: how to do this??
- }
- }
}