Skip to content

Import a 3D Model and automatically assign and export animations

TypeScript

Drop animation that we might not be linking to a bone (dropped hands)

Scott Petrovicf287043185b0
diff --git a/src/lib/processes/export-to-file/ExportAnimationCleanupService.test.ts b/src/lib/processes/export-to-file/ExportAnimationCleanupService.test.ts
new file mode 100644
index 0000000..4dc216f
--- /dev/null
+++ b/src/lib/processes/export-to-file/ExportAnimationCleanupService.test.ts
@@ -0,0 +1,96 @@
+import { describe, it, expect } from 'vitest'
+import { AnimationClip, Bone, NumberKeyframeTrack, Object3D, QuaternionKeyframeTrack, VectorKeyframeTrack } from 'three'
+import { ExportAnimationCleanupService } from './ExportAnimationCleanupService'
+
+/**
+ * Builds a small rig the way exported models look: the bones hang off a root
+ * object that gets moved into the export scene.
+ */
+function make_export_root (): Object3D {
+ const root = new Object3D()
+ root.name = 'Armature'
+
+ const hips = new Bone()
+ hips.name = 'Hips'
+ const spine = new Bone()
+ spine.name = 'Spine'
+
+ root.add(hips)
+ hips.add(spine)
+
+ return root
+}
+
+function make_clip (tracks: Array<QuaternionKeyframeTrack | VectorKeyframeTrack | NumberKeyframeTrack>): AnimationClip {
+ return new AnimationClip('walk', -1, tracks)
+}
+
+describe('ExportAnimationCleanupService', () => {
+ it('removes tracks whose joint is not part of the export hierarchy', () => {
+ const export_root = make_export_root()
+ const clip = make_clip([
+ new QuaternionKeyframeTrack('Hips.quaternion', [0, 1], [0, 0, 0, 1, 0, 0, 0, 1]),
+ new QuaternionKeyframeTrack('IndexFinger_L.quaternion', [0, 1], [0, 0, 0, 1, 0, 0, 0, 1])
+ ])
+
+ ExportAnimationCleanupService.clean_clips_for_export([clip], [export_root])
+
+ expect(clip.tracks.map((track) => track.name)).toEqual(['Hips.quaternion'])
+ })
+
+ it('keeps tracks bound to any of the export roots', () => {
+ const first_root = make_export_root()
+ const second_root = new Object3D()
+ second_root.name = 'Prop'
+
+ const clip = make_clip([
+ new QuaternionKeyframeTrack('Spine.quaternion', [0, 1], [0, 0, 0, 1, 0, 0, 0, 1]),
+ new VectorKeyframeTrack('Prop.position', [0, 1], [0, 0, 0, 1, 1, 1])
+ ])
+
+ ExportAnimationCleanupService.clean_clips_for_export([clip], [first_root, second_root])
+
+ expect(clip.tracks).toHaveLength(2)
+ })
+
+ it('drops keyframes whose float32 time collapses into the previous keyframe', () => {
+ const export_root = make_export_root()
+
+ // 4/3 and the next-closest float64 value are different in float64, but both round to
+ // the same float32, which is how ACCESSOR_ANIMATION_INPUT_NON_INCREASING happens.
+ const time_a = 4 / 3
+ const time_b = time_a + Number.EPSILON
+ expect(Math.fround(time_a)).toBe(Math.fround(time_b))
+
+ const clip = make_clip([
+ new VectorKeyframeTrack('Hips.position', [0, time_a, time_b, 2], [
+ 0, 0, 0,
+ 1, 1, 1,
+ 2, 2, 2,
+ 3, 3, 3
+ ])
+ ])
+
+ ExportAnimationCleanupService.clean_clips_for_export([clip], [export_root])
+
+ const track = clip.tracks[0]
+ expect(Array.from(track.times)).toEqual([0, Math.fround(time_a), 2])
+ expect(Array.from(track.values)).toEqual([0, 0, 0, 1, 1, 1, 3, 3, 3])
+
+ for (let i = 1; i < track.times.length; i++) {
+ expect(track.times[i]).toBeGreaterThan(track.times[i - 1])
+ }
+ })
+
+ it('leaves tracks with strictly increasing times untouched', () => {
+ const export_root = make_export_root()
+ const track = new NumberKeyframeTrack('Hips.scale[x]', [0, 0.5, 1], [1, 2, 3])
+ const original_times = track.times
+ const original_values = track.values
+
+ ExportAnimationCleanupService.clean_clips_for_export([make_clip([track])], [export_root])
+
+ expect(track.times).toBe(original_times)
+ expect(track.values).toBe(original_values)
+ })
+})
diff --git a/src/lib/processes/export-to-file/ExportAnimationCleanupService.ts b/src/lib/processes/export-to-file/ExportAnimationCleanupService.ts
new file mode 100644
index 0000000..1dfbdd2
--- /dev/null
+++ b/src/lib/processes/export-to-file/ExportAnimationCleanupService.ts
@@ -0,0 +1,78 @@
+import { type AnimationClip, type KeyframeTrack, type Object3D, PropertyBinding } from 'three'
+
+/**
+ * Cleans animation clips right before they are handed to an exporter.
+ *
+ * The animation library is authored against the full skeleton, but the user can delete
+ * joints (fingers, tail, ...) before exporting. Tracks that target a deleted joint have
+ * nothing to bind to, so they are stripped here instead of relying on every exporter to
+ * quietly skip them.
+ *
+ * Keyframe times also need to be strictly increasing. Times are parsed as float64 but
+ * KeyframeTrack stores them as float32, so two times that were distinct in the source
+ * file can collapse into the same float32 value. glTF validators reject that with
+ * ACCESSOR_ANIMATION_INPUT_NON_INCREASING, so duplicated times are dropped here.
+ */
+export class ExportAnimationCleanupService {
+ /**
+ * Cleans the clips in place: removes tracks that do not resolve to a node inside the
+ * export hierarchy, then drops keyframes whose time is not strictly greater than the
+ * previous keyframe's time.
+ *
+ * @param animation_clips clips that are about to be exported
+ * @param export_roots the objects being moved into the export scene
+ */
+ public static clean_clips_for_export (animation_clips: AnimationClip[], export_roots: Object3D[]): void {
+ animation_clips.forEach((animation_clip) => {
+ animation_clip.tracks = animation_clip.tracks.filter((track) => {
+ const is_bound = this.track_binds_to_export_hierarchy(track, export_roots)
+
+ if (!is_bound) {
+ console.log(`Export cleanup: removing animation track "${track.name}" because its joint is not part of the exported skeleton`)
+ }
+
+ return is_bound
+ })
+
+ animation_clip.tracks.forEach((track) => { this.remove_non_increasing_keyframes(track) })
+ })
+ }
+
+ private static track_binds_to_export_hierarchy (track: KeyframeTrack, export_roots: Object3D[]): boolean {
+ const node_name: string | undefined = PropertyBinding.parseTrackName(track.name).nodeName
+
+ return export_roots.some((export_root) => {
+ return PropertyBinding.findNode(export_root, node_name) !== null
+ })
+ }
+
+ private static remove_non_increasing_keyframes (track: KeyframeTrack): void {
+ const times = track.times
+ const value_size = track.getValueSize()
+ const kept_indices: number[] = []
+
+ for (let i = 0; i < times.length; i++) {
+ if (kept_indices.length === 0 || times[i] > times[kept_indices[kept_indices.length - 1]]) {
+ kept_indices.push(i)
+ }
+ }
+
+ if (kept_indices.length === times.length) {
+ return // already strictly increasing
+ }
+
+ const cleaned_times = new Float32Array(kept_indices.length)
+ const cleaned_values = new Float32Array(kept_indices.length * value_size)
+
+ kept_indices.forEach((source_index, kept_index) => {
+ cleaned_times[kept_index] = times[source_index]
+
+ for (let component = 0; component < value_size; component++) {
+ cleaned_values[kept_index * value_size + component] = track.values[source_index * value_size + component]
+ }
+ })
+
+ track.times = cleaned_times
+ track.values = cleaned_values
+ }
+}
diff --git a/src/lib/processes/export-to-file/StepExportToFile.ts b/src/lib/processes/export-to-file/StepExportToFile.ts
index 5455d9c..9935c71 100644
--- a/src/lib/processes/export-to-file/StepExportToFile.ts
+++ b/src/lib/processes/export-to-file/StepExportToFile.ts
@@ -5,6 +5,7 @@ import { type AnimationClip, Scene, type SkinnedMesh, type Object3D } from 'thre
import { type DownloadSettings, ExportContents, ExportFormat, type FbxExportPreset } from './DownloadSettings.ts'
import { ExportBoneNamingService } from './ExportBoneNamingService.ts'
import { ExportHierarchyService } from './ExportHierarchyService.ts'
+import { ExportAnimationCleanupService } from './ExportAnimationCleanupService.ts'
import { GlbSkinCleanupService } from './GlbSkinCleanupService.ts'
import { AnimationUtility } from '../animations-listing/AnimationUtility.ts'
import { type AnimationExportSelection } from '../animations-listing/interfaces/AnimationExportSelection.ts'
@@ -74,6 +75,11 @@ export class StepExportToFile extends EventTarget {
const skeleton_only = download_settings.export_contents() === ExportContents.Skeleton
const objects_to_export: Object3D[] = ExportHierarchyService.collect_objects_to_export(skinned_meshes, skeleton_only)
+ // The base animation data can contain tracks for joints the user removed (e.g. fingers),
+ // and keyframe times can contain float32 duplicates that glTF validators reject.
+ // This runs after bone renaming so the track names match the final bone names.
+ ExportAnimationCleanupService.clean_clips_for_export(export_clips, objects_to_export)
+
// When exporting to a file, we need to temporarily move the exported objects to a new
// scene. An object can only be part of one scene at a time, so we must move it back to
// its original parent after exporting. For a skeleton-only export, the root bone's
diff --git a/src/retarget/steps/StepExportRetargetedAnimations.ts b/src/retarget/steps/StepExportRetargetedAnimations.ts
index 30ce0c0..cf30918 100644
--- a/src/retarget/steps/StepExportRetargetedAnimations.ts
+++ b/src/retarget/steps/StepExportRetargetedAnimations.ts
@@ -7,6 +7,7 @@ import { type AnimationExportSelection } from '../../lib/processes/animations-li
import { type DownloadSettings, ExportContents, ExportFormat, type FbxExportPreset } from '../../lib/processes/export-to-file/DownloadSettings'
import { ExportBoneNamingService } from '../../lib/processes/export-to-file/ExportBoneNamingService'
import { ExportHierarchyService } from '../../lib/processes/export-to-file/ExportHierarchyService'
+import { ExportAnimationCleanupService } from '../../lib/processes/export-to-file/ExportAnimationCleanupService'
import { GlbSkinCleanupService } from '../../lib/processes/export-to-file/GlbSkinCleanupService'
import { FbxTextureCompatibilityService } from '../../lib/processes/export-to-file/FbxTextureCompatibilityService'
@@ -73,6 +74,11 @@ export class StepExportRetargetedAnimations extends EventTarget {
const skeleton_only = download_settings.export_contents() === ExportContents.Skeleton
const objects_to_export: Object3D[] = ExportHierarchyService.collect_objects_to_export(skinned_meshes, skeleton_only)
+ // The base animation data can contain tracks for joints the target skeleton does not
+ // have, and keyframe times can contain float32 duplicates that glTF validators reject.
+ // This runs after bone renaming so the track names match the final bone names.
+ ExportAnimationCleanupService.clean_clips_for_export(animations_to_export, objects_to_export)
+
const original_parents = new Map<Object3D, Object3D | null>()
objects_to_export.forEach((object_to_export) => {