File size: 12,398 Bytes
e1bb50d
7ec132a
e1bb50d
 
 
7ec132a
 
e1bb50d
 
 
 
 
 
 
 
 
 
 
7ec132a
e1bb50d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ec132a
 
 
e1bb50d
 
 
 
 
 
 
 
 
 
7ec132a
 
 
 
 
e1bb50d
 
7ec132a
 
 
 
 
 
 
 
 
 
 
 
 
 
e1bb50d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ec132a
e1bb50d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b788554
 
 
 
 
 
 
 
 
 
7ec132a
 
 
 
 
 
 
e1bb50d
 
 
7ec132a
 
e1bb50d
 
 
 
 
 
 
 
 
 
 
 
7ec132a
e1bb50d
 
7ec132a
 
 
 
 
 
e1bb50d
7ec132a
e1bb50d
 
7ec132a
 
 
 
 
 
e1bb50d
7ec132a
e1bb50d
7ec132a
 
 
e1bb50d
7ec132a
 
e1bb50d
 
7ec132a
 
 
b788554
 
 
 
 
 
 
 
 
7ec132a
 
 
 
 
 
 
e1bb50d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * MotionController โ€” unified animation system supporting VRMA and FBX actions.
 *
 * Uses a single persistent AnimationMixer with crossFade transitions to avoid
 * T-pose flickering between animations.
 *
 * Simplified: removed dance system, kept action presets for human-like behavior.
 */

import * as THREE from 'three'
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'
import { VRMAnimationLoaderPlugin, createVRMAnimationClip } from '@pixiv/three-vrm-animation'
import type { VRMAnimation } from '@pixiv/three-vrm-animation'
import type { VRM } from '@pixiv/three-vrm'
import { loadMixamoAnimation } from './mixamo-loader'

// โ”€โ”€ Motion file types โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

export type MotionFileType = 'vrma' | 'fbx'

// โ”€โ”€ Motion presets โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

export interface MotionPreset {
  label: string
  type: MotionFileType
  url: string
}

// Actions: short one-shot gestures triggered by emotions / interactions
export const actionPresets: Record<string, MotionPreset> = {
  akimbo:       { label: 'ๅ‰่…ฐ',   type: 'vrma', url: '/friend/akimbo.vrma' },
  playFingers:  { label: 'ๆ“ๆ‰‹',   type: 'vrma', url: '/friend/playFingers.vrma' },
  scratchHead:  { label: 'ๆŒ ๅคด',   type: 'vrma', url: '/friend/scratchHead.vrma' },
  stretch:      { label: 'ไผธๅฑ•',   type: 'vrma', url: '/friend/stretch.vrma' },

  happy:        { label: 'ๅผ€ๅฟƒ',     type: 'fbx', url: '/friend/happy.fbx' },
  angry:        { label: '็”Ÿๆฐ”',     type: 'fbx', url: '/friend/angry.fbx' },
  greeting:     { label: 'ๆ‹›ๅ‘ผ',     type: 'fbx', url: '/friend/greeting.fbx' },
  excited:      { label: 'ๅ…ดๅฅ‹',     type: 'fbx', url: '/friend/excited.fbx' },
  shy:          { label: 'ๅฎณ็พž',     type: 'fbx', url: '/friend/shy.fbx' },
  point:        { label: 'ๆŒ‡็‚น',     type: 'fbx', url: '/friend/point.fbx' },
  salute:       { label: 'ๆ•ฌ็คผ',     type: 'fbx', url: '/friend/salute.fbx' },
  angryPump:    { label: 'ๆšดๆ€’',     type: 'fbx', url: '/friend/angryPump.fbx' },
}

// โ”€โ”€ Utility: re-anchor root position โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

function reAnchorRootPositionTrack(clip: THREE.AnimationClip, vrm: VRM) {
  const hipNode = vrm.humanoid?.getNormalizedBoneNode('hips')
  if (!hipNode) return

  hipNode.updateMatrixWorld(true)
  const defaultHipPos = new THREE.Vector3()
  hipNode.getWorldPosition(defaultHipPos)

  const hipsTrack = clip.tracks.find(
    (t) =>
      t instanceof THREE.VectorKeyframeTrack &&
      t.name === `${hipNode.name}.position`,
  )
  if (!(hipsTrack instanceof THREE.VectorKeyframeTrack)) return

  const animeHipPos = new THREE.Vector3(
    hipsTrack.values[0],
    hipsTrack.values[1],
    hipsTrack.values[2],
  )
  const delta = new THREE.Vector3().subVectors(animeHipPos, defaultHipPos)

  clip.tracks.forEach((track) => {
    if (
      track.name.endsWith('.position') &&
      track instanceof THREE.VectorKeyframeTrack
    ) {
      for (let i = 0; i < track.values.length; i += 3) {
        track.values[i] -= delta.x
        track.values[i + 1] -= delta.y
        track.values[i + 2] -= delta.z
      }
    }
  })
}

// โ”€โ”€ MotionController โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

export class MotionController {
  private vrm: VRM
  private mixer: THREE.AnimationMixer | null = null
  private idleClip: THREE.AnimationClip | null = null
  private idleAction: THREE.AnimationAction | null = null
  private currentAction: THREE.AnimationAction | null = null
  private clipCache = new Map<string, THREE.AnimationClip>()
  private gltfLoader: GLTFLoader
  private _actionPlaying = false
  private holdTimer: ReturnType<typeof setTimeout> | null = null
  private _actionSafetyTimer: ReturnType<typeof setTimeout> | null = null
  private actionQueue: Array<{ name: string; hold: boolean }> = []
  private _settleGen = 0       // generation at which the current settle is valid
  private _settleHold = false  // hold flag for current settle

  constructor(vrm: VRM) {
    this.vrm = vrm
    this.mixer = new THREE.AnimationMixer(vrm.scene)
    this.gltfLoader = new GLTFLoader()
    this.gltfLoader.register((parser) => new VRMAnimationLoaderPlugin(parser))
  }

  get actionPlaying() { return this._actionPlaying }

  update(delta: number) {
    if (this.mixer) {
      this.mixer.update(delta)
      this.checkActionCompletion()
    }
  }

  /**
   * Frame-accurate action completion detection.
   * THREE.AnimationMixer 'finished' event only fires when ALL actions finish,
   * which never happens with a looping idle. So we check per-frame instead.
   */
  private checkActionCompletion() {
    if (!this._actionPlaying || !this.currentAction) return
    const clip = this.currentAction.getClip()
    if (!clip || clip.duration <= 0) return

    // Allow a 1-frame epsilon (โ‰ˆ16ms at 60fps) to avoid precision issues
    if (this.currentAction.time >= clip.duration - 0.02) {
      this.finishCurrentAction()
    }
  }

  // โ”€โ”€ CrossFade helper โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  private crossFadeTo(newAction: THREE.AnimationAction, duration = 0.3) {
    newAction.reset().setEffectiveWeight(1).play()
    const prev = this.currentAction ?? this.idleAction
    if (prev && prev !== newAction) {
      prev.crossFadeTo(newAction, duration, false)
    }
    this.currentAction = newAction
  }

  // โ”€โ”€ Load & play idle animation โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  async loadIdle(path: string) {
    const clip = await this.loadVRMA(path)
    if (!clip) return
    reAnchorRootPositionTrack(clip, this.vrm)
    this.idleClip = clip
    this.startIdle()
  }

  /** (Re)start idle via crossFade. */
  private startIdle() {
    if (!this.idleClip || !this.mixer) return
    this.idleAction = this.mixer.clipAction(this.idleClip)
    this.crossFadeTo(this.idleAction)
  }

  // โ”€โ”€ Clear current action (private) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  private clearTimers() {
    if (this.holdTimer) { clearTimeout(this.holdTimer); this.holdTimer = null }
    if (this._actionSafetyTimer) { clearTimeout(this._actionSafetyTimer); this._actionSafetyTimer = null }
  }

  // โ”€โ”€ Reset to idle (public) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  resetToIdle() {
    this.clearTimers()
    this._actionPlaying = false
    this._actionGeneration++

    // CrossFade back to idle
    if (this.mixer && this.idleClip) {
      this.idleAction = this.mixer.clipAction(this.idleClip)
      this.crossFadeTo(this.idleAction)
    }
  }

  // โ”€โ”€ Play a one-shot action โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  private _actionGeneration = 0

  async playAction(name: string, hold = false) {
    const preset = actionPresets[name]
    if (!preset) { console.warn('[Motion] unknown action:', name); return }

    // If currently holding (pose frozen, not actively animating), interrupt hold
    // and play the new action immediately. This prevents LLM text-message actions
    // from being blocked by a stale 10s hold timer.
    if (this._actionPlaying && this.holdTimer !== null) {
      this.clearTimers()
      this._actionPlaying = false
      // fall through to play new action
    } else if (this._actionPlaying) {
      // Normal queue: only when an action is actively animating (e.g. two rapid
      // LLM tool calls). Hold does NOT queue โ€” it interrupts.
      const last = this.actionQueue[this.actionQueue.length - 1]
      if (!last || last.name !== name) {
        this.actionQueue.push({ name, hold })
      }
      return
    }

    // Set lock BEFORE async load to prevent concurrent playAction calls
    this._actionPlaying = true
    const gen = ++this._actionGeneration
    this._settleGen = gen
    this._settleHold = hold

    const clip = await this.loadClip(preset)

    // Check if state was reset or another action started during await
    if (gen !== this._actionGeneration) return
    if (!clip) { console.warn('[Motion] clip load failed for:', name); this._actionPlaying = false; return }
    if (!this.mixer) { this._actionPlaying = false; return }

    this.clearTimers()

    const action = this.mixer.clipAction(clip)
    action.setLoop(THREE.LoopOnce, 1)
    action.clampWhenFinished = true
    this.crossFadeTo(action)

    // Frame-accurate completion is handled in checkActionCompletion() via update()
    // Safety timer: generous fallback (should never fire if checkActionCompletion works)
    const safeDuration = Math.max(clip.duration, 3) + 5
    this._actionSafetyTimer = setTimeout(() => {
      if (gen === this._actionGeneration && this._actionPlaying) {
        this.finishCurrentAction()
      }
    }, safeDuration * 1000)
  }

  /** Called by checkActionCompletion() or safety timer when current action ends. */
  private finishCurrentAction() {
    if (!this._actionPlaying) return
    this.clearTimers()
    const gen = this._settleGen
    const hold = this._settleHold

    if (gen !== this._actionGeneration) return

    // Process next queued action
    const next = this.actionQueue.shift()
    if (next) {
      this._actionPlaying = false
      this.playAction(next.name, next.hold)
      return
    }

    if (hold) {
      this.holdTimer = setTimeout(() => {
        if (gen !== this._actionGeneration) return
        this.clearTimers()
        // Drain any actions queued during hold before going idle โ€”
        // prevents the queue leak where LLM actions are silently dropped.
        const queued = this.actionQueue.shift()
        if (queued) {
          this._actionPlaying = false
          this.playAction(queued.name, queued.hold)
          return
        }
        this._actionPlaying = false
        this.startIdle()
      }, 10000)
    } else {
      this._actionPlaying = false
      this.startIdle()
    }
  }

  /** Cleanup when controller is being destroyed (model reload etc.) */
  dispose() {
    this.clearTimers()
    this._actionPlaying = false
    this._actionGeneration++
    if (this.mixer) {
      this.mixer.stopAllAction()
      this.mixer.uncacheRoot(this.vrm.scene)
      this.mixer = null
    }
    this.idleAction = null
    this.currentAction = null
  }

  // โ”€โ”€ Internal โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  private async loadClip(preset: MotionPreset): Promise<THREE.AnimationClip | null> {
    const cached = this.clipCache.get(preset.url)
    if (cached) return cached

    let clip: THREE.AnimationClip | null = null

    try {
      switch (preset.type) {
        case 'vrma':
          clip = await this.loadVRMA(preset.url)
          if (clip) reAnchorRootPositionTrack(clip, this.vrm)
          break
        case 'fbx':
          clip = await loadMixamoAnimation(preset.url, this.vrm)
          break
      }
    } catch (err) {
      console.error('Failed to load clip:', preset.url, err)
      return null
    }

    if (clip) {
      clip.name = preset.url
      this.clipCache.set(preset.url, clip)
    }
    return clip
  }

  private async loadVRMA(url: string): Promise<THREE.AnimationClip | null> {
    try {
      const gltf = await this.gltfLoader.loadAsync(url)
      const anims = gltf.userData.vrmAnimations as VRMAnimation[]
      if (anims?.length) {
        return createVRMAnimationClip(anims[0], this.vrm)
      }
    } catch (err) {
      console.warn(`Failed to load VRMA: ${url}`, err)
    }
    return null
  }
}