@hackbuild/avatar-host 0.1.0 → 0.1.2

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/README.md CHANGED
@@ -83,6 +83,18 @@ The main entry has no three.js:
83
83
  loads once, on the first body.
84
84
  - `placeholderBody()`: a mannequin of capsules on a humanoid skeleton,
85
85
  built in code, head top near 1.74 m (computed). No asset file.
86
+ - `/thumbs`: previews drawn in the background. `clipThumbs({ save })`
87
+ poses one clay figure (the placeholder body, or a figure you pass) at
88
+ each clip's most telling frame, the sampled frame between 10 and 90
89
+ percent of the clip furthest from rest by the limbs and trunk
90
+ (`tellingTime`), into a 192 px square. `avatarThumbs({ save })` loads
91
+ each body source and draws it at rest, 240 by 320 px. Both run on
92
+ `ThumbQueue`: one item at a time on one renderer, urgent items first,
93
+ each item tried once per session, a rest between items as long as the
94
+ last render within 40 to 400 ms, one task yield instead in a hidden tab,
95
+ a lost context rebuilds the renderer, and the renderer lingers 20 s after
96
+ the queue empties (vendor figures, all options). `save(id, blob)` gets a
97
+ PNG Blob; `failed(id, reason)` names why an item gave none.
86
98
  - `defineAvatarHost(tag?, opts?)`: defines `hb-avatar-host`. Attributes
87
99
  `src` (a model URL; the placeholder shows without one), `environment`
88
100
  (a scene id), `paused`,
@@ -143,6 +155,17 @@ The example page `examples/avatar-host` runs the browser rows with `?auto`.
143
155
 
144
156
  ### Verified on this machine
145
157
 
158
+ - 2026-11-24: `npx vitest run packages/avatar-host` passed 41 of 41
159
+ tests (counted), 8 of them in `test/thumbs.test.ts` with a stand in
160
+ renderer and fake timers: an urgent request jumps the queue, waiting
161
+ items included; an item is tried once; the renderer is disposed 20 s
162
+ after the queue empties and rebuilt for a later request; a failed render
163
+ reports its reason and the next item still draws; a lost context
164
+ rebuilds; the rest after a 250 ms render is 250 ms; a renderer that
165
+ cannot be built fails every waiting item with its reason; the telling
166
+ frame of a wave on the placeholder lands within half a sample of the
167
+ peak at 0.6 s (computed).
168
+
146
169
  - 2026-11-24: `npx vitest run packages/avatar-host` passed 33 of 33
147
170
  tests (counted), with the face driver and rest stance: a played clip
148
171
  hands back to the rest stance with the hand below the shoulder;
@@ -192,7 +215,9 @@ The example page `examples/avatar-host` runs the browser rows with `?auto`.
192
215
  - The room, cafe and outdoors scenes have not been shown on this stage;
193
216
  their files are not in the repository. The pixel ratio cap was measured
194
217
  at a device ratio of 1 only.
195
- - Thumbnails are a later item and not in this package yet. The face
218
+ - No thumbnail has been drawn in a browser: `ClipPortrait` and
219
+ `AvatarPortrait` need WebGL and have not rendered an image yet. The
220
+ face
196
221
  driver has not run on a real face in a browser.
197
222
 
198
223
  ## Size budget
@@ -8846,13 +8846,14 @@ var HackbuildAvatarHost = (function(exports, three) {
8846
8846
  function normalizeHumanoid(model, opts = {}) {
8847
8847
  model.updateMatrixWorld(true);
8848
8848
  const mapped = mapObject3D(model);
8849
+ if (opts.deform) for (const d of mapped.report.deform) mapped.bones[d.bone] = mapped.nodes[d.node];
8849
8850
  if (mapped.report.missingRequired.length) throw new Error(`avatar: missing required bones: ${mapped.report.missingRequired.join(", ")}.`);
8850
8851
  const rest = restOf(mapped.bones);
8851
8852
  if (!rest) throw new Error("avatar: rest analysis needs hips, head and both arms.");
8852
8853
  const fix = {};
8853
8854
  if (opts.tPoseArms !== void 0) fix.tPoseArms = opts.tPoseArms;
8854
8855
  if (opts.straightLegs !== void 0) fix.straightLegs = opts.straightLegs;
8855
- const s = opts.headHeight ? opts.headHeight / rest.height : rest.scale;
8856
+ const s = opts.headHeight ? opts.headHeight / rest.height : opts.unit ?? rest.scale;
8856
8857
  bakeScale(model, s);
8857
8858
  const root = applyRestFix(model, mapped.bones, {
8858
8859
  ...rest,
@@ -0,0 +1,71 @@
1
+ import { Box3, type AnimationClip, OrthographicCamera } from "three";
2
+ import type { HumanBone } from "@hackbuild/rig/bones";
3
+ import { type Avatar } from "@hackbuild/avatar/three";
4
+ import { type BodyLoadOptions } from "./load.js";
5
+ import type { BodySource } from "./source.js";
6
+ import type { ThumbRenderer } from "./thumb-queue.js";
7
+ /** Frames tried when looking for the most telling one. */
8
+ export declare const SAMPLES = 24;
9
+ /** Bones that judge a frame; fingers would outvote them by count. */
10
+ export declare const MEASURED: readonly HumanBone[];
11
+ export interface PortraitOptions {
12
+ /** Image width in pixels. Default 192. */
13
+ width?: number;
14
+ /** Image height in pixels. Default the width. */
15
+ height?: number;
16
+ /** A canvas to draw into; default a new one. */
17
+ canvas?: HTMLCanvasElement;
18
+ }
19
+ /** Points an orthographic camera at `box` from the portrait angle and fits it, `aspect` width over height. */
20
+ export declare function frameBox(cam: OrthographicCamera, box: Box3, aspect?: number): void;
21
+ /**
22
+ * The time of the clip's most telling frame on `figure`: for a held pose
23
+ * or a clip under 0.05 s its end, else the sampled frame between 10 and 90
24
+ * percent whose measured bones turn furthest from their rest rotation
25
+ * (the ends are where most clips stand near rest). Leaves the figure posed
26
+ * at that time; the caller resets it.
27
+ */
28
+ export declare function tellingTime(figure: Avatar, clip: AnimationClip, hold?: boolean, samples?: number): number;
29
+ /** One clip to preview: its id, the clip in normalized bone names, and whether it is a held pose. */
30
+ export interface ClipThumbJob {
31
+ id: string;
32
+ clip(): AnimationClip | Promise<AnimationClip>;
33
+ /** A pose: show its last frame. */
34
+ hold?: boolean;
35
+ }
36
+ export interface ClipPortraitOptions extends PortraitOptions {
37
+ /** Clay colour. Default a warm grey. */
38
+ color?: string | number;
39
+ /** The figure; default the built in placeholder body. Its materials are replaced by the clay. */
40
+ figure?: () => Avatar | Promise<Avatar>;
41
+ }
42
+ /** Clip previews on one clay figure. */
43
+ export declare class ClipPortrait implements ThumbRenderer<ClipThumbJob> {
44
+ readonly figure: Avatar;
45
+ private readonly shot;
46
+ private readonly rest;
47
+ private readonly material;
48
+ private constructor();
49
+ static create(opts?: ClipPortraitOptions): Promise<ClipPortrait>;
50
+ get lost(): boolean;
51
+ draw(job: ClipThumbJob): Promise<Blob | null>;
52
+ dispose(): void;
53
+ }
54
+ /** One avatar to preview. The queue calls `release` on the source once its load settles. */
55
+ export interface AvatarThumbJob {
56
+ id: string;
57
+ source: BodySource;
58
+ }
59
+ export interface AvatarPortraitOptions extends PortraitOptions, BodyLoadOptions {
60
+ }
61
+ /** Avatar previews: each character loads, is drawn at rest with its own materials, and is freed. */
62
+ export declare class AvatarPortrait implements ThumbRenderer<AvatarThumbJob> {
63
+ private readonly shot;
64
+ private readonly opts;
65
+ private hook;
66
+ private constructor();
67
+ static create(opts?: AvatarPortraitOptions): AvatarPortrait;
68
+ get lost(): boolean;
69
+ draw(job: AvatarThumbJob): Promise<Blob | null>;
70
+ dispose(): void;
71
+ }
@@ -0,0 +1,226 @@
1
+ // Still previews with three.js. One renderer draws synchronously into its
2
+ // own canvas, so it works in a background tab with no animation frames,
3
+ // and one instance serves every item, so the page holds one extra WebGL
4
+ // context. Clip previews pose one plain figure in a single flat clay
5
+ // colour, so every preview looks alike whichever character is loaded,
6
+ // at the clip's most telling frame: the sampled frame furthest from rest
7
+ // by the limbs and trunk. Avatar previews draw the loaded character at
8
+ // rest with its own materials. Both are seen from a little to the
9
+ // figure's left and above, orthographic, so every preview has the same
10
+ // scale cues.
11
+ import { AnimationMixer, Box3, Color, DirectionalLight, HemisphereLight, MathUtils, MeshStandardMaterial, OrthographicCamera, PropertyBinding, Quaternion, SRGBColorSpace, Scene, Vector3, WebGLRenderer, } from "three";
12
+ import { disposeObject, posedBounds } from "@hackbuild/avatar/three";
13
+ import { placeholderBody } from "./placeholder.js";
14
+ import { loadBody } from "./load.js";
15
+ const YAW = MathUtils.degToRad(24);
16
+ const PITCH = MathUtils.degToRad(10);
17
+ const MARGIN = 1.06;
18
+ /** Frames tried when looking for the most telling one. */
19
+ export const SAMPLES = 24;
20
+ /** Bones that judge a frame; fingers would outvote them by count. */
21
+ export const MEASURED = ["spine", "chest", "neck", "head", "leftShoulder", "leftUpperArm", "leftLowerArm", "rightShoulder", "rightUpperArm", "rightLowerArm", "leftUpperLeg", "leftLowerLeg", "rightUpperLeg", "rightLowerLeg"];
22
+ const v = new Vector3();
23
+ /** One renderer, scene, lights and camera, and the framing both portraits share. */
24
+ class Shot {
25
+ canvas;
26
+ renderer;
27
+ scene = new Scene();
28
+ camera = new OrthographicCamera();
29
+ constructor(opts) {
30
+ const w = opts.width ?? 192;
31
+ const h = opts.height ?? w;
32
+ this.canvas = opts.canvas ?? document.createElement("canvas");
33
+ this.renderer = new WebGLRenderer({ canvas: this.canvas, alpha: true, antialias: true, preserveDrawingBuffer: true });
34
+ this.renderer.setPixelRatio(1);
35
+ this.renderer.setSize(w, h, false);
36
+ this.renderer.outputColorSpace = SRGBColorSpace;
37
+ this.renderer.setClearColor(0x000000, 0);
38
+ const key = new DirectionalLight(0xffffff, 2.6);
39
+ key.position.set(1.6, 2.6, 2.4);
40
+ const rim = new DirectionalLight(0xffffff, 1.4);
41
+ rim.position.set(-2, 1.4, -2);
42
+ this.scene.add(key, rim, new HemisphereLight(0xffffff, 0x303038, 1.3));
43
+ }
44
+ get lost() {
45
+ return this.renderer.getContext().isContextLost();
46
+ }
47
+ /** Fits `box` into the image, centred, and draws it as a PNG. */
48
+ draw(box) {
49
+ frameBox(this.camera, box, this.canvas.width / Math.max(1, this.canvas.height));
50
+ this.renderer.render(this.scene, this.camera);
51
+ return new Promise((ok) => this.canvas.toBlob(ok, "image/png"));
52
+ }
53
+ dispose() {
54
+ this.renderer.dispose();
55
+ this.renderer.forceContextLoss();
56
+ }
57
+ }
58
+ /** Points an orthographic camera at `box` from the portrait angle and fits it, `aspect` width over height. */
59
+ export function frameBox(cam, box, aspect = 1) {
60
+ const center = box.getCenter(new Vector3());
61
+ const reach = Math.max(1e-3, box.getSize(v).length() * 2);
62
+ const dir = new Vector3(Math.sin(YAW) * Math.cos(PITCH), Math.sin(PITCH), Math.cos(YAW) * Math.cos(PITCH));
63
+ cam.position.copy(center).addScaledVector(dir, reach);
64
+ cam.lookAt(center);
65
+ cam.updateMatrixWorld(true);
66
+ const lo = new Vector3(Infinity, Infinity, Infinity);
67
+ const hi = new Vector3(-Infinity, -Infinity, -Infinity);
68
+ const { min, max } = box;
69
+ for (let i = 0; i < 8; i++) {
70
+ v.set(i & 1 ? max.x : min.x, i & 2 ? max.y : min.y, i & 4 ? max.z : min.z).applyMatrix4(cam.matrixWorldInverse);
71
+ lo.min(v);
72
+ hi.max(v);
73
+ }
74
+ const halfH = (Math.max(hi.y - lo.y, (hi.x - lo.x) / aspect) / 2) * MARGIN;
75
+ const halfW = halfH * aspect;
76
+ const cx = (lo.x + hi.x) / 2;
77
+ const cy = (lo.y + hi.y) / 2;
78
+ Object.assign(cam, { left: cx - halfW, right: cx + halfW, top: cy + halfH, bottom: cy - halfH, near: 0.01, far: reach * 3 });
79
+ cam.updateProjectionMatrix();
80
+ }
81
+ const restOf = (figure) => {
82
+ const out = [];
83
+ figure.root.traverse((node) => out.push({ node, q: node.quaternion.clone(), p: node.position.clone() }));
84
+ return out;
85
+ };
86
+ const reset = (rest) => {
87
+ for (const r of rest) {
88
+ r.node.quaternion.copy(r.q);
89
+ r.node.position.copy(r.p);
90
+ }
91
+ };
92
+ /**
93
+ * The time of the clip's most telling frame on `figure`: for a held pose
94
+ * or a clip under 0.05 s its end, else the sampled frame between 10 and 90
95
+ * percent whose measured bones turn furthest from their rest rotation
96
+ * (the ends are where most clips stand near rest). Leaves the figure posed
97
+ * at that time; the caller resets it.
98
+ */
99
+ export function tellingTime(figure, clip, hold = false, samples = SAMPLES) {
100
+ const mixer = new AnimationMixer(figure.root);
101
+ mixer.clipAction(clip).play();
102
+ const d = clip.duration;
103
+ const times = hold || d < 0.05 ? [d] : Array.from({ length: samples }, (_, i) => d * (0.1 + (0.8 * i) / Math.max(1, samples - 1)));
104
+ let best = times[0];
105
+ if (times.length > 1) {
106
+ const bones = MEASURED.map((b) => figure.bones[b]).filter((n) => !!n);
107
+ const rest = bones.map((n) => n.quaternion.clone());
108
+ let bestScore = -1;
109
+ for (const t of times) {
110
+ mixer.setTime(t);
111
+ let score = 0;
112
+ bones.forEach((n, i) => (score += n.quaternion.angleTo(rest[i])));
113
+ if (score > bestScore)
114
+ [best, bestScore] = [t, score];
115
+ }
116
+ }
117
+ mixer.setTime(best);
118
+ // stopping the mixer puts the bones back, so the pose is kept by hand
119
+ const posed = restOf(figure);
120
+ mixer.stopAllAction();
121
+ mixer.uncacheRoot(figure.root);
122
+ reset(posed);
123
+ return best;
124
+ }
125
+ function clay(root, material) {
126
+ const old = new Set();
127
+ root.traverse((o) => {
128
+ const mesh = o;
129
+ if (!mesh.isMesh)
130
+ return;
131
+ for (const m of Array.isArray(mesh.material) ? mesh.material : [mesh.material])
132
+ if (m !== material)
133
+ old.add(m);
134
+ mesh.material = material;
135
+ });
136
+ for (const m of old) {
137
+ for (const val of Object.values(m))
138
+ if (val && val.isTexture)
139
+ val.dispose();
140
+ m.dispose();
141
+ }
142
+ }
143
+ /** Clip previews on one clay figure. */
144
+ export class ClipPortrait {
145
+ figure;
146
+ shot;
147
+ rest;
148
+ material;
149
+ constructor(figure, shot, color) {
150
+ this.figure = figure;
151
+ this.shot = shot;
152
+ this.material = new MeshStandardMaterial({ name: "clay", color: new Color(color), roughness: 0.8, metalness: 0 });
153
+ clay(figure.root, this.material);
154
+ figure.root.traverse((o) => (o.frustumCulled = false));
155
+ shot.scene.add(figure.root);
156
+ this.rest = restOf(figure);
157
+ }
158
+ static async create(opts = {}) {
159
+ const figure = await (opts.figure ?? (() => placeholderBody()))();
160
+ return new ClipPortrait(figure, new Shot(opts), opts.color ?? 0xc9c1b3);
161
+ }
162
+ get lost() {
163
+ return this.shot.lost;
164
+ }
165
+ async draw(job) {
166
+ const clip = await job.clip();
167
+ const bound = clip.tracks.some((t) => this.figure.root.getObjectByName(PropertyBinding.parseTrackName(t.name).nodeName));
168
+ if (!bound)
169
+ throw new Error("the clip moves no bone of this figure.");
170
+ reset(this.rest);
171
+ tellingTime(this.figure, clip, job.hold ?? false);
172
+ this.figure.update(0);
173
+ this.figure.root.updateMatrixWorld(true);
174
+ const image = await this.shot.draw(posedBounds(this.figure.bones, 0.12));
175
+ reset(this.rest);
176
+ return image;
177
+ }
178
+ dispose() {
179
+ this.figure.dispose();
180
+ this.material.dispose();
181
+ this.shot.dispose();
182
+ }
183
+ }
184
+ /** Avatar previews: each character loads, is drawn at rest with its own materials, and is freed. */
185
+ export class AvatarPortrait {
186
+ shot;
187
+ opts;
188
+ hook = null;
189
+ constructor(shot, opts) {
190
+ this.shot = shot;
191
+ this.opts = opts;
192
+ }
193
+ static create(opts = {}) {
194
+ return new AvatarPortrait(new Shot({ width: 240, height: 320, ...opts }), opts);
195
+ }
196
+ get lost() {
197
+ return this.shot.lost;
198
+ }
199
+ async draw(job) {
200
+ const src = job.source;
201
+ let hook = null;
202
+ if (src.kind === "vrm" && this.opts.vrm)
203
+ hook = await (this.hook ??= this.opts.vrm());
204
+ let avatar = null;
205
+ try {
206
+ avatar = await loadBody(src, hook, this.opts);
207
+ avatar.root.traverse((o) => (o.frustumCulled = false));
208
+ this.shot.scene.add(avatar.root);
209
+ avatar.update(0);
210
+ avatar.root.updateMatrixWorld(true);
211
+ const box = new Box3().setFromObject(avatar.root);
212
+ return await this.shot.draw(box.isEmpty() ? posedBounds(avatar.bones) : box);
213
+ }
214
+ finally {
215
+ src.release?.();
216
+ if (avatar)
217
+ avatar.dispose();
218
+ }
219
+ }
220
+ dispose() {
221
+ for (const o of [...this.shot.scene.children])
222
+ if (!o.isLight)
223
+ disposeObject(o);
224
+ this.shot.dispose();
225
+ }
226
+ }
@@ -0,0 +1,63 @@
1
+ /** Counts for a progress line: items done of items asked for in this run. */
2
+ export interface ThumbProgress {
3
+ active: boolean;
4
+ done: number;
5
+ total: number;
6
+ }
7
+ /** Draws one item to an image. */
8
+ export interface ThumbRenderer<J> {
9
+ /** True once the GPU context is gone; the queue builds a new renderer. */
10
+ readonly lost: boolean;
11
+ /** The image, or null when the render gave none. Throws with a reason the queue reports. */
12
+ draw(job: J): Promise<Blob | null>;
13
+ dispose(): void;
14
+ }
15
+ export interface ThumbQueueOptions<J> {
16
+ /** Builds the renderer, on first need and after a lost context. Null or a throw ends the run. */
17
+ renderer(): Promise<ThumbRenderer<J> | null>;
18
+ /** Keeps a drawn image, for instance in a blob store by content hash. */
19
+ save(id: string, image: Blob): Promise<void>;
20
+ /** An item that gave no image, and why. It is not tried again this session. */
21
+ failed?(id: string, reason: string): void;
22
+ onProgress?(p: ThumbProgress): void;
23
+ /** How long the renderer is kept once the queue is empty, ms. Default 20000 (vendor). */
24
+ lingerMs?: number;
25
+ /** Rest between items, ms: at least this. Default 40 (vendor). */
26
+ minRestMs?: number;
27
+ /** Rest between items, ms: at most this. Default 400 (vendor). */
28
+ maxRestMs?: number;
29
+ /** Clock in ms; default `performance.now`. */
30
+ now?(): number;
31
+ /** True while the page is hidden; default reads `document.visibilityState`. */
32
+ hidden?(): boolean;
33
+ }
34
+ export declare class ThumbQueue<J extends {
35
+ id: string;
36
+ }> {
37
+ private readonly opts;
38
+ private readonly state;
39
+ private readonly queue;
40
+ private readonly seen;
41
+ private current;
42
+ private running;
43
+ private stopped;
44
+ private linger;
45
+ constructor(opts: ThumbQueueOptions<J>);
46
+ get progress(): ThumbProgress;
47
+ /** Ids waiting, next first. */
48
+ get waiting(): string[];
49
+ /** True while a renderer is built or lingering. */
50
+ get holding(): boolean;
51
+ /** Resolves when the current run has drained. */
52
+ idle(): Promise<void>;
53
+ /** Asks for previews. Items seen this session are skipped; `urgent` puts these first, waiting ones included. */
54
+ want(jobs: readonly J[], urgent?: boolean): void;
55
+ /** Stops, forgets what was seen and frees the renderer. */
56
+ destroy(): void;
57
+ private report;
58
+ private drain;
59
+ private renderer;
60
+ private render;
61
+ private rest;
62
+ private teardown;
63
+ }
@@ -0,0 +1,156 @@
1
+ // The thumbnail queue: still previews drawn in the background, one at a
2
+ // time, on one renderer the queue builds on first need. Callers say which
3
+ // items they want; urgent ones (on screen, just added) jump the queue. An
4
+ // item is tried once per session. Between items the queue rests at least
5
+ // as long as the last render took, inside a floor and a ceiling, so
6
+ // drawing uses at most about half of the main thread; in a hidden tab,
7
+ // where timers crawl, it yields one task instead. A renderer whose GPU
8
+ // context was lost is rebuilt before the next item. Once the queue is
9
+ // empty the renderer lingers, so items scrolled into view soon after do
10
+ // not rebuild it, and is then disposed. No three.js here: the renderer is
11
+ // injected, the three.js portraits are in portrait.ts.
12
+ const reasonOf = (e) => (e instanceof Error ? e.message : String(e));
13
+ export class ThumbQueue {
14
+ opts;
15
+ state = { active: false, done: 0, total: 0 };
16
+ queue = [];
17
+ seen = new Set();
18
+ current = null;
19
+ running = null;
20
+ stopped = false;
21
+ linger = null;
22
+ constructor(opts) {
23
+ this.opts = opts;
24
+ }
25
+ get progress() {
26
+ return { ...this.state };
27
+ }
28
+ /** Ids waiting, next first. */
29
+ get waiting() {
30
+ return this.queue.map((j) => j.id);
31
+ }
32
+ /** True while a renderer is built or lingering. */
33
+ get holding() {
34
+ return this.current !== null;
35
+ }
36
+ /** Resolves when the current run has drained. */
37
+ idle() {
38
+ return this.running ?? Promise.resolve();
39
+ }
40
+ /** Asks for previews. Items seen this session are skipped; `urgent` puts these first, waiting ones included. */
41
+ want(jobs, urgent = false) {
42
+ if (urgent) {
43
+ const ids = new Set(jobs.map((j) => j.id));
44
+ const waiting = this.queue.filter((j) => ids.has(j.id));
45
+ if (waiting.length) {
46
+ for (let i = this.queue.length - 1; i >= 0; i--)
47
+ if (ids.has(this.queue[i].id))
48
+ this.queue.splice(i, 1);
49
+ this.queue.unshift(...waiting);
50
+ }
51
+ }
52
+ const fresh = [];
53
+ for (const j of jobs)
54
+ if (!this.seen.has(j.id)) {
55
+ this.seen.add(j.id);
56
+ fresh.push(j);
57
+ }
58
+ if (!fresh.length)
59
+ return;
60
+ if (urgent)
61
+ this.queue.unshift(...fresh);
62
+ else
63
+ this.queue.push(...fresh);
64
+ if (!this.running)
65
+ this.state.done = this.state.total = 0;
66
+ this.state.total += fresh.length;
67
+ this.stopped = false;
68
+ this.running ??= this.drain().finally(() => (this.running = null));
69
+ }
70
+ /** Stops, forgets what was seen and frees the renderer. */
71
+ destroy() {
72
+ this.stopped = true;
73
+ this.queue.length = 0;
74
+ this.seen.clear();
75
+ if (this.linger)
76
+ clearTimeout(this.linger);
77
+ this.linger = null;
78
+ this.teardown();
79
+ }
80
+ report() {
81
+ this.opts.onProgress?.({ ...this.state });
82
+ }
83
+ async drain() {
84
+ if (this.linger)
85
+ clearTimeout(this.linger);
86
+ this.linger = null;
87
+ const now = this.opts.now ?? (() => performance.now());
88
+ this.state.active = true;
89
+ this.report();
90
+ while (this.queue.length && !this.stopped) {
91
+ const started = now();
92
+ const r = await this.renderer();
93
+ if (!r.renderer) {
94
+ const reason = r.reason ?? "no figure to draw on.";
95
+ for (const j of this.queue.splice(0))
96
+ this.opts.failed?.(j.id, reason);
97
+ break;
98
+ }
99
+ const job = this.queue.shift();
100
+ await this.render(r.renderer, job);
101
+ this.state.done++;
102
+ this.report();
103
+ if (this.queue.length && !this.stopped)
104
+ await this.rest(Math.min(this.opts.maxRestMs ?? 400, Math.max(this.opts.minRestMs ?? 40, now() - started)));
105
+ }
106
+ this.state.active = false;
107
+ this.report();
108
+ if (!this.stopped)
109
+ this.linger = setTimeout(() => !this.running && this.teardown(), this.opts.lingerMs ?? 20_000);
110
+ }
111
+ async renderer() {
112
+ const had = await this.current;
113
+ if (had?.lost)
114
+ this.teardown();
115
+ let reason;
116
+ this.current ??= this.opts.renderer().catch((e) => {
117
+ reason = reasonOf(e);
118
+ return null;
119
+ });
120
+ const renderer = await this.current;
121
+ if (!renderer)
122
+ this.current = null;
123
+ return reason === undefined ? { renderer } : { renderer, reason };
124
+ }
125
+ async render(r, job) {
126
+ try {
127
+ const image = await r.draw(job);
128
+ if (image)
129
+ await this.opts.save(job.id, image);
130
+ else
131
+ this.opts.failed?.(job.id, "the render gave no image.");
132
+ }
133
+ catch (e) {
134
+ this.opts.failed?.(job.id, reasonOf(e));
135
+ }
136
+ }
137
+ rest(ms) {
138
+ const hidden = this.opts.hidden ?? (() => typeof document !== "undefined" && document.visibilityState === "hidden");
139
+ if (hidden() && typeof MessageChannel !== "undefined") {
140
+ return new Promise((ok) => {
141
+ const ch = new MessageChannel();
142
+ ch.port1.onmessage = () => {
143
+ ch.port1.close();
144
+ ok();
145
+ };
146
+ ch.port2.postMessage(null);
147
+ });
148
+ }
149
+ return new Promise((ok) => setTimeout(() => (typeof requestIdleCallback === "function" ? requestIdleCallback(() => ok(), { timeout: 1000 }) : ok()), ms));
150
+ }
151
+ teardown() {
152
+ const p = this.current;
153
+ this.current = null;
154
+ void p?.then((r) => r?.dispose());
155
+ }
156
+ }
@@ -0,0 +1,14 @@
1
+ import { type AvatarPortraitOptions, type AvatarThumbJob, type ClipPortraitOptions, type ClipThumbJob } from "./portrait.js";
2
+ import { ThumbQueue, type ThumbQueueOptions } from "./thumb-queue.js";
3
+ export * from "./thumb-queue.js";
4
+ export * from "./portrait.js";
5
+ export type ClipThumbOptions = Omit<ThumbQueueOptions<ClipThumbJob>, "renderer"> & {
6
+ portrait?: ClipPortraitOptions;
7
+ };
8
+ export type AvatarThumbOptions = Omit<ThumbQueueOptions<AvatarThumbJob>, "renderer"> & {
9
+ portrait?: AvatarPortraitOptions;
10
+ };
11
+ /** A queue of clip previews on one clay figure, 192 px square by default. */
12
+ export declare function clipThumbs(opts: ClipThumbOptions): ThumbQueue<ClipThumbJob>;
13
+ /** A queue of avatar previews, 240 by 320 px by default. */
14
+ export declare function avatarThumbs(opts: AvatarThumbOptions): ThumbQueue<AvatarThumbJob>;
package/dist/thumbs.js ADDED
@@ -0,0 +1,17 @@
1
+ // @hackbuild/avatar-host/thumbs: clip and avatar previews drawn in the
2
+ // background. `clipThumbs` poses one clay figure (the built in placeholder
3
+ // body by default) at each clip's most telling frame; `avatarThumbs` loads
4
+ // each character and draws it at rest. Both run on the pacing queue of
5
+ // thumb-queue.ts and hand back PNG Blobs through `save`.
6
+ import { AvatarPortrait, ClipPortrait } from "./portrait.js";
7
+ import { ThumbQueue } from "./thumb-queue.js";
8
+ export * from "./thumb-queue.js";
9
+ export * from "./portrait.js";
10
+ /** A queue of clip previews on one clay figure, 192 px square by default. */
11
+ export function clipThumbs(opts) {
12
+ return new ThumbQueue({ ...opts, renderer: () => ClipPortrait.create(opts.portrait) });
13
+ }
14
+ /** A queue of avatar previews, 240 by 320 px by default. */
15
+ export function avatarThumbs(opts) {
16
+ return new ThumbQueue({ ...opts, renderer: async () => AvatarPortrait.create(opts.portrait) });
17
+ }
package/how.ts ADDED
@@ -0,0 +1,35 @@
1
+ // how this works: the fold of the package page and of the suite tool. Plain data, no imports;
2
+ // shape in tools/how.d.ts, checked by tsconfig.how.json, shipped in the tarball, never imported
3
+ // by the runtime entry. Text from the README.
4
+ const how: HowDoc = {
5
+ what: "host a character on a three.js stage in any container: ticketed loads through @hackbuild/avatar, a follow camera, the presence frame order, a loop that pauses when hidden, and a hb-avatar-host element.",
6
+ how: [
7
+ "a character on a three.js stage in any container. bodies load through @hackbuild/avatar into the normalized humanoid space; the camera frames and follows the posed body.",
8
+ "loads are ticketed: show(source) resolves to the result, or to null when a later show replaced it, so a slow file never lands over a newer one. a drop of files finds the model and the files it references by path, then by name.",
9
+ "one animation loop runs, and it stops while the page is hidden, the host is off screen or at zero size, or a sheet covers it. the main entry has no three.js; the hb-avatar-host element is under /three.",
10
+ "/thumbs draws previews in the background, one at a time on one renderer: clips on a clay figure at their most telling frame, characters at rest. urgent items go first, each is tried once, and the renderer is freed 20 s after the queue empties. save gets a png blob.",
11
+ ],
12
+ packages: ["@hackbuild/avatar-host"],
13
+ install: "npm install @hackbuild/avatar-host",
14
+ today: "git clone https://github.com/hackbuild/hackbuild-motion && cd hackbuild-motion && npm ci && npm run build && npm pack -w @hackbuild/avatar-host",
15
+ code: `import { defineAvatarHost } from "@hackbuild/avatar-host/three";
16
+ import { droppedFiles } from "@hackbuild/avatar-host";
17
+
18
+ defineAvatarHost("hb-avatar-host", {
19
+ // three-vrm (MIT) is imported on the first .vrm only
20
+ vrm: () => import("@hackbuild/avatar/vrm").then((m) => m.vrmHook()),
21
+ });
22
+ const el = document.querySelector("hb-avatar-host")!;
23
+ el.addEventListener("loaded", (e) => console.info(e.detail.caps));
24
+ el.addEventListener("failed", (e) => showError(e.detail.message));
25
+ zone.addEventListener("drop", async (e) => el.showFiles(await droppedFiles(e.dataTransfer!)));
26
+
27
+ // clip previews, the clips on screen first
28
+ const { clipThumbs } = await import("@hackbuild/avatar-host/thumbs");
29
+ const thumbs = clipThumbs({ save: (id, png) => blobs.put(id, png), failed: (id, why) => console.info(id, why) });
30
+ thumbs.want(visible.map((c) => ({ id: c.id, clip: () => c.load() })), true);`,
31
+ lang: "ts",
32
+ links: { page: "https://hackbuild.github.io/hackbuild-motion/avatar-host/", source: "https://github.com/hackbuild/hackbuild-motion/tree/main/packages/avatar-host" },
33
+ };
34
+
35
+ export default how;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hackbuild/avatar-host",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Host a character on a three.js stage in any container: ticketed loads through @hackbuild/avatar, a follow camera, the presence frame order, a loop that pauses when hidden, and a hb-avatar-host element.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -23,6 +23,10 @@
23
23
  "types": "./dist/three.d.ts",
24
24
  "import": "./dist/three.js"
25
25
  },
26
+ "./thumbs": {
27
+ "types": "./dist/thumbs.d.ts",
28
+ "import": "./dist/thumbs.js"
29
+ },
26
30
  "./iife": "./dist/avatar-host.iife.js"
27
31
  },
28
32
  "unpkg": "dist/avatar-host.iife.js",
@@ -30,18 +34,19 @@
30
34
  "files": [
31
35
  "dist",
32
36
  "README.md",
33
- "LICENSE"
37
+ "LICENSE",
38
+ "how.ts"
34
39
  ],
35
40
  "scripts": {
36
41
  "build": "node ../../tools/build-package.mjs avatar-host"
37
42
  },
38
43
  "dependencies": {
39
- "@hackbuild/avatar": "0.1.0",
40
- "@hackbuild/environment": "0.1.0",
41
- "@hackbuild/lipsync": "0.1.0",
42
- "@hackbuild/organic": "0.1.0",
43
- "@hackbuild/presence": "0.1.0",
44
- "@hackbuild/rig": "0.1.0"
44
+ "@hackbuild/avatar": "0.1.2",
45
+ "@hackbuild/environment": "0.1.1",
46
+ "@hackbuild/lipsync": "0.1.1",
47
+ "@hackbuild/organic": "0.1.1",
48
+ "@hackbuild/presence": "0.1.1",
49
+ "@hackbuild/rig": "0.1.1"
45
50
  },
46
51
  "peerDependencies": {
47
52
  "three": ">=0.186.1"