Skip to content

Sharing Animation Clips

Description

You can load a single THREE.AnimationClip and use it in two different models.

In this example, two different model files are loaded along with three different animation clips.

A custom animation clip is also created which is first cloned from one of the other animation clips and all keytracks are removed except for a select few. See the clonedRightArm buttons.

The same animation clips can be applied to either models. This is possible since the key tracks in the animation clips refer to named bones that already exist within the loaded models.

The bones contained in each models skeletons share the same hierarchy and naming.

Lesson Script

./src/client/client.ts

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import Stats from 'three/examples/jsm/libs/stats.module'
import { GUI } from 'three/examples/jsm/libs/dat.gui.module'

const scene = new THREE.Scene()
scene.add(new THREE.AxesHelper(5))

const light1 = new THREE.SpotLight()
light1.position.set(2.5, 5, 5)
light1.angle = Math.PI / 4
light1.penumbra = 0.5
light1.castShadow = true
light1.shadow.mapSize.width = 1024
light1.shadow.mapSize.height = 1024
light1.shadow.camera.near = 0.5
light1.shadow.camera.far = 20
scene.add(light1)

const light2 = new THREE.SpotLight()
light2.position.set(-2.5, 5, 5)
light2.angle = Math.PI / 4
light2.penumbra = 0.5
light2.castShadow = true
light2.shadow.mapSize.width = 1024
light2.shadow.mapSize.height = 1024
light2.shadow.camera.near = 0.5
light2.shadow.camera.far = 20
scene.add(light2)

const camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
)
camera.position.y = 1.5
camera.position.z = 2.5

const renderer = new THREE.WebGLRenderer()
renderer.shadowMap.enabled = true
// renderer.outputEncoding = THREE.sRGBEncoding
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true
controls.target.y = 1

const animationClips: { [key: string]: THREE.AnimationClip } = {}

let xbotMixer: THREE.AnimationMixer
let ybotMixer: THREE.AnimationMixer
let xbotLastAction: THREE.AnimationClip
let ybotLastAction: THREE.AnimationClip

const totalBots = 2
let botsLoaded = 0
let botsReady = false

const gltfLoader = new GLTFLoader()
gltfLoader.load(
    'models/xbot.glb',
    (gltf) => {
        xbotMixer = new THREE.AnimationMixer(gltf.scene)

        animationClips['xbotDefault'] = gltf.animations[0]
        xbotLastAction = animationClips['xbotDefault']
        xbotFolder.add(xbotButtons, 'default')

        gltf.scene.traverse(function (child) {
            if ((child as THREE.Mesh).isMesh) {
                const m = child as THREE.Mesh
                m.castShadow = true
            }
        })
        gltf.scene.position.x = -1

        const helper = new THREE.SkeletonHelper(gltf.scene)
        scene.add(helper)

        scene.add(gltf.scene)

        botsLoaded++

        loadAnimations()
    },
    (xhr) => {
        console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
    },
    (error) => {
        console.log(error)
    }
)

gltfLoader.load(
    'models/ybot.glb',
    function (gltf) {
        ybotMixer = new THREE.AnimationMixer(gltf.scene)

        animationClips['ybotDefault'] = gltf.animations[0]
        ybotLastAction = animationClips['ybotDefault']
        ybotFolder.add(ybotButtons, 'default')

        gltf.scene.traverse(function (child) {
            console.log(child.name + ' ' + child.type)
            if ((child as THREE.Mesh).isMesh) {
                const m = child as THREE.Mesh
                m.castShadow = true
            }
        })
        gltf.scene.position.x = 1

        const helper = new THREE.SkeletonHelper(gltf.scene)
        scene.add(helper)

        scene.add(gltf.scene)

        botsLoaded++

        loadAnimations()
    },
    (xhr) => {
        console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
    },
    (error) => {
        console.log(error)
    }
)

function loadAnimations() {
    if (botsLoaded === totalBots) {
        //add an animation from another file
        gltfLoader.load(
            'models/actionClip@samba.glb',
            (gltf) => {
                console.log('loaded samba')
                animationClips['samba'] = gltf.animations[0]

                xbotFolder.add(xbotButtons, 'samba')
                ybotFolder.add(ybotButtons, 'samba')

                //add an animation from another file
                gltfLoader.load(
                    'models/actionClip@bellydance.glb',
                    (gltf) => {
                        console.log('loaded bellyDance')

                        animationClips['bellyDance'] = gltf.animations[0]

                        xbotFolder.add(xbotButtons, 'bellyDance')
                        ybotFolder.add(ybotButtons, 'bellyDance')

                        //add an animation from another file
                        gltfLoader.load(
                            'models/actionClip@goofyrunning.glb',
                            (gltf) => {
                                console.log('loaded goofyRunning')
                                ;(gltf as any).animations[0].tracks.shift() //delete the specific track that moves the object forward while running
                                animationClips['goofyRunning'] =
                                    gltf.animations[0]

                                xbotFolder.add(xbotButtons, 'goofyRunning')
                                ybotFolder.add(ybotButtons, 'goofyRunning')

                                //clone goofyrunning and create an animation clip using just one of the arms

                                animationClips['clonedRightArm'] =
                                    animationClips['goofyRunning'].clone()
                                let i =
                                    animationClips['clonedRightArm'].tracks
                                        .length
                                while (i--) {
                                    let trackName =
                                        animationClips['clonedRightArm'].tracks[
                                            i
                                        ].name
                                    if (
                                        !(
                                            trackName.startsWith(
                                                'mixamorigRightShoulder'
                                            ) ||
                                            trackName.startsWith(
                                                'mixamorigRightArm'
                                            ) ||
                                            trackName.startsWith(
                                                'mixamorigRightForeArm'
                                            ) ||
                                            trackName.startsWith(
                                                'mixamorigRightHand'
                                            )
                                        )
                                    ) {
                                        animationClips[
                                            'clonedRightArm'
                                        ].tracks.splice(i, 1)
                                    }
                                }
                                xbotFolder.add(xbotButtons, 'clonedRightArm')
                                ybotFolder.add(ybotButtons, 'clonedRightArm')

                                console.log(animationClips['clonedRightArm'])

                                botsReady = true
                            },
                            (xhr) => {
                                console.log(
                                    (xhr.loaded / xhr.total) * 100 + '% loaded'
                                )
                            },
                            (error) => {
                                console.log(error)
                            }
                        )
                    },
                    (xhr) => {
                        console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
                    },
                    (error) => {
                        console.log(error)
                    }
                )
            },
            (xhr) => {
                console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
            },
            (error) => {
                console.log(error)
            }
        )
    }
}

const phongMaterial = new THREE.MeshPhongMaterial()

const planeGeometry = new THREE.PlaneGeometry(25, 25)
const planeMesh = new THREE.Mesh(planeGeometry, phongMaterial)
planeMesh.rotateX(-Math.PI / 2)
planeMesh.receiveShadow = true
scene.add(planeMesh)

window.addEventListener('resize', onWindowResize, false)
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
    render()
}

const xbotButtons = {
    default: function () {
        xbotMixer.clipAction(xbotLastAction).fadeOut(0.5)
        xbotMixer
            .clipAction(animationClips['xbotDefault'])
            .reset()
            .fadeIn(0.5)
            .play()
        xbotLastAction = animationClips['xbotDefault']
    },
    samba: function () {
        xbotMixer.clipAction(xbotLastAction).fadeOut(0.5)
        xbotMixer.clipAction(animationClips['samba']).reset().fadeIn(0.5).play()
        xbotLastAction = animationClips['samba']
    },
    bellyDance: function () {
        xbotMixer.clipAction(xbotLastAction).fadeOut(0.5)
        xbotMixer
            .clipAction(animationClips['bellyDance'])
            .reset()
            .fadeIn(0.5)
            .play()
        xbotLastAction = animationClips['bellyDance']
    },
    goofyRunning: function () {
        xbotMixer.clipAction(xbotLastAction).fadeOut(0.5)
        xbotMixer
            .clipAction(animationClips['goofyRunning'])
            .reset()
            .fadeIn(0.5)
            .play()
        xbotLastAction = animationClips['goofyRunning']
    },
    clonedRightArm: function () {
        xbotMixer.clipAction(xbotLastAction).fadeOut(0.5)
        xbotMixer
            .clipAction(animationClips['clonedRightArm'])
            .reset()
            .fadeIn(0.5)
            .play()
        xbotLastAction = animationClips['clonedRightArm']
    },
}

const ybotButtons = {
    default: function () {
        ybotMixer.clipAction(ybotLastAction).fadeOut(0.5)
        ybotMixer
            .clipAction(animationClips['ybotDefault'])
            .reset()
            .fadeIn(0.5)
            .play()
        ybotLastAction = animationClips['ybotDefault']
    },
    samba: function () {
        ybotMixer.clipAction(ybotLastAction).fadeOut(0.5)
        ybotMixer.clipAction(animationClips['samba']).reset().fadeIn(0.5).play()
        ybotLastAction = animationClips['samba']
    },
    bellyDance: function () {
        ybotMixer.clipAction(ybotLastAction).fadeOut(0.5)
        ybotMixer
            .clipAction(animationClips['bellyDance'])
            .reset()
            .fadeIn(0.5)
            .play()
        ybotLastAction = animationClips['bellyDance']
    },
    goofyRunning: function () {
        ybotMixer.clipAction(ybotLastAction).fadeOut(0.5)
        ybotMixer
            .clipAction(animationClips['goofyRunning'])
            .reset()
            .fadeIn(0.5)
            .play()
        ybotLastAction = animationClips['goofyRunning']
    },
    clonedRightArm: function () {
        ybotMixer.clipAction(ybotLastAction).fadeOut(0.5)
        ybotMixer
            .clipAction(animationClips['clonedRightArm'])
            .reset()
            .fadeIn(0.5)
            .play()
        ybotLastAction = animationClips['clonedRightArm']
    },
}

const gui = new GUI()
const xbotFolder = gui.addFolder('xbot')
xbotFolder.open()
const ybotFolder = gui.addFolder('ybot')
ybotFolder.open()

const stats = Stats()
document.body.appendChild(stats.dom)

const clock = new THREE.Clock()
let delta = 0

function animate() {
    requestAnimationFrame(animate)

    controls.update()

    delta = clock.getDelta()
    if (botsReady) {
        xbotMixer.update(delta)
        ybotMixer.update(delta)
    }

    render()

    stats.update()
}

function render() {
    renderer.render(scene, camera)
}

animate()