@hackbuild/avatar-host 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 +211 -2
- package/dist/avatar-host.iife.js +13454 -0
- package/dist/body.d.ts +78 -0
- package/dist/body.js +191 -0
- package/dist/drop.d.ts +20 -0
- package/dist/drop.js +44 -0
- package/dist/element.d.ts +9 -0
- package/dist/element.js +77 -0
- package/dist/environment.d.ts +35 -0
- package/dist/environment.js +59 -0
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +25 -0
- package/dist/follow.d.ts +42 -0
- package/dist/follow.js +97 -0
- package/dist/host.d.ts +39 -0
- package/dist/host.js +88 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +10 -0
- package/dist/load.d.ts +21 -0
- package/dist/load.js +79 -0
- package/dist/loop.d.ts +50 -0
- package/dist/loop.js +102 -0
- package/dist/placeholder.d.ts +11 -0
- package/dist/placeholder.js +90 -0
- package/dist/single.d.ts +2 -0
- package/dist/single.js +4 -0
- package/dist/source.d.ts +35 -0
- package/dist/source.js +83 -0
- package/dist/stage.d.ts +167 -0
- package/dist/stage.js +436 -0
- package/dist/three.d.ts +7 -0
- package/dist/three.js +10 -0
- package/how.ts +29 -0
- package/package.json +53 -4
package/dist/body.d.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { AnimationClip, Object3D } from "three";
|
|
2
|
+
import { Vector3 } from "three";
|
|
3
|
+
import type { Rng } from "@hackbuild/organic";
|
|
4
|
+
import { type Clip, ClipPlayer, Face, GazeController, type GazeMode, type PlayOptions, type Layer } from "@hackbuild/presence";
|
|
5
|
+
import { LipSync, type MouthTarget } from "@hackbuild/lipsync";
|
|
6
|
+
import { type HumanBone } from "@hackbuild/rig/bones";
|
|
7
|
+
import type { Avatar, Part } from "@hackbuild/avatar/three";
|
|
8
|
+
export interface BodyOptions {
|
|
9
|
+
rng: Rng;
|
|
10
|
+
/** Gaze on neck, head and eyes. auto turns it on when the head's rest frame is upright and facing +Z. Default auto. */
|
|
11
|
+
gaze?: boolean | "auto";
|
|
12
|
+
/** Lift a head that clips hold low. Default on when gaze is on. */
|
|
13
|
+
levelHead?: boolean;
|
|
14
|
+
/** Which face channels the mouth writes. Default picked from the face's names. */
|
|
15
|
+
mouth?: MouthTarget;
|
|
16
|
+
/** Base layer: "relaxed" lowers the arms to the sides, "rest" keeps the loaded rest pose. Default relaxed. */
|
|
17
|
+
stance?: "relaxed" | "rest";
|
|
18
|
+
/** Weights a quiet face rests at; false for a neutral face. Default RESTING_FACE (a slight smile). */
|
|
19
|
+
restingFace?: Readonly<Record<string, number>> | false;
|
|
20
|
+
}
|
|
21
|
+
/** What a loaded body can do, for the capability note under the stage. */
|
|
22
|
+
export interface BodyCaps {
|
|
23
|
+
bones: number;
|
|
24
|
+
expressions: string[];
|
|
25
|
+
clips: string[];
|
|
26
|
+
parts: number;
|
|
27
|
+
mouth: boolean;
|
|
28
|
+
blink: boolean;
|
|
29
|
+
gaze: boolean;
|
|
30
|
+
}
|
|
31
|
+
export declare class Body {
|
|
32
|
+
readonly avatar: Avatar;
|
|
33
|
+
readonly names: HumanBone[];
|
|
34
|
+
readonly bones: Object3D[];
|
|
35
|
+
readonly player: ClipPlayer;
|
|
36
|
+
readonly gaze: GazeController | null;
|
|
37
|
+
readonly lip: LipSync;
|
|
38
|
+
/** The face driver every expression weight goes through. */
|
|
39
|
+
readonly face: Face;
|
|
40
|
+
readonly caps: BodyCaps;
|
|
41
|
+
readonly mouth: MouthTarget;
|
|
42
|
+
/** Turn gaze off and on without a new body. */
|
|
43
|
+
gazeOn: boolean;
|
|
44
|
+
private readonly level;
|
|
45
|
+
private readonly head;
|
|
46
|
+
private readonly rig;
|
|
47
|
+
private readonly vrmLook;
|
|
48
|
+
private readonly converted;
|
|
49
|
+
private speaking;
|
|
50
|
+
private readonly eye;
|
|
51
|
+
private readonly tmp;
|
|
52
|
+
private readonly q;
|
|
53
|
+
constructor(avatar: Avatar, opts: BodyOptions);
|
|
54
|
+
/** Expression names the face carries: VRM presets and custom names, or presets the morph rig resolved. */
|
|
55
|
+
expressionNames(): string[];
|
|
56
|
+
get name(): string;
|
|
57
|
+
get wardrobe(): Part[];
|
|
58
|
+
/** Holds one mood, eased in by the face driver; null hands the face back to its resting weights. */
|
|
59
|
+
setExpression(name: string | null, weight?: number): void;
|
|
60
|
+
/** A presence clip over this body's bone order, from one of its animations (by name or object). */
|
|
61
|
+
clipOf(anim: AnimationClip | string, loop?: boolean): Clip | null;
|
|
62
|
+
/** Plays a clip; returns its ticket, or -1 when the name is not one of the body's clips. */
|
|
63
|
+
play(clip: Clip | AnimationClip | string, opts?: PlayOptions): number;
|
|
64
|
+
stop(layer?: Layer, fade?: number): void;
|
|
65
|
+
setGazeMode(mode: GazeMode): void;
|
|
66
|
+
setPartVisible(id: string, on: boolean): void;
|
|
67
|
+
/** True while a clip or a mouth moves the body by itself (reduced motion keeps drawing then). */
|
|
68
|
+
moving(): boolean;
|
|
69
|
+
/** Where the eyes sit, world space. */
|
|
70
|
+
eyePosition(out: Vector3): Vector3;
|
|
71
|
+
/**
|
|
72
|
+
* One frame. `look` is the gaze target in world space, null to keep the
|
|
73
|
+
* last; `still` stops idle motion (gaze, blink) for reduced motion;
|
|
74
|
+
* `mouthTime` is the clock the speech events were timed on.
|
|
75
|
+
*/
|
|
76
|
+
update(dt: number, look: Vector3 | null, still: boolean, mouthTime: number): void;
|
|
77
|
+
dispose(): void;
|
|
78
|
+
}
|
package/dist/body.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { Quaternion, Vector3 } from "three";
|
|
2
|
+
import { ClipPlayer, Face, GazeController, HeadLevel, RESTING_FACE } from "@hackbuild/presence";
|
|
3
|
+
import { applyGaze, applyPose, clipFromThree, restStanceFromThree } from "@hackbuild/presence/three";
|
|
4
|
+
import { LipSync, drive } from "@hackbuild/lipsync";
|
|
5
|
+
import { HUMAN_BONES } from "@hackbuild/rig/bones";
|
|
6
|
+
const UPPER = /^(spine|chest|upperChest|neck|head|left|right)(?!.*(Leg|Foot|Toes))/;
|
|
7
|
+
// the rest frame is upright and faces +Z within about 10 degrees (proposed)
|
|
8
|
+
const aligned = (o) => !o || o.getWorldQuaternion(new Quaternion()).angleTo(new Quaternion()) < 0.17;
|
|
9
|
+
export class Body {
|
|
10
|
+
avatar;
|
|
11
|
+
names = [];
|
|
12
|
+
bones = [];
|
|
13
|
+
player;
|
|
14
|
+
gaze;
|
|
15
|
+
lip = new LipSync();
|
|
16
|
+
/** The face driver every expression weight goes through. */
|
|
17
|
+
face;
|
|
18
|
+
caps;
|
|
19
|
+
mouth;
|
|
20
|
+
/** Turn gaze off and on without a new body. */
|
|
21
|
+
gazeOn;
|
|
22
|
+
level;
|
|
23
|
+
head;
|
|
24
|
+
rig;
|
|
25
|
+
vrmLook;
|
|
26
|
+
converted = new WeakMap();
|
|
27
|
+
speaking = false;
|
|
28
|
+
eye = new Vector3();
|
|
29
|
+
tmp = new Vector3();
|
|
30
|
+
q = new Quaternion();
|
|
31
|
+
constructor(avatar, opts) {
|
|
32
|
+
this.avatar = avatar;
|
|
33
|
+
for (const name of HUMAN_BONES) {
|
|
34
|
+
const b = avatar.bones[name];
|
|
35
|
+
if (b) {
|
|
36
|
+
this.names.push(name);
|
|
37
|
+
this.bones.push(b);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
avatar.root.updateMatrixWorld(true);
|
|
41
|
+
let rest;
|
|
42
|
+
if (opts.stance === "rest") {
|
|
43
|
+
rest = { name: "rest", fps: 30, frames: 2, bones: this.bones.length, loop: true, rotations: new Float32Array(this.bones.length * 8) };
|
|
44
|
+
this.bones.forEach((b, i) => {
|
|
45
|
+
b.quaternion.toArray(rest.rotations, i * 4);
|
|
46
|
+
b.quaternion.toArray(rest.rotations, (this.bones.length + i) * 4);
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
else
|
|
50
|
+
rest = restStanceFromThree(this.bones, this.names, avatar.root);
|
|
51
|
+
this.face = new Face(avatar.expressions, { resting: opts.restingFace === false ? {} : (opts.restingFace ?? RESTING_FACE) });
|
|
52
|
+
const upper = [];
|
|
53
|
+
this.names.forEach((n, i) => UPPER.test(n) && upper.push(i));
|
|
54
|
+
this.player = new ClipPlayer({ idle: rest, upperBones: upper });
|
|
55
|
+
const head = avatar.bones.head;
|
|
56
|
+
const vrm = (avatar.vrm?.vrm ?? null);
|
|
57
|
+
const upright = !!head && (!!vrm || (aligned(head) && aligned(avatar.bones.neck)));
|
|
58
|
+
const gaze = opts.gaze ?? "auto";
|
|
59
|
+
this.gazeOn = gaze === "auto" ? upright : gaze && !!head;
|
|
60
|
+
this.gaze = head ? new GazeController({ rng: opts.rng }) : null;
|
|
61
|
+
this.vrmLook = vrm?.lookAt ?? null;
|
|
62
|
+
this.rig = head
|
|
63
|
+
? {
|
|
64
|
+
head,
|
|
65
|
+
neck: avatar.bones.neck ?? null,
|
|
66
|
+
// eye bones that do not rest upright would spin; three-vrm drives VRM eyes through its look at
|
|
67
|
+
leftEye: !this.vrmLook && aligned(avatar.bones.leftEye) ? (avatar.bones.leftEye ?? null) : null,
|
|
68
|
+
rightEye: !this.vrmLook && aligned(avatar.bones.rightEye) ? (avatar.bones.rightEye ?? null) : null,
|
|
69
|
+
}
|
|
70
|
+
: null;
|
|
71
|
+
this.head = this.names.indexOf("head");
|
|
72
|
+
this.level = (opts.levelHead ?? this.gazeOn) && this.head >= 0 ? new HeadLevel() : null;
|
|
73
|
+
const expressions = this.expressionNames();
|
|
74
|
+
const morphs = avatar.expressions.found ? Object.keys(avatar.expressions.found) : [];
|
|
75
|
+
const raw = avatar.expressions.morphNames ?? [];
|
|
76
|
+
this.mouth = opts.mouth ?? (expressions.includes("aa") ? "vrm" : raw.some((m) => /^viseme_/.test(m)) ? "oculus" : raw.includes("jawOpen") ? "arkit" : "vrm");
|
|
77
|
+
this.caps = {
|
|
78
|
+
bones: this.bones.length,
|
|
79
|
+
expressions,
|
|
80
|
+
clips: avatar.animations.map((a, i) => a.name || `clip ${i}`),
|
|
81
|
+
parts: avatar.wardrobe.parts.length,
|
|
82
|
+
mouth: expressions.includes("aa") || raw.some((m) => /^viseme_/.test(m)) || raw.includes("jawOpen"),
|
|
83
|
+
blink: expressions.includes("blink") || morphs.includes("blink"),
|
|
84
|
+
gaze: this.gazeOn,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/** Expression names the face carries: VRM presets and custom names, or presets the morph rig resolved. */
|
|
88
|
+
expressionNames() {
|
|
89
|
+
const vrm = (this.avatar.vrm?.vrm ?? null);
|
|
90
|
+
const list = vrm?.expressionManager?.expressions?.map((e) => e.expressionName);
|
|
91
|
+
if (list)
|
|
92
|
+
return list;
|
|
93
|
+
return this.avatar.expressions.found ? Object.keys(this.avatar.expressions.found) : [];
|
|
94
|
+
}
|
|
95
|
+
get name() {
|
|
96
|
+
return this.avatar.root.name || this.avatar.dialect;
|
|
97
|
+
}
|
|
98
|
+
get wardrobe() {
|
|
99
|
+
return this.avatar.wardrobe.parts;
|
|
100
|
+
}
|
|
101
|
+
/** Holds one mood, eased in by the face driver; null hands the face back to its resting weights. */
|
|
102
|
+
setExpression(name, weight = 1) {
|
|
103
|
+
this.face.set(name, weight);
|
|
104
|
+
}
|
|
105
|
+
/** A presence clip over this body's bone order, from one of its animations (by name or object). */
|
|
106
|
+
clipOf(anim, loop) {
|
|
107
|
+
const a = typeof anim === "string" ? this.avatar.animations.find((x) => x.name === anim) : anim;
|
|
108
|
+
if (!a)
|
|
109
|
+
return null;
|
|
110
|
+
let c = this.converted.get(a);
|
|
111
|
+
if (!c) {
|
|
112
|
+
c = clipFromThree(a, this.bones.map((b) => b.name), { rest: this.bones, ...(loop === undefined ? {} : { loop }) });
|
|
113
|
+
this.converted.set(a, c);
|
|
114
|
+
}
|
|
115
|
+
return c;
|
|
116
|
+
}
|
|
117
|
+
/** Plays a clip; returns its ticket, or -1 when the name is not one of the body's clips. */
|
|
118
|
+
play(clip, opts = {}) {
|
|
119
|
+
const c = typeof clip === "string" || !("rotations" in clip) ? this.clipOf(clip) : clip;
|
|
120
|
+
if (!c)
|
|
121
|
+
return -1;
|
|
122
|
+
if (c.bones !== this.bones.length)
|
|
123
|
+
throw new Error(`this clip has ${c.bones} bones and the body ${this.bones.length}. build it with clipOf or over body.names.`);
|
|
124
|
+
return this.player.play(c, opts);
|
|
125
|
+
}
|
|
126
|
+
stop(layer = "body", fade) {
|
|
127
|
+
this.player.stop(layer, fade);
|
|
128
|
+
}
|
|
129
|
+
setGazeMode(mode) {
|
|
130
|
+
this.gaze?.setMode(mode);
|
|
131
|
+
}
|
|
132
|
+
setPartVisible(id, on) {
|
|
133
|
+
this.avatar.wardrobe.setVisible(id, on);
|
|
134
|
+
}
|
|
135
|
+
/** True while a clip or a mouth moves the body by itself (reduced motion keeps drawing then). */
|
|
136
|
+
moving() {
|
|
137
|
+
return this.player.layerWeight("body") > 0 || this.player.layerWeight("upper") > 0 || this.speaking || this.face.settling();
|
|
138
|
+
}
|
|
139
|
+
/** Where the eyes sit, world space. */
|
|
140
|
+
eyePosition(out) {
|
|
141
|
+
const l = this.avatar.bones.leftEye;
|
|
142
|
+
const r = this.avatar.bones.rightEye;
|
|
143
|
+
if (l && r)
|
|
144
|
+
return l.getWorldPosition(out).add(r.getWorldPosition(this.tmp)).multiplyScalar(0.5);
|
|
145
|
+
const head = this.avatar.bones.head;
|
|
146
|
+
if (!head)
|
|
147
|
+
return this.avatar.root.getWorldPosition(out);
|
|
148
|
+
return head.getWorldPosition(out).add(this.tmp.set(0, 0.07, 0.08));
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* One frame. `look` is the gaze target in world space, null to keep the
|
|
152
|
+
* last; `still` stops idle motion (gaze, blink) for reduced motion;
|
|
153
|
+
* `mouthTime` is the clock the speech events were timed on.
|
|
154
|
+
*/
|
|
155
|
+
update(dt, look, still, mouthTime) {
|
|
156
|
+
const pose = this.player.update(dt);
|
|
157
|
+
if (this.level && !still)
|
|
158
|
+
this.level.apply(dt, pose, this.head);
|
|
159
|
+
applyPose(pose, this.bones);
|
|
160
|
+
if (this.gazeOn && this.gaze && this.rig && !still) {
|
|
161
|
+
this.avatar.root.updateMatrixWorld(true);
|
|
162
|
+
if (look)
|
|
163
|
+
this.gaze.setTarget([look.x, look.y, look.z]);
|
|
164
|
+
const e = this.eyePosition(this.eye);
|
|
165
|
+
const hips = this.avatar.bones.hips;
|
|
166
|
+
let yaw = 0;
|
|
167
|
+
if (hips) {
|
|
168
|
+
const f = this.tmp.set(0, 0, 1).applyQuaternion(hips.getWorldQuaternion(this.q));
|
|
169
|
+
yaw = Math.atan2(f.x, f.z);
|
|
170
|
+
}
|
|
171
|
+
const g = this.gaze.update(dt, [e.x, e.y, e.z], yaw);
|
|
172
|
+
applyGaze(g, this.rig);
|
|
173
|
+
if (this.vrmLook) {
|
|
174
|
+
this.vrmLook.yaw = (g.eyeYaw * 180) / Math.PI;
|
|
175
|
+
this.vrmLook.pitch = (g.eyePitch * 180) / Math.PI;
|
|
176
|
+
}
|
|
177
|
+
this.face.lid(g.blink);
|
|
178
|
+
}
|
|
179
|
+
else if (still)
|
|
180
|
+
this.face.lid(0);
|
|
181
|
+
const mouth = this.lip.update(mouthTime, dt);
|
|
182
|
+
this.speaking = mouth.source !== "silent";
|
|
183
|
+
drive(this.face.mouth, mouth, this.mouth);
|
|
184
|
+
this.face.update(dt, this.player.faces);
|
|
185
|
+
this.avatar.update(dt);
|
|
186
|
+
}
|
|
187
|
+
dispose() {
|
|
188
|
+
this.lip.stop();
|
|
189
|
+
this.avatar.dispose();
|
|
190
|
+
}
|
|
191
|
+
}
|
package/dist/drop.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** The parts of FileSystemEntry the walk reads; tests pass plain objects. */
|
|
2
|
+
export interface EntryLike {
|
|
3
|
+
isFile: boolean;
|
|
4
|
+
isDirectory: boolean;
|
|
5
|
+
fullPath: string;
|
|
6
|
+
file?(ok: (f: File) => void, fail?: (e: unknown) => void): void;
|
|
7
|
+
createReader?(): {
|
|
8
|
+
readEntries(ok: (batch: EntryLike[]) => void, fail?: (e: unknown) => void): void;
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
export interface DropLike {
|
|
12
|
+
items?: ArrayLike<{
|
|
13
|
+
webkitGetAsEntry?(): EntryLike | null;
|
|
14
|
+
}>;
|
|
15
|
+
files?: ArrayLike<File>;
|
|
16
|
+
}
|
|
17
|
+
/** Every file under the entries, each with `webkitRelativePath` set from its place in the drop. */
|
|
18
|
+
export declare function filesFromEntries(entries: readonly EntryLike[]): Promise<File[]>;
|
|
19
|
+
/** The files of a drop; folders are walked when the browser gives entries. */
|
|
20
|
+
export declare function droppedFiles(dt: DropLike): Promise<File[]>;
|
package/dist/drop.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Reads a drag and drop into a flat file list, walking dropped folders and
|
|
2
|
+
// keeping each file's path relative to the drop, so a model finds the
|
|
3
|
+
// textures in the folders beside it.
|
|
4
|
+
/** Every file under the entries, each with `webkitRelativePath` set from its place in the drop. */
|
|
5
|
+
export async function filesFromEntries(entries) {
|
|
6
|
+
const out = [];
|
|
7
|
+
const readAll = (e) => new Promise((ok, fail) => {
|
|
8
|
+
const reader = e.createReader();
|
|
9
|
+
const acc = [];
|
|
10
|
+
// readEntries hands out batches until an empty one
|
|
11
|
+
const more = () => reader.readEntries((batch) => {
|
|
12
|
+
if (!batch.length)
|
|
13
|
+
ok(acc);
|
|
14
|
+
else {
|
|
15
|
+
acc.push(...batch);
|
|
16
|
+
more();
|
|
17
|
+
}
|
|
18
|
+
}, fail);
|
|
19
|
+
more();
|
|
20
|
+
});
|
|
21
|
+
const visit = async (e) => {
|
|
22
|
+
if (e.isFile && e.file) {
|
|
23
|
+
const f = await new Promise((ok, fail) => e.file(ok, fail));
|
|
24
|
+
Object.defineProperty(f, "webkitRelativePath", { value: e.fullPath.replace(/^\//, ""), configurable: true });
|
|
25
|
+
out.push(f);
|
|
26
|
+
}
|
|
27
|
+
else if (e.isDirectory && e.createReader) {
|
|
28
|
+
for (const child of await readAll(e))
|
|
29
|
+
await visit(child);
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
for (const e of entries)
|
|
33
|
+
await visit(e);
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
/** The files of a drop; folders are walked when the browser gives entries. */
|
|
37
|
+
export async function droppedFiles(dt) {
|
|
38
|
+
const entries = Array.from(dt.items ?? [])
|
|
39
|
+
.map((i) => i.webkitGetAsEntry?.() ?? null)
|
|
40
|
+
.filter((e) => !!e);
|
|
41
|
+
if (!entries.some((e) => e.isDirectory))
|
|
42
|
+
return Array.from(dt.files ?? []);
|
|
43
|
+
return filesFromEntries(entries);
|
|
44
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { AvatarStage, type StageOptions } from "./stage.js";
|
|
2
|
+
import type { DroppedFile } from "./source.js";
|
|
3
|
+
export interface AvatarHostElement extends HTMLElement {
|
|
4
|
+
readonly stage: AvatarStage | null;
|
|
5
|
+
/** Shows dropped or picked files; resolves when the load settles. */
|
|
6
|
+
showFiles(files: readonly DroppedFile[]): Promise<void>;
|
|
7
|
+
}
|
|
8
|
+
/** Defines the element once under `tag`, with stage options every instance shares. Returns its class. */
|
|
9
|
+
export declare function defineAvatarHost(tag?: string, options?: StageOptions): CustomElementConstructor;
|
package/dist/element.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// hb-avatar-host: the stage as a custom element for vanilla pages and for
|
|
2
|
+
// the slot of a Vue stage part. Attributes: src (a model URL; the
|
|
3
|
+
// placeholder body shows without one), environment (a scene id, studio
|
|
4
|
+
// needs no file), paused, inactive, covered. Stage
|
|
5
|
+
// events are dispatched as DOM events of the same name (loaded, failed,
|
|
6
|
+
// stats, state, lost, restored) with the stage event as detail. The class
|
|
7
|
+
// is made when `defineAvatarHost` runs, so importing this module defines
|
|
8
|
+
// nothing and runs in a worker or in Node.
|
|
9
|
+
import { AvatarStage } from "./stage.js";
|
|
10
|
+
const EVENTS = ["loaded", "failed", "stats", "state", "lost", "restored"];
|
|
11
|
+
/** Defines the element once under `tag`, with stage options every instance shares. Returns its class. */
|
|
12
|
+
export function defineAvatarHost(tag = "hb-avatar-host", options = {}) {
|
|
13
|
+
const known = customElements.get(tag);
|
|
14
|
+
if (known)
|
|
15
|
+
return known;
|
|
16
|
+
class Element extends HTMLElement {
|
|
17
|
+
static observedAttributes = ["src", "environment", "paused", "inactive", "covered"];
|
|
18
|
+
stage = null;
|
|
19
|
+
offs = [];
|
|
20
|
+
connectedCallback() {
|
|
21
|
+
if (this.stage)
|
|
22
|
+
return;
|
|
23
|
+
if (!this.style.display)
|
|
24
|
+
this.style.display = "block";
|
|
25
|
+
const stage = new AvatarStage(this, options);
|
|
26
|
+
this.stage = stage;
|
|
27
|
+
for (const type of EVENTS)
|
|
28
|
+
this.offs.push(stage.on(type, (e) => this.dispatchEvent(new CustomEvent(type, { detail: e }))));
|
|
29
|
+
this.sync();
|
|
30
|
+
const env = this.getAttribute("environment");
|
|
31
|
+
if (env)
|
|
32
|
+
void stage.showEnvironment(env);
|
|
33
|
+
const src = this.getAttribute("src");
|
|
34
|
+
if (src)
|
|
35
|
+
void stage.show(src);
|
|
36
|
+
else
|
|
37
|
+
stage.showPlaceholder();
|
|
38
|
+
}
|
|
39
|
+
disconnectedCallback() {
|
|
40
|
+
for (const off of this.offs)
|
|
41
|
+
off();
|
|
42
|
+
this.offs = [];
|
|
43
|
+
this.stage?.dispose();
|
|
44
|
+
this.stage = null;
|
|
45
|
+
}
|
|
46
|
+
attributeChangedCallback(name, was, now) {
|
|
47
|
+
if (!this.stage || was === now)
|
|
48
|
+
return;
|
|
49
|
+
if (name === "src") {
|
|
50
|
+
if (now)
|
|
51
|
+
void this.stage.show(now);
|
|
52
|
+
else
|
|
53
|
+
this.stage.showPlaceholder();
|
|
54
|
+
}
|
|
55
|
+
else if (name === "environment")
|
|
56
|
+
void this.stage.showEnvironment(now || null);
|
|
57
|
+
else
|
|
58
|
+
this.sync();
|
|
59
|
+
}
|
|
60
|
+
async showFiles(files) {
|
|
61
|
+
await this.stage?.show(files);
|
|
62
|
+
}
|
|
63
|
+
sync() {
|
|
64
|
+
const s = this.stage;
|
|
65
|
+
if (!s)
|
|
66
|
+
return;
|
|
67
|
+
if (this.hasAttribute("paused"))
|
|
68
|
+
s.pause();
|
|
69
|
+
else
|
|
70
|
+
s.play();
|
|
71
|
+
s.setActive(!this.hasAttribute("inactive"));
|
|
72
|
+
s.setCovered(this.hasAttribute("covered"));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
customElements.define(tag, Element);
|
|
76
|
+
return Element;
|
|
77
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { Scene, WebGLRenderer } from "three";
|
|
2
|
+
import type { EnvironmentPreset } from "@hackbuild/environment";
|
|
3
|
+
import type { LoadedEnvironment, Resolve } from "@hackbuild/environment/three";
|
|
4
|
+
export interface EnvironmentTarget {
|
|
5
|
+
readonly scene: Scene;
|
|
6
|
+
readonly renderer: WebGLRenderer;
|
|
7
|
+
/** Swaps the shown scene: disposes the old one, attaches the new one or none. */
|
|
8
|
+
setEnvironment(env: LoadedEnvironment | null): void;
|
|
9
|
+
}
|
|
10
|
+
export interface EnvironmentRequest {
|
|
11
|
+
/** A preset id (studio, room, cafe, outdoors) or a preset. */
|
|
12
|
+
preset: string | EnvironmentPreset;
|
|
13
|
+
/** Gives the files the preset needs; the studio needs none. */
|
|
14
|
+
resolve?: Resolve;
|
|
15
|
+
}
|
|
16
|
+
export type EnvironmentLoader = (req: EnvironmentRequest, target: EnvironmentTarget) => Promise<LoadedEnvironment>;
|
|
17
|
+
export declare class EnvironmentSlot {
|
|
18
|
+
private readonly target;
|
|
19
|
+
private readonly load;
|
|
20
|
+
private ticket;
|
|
21
|
+
private shown;
|
|
22
|
+
constructor(target: EnvironmentTarget, load?: EnvironmentLoader);
|
|
23
|
+
/** Id of the scene showing now, or null for the plain stage. */
|
|
24
|
+
get current(): string | null;
|
|
25
|
+
/**
|
|
26
|
+
* Shows a scene, or the plain stage for null. Resolves to the scene, or
|
|
27
|
+
* null when it was cleared or a later call overtook it; the same id
|
|
28
|
+
* again does nothing. A load failure rejects and keeps the current scene.
|
|
29
|
+
*/
|
|
30
|
+
set(req: EnvironmentRequest | string | null): Promise<LoadedEnvironment | null>;
|
|
31
|
+
/** Overtakes any load in flight. */
|
|
32
|
+
cancel(): void;
|
|
33
|
+
}
|
|
34
|
+
/** Device pixels per CSS pixel: at most `max`, and at most 1.5 with a lit scene (vendor). */
|
|
35
|
+
export declare function stagePixelRatio(device: number, max?: number, scene?: boolean): number;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const defaultLoad = async (req, target) => {
|
|
2
|
+
const { loadEnvironment } = await import("@hackbuild/environment/three");
|
|
3
|
+
return loadEnvironment(req.preset, target.scene, target.renderer, req.resolve ? { resolve: req.resolve } : {});
|
|
4
|
+
};
|
|
5
|
+
export class EnvironmentSlot {
|
|
6
|
+
target;
|
|
7
|
+
load;
|
|
8
|
+
ticket = 0;
|
|
9
|
+
shown = null;
|
|
10
|
+
constructor(target, load = defaultLoad) {
|
|
11
|
+
this.target = target;
|
|
12
|
+
this.load = load;
|
|
13
|
+
}
|
|
14
|
+
/** Id of the scene showing now, or null for the plain stage. */
|
|
15
|
+
get current() {
|
|
16
|
+
return this.shown;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Shows a scene, or the plain stage for null. Resolves to the scene, or
|
|
20
|
+
* null when it was cleared or a later call overtook it; the same id
|
|
21
|
+
* again does nothing. A load failure rejects and keeps the current scene.
|
|
22
|
+
*/
|
|
23
|
+
async set(req) {
|
|
24
|
+
const mine = ++this.ticket;
|
|
25
|
+
const r = typeof req === "string" ? { preset: req } : req;
|
|
26
|
+
const id = r ? (typeof r.preset === "string" ? r.preset : r.preset.id) : null;
|
|
27
|
+
if (id === this.shown)
|
|
28
|
+
return null;
|
|
29
|
+
if (!r) {
|
|
30
|
+
this.shown = null;
|
|
31
|
+
this.target.setEnvironment(null);
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
let env;
|
|
35
|
+
try {
|
|
36
|
+
env = await this.load(r, this.target);
|
|
37
|
+
}
|
|
38
|
+
catch (e) {
|
|
39
|
+
if (mine !== this.ticket)
|
|
40
|
+
return null;
|
|
41
|
+
throw e;
|
|
42
|
+
}
|
|
43
|
+
if (mine !== this.ticket) {
|
|
44
|
+
env.dispose();
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
this.shown = id;
|
|
48
|
+
this.target.setEnvironment(env);
|
|
49
|
+
return env;
|
|
50
|
+
}
|
|
51
|
+
/** Overtakes any load in flight. */
|
|
52
|
+
cancel() {
|
|
53
|
+
this.ticket++;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/** Device pixels per CSS pixel: at most `max`, and at most 1.5 with a lit scene (vendor). */
|
|
57
|
+
export function stagePixelRatio(device, max = 2, scene = false) {
|
|
58
|
+
return Math.min(device || 1, max, scene ? 1.5 : Infinity);
|
|
59
|
+
}
|
package/dist/errors.d.ts
ADDED
package/dist/errors.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Failure copy for the stage chrome: lowercase, terse, names the failure
|
|
2
|
+
// and what to do. The raw error stays with the event as its cause.
|
|
3
|
+
const RULES = [
|
|
4
|
+
[/missing required bones: ([^.]+)/, (m) => `this model has no humanoid rig the stage can map. missing bones: ${m[1]}.`],
|
|
5
|
+
[/rest analysis needs/, () => "the rig was found but its rest pose could not be read. it needs hips, head and both arms."],
|
|
6
|
+
[/vrma file is an animation/, () => "a vrma file is an animation. load it as a clip, then drop a body."],
|
|
7
|
+
[/unknown model format/, () => "this file is not a model the stage reads. drop a .vrm, .glb, .gltf or .fbx."],
|
|
8
|
+
[/fetch failed with (\d+)/, (m) => `the model did not download (http ${m[1]}). check the url.`],
|
|
9
|
+
[/failed to fetch|networkerror|load failed/i, () => "the model did not download. check the url and that its server allows this page."],
|
|
10
|
+
[/webgl|creating webgl|context/i, () => "no webgl here. the 3d view cannot start on this device."],
|
|
11
|
+
[/no adapter for (\w+) files/, (m) => `${m[1]} files are not read here. drop a .vrm, .glb, .gltf or .fbx.`],
|
|
12
|
+
];
|
|
13
|
+
/** Copy for the person from a load or start failure. Copy this package already wrote passes through. */
|
|
14
|
+
export function bodyError(e) {
|
|
15
|
+
const raw = e instanceof Error ? e.message : String(e);
|
|
16
|
+
for (const [re, copy] of RULES) {
|
|
17
|
+
const m = raw.match(re);
|
|
18
|
+
if (m)
|
|
19
|
+
return copy(m);
|
|
20
|
+
}
|
|
21
|
+
// messages this package throws are already written for the person
|
|
22
|
+
if (/^[a-z0-9 .,:()'/-]+$/.test(raw) && raw.endsWith("."))
|
|
23
|
+
return raw;
|
|
24
|
+
return "the model did not load. its file may be damaged or of a kind the stage does not read.";
|
|
25
|
+
}
|
package/dist/follow.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { Box3, type PerspectiveCamera, Vector3 } from "three";
|
|
2
|
+
export interface FollowOptions {
|
|
3
|
+
/** Ease rate per second toward a new framing. Default 3 (vendor). */
|
|
4
|
+
rate?: number;
|
|
5
|
+
/** Body movement under this share of its height moves nothing. Default 0.06 (vendor). */
|
|
6
|
+
deadZone?: number;
|
|
7
|
+
/** Comes closer only when this share too far. Default 0.12 (vendor). */
|
|
8
|
+
slack?: number;
|
|
9
|
+
/** Fit margin over the tight fit. Default 1.12 (vendor). */
|
|
10
|
+
margin?: number;
|
|
11
|
+
}
|
|
12
|
+
export declare class FollowCamera {
|
|
13
|
+
readonly camera: PerspectiveCamera;
|
|
14
|
+
/** The orbit target the camera looks at (OrbitControls.target). */
|
|
15
|
+
readonly target: Vector3;
|
|
16
|
+
/** Set when the person picked a distance; fitting then leaves it alone. */
|
|
17
|
+
zoomed: boolean;
|
|
18
|
+
/** Where the person panned to, from the body's centre. */
|
|
19
|
+
readonly offset: Vector3;
|
|
20
|
+
readonly rate: number;
|
|
21
|
+
readonly deadZone: number;
|
|
22
|
+
readonly slack: number;
|
|
23
|
+
readonly margin: number;
|
|
24
|
+
private readonly v1;
|
|
25
|
+
private readonly v2;
|
|
26
|
+
private readonly v3;
|
|
27
|
+
constructor(camera: PerspectiveCamera,
|
|
28
|
+
/** The orbit target the camera looks at (OrbitControls.target). */
|
|
29
|
+
target: Vector3, opts?: FollowOptions);
|
|
30
|
+
distance(): number;
|
|
31
|
+
/** Distance at which the box fills the view with the margin, from any side. */
|
|
32
|
+
fitDistance(box: Box3): number;
|
|
33
|
+
/** Frames the box from the front (+Z) and forgets the person's pan and zoom. */
|
|
34
|
+
frame(box: Box3): void;
|
|
35
|
+
/** After the person let go: keep their pan as an offset, and their distance when it changed. */
|
|
36
|
+
released(box: Box3 | null, startDistance: number): void;
|
|
37
|
+
/** One frame of following. Returns true when the camera moved. */
|
|
38
|
+
step(box: Box3, dt: number): boolean;
|
|
39
|
+
/** factor above 1 moves closer; the distance is then the person's. */
|
|
40
|
+
zoomBy(factor: number, min?: number, max?: number): void;
|
|
41
|
+
private setDistance;
|
|
42
|
+
}
|