@hackbuild/motion-views 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +175 -2
- package/dist/avatar-drop.d.ts +56 -0
- package/dist/avatar-drop.js +153 -0
- package/dist/character-stage.d.ts +85 -0
- package/dist/character-stage.js +367 -0
- package/dist/clip-strip.d.ts +48 -0
- package/dist/clip-strip.js +151 -0
- package/dist/clips.d.ts +53 -0
- package/dist/clips.js +39 -0
- package/dist/dom.d.ts +14 -0
- package/dist/dom.js +52 -0
- package/dist/elements.d.ts +26 -0
- package/dist/elements.js +120 -0
- package/dist/gestures.d.ts +14 -0
- package/dist/gestures.js +73 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +7 -0
- package/dist/motion-views.iife.js +15344 -0
- package/dist/single.d.ts +1 -0
- package/dist/single.js +3 -0
- package/dist/speech.d.ts +37 -0
- package/dist/speech.js +38 -0
- package/dist/thumb.d.ts +13 -0
- package/dist/thumb.js +62 -0
- package/dist/vanilla.d.ts +6 -0
- package/dist/vanilla.js +9 -0
- package/dist/vue.d.ts +169 -0
- package/dist/vue.js +112 -0
- package/dist/words.d.ts +57 -0
- package/dist/words.js +96 -0
- package/how.ts +27 -0
- package/llms.md +581 -0
- package/package.json +62 -4
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
// CharacterStage: a character on a lit stage, staged as the original twin
|
|
2
|
+
// page stages it. The avatar-host stage draws the body with its idle,
|
|
3
|
+
// gaze, blinks and lips; this view adds the corner plate (name, then what
|
|
4
|
+
// the body is doing), turn around and framing (bust or full body) at the
|
|
5
|
+
// top right, the verb row at the foot, an inset slot at the top left, and
|
|
6
|
+
// drop to replace the body. It writes into a `.hb-lay-stage` host, so it
|
|
7
|
+
// sits in the stage and rack layout of hackbuild-ui as it is.
|
|
8
|
+
import { Box3, Vector3 } from "three";
|
|
9
|
+
import { bandsFromSpectrum, rms } from "@hackbuild/lipsync";
|
|
10
|
+
import { estimateSeconds, speechEvents } from "./speech.js";
|
|
11
|
+
import { posedBounds } from "@hackbuild/avatar/three";
|
|
12
|
+
import { AvatarStage } from "@hackbuild/avatar-host/three";
|
|
13
|
+
import { dropRoutes } from "@virgilvox/hackbuild-ui/vanilla";
|
|
14
|
+
import { button, el, iconButton, part } from "./dom.js";
|
|
15
|
+
import { GESTURES, gestureClip } from "./gestures.js";
|
|
16
|
+
/** The verbs a stage shows by default: say hello is the next thing to do. */
|
|
17
|
+
export const DEFAULT_VERBS = [
|
|
18
|
+
{ id: "say", label: "say hello", go: true },
|
|
19
|
+
{ id: "wave", label: "wave" },
|
|
20
|
+
{ id: "nod", label: "nod" },
|
|
21
|
+
{ id: "look", label: "look around" },
|
|
22
|
+
];
|
|
23
|
+
const HELLO = "hello. drop a vrm, glb or fbx on me and i will wear it.";
|
|
24
|
+
/** Mounts a character stage into `host`, which becomes the `.hb-lay-stage`. */
|
|
25
|
+
export function characterStage(host, opts = {}) {
|
|
26
|
+
const doc = host.ownerDocument;
|
|
27
|
+
host.classList.add("hb-lay-stage");
|
|
28
|
+
const subject = part(host, "hb-lay-subject", () => el(doc, "div", "hb-lay-subject"));
|
|
29
|
+
subject.classList.add("hb-stage-lit");
|
|
30
|
+
subject.dataset.ux = "subject";
|
|
31
|
+
if (!subject.getAttribute("aria-label"))
|
|
32
|
+
subject.setAttribute("aria-label", "the character");
|
|
33
|
+
const inset = part(host, "hb-lay-inset", () => el(doc, "div", "hb-lay-inset"));
|
|
34
|
+
inset.dataset.ux = "inset";
|
|
35
|
+
const verbsEl = part(host, "hb-lay-verbs", () => el(doc, "div", "hb-lay-verbs", { role: "toolbar", "aria-label": "what he does" }));
|
|
36
|
+
verbsEl.dataset.ux = "verbs";
|
|
37
|
+
// the plate and the two stage tools, top right, as the original has them
|
|
38
|
+
const nameEl = el(doc, "b", "", {}, [opts.name ?? ""]);
|
|
39
|
+
const doingEl = el(doc, "span", "", { "aria-live": "polite" }, ["idle"]);
|
|
40
|
+
const turnBtn = iconButton(doc, "flip", "turn around");
|
|
41
|
+
const frameBtn = iconButton(doc, "frame", "full body", { "aria-pressed": "false" });
|
|
42
|
+
const tag = el(doc, "div", "hb-stage-tag", {}, [nameEl, doingEl]);
|
|
43
|
+
const tagCorner = el(doc, "div", "hb-ov hb-ov-tl");
|
|
44
|
+
const corner = el(doc, "div", "hb-ov hb-ov-tr", {}, [turnBtn, frameBtn]);
|
|
45
|
+
// the stage first, so its canvas sits under the plate
|
|
46
|
+
const stage = new AvatarStage(subject, opts);
|
|
47
|
+
subject.append(tagCorner, corner);
|
|
48
|
+
const listeners = new Set();
|
|
49
|
+
const emit = (e) => {
|
|
50
|
+
for (const f of listeners)
|
|
51
|
+
f(e);
|
|
52
|
+
};
|
|
53
|
+
let framing = opts.framing ?? "bust";
|
|
54
|
+
let doing = "idle";
|
|
55
|
+
let doingTimer;
|
|
56
|
+
const setDoing = (word, seconds = 0) => {
|
|
57
|
+
clearTimeout(doingTimer);
|
|
58
|
+
doing = word;
|
|
59
|
+
doingEl.textContent = word;
|
|
60
|
+
emit({ type: "doing", word });
|
|
61
|
+
if (seconds > 0)
|
|
62
|
+
doingTimer = setTimeout(() => setDoing("idle"), seconds * 1000);
|
|
63
|
+
};
|
|
64
|
+
// the plate sits top left as in the original; with an inset there, it moves over the tools
|
|
65
|
+
const syncInset = () => {
|
|
66
|
+
inset.hidden = inset.childElementCount === 0;
|
|
67
|
+
if (inset.hidden)
|
|
68
|
+
tagCorner.append(tag);
|
|
69
|
+
else
|
|
70
|
+
corner.prepend(tag);
|
|
71
|
+
};
|
|
72
|
+
const insetWatch = new MutationObserver(syncInset);
|
|
73
|
+
insetWatch.observe(inset, { childList: true });
|
|
74
|
+
syncInset();
|
|
75
|
+
const offs = [];
|
|
76
|
+
offs.push(stage.on("loaded", (e) => {
|
|
77
|
+
if (!opts.name)
|
|
78
|
+
nameEl.textContent = e.placeholder ? "stand-in" : e.name;
|
|
79
|
+
applyFraming();
|
|
80
|
+
setDoing("idle");
|
|
81
|
+
emit({ type: "loaded", name: e.name, caps: e.caps, warnings: e.warnings, placeholder: e.placeholder });
|
|
82
|
+
}), stage.on("failed", (e) => emit({ type: "failed", message: e.message })));
|
|
83
|
+
// bust: the knees to the top of the head, the original's opening shot; full: the follow camera
|
|
84
|
+
function applyFraming() {
|
|
85
|
+
const body = stage.body;
|
|
86
|
+
frameBtn.setAttribute("aria-pressed", String(framing === "full"));
|
|
87
|
+
frameBtn.setAttribute("aria-label", framing === "full" ? "head and shoulders" : "full body");
|
|
88
|
+
frameBtn.title = frameBtn.getAttribute("aria-label");
|
|
89
|
+
if (!body)
|
|
90
|
+
return;
|
|
91
|
+
if (framing === "full") {
|
|
92
|
+
stage.setFollow(true);
|
|
93
|
+
stage.resetView();
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const bones = body.avatar.bones;
|
|
97
|
+
body.avatar.root.updateMatrixWorld(true);
|
|
98
|
+
const all = posedBounds(bones, 0.04);
|
|
99
|
+
const h = Math.max(0.3, all.max.y - all.min.y);
|
|
100
|
+
const knee = (bones.leftLowerLeg ?? bones.rightLowerLeg ?? bones.hips)?.getWorldPosition(new Vector3());
|
|
101
|
+
const head = bones.head?.getWorldPosition(new Vector3());
|
|
102
|
+
if (!knee || !head) {
|
|
103
|
+
stage.setFollow(true);
|
|
104
|
+
stage.resetView();
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
// the original's opening shot: from the knees to just over the head
|
|
108
|
+
const top = Math.max(all.max.y, head.y + 0.08 * h) + 0.04 * h;
|
|
109
|
+
const box = new Box3(new Vector3(head.x - 0.2 * h, knee.y, head.z - 0.1 * h), new Vector3(head.x + 0.2 * h, top, head.z + 0.1 * h));
|
|
110
|
+
stage.setFollow(false);
|
|
111
|
+
stage.follow.frame(box);
|
|
112
|
+
stage.controls.update();
|
|
113
|
+
stage.loop.invalidate();
|
|
114
|
+
}
|
|
115
|
+
function frame(mode) {
|
|
116
|
+
framing = mode;
|
|
117
|
+
applyFraming();
|
|
118
|
+
emit({ type: "framing", framing });
|
|
119
|
+
}
|
|
120
|
+
function turn() {
|
|
121
|
+
const body = stage.body;
|
|
122
|
+
if (!body)
|
|
123
|
+
return;
|
|
124
|
+
body.avatar.root.rotation.y += Math.PI;
|
|
125
|
+
stage.loop.invalidate();
|
|
126
|
+
}
|
|
127
|
+
function play(clip, o = {}) {
|
|
128
|
+
const body = stage.body;
|
|
129
|
+
if (!body)
|
|
130
|
+
return -1;
|
|
131
|
+
const ticket = body.play(clip, { fade: 0.15, ...o });
|
|
132
|
+
if (ticket < 0)
|
|
133
|
+
return ticket;
|
|
134
|
+
const name = typeof clip === "string" ? clip : clip.name;
|
|
135
|
+
const loop = o.loop ?? (typeof clip === "object" && "loop" in clip ? clip.loop : false);
|
|
136
|
+
const seconds = typeof clip === "object" ? ("frames" in clip ? (clip.frames - 1) / clip.fps : clip.duration) : 0;
|
|
137
|
+
setDoing(name || "a clip", loop ? 0 : seconds);
|
|
138
|
+
stage.loop.sync();
|
|
139
|
+
return ticket;
|
|
140
|
+
}
|
|
141
|
+
function stop() {
|
|
142
|
+
stage.body?.stop("body");
|
|
143
|
+
stage.body?.stop("upper");
|
|
144
|
+
stage.body?.lip.stop();
|
|
145
|
+
setDoing("idle");
|
|
146
|
+
stage.loop.sync();
|
|
147
|
+
}
|
|
148
|
+
function gesture(id) {
|
|
149
|
+
const body = stage.body;
|
|
150
|
+
if (!body)
|
|
151
|
+
return false;
|
|
152
|
+
const base = new Float32Array(body.bones.length * 4);
|
|
153
|
+
body.bones.forEach((b, i) => b.quaternion.toArray(base, i * 4));
|
|
154
|
+
const clip = gestureClip(id, body.names, base);
|
|
155
|
+
if (!clip)
|
|
156
|
+
return false;
|
|
157
|
+
return play(clip, { layer: id === "bow" ? "body" : "upper" }) >= 0;
|
|
158
|
+
}
|
|
159
|
+
// real speech: the audio plays through an analyser, its level and bands
|
|
160
|
+
// open the mouth between the timings the engine gave; text alone is
|
|
161
|
+
// spoken on estimated timings with no sound
|
|
162
|
+
let speaking = 0;
|
|
163
|
+
let audioCtx = opts.audioContext ?? null;
|
|
164
|
+
const elementSources = new WeakMap();
|
|
165
|
+
let stopAudio = null;
|
|
166
|
+
let lastSource = null;
|
|
167
|
+
async function say(input, seconds) {
|
|
168
|
+
const body = stage.body;
|
|
169
|
+
const sp = typeof input === "string" ? { text: input } : input;
|
|
170
|
+
if (!body || (!sp.audio && !sp.text?.trim() && !sp.events?.length))
|
|
171
|
+
return;
|
|
172
|
+
const mine = ++speaking;
|
|
173
|
+
stopAudio?.();
|
|
174
|
+
stopAudio = null;
|
|
175
|
+
let dur = seconds ?? (sp.text ? estimateSeconds(sp.text) : 1);
|
|
176
|
+
let start = null;
|
|
177
|
+
let ended = null;
|
|
178
|
+
let analyser = null;
|
|
179
|
+
if (sp.audio) {
|
|
180
|
+
audioCtx ??= new AudioContext();
|
|
181
|
+
const ctx = audioCtx;
|
|
182
|
+
// a page with no press yet keeps the context suspended; the mouth still moves on the timings
|
|
183
|
+
if (ctx.state === "suspended")
|
|
184
|
+
await Promise.race([ctx.resume().catch(() => undefined), new Promise((ok) => setTimeout(ok, 300))]);
|
|
185
|
+
analyser = ctx.createAnalyser();
|
|
186
|
+
analyser.fftSize = 1024;
|
|
187
|
+
analyser.connect(ctx.destination);
|
|
188
|
+
const a = sp.audio;
|
|
189
|
+
if (a instanceof AudioBuffer) {
|
|
190
|
+
const node = ctx.createBufferSource();
|
|
191
|
+
node.buffer = a;
|
|
192
|
+
node.connect(analyser);
|
|
193
|
+
dur = a.duration;
|
|
194
|
+
ended = new Promise((ok) => (node.onended = () => ok()));
|
|
195
|
+
start = () => node.start();
|
|
196
|
+
stopAudio = () => {
|
|
197
|
+
node.onended = null;
|
|
198
|
+
try {
|
|
199
|
+
node.stop();
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
// never started
|
|
203
|
+
}
|
|
204
|
+
node.disconnect();
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
else {
|
|
208
|
+
let node = elementSources.get(a);
|
|
209
|
+
if (!node)
|
|
210
|
+
elementSources.set(a, (node = ctx.createMediaElementSource(a)));
|
|
211
|
+
node.disconnect();
|
|
212
|
+
node.connect(analyser);
|
|
213
|
+
if (!(a.duration > 0))
|
|
214
|
+
await new Promise((ok) => a.addEventListener("loadedmetadata", ok, { once: true }));
|
|
215
|
+
dur = Number.isFinite(a.duration) ? a.duration : dur;
|
|
216
|
+
ended = new Promise((ok) => a.addEventListener("ended", () => ok(), { once: true }));
|
|
217
|
+
start = () => {
|
|
218
|
+
a.currentTime = 0;
|
|
219
|
+
void a.play();
|
|
220
|
+
};
|
|
221
|
+
stopAudio = () => {
|
|
222
|
+
a.pause();
|
|
223
|
+
node.disconnect();
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
if (mine !== speaking || stage.body !== body)
|
|
228
|
+
return;
|
|
229
|
+
const t0 = stage.loop.time;
|
|
230
|
+
const { events, source } = speechEvents(sp, t0, dur);
|
|
231
|
+
lastSource = source;
|
|
232
|
+
body.lip.stop();
|
|
233
|
+
body.lip.push(events);
|
|
234
|
+
body.setGazeMode("talk");
|
|
235
|
+
setDoing("talking");
|
|
236
|
+
stage.loop.sync();
|
|
237
|
+
start?.();
|
|
238
|
+
if (analyser && audioCtx) {
|
|
239
|
+
const an = analyser;
|
|
240
|
+
const rate = audioCtx.sampleRate;
|
|
241
|
+
const wave = new Float32Array(an.fftSize);
|
|
242
|
+
const spectrum = new Uint8Array(an.frequencyBinCount);
|
|
243
|
+
const tick = () => {
|
|
244
|
+
if (mine !== speaking)
|
|
245
|
+
return;
|
|
246
|
+
an.getFloatTimeDomainData(wave);
|
|
247
|
+
an.getByteFrequencyData(spectrum);
|
|
248
|
+
stage.body?.lip.setLevel(rms(wave), bandsFromSpectrum(spectrum, rate, an.fftSize));
|
|
249
|
+
stage.loop.sync();
|
|
250
|
+
requestAnimationFrame(tick);
|
|
251
|
+
};
|
|
252
|
+
requestAnimationFrame(tick);
|
|
253
|
+
}
|
|
254
|
+
await Promise.race([ended ?? new Promise(() => undefined), new Promise((ok) => setTimeout(ok, dur * 1000 + (ended ? 500 : 0)))]);
|
|
255
|
+
if (mine !== speaking)
|
|
256
|
+
return;
|
|
257
|
+
speaking++;
|
|
258
|
+
stopAudio?.();
|
|
259
|
+
stopAudio = null;
|
|
260
|
+
analyser?.disconnect();
|
|
261
|
+
stage.body?.lip.setLevel(0);
|
|
262
|
+
stage.body?.setGazeMode("listen");
|
|
263
|
+
if (doing === "talking")
|
|
264
|
+
setDoing("idle");
|
|
265
|
+
}
|
|
266
|
+
function look() {
|
|
267
|
+
const body = stage.body;
|
|
268
|
+
if (!body)
|
|
269
|
+
return;
|
|
270
|
+
body.setGazeMode("think");
|
|
271
|
+
setDoing("looking around", 3);
|
|
272
|
+
stage.loop.sync();
|
|
273
|
+
setTimeout(() => stage.body?.setGazeMode("listen"), 3000);
|
|
274
|
+
}
|
|
275
|
+
function runVerb(id) {
|
|
276
|
+
emit({ type: "verb", id });
|
|
277
|
+
if (id === "say") {
|
|
278
|
+
const h = opts.hello ?? HELLO;
|
|
279
|
+
void Promise.resolve(typeof h === "function" ? h() : h).then((sp) => say(sp));
|
|
280
|
+
}
|
|
281
|
+
else if (id === "look")
|
|
282
|
+
look();
|
|
283
|
+
else if (id === "turn")
|
|
284
|
+
turn();
|
|
285
|
+
else if (GESTURES.includes(id))
|
|
286
|
+
gesture(id);
|
|
287
|
+
}
|
|
288
|
+
function setVerbs(verbs) {
|
|
289
|
+
verbsEl.replaceChildren(...verbs.map((v) => button(doc, v.label, v.go === true, { "data-verb": v.id })));
|
|
290
|
+
verbsEl.hidden = verbs.length === 0;
|
|
291
|
+
}
|
|
292
|
+
const ac = new AbortController();
|
|
293
|
+
verbsEl.addEventListener("click", (e) => {
|
|
294
|
+
const b = e.target.closest("[data-verb]");
|
|
295
|
+
if (b && verbsEl.contains(b))
|
|
296
|
+
runVerb(b.dataset.verb);
|
|
297
|
+
}, { signal: ac.signal });
|
|
298
|
+
turnBtn.addEventListener("click", turn, { signal: ac.signal });
|
|
299
|
+
frameBtn.addEventListener("click", () => frame(framing === "bust" ? "full" : "bust"), { signal: ac.signal });
|
|
300
|
+
// the follow camera reframes on resize in full; bust is fixed, so it is framed again
|
|
301
|
+
const ro = new ResizeObserver(() => framing === "bust" && applyFraming());
|
|
302
|
+
ro.observe(subject);
|
|
303
|
+
const drop = opts.drop === false
|
|
304
|
+
? null
|
|
305
|
+
: dropRoutes(subject, [{ name: "model", accept: () => true, on: (files) => void show(files) }], { overlay: subject });
|
|
306
|
+
function show(source) {
|
|
307
|
+
setDoing("loading");
|
|
308
|
+
return stage.show(source).then((b) => {
|
|
309
|
+
if (!b)
|
|
310
|
+
setDoing("idle");
|
|
311
|
+
return b;
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
setVerbs(opts.verbs ?? DEFAULT_VERBS);
|
|
315
|
+
if (opts.src) {
|
|
316
|
+
stage.showPlaceholder();
|
|
317
|
+
void show(opts.src);
|
|
318
|
+
}
|
|
319
|
+
else
|
|
320
|
+
stage.showPlaceholder();
|
|
321
|
+
return {
|
|
322
|
+
stage,
|
|
323
|
+
get body() {
|
|
324
|
+
return stage.body;
|
|
325
|
+
},
|
|
326
|
+
inset,
|
|
327
|
+
verbsEl,
|
|
328
|
+
subject,
|
|
329
|
+
get doing() {
|
|
330
|
+
return doing;
|
|
331
|
+
},
|
|
332
|
+
get framing() {
|
|
333
|
+
return framing;
|
|
334
|
+
},
|
|
335
|
+
get speechSource() {
|
|
336
|
+
return lastSource;
|
|
337
|
+
},
|
|
338
|
+
show,
|
|
339
|
+
showPlaceholder: () => void stage.showPlaceholder(),
|
|
340
|
+
say,
|
|
341
|
+
gesture,
|
|
342
|
+
play,
|
|
343
|
+
stop,
|
|
344
|
+
turn,
|
|
345
|
+
frame,
|
|
346
|
+
setVerbs,
|
|
347
|
+
on(fn) {
|
|
348
|
+
listeners.add(fn);
|
|
349
|
+
return () => listeners.delete(fn);
|
|
350
|
+
},
|
|
351
|
+
dispose() {
|
|
352
|
+
clearTimeout(doingTimer);
|
|
353
|
+
speaking++;
|
|
354
|
+
stopAudio?.();
|
|
355
|
+
ac.abort();
|
|
356
|
+
ro.disconnect();
|
|
357
|
+
insetWatch.disconnect();
|
|
358
|
+
drop?.dispose();
|
|
359
|
+
for (const off of offs)
|
|
360
|
+
off();
|
|
361
|
+
listeners.clear();
|
|
362
|
+
stage.dispose();
|
|
363
|
+
corner.remove();
|
|
364
|
+
tagCorner.remove();
|
|
365
|
+
},
|
|
366
|
+
};
|
|
367
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { AnimationClip } from "three";
|
|
2
|
+
import { type ClipItem } from "./clips.js";
|
|
3
|
+
/** A clip in the strip; `animation` lets the strip draw its still. */
|
|
4
|
+
export interface StripItem extends ClipItem {
|
|
5
|
+
animation?: () => AnimationClip | Promise<AnimationClip>;
|
|
6
|
+
}
|
|
7
|
+
/** Options of `clipStrip`: the items, the picked clip, the play button and stills. */
|
|
8
|
+
export interface ClipStripOptions {
|
|
9
|
+
items?: readonly StripItem[];
|
|
10
|
+
/** The picked clip; default the first. */
|
|
11
|
+
current?: string | null;
|
|
12
|
+
/** The play button is the one pink action of the screen. Default true. */
|
|
13
|
+
go?: boolean;
|
|
14
|
+
/** Accessible name of the strip. */
|
|
15
|
+
label?: string;
|
|
16
|
+
/** Draw missing stills from `animation`. Default true. */
|
|
17
|
+
thumbs?: boolean;
|
|
18
|
+
}
|
|
19
|
+
/** Events of ClipStrip: a clip picked, play or stop pressed, a still drawn or failed. */
|
|
20
|
+
export type ClipStripEvent = {
|
|
21
|
+
type: "pick";
|
|
22
|
+
item: StripItem;
|
|
23
|
+
} | {
|
|
24
|
+
type: "play";
|
|
25
|
+
item: StripItem;
|
|
26
|
+
} | {
|
|
27
|
+
type: "stop";
|
|
28
|
+
item: StripItem;
|
|
29
|
+
} | {
|
|
30
|
+
type: "thumb";
|
|
31
|
+
id: string;
|
|
32
|
+
ok: boolean;
|
|
33
|
+
};
|
|
34
|
+
/** The handle `clipStrip` returns: set items, pick, set the play state, wait for stills, listen. */
|
|
35
|
+
export interface ClipStripHandle {
|
|
36
|
+
readonly current: StripItem | null;
|
|
37
|
+
readonly playing: boolean;
|
|
38
|
+
setItems(items: readonly StripItem[], current?: string | null): void;
|
|
39
|
+
pick(id: string): void;
|
|
40
|
+
/** The play state as the page knows it: true while the picked clip plays. */
|
|
41
|
+
setPlaying(on: boolean): void;
|
|
42
|
+
/** Resolves when every still asked for so far is drawn or has failed. */
|
|
43
|
+
thumbsIdle(): Promise<void>;
|
|
44
|
+
on(fn: (e: ClipStripEvent) => void): () => void;
|
|
45
|
+
dispose(): void;
|
|
46
|
+
}
|
|
47
|
+
/** Mounts a clip strip into `host`. */
|
|
48
|
+
export declare function clipStrip(host: HTMLElement, opts?: ClipStripOptions): ClipStripHandle;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { button, el } from "./dom.js";
|
|
2
|
+
import { clipMeta, nextClip } from "./clips.js";
|
|
3
|
+
import { secondsWord } from "./words.js";
|
|
4
|
+
/** Mounts a clip strip into `host`. */
|
|
5
|
+
export function clipStrip(host, opts = {}) {
|
|
6
|
+
const doc = host.ownerDocument;
|
|
7
|
+
// hackbuild-ui's clip strip: name and length per clip, the picked one pressed, the playing one marked
|
|
8
|
+
const list = el(doc, "ul", "hb-clipstrip", { "aria-label": opts.label ?? "clips" });
|
|
9
|
+
const playBtn = button(doc, "play", opts.go !== false, { "data-play": "" });
|
|
10
|
+
host.append(list, playBtn);
|
|
11
|
+
const listeners = new Set();
|
|
12
|
+
const emit = (e) => {
|
|
13
|
+
for (const f of listeners)
|
|
14
|
+
f(e);
|
|
15
|
+
};
|
|
16
|
+
let items = [];
|
|
17
|
+
let current = null;
|
|
18
|
+
let playing = false;
|
|
19
|
+
const urls = new Map();
|
|
20
|
+
const failed = new Set();
|
|
21
|
+
let queue = null;
|
|
22
|
+
let disposed = false;
|
|
23
|
+
const thumbSrc = (it) => {
|
|
24
|
+
if (typeof it.thumb === "string")
|
|
25
|
+
return it.thumb;
|
|
26
|
+
const have = urls.get(it.id);
|
|
27
|
+
if (have)
|
|
28
|
+
return have;
|
|
29
|
+
if (it.thumb instanceof Blob) {
|
|
30
|
+
const u = URL.createObjectURL(it.thumb);
|
|
31
|
+
urls.set(it.id, u);
|
|
32
|
+
return u;
|
|
33
|
+
}
|
|
34
|
+
return "";
|
|
35
|
+
};
|
|
36
|
+
function render() {
|
|
37
|
+
list.replaceChildren(...items.map((it) => {
|
|
38
|
+
const src = thumbSrc(it);
|
|
39
|
+
const meta = clipMeta(it);
|
|
40
|
+
const on = it.id === current;
|
|
41
|
+
const kids = [];
|
|
42
|
+
if (src)
|
|
43
|
+
kids.push(el(doc, "img", "", { src, alt: "", width: 48, height: 48, loading: "lazy" }));
|
|
44
|
+
kids.push(el(doc, "span", "hb-clipstrip-name", {}, [it.name]), el(doc, "span", "hb-clipstrip-len", {}, [secondsWord(it.seconds)]));
|
|
45
|
+
const b = el(doc, "button", "", { type: "button", "data-id": it.id, "aria-pressed": String(on), "aria-current": on && playing ? "true" : null, title: it.warn ? `${it.name}, ${meta}. ${it.warn}` : `${it.name}, ${meta}` }, kids);
|
|
46
|
+
return el(doc, "li", `hb-clipstrip-item${on ? " is-on" : ""}${on && playing ? " is-playing" : ""}`, {}, [b]);
|
|
47
|
+
}));
|
|
48
|
+
const cur = items.find((i) => i.id === current);
|
|
49
|
+
playBtn.hidden = !cur;
|
|
50
|
+
playBtn.textContent = playing ? "stop" : cur ? `play ${cur.name}` : "play";
|
|
51
|
+
}
|
|
52
|
+
function wantThumbs() {
|
|
53
|
+
if (opts.thumbs === false)
|
|
54
|
+
return;
|
|
55
|
+
const jobs = items.filter((i) => !i.thumb && i.animation && !urls.has(i.id) && !failed.has(i.id)).map((i) => ({ id: i.id, clip: i.animation }));
|
|
56
|
+
if (!jobs.length)
|
|
57
|
+
return;
|
|
58
|
+
queue ??= import("@hackbuild/avatar-host/thumbs").then(({ clipThumbs }) => clipThumbs({
|
|
59
|
+
save: async (id, png) => {
|
|
60
|
+
if (disposed)
|
|
61
|
+
return;
|
|
62
|
+
urls.set(id, URL.createObjectURL(png));
|
|
63
|
+
render();
|
|
64
|
+
emit({ type: "thumb", id, ok: true });
|
|
65
|
+
},
|
|
66
|
+
failed: (id) => {
|
|
67
|
+
failed.add(id);
|
|
68
|
+
emit({ type: "thumb", id, ok: false });
|
|
69
|
+
},
|
|
70
|
+
}));
|
|
71
|
+
void queue.then((q) => q.want(jobs));
|
|
72
|
+
}
|
|
73
|
+
function setItems(next, cur) {
|
|
74
|
+
items = next;
|
|
75
|
+
const keep = cur !== undefined ? cur : current;
|
|
76
|
+
current = keep && items.some((i) => i.id === keep) ? keep : (items[0]?.id ?? null);
|
|
77
|
+
playing = false;
|
|
78
|
+
render();
|
|
79
|
+
wantThumbs();
|
|
80
|
+
}
|
|
81
|
+
function pick(id) {
|
|
82
|
+
const it = items.find((i) => i.id === id);
|
|
83
|
+
if (!it)
|
|
84
|
+
return;
|
|
85
|
+
const was = current;
|
|
86
|
+
current = id;
|
|
87
|
+
render();
|
|
88
|
+
list.querySelector(`[data-id="${CSS.escape(id)}"]`)?.focus();
|
|
89
|
+
if (was !== id || !playing)
|
|
90
|
+
emit({ type: "pick", item: it });
|
|
91
|
+
}
|
|
92
|
+
const ac = new AbortController();
|
|
93
|
+
list.addEventListener("click", (e) => {
|
|
94
|
+
const b = e.target.closest("[data-id]");
|
|
95
|
+
if (b)
|
|
96
|
+
pick(b.dataset.id);
|
|
97
|
+
}, { signal: ac.signal });
|
|
98
|
+
list.addEventListener("keydown", (e) => {
|
|
99
|
+
const step = e.key === "ArrowRight" || e.key === "ArrowDown" ? 1 : e.key === "ArrowLeft" || e.key === "ArrowUp" ? -1 : 0;
|
|
100
|
+
if (!step)
|
|
101
|
+
return;
|
|
102
|
+
e.preventDefault();
|
|
103
|
+
const id = nextClip(items, current, step);
|
|
104
|
+
if (id)
|
|
105
|
+
pick(id);
|
|
106
|
+
}, { signal: ac.signal });
|
|
107
|
+
playBtn.addEventListener("click", () => {
|
|
108
|
+
const it = items.find((i) => i.id === current);
|
|
109
|
+
if (!it)
|
|
110
|
+
return;
|
|
111
|
+
playing = !playing;
|
|
112
|
+
render();
|
|
113
|
+
emit({ type: playing ? "play" : "stop", item: it });
|
|
114
|
+
}, { signal: ac.signal });
|
|
115
|
+
setItems(opts.items ?? [], opts.current ?? null);
|
|
116
|
+
return {
|
|
117
|
+
get current() {
|
|
118
|
+
return items.find((i) => i.id === current) ?? null;
|
|
119
|
+
},
|
|
120
|
+
get playing() {
|
|
121
|
+
return playing;
|
|
122
|
+
},
|
|
123
|
+
setItems,
|
|
124
|
+
pick,
|
|
125
|
+
setPlaying(on) {
|
|
126
|
+
if (playing === on)
|
|
127
|
+
return;
|
|
128
|
+
playing = on;
|
|
129
|
+
render();
|
|
130
|
+
},
|
|
131
|
+
async thumbsIdle() {
|
|
132
|
+
if (queue)
|
|
133
|
+
await (await queue).idle();
|
|
134
|
+
},
|
|
135
|
+
on(fn) {
|
|
136
|
+
listeners.add(fn);
|
|
137
|
+
return () => listeners.delete(fn);
|
|
138
|
+
},
|
|
139
|
+
dispose() {
|
|
140
|
+
disposed = true;
|
|
141
|
+
ac.abort();
|
|
142
|
+
void queue?.then((q) => q.destroy());
|
|
143
|
+
for (const u of urls.values())
|
|
144
|
+
URL.revokeObjectURL(u);
|
|
145
|
+
urls.clear();
|
|
146
|
+
listeners.clear();
|
|
147
|
+
list.remove();
|
|
148
|
+
playBtn.remove();
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
}
|
package/dist/clips.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** Where a clip came from: a baked pack, a retarget, the body's own file, or code. */
|
|
2
|
+
export type ClipFrom = "bake" | "retarget" | "body" | "code";
|
|
3
|
+
/** One clip as the strip shows it: id, name, length, loop, source, tags, warning and still. */
|
|
4
|
+
export interface ClipItem {
|
|
5
|
+
id: string;
|
|
6
|
+
name: string;
|
|
7
|
+
/** Length in seconds. */
|
|
8
|
+
seconds: number;
|
|
9
|
+
loop: boolean;
|
|
10
|
+
from: ClipFrom;
|
|
11
|
+
/** Words for what the body does: walk, wave, nod. */
|
|
12
|
+
tags?: string[];
|
|
13
|
+
/** A problem a person should see before they pick it: "the loop jumps 14 degrees at the seam". */
|
|
14
|
+
warn?: string;
|
|
15
|
+
/** A thumbnail: an image URL or a PNG Blob. The strip draws one from `clip` when this is missing. */
|
|
16
|
+
thumb?: string | Blob;
|
|
17
|
+
}
|
|
18
|
+
/** The strip's second line: "2.4 s, loops" or "walk, 2.4 s, loops". */
|
|
19
|
+
export declare function clipMeta(c: Pick<ClipItem, "seconds" | "loop" | "tags">): string;
|
|
20
|
+
/** What bake's decodePack returns, in the fields the strip reads. */
|
|
21
|
+
export interface PackLike {
|
|
22
|
+
fps: number;
|
|
23
|
+
clips: Record<string, {
|
|
24
|
+
name: string;
|
|
25
|
+
dur: number;
|
|
26
|
+
n: number;
|
|
27
|
+
loop: boolean;
|
|
28
|
+
}>;
|
|
29
|
+
}
|
|
30
|
+
/** What bake's bakeClips reports per clip, in the fields the strip reads. */
|
|
31
|
+
export interface PackReportLike {
|
|
32
|
+
name: string;
|
|
33
|
+
seamAngleDeg: number | null;
|
|
34
|
+
seamOk: boolean | null;
|
|
35
|
+
maxAngleErrorDeg: number;
|
|
36
|
+
}
|
|
37
|
+
/** Items from a clip pack, with the bake report's seam check as a warning. */
|
|
38
|
+
export declare function clipsFromPack(pack: PackLike, report?: readonly PackReportLike[], prefix?: string): ClipItem[];
|
|
39
|
+
/** What retarget's analyzeMotion returns, in the fields the strip reads. */
|
|
40
|
+
export interface FindingsLike {
|
|
41
|
+
duration: number;
|
|
42
|
+
looping: boolean;
|
|
43
|
+
tags: readonly string[];
|
|
44
|
+
}
|
|
45
|
+
/** An item from a retargeted motion and its findings. */
|
|
46
|
+
export declare function clipFromFindings(id: string, name: string, f: FindingsLike): ClipItem;
|
|
47
|
+
/** Items for the clips a loaded file carries, by name and length. */
|
|
48
|
+
export declare function clipsFromBody(clips: readonly {
|
|
49
|
+
name: string;
|
|
50
|
+
duration: number;
|
|
51
|
+
}[], prefix?: string): ClipItem[];
|
|
52
|
+
/** The next id after `id` in the strip, wrapping, for a key or a play all. */
|
|
53
|
+
export declare function nextClip(items: readonly ClipItem[], id: string | null, step?: number): string | null;
|
package/dist/clips.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Clip items for the strip: one shape for clips from a baked pack
|
|
2
|
+
// (@hackbuild/bake), from a retarget (@hackbuild/retarget) and from a body's
|
|
3
|
+
// own file. The adapters read structural types, so this entry needs neither
|
|
4
|
+
// wasm package; pass what bake and retarget hand back.
|
|
5
|
+
import { secondsWord } from "./words.js";
|
|
6
|
+
/** The strip's second line: "2.4 s, loops" or "walk, 2.4 s, loops". */
|
|
7
|
+
export function clipMeta(c) {
|
|
8
|
+
const tag = c.tags?.[0];
|
|
9
|
+
return [tag, secondsWord(c.seconds), c.loop ? "loops" : "once"].filter(Boolean).join(", ");
|
|
10
|
+
}
|
|
11
|
+
/** Items from a clip pack, with the bake report's seam check as a warning. */
|
|
12
|
+
export function clipsFromPack(pack, report = [], prefix = "pack") {
|
|
13
|
+
const by = new Map(report.map((r) => [r.name, r]));
|
|
14
|
+
return Object.values(pack.clips).map((c) => {
|
|
15
|
+
const r = by.get(c.name);
|
|
16
|
+
const item = { id: `${prefix}:${c.name}`, name: c.name, seconds: c.n > 1 ? (c.n - 1) / pack.fps : c.dur, loop: c.loop, from: "bake" };
|
|
17
|
+
if (r && c.loop && r.seamOk === false && r.seamAngleDeg !== null)
|
|
18
|
+
item.warn = `the loop jumps ${Math.round(r.seamAngleDeg)} degrees at the seam.`;
|
|
19
|
+
else if (r && r.maxAngleErrorDeg > 2)
|
|
20
|
+
item.warn = `packing moved a bone up to ${r.maxAngleErrorDeg.toFixed(1)} degrees.`;
|
|
21
|
+
return item;
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
/** An item from a retargeted motion and its findings. */
|
|
25
|
+
export function clipFromFindings(id, name, f) {
|
|
26
|
+
return { id, name, seconds: f.duration, loop: f.looping, from: "retarget", tags: [...f.tags] };
|
|
27
|
+
}
|
|
28
|
+
/** Items for the clips a loaded file carries, by name and length. */
|
|
29
|
+
export function clipsFromBody(clips, prefix = "body") {
|
|
30
|
+
return clips.map((c, i) => ({ id: `${prefix}:${i}`, name: c.name || `clip ${i + 1}`, seconds: c.duration, loop: /loop|idle|walk|run/i.test(c.name), from: "body" }));
|
|
31
|
+
}
|
|
32
|
+
/** The next id after `id` in the strip, wrapping, for a key or a play all. */
|
|
33
|
+
export function nextClip(items, id, step = 1) {
|
|
34
|
+
if (!items.length)
|
|
35
|
+
return null;
|
|
36
|
+
const i = items.findIndex((c) => c.id === id);
|
|
37
|
+
const n = items.length;
|
|
38
|
+
return items[(((i < 0 ? (step > 0 ? -1 : 0) : i) + step) % n + n) % n].id;
|
|
39
|
+
}
|
package/dist/dom.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
type Attrs = Record<string, string | number | boolean | null | undefined>;
|
|
2
|
+
/** An element with classes, attributes and children. A false or null attribute is left off. */
|
|
3
|
+
export declare function el<K extends keyof HTMLElementTagNameMap>(doc: Document, tag: K, cls?: string, attrs?: Attrs, kids?: (Node | string)[]): HTMLElementTagNameMap[K];
|
|
4
|
+
/** A child of `host` with this class, made and appended when missing, so a Vue shell or a page can supply it. */
|
|
5
|
+
export declare function part(host: HTMLElement, cls: string, make: () => HTMLElement): HTMLElement;
|
|
6
|
+
/** A 44 px icon button from the hackbuild-ui stroke set. */
|
|
7
|
+
export declare function iconButton(doc: Document, icon: string, label: string, attrs?: Attrs): HTMLButtonElement;
|
|
8
|
+
/** A light button, or the one pink action when `go`. */
|
|
9
|
+
export declare function button(doc: Document, label: string, go?: boolean, attrs?: Attrs): HTMLButtonElement;
|
|
10
|
+
/** Text with a tone for hackbuild-ui's status line. */
|
|
11
|
+
export declare function statusLine(doc: Document, text: string, tone: "ok" | "warn" | "bad" | "info" | "busy"): HTMLElement;
|
|
12
|
+
/** An object URL that is revoked on the next call, so one thumbnail slot never leaks. */
|
|
13
|
+
export declare function urlSlot(): (blob: Blob | string | null | undefined) => string;
|
|
14
|
+
export {};
|