-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbabplay.html
More file actions
317 lines (264 loc) · 11.6 KB
/
babplay.html
File metadata and controls
317 lines (264 loc) · 11.6 KB
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
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>Babylon.js Play System</title>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<script src="https://cdn.babylonjs.com/babylon.js"></script>
<script src="https://cdn.babylonjs.com/loaders/babylonjs.loaders.js"></script>
<style>
html, body, #renderCanvas { width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden; background: #111; }
#ui {
position: fixed; bottom: 16px; left: 50%; transform: translateX(-50%);
font: 13px monospace; color: #fff; text-align: center;
display: flex; flex-direction: column; align-items: center; gap: 6px;
pointer-events: none;
}
#log {
position: fixed; top: 16px; left: 16px;
font: 12px monospace; color: #0f0;
background: rgba(0,0,0,0.7); padding: 10px; border-radius: 4px;
max-width: 420px; pointer-events: none;
}
</style>
</head>
<body>
<canvas id="renderCanvas"></canvas>
<div id="ui"><div id="status">Loading…</div></div>
<div id="log"></div>
<script type="module">
// -------------------------------------------------------------------------
// Coordinate space rules (must all hold simultaneously):
// 1. Camera alpha = -π/2 → avatar faces -Z
// 2. Rotation keyframes → conjugate 180°Y: (-qx, qy, -qz, qw)
// 3. Hips position → pre-negate X and Z
// -------------------------------------------------------------------------
const statusEl = document.getElementById('status');
const logEl = document.getElementById('log');
const logLines = [];
function log(msg) {
logLines.push(msg);
if (logLines.length > 12) logLines.shift();
logEl.textContent = logLines.join('\n');
console.log(msg);
}
// -------------------------------------------------------------------------
// Load VRM loader CDN
// -------------------------------------------------------------------------
await new Promise((resolve, reject) => {
const s = document.createElement('script');
s.src = 'https://xuhuisheng.github.io/babylonjs-vrm/babylon-vrm-loader.js';
s.onload = resolve; s.onerror = reject;
document.head.appendChild(s);
});
// -------------------------------------------------------------------------
// Scene
// -------------------------------------------------------------------------
const canvas = document.getElementById('renderCanvas');
const engine = new BABYLON.Engine(canvas, true);
engine.setHardwareScalingLevel(1);
const scene = new BABYLON.Scene(engine);
const camera = new BABYLON.ArcRotateCamera('cam', -Math.PI / 2, Math.PI / 2 - 0.12, 6,
new BABYLON.Vector3(0, 0.9, 0), scene);
camera.attachControl(canvas, true);
camera.lowerRadiusLimit = 0.5;
camera.upperRadiusLimit = 20;
new BABYLON.HemisphericLight('hemi', new BABYLON.Vector3(0, 1, 0), scene);
const dir = new BABYLON.DirectionalLight('dir', new BABYLON.Vector3(-1, -2, -1), scene);
dir.intensity = 0.5;
// -------------------------------------------------------------------------
// VrmaPlayer — single actor VRMA retargeter
// Multi-actor fix: does NOT clear vrmAnimationManagers globally.
// Instead captures the manager appended by this specific load.
// -------------------------------------------------------------------------
class VrmaPlayer {
constructor(scene, vrmManager) {
this.scene = scene;
this.vrmManager = vrmManager;
this.currentGroup = null;
this.currentContainer = null;
const hips = vrmManager.humanoidBone['hips'];
this.vrmHipsY = hips?.absolutePosition?.y ?? hips?.getAbsolutePosition?.().y ?? 1;
}
async play(vrmaUrl, loop = true) {
if (this.currentGroup) {
this.currentGroup.stop();
this.currentGroup.dispose();
this.currentGroup = null;
}
if (this.currentContainer) {
this.currentContainer.dispose();
this.currentContainer = null;
}
// Record how many managers exist before this load so we can grab ours after.
const managersBefore = (this.scene.metadata?.vrmAnimationManagers ?? []).length;
const container = await BABYLON.LoadAssetContainerAsync(vrmaUrl, this.scene);
this.currentContainer = container;
// Grab the manager appended by this load — never clear the whole array.
const managers = this.scene.metadata?.vrmAnimationManagers ?? [];
const vrmAnimManager = managers[managersBefore] ?? managers[managers.length - 1];
const animGroup = container.animationGroups[0];
if (!vrmAnimManager?.animationMap || !animGroup) {
console.warn('[VrmaPlayer] No animation data in', vrmaUrl);
return null;
}
// Translation scale
let translationScale = 1;
const hipsEntry = [...vrmAnimManager.animationMap.entries()]
.find(([, name]) => name === 'hips');
if (hipsEntry) {
const vrmaHipsY = animGroup.targetedAnimations[hipsEntry[0]]
?.target?.absolutePosition?.y ?? 0;
if (vrmaHipsY !== 0) translationScale = this.vrmHipsY / vrmaHipsY;
}
const remapped = new BABYLON.AnimationGroup('vrma-' + vrmaUrl, this.scene);
animGroup.targetedAnimations.forEach((targeted, i) => {
const boneName = vrmAnimManager.animationMap.get(i);
const bone = this.vrmManager.humanoidBone[boneName];
if (!bone) return;
const anim = targeted.animation.clone(`anim_${boneName}_${vrmaUrl}`);
if (anim.targetProperty === 'rotationQuaternion') {
anim.getKeys().forEach(kf => {
const q = kf.value;
kf.value = new BABYLON.Quaternion(-q.x, q.y, -q.z, q.w);
});
}
if (anim.targetProperty === 'position' && boneName === 'hips') {
anim.getKeys().forEach(kf => {
const v = kf.value.scale(translationScale);
kf.value = new BABYLON.Vector3(-v.x, v.y, -v.z);
});
}
remapped.addTargetedAnimation(anim, bone);
});
remapped.start(loop, 1.0, remapped.from, remapped.to, false);
remapped.goToFrame(remapped.from);
this.scene.render();
this.currentGroup = remapped;
log(`[VrmaPlayer] ${vrmaUrl} — ${remapped.targetedAnimations.length} tracks`);
return remapped;
}
stop() { this.currentGroup?.stop(); }
dispose() {
this.stop();
this.currentGroup?.dispose();
this.currentContainer?.dispose();
}
}
// -------------------------------------------------------------------------
// Actor — a VRM character in the scene with its own root node
// -------------------------------------------------------------------------
class Actor {
constructor(id, scene) {
this.id = id;
this.scene = scene;
this.player = null;
this.root = null;
}
async load(vrmUrl, pos, rotY = 0) {
log(`[Actor:${this.id}] loading ${vrmUrl}…`);
// Root node controls world position/rotation for this actor
this.root = new BABYLON.TransformNode(`actor_root_${this.id}`, this.scene);
this.root.position = new BABYLON.Vector3(pos.x, pos.y, pos.z);
this.root.rotation = new BABYLON.Vector3(0, rotY * Math.PI / 180, 0);
// Count meshes before import so we can parent only this actor's meshes
const meshCountBefore = this.scene.meshes.length;
await BABYLON.ImportMeshAsync(vrmUrl, this.scene);
// Parent all newly-added meshes/nodes to this actor's root
this.scene.meshes.slice(meshCountBefore).forEach(m => {
if (!m.parent) m.parent = this.root;
});
this.scene.transformNodes.forEach(n => {
if (n !== this.root && !n.parent && n.name.includes(this.id)) {
n.parent = this.root;
}
});
const managers = this.scene.metadata?.vrmManagers ?? [];
const vrmManager = managers[managers.length - 1];
if (!vrmManager) throw new Error(`[Actor:${this.id}] VRM manager not found`);
this.player = new VrmaPlayer(this.scene, vrmManager);
log(`[Actor:${this.id}] loaded`);
}
async animate(vrmaUrl, loop = true) {
log(`[Actor:${this.id}] animate ${vrmaUrl}`);
return this.player.play(vrmaUrl, loop);
}
stop() { this.player?.stop(); }
dispose() { this.player?.dispose(); this.root?.dispose(); }
}
// -------------------------------------------------------------------------
// PlayController — loads scene JSON, spawns actors, fires timeline
// -------------------------------------------------------------------------
class PlayController {
constructor(scene) {
this.scene = scene;
this.actors = new Map();
this.script = null;
this.clock = 0;
this._playing = false;
}
async loadScript(url) {
this.script = await fetch(url).then(r => r.json());
log(`[Play] script: "${this.script.metadata?.title}" — ${this.script.actors.length} actors, ${this.script.timeline.length} events`);
}
async preload() {
for (const actorDef of this.script.actors) {
const actor = new Actor(actorDef.id, this.scene);
await actor.load(
actorDef.vrm,
actorDef.startPosition ?? {x: 0, y: 0, z: 0},
actorDef.startRotation?.y ?? 0
);
this.actors.set(actorDef.id, actor);
}
log(`[Play] preload complete — ${this.actors.size} actors ready`);
}
async play() {
if (!this.script) throw new Error('Call loadScript() first');
this._playing = true;
this.clock = 0;
// Fire all t=0 events immediately
const pending = [...this.script.timeline].sort((a, b) => a.start - b.start);
const toFire = pending.filter(e => e.start === 0);
const future = pending.filter(e => e.start > 0);
for (const event of toFire) await this._fire(event);
// Schedule future events
future.forEach(event => {
setTimeout(() => this._fire(event), event.start * 1000);
});
window.playReady = true;
log('[Play] playing');
}
async _fire(event) {
const actor = this.actors.get(event.actor);
if (!actor) { log(`[Play] unknown actor: ${event.actor}`); return; }
log(`[Play] t=${event.start} ${event.actor} → ${event.action} ${event.clip ?? ''}`);
if (event.action === 'animate') {
await actor.animate(event.clip, event.loop ?? true);
} else if (event.action === 'stop') {
actor.stop();
}
}
stop() {
this._playing = false;
this.actors.forEach(a => a.stop());
}
}
// -------------------------------------------------------------------------
// Main
// -------------------------------------------------------------------------
window.playReady = false;
statusEl.textContent = 'Loading scene…';
const controller = new PlayController(scene);
await controller.loadScript('scenes/test_scene.json');
statusEl.textContent = 'Loading actors…';
await controller.preload();
statusEl.textContent = 'Playing…';
await controller.play();
statusEl.textContent = controller.script.metadata?.title ?? 'Playing';
window.playController = controller;
engine.runRenderLoop(() => scene.render());
window.addEventListener('resize', () => engine.resize());
</script>
</body>
</html>