procedural-bot-animations 0.0.0-stage → 0.1.0
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 +82 -2
- package/dist/bind.d.ts +27 -0
- package/dist/bind.js +42 -0
- package/dist/blink.d.ts +25 -0
- package/dist/blink.js +48 -0
- package/dist/brain.d.ts +39 -0
- package/dist/brain.js +57 -0
- package/dist/fake3d.d.ts +20 -0
- package/dist/fake3d.js +24 -0
- package/dist/gaze.d.ts +60 -0
- package/dist/gaze.js +90 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +14 -0
- package/dist/moods.d.ts +48 -0
- package/dist/moods.js +76 -0
- package/dist/noise.d.ts +16 -0
- package/dist/noise.js +17 -0
- package/dist/reactions.d.ts +44 -0
- package/dist/reactions.js +120 -0
- package/dist/render.d.ts +29 -0
- package/dist/render.js +97 -0
- package/dist/rng.d.ts +10 -0
- package/dist/rng.js +18 -0
- package/dist/scroll-traveler.d.ts +41 -0
- package/dist/scroll-traveler.js +43 -0
- package/dist/spring.d.ts +21 -0
- package/dist/spring.js +33 -0
- package/dist/state-machine.d.ts +49 -0
- package/dist/state-machine.js +68 -0
- package/dist/types.d.ts +63 -0
- package/dist/types.js +46 -0
- package/package.json +55 -4
package/dist/moods.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { clamp, lerp } from "./spring.js";
|
|
2
|
+
/** A starting set covering most app states; add your own with the same shape. */
|
|
3
|
+
export const builtinMoods = {
|
|
4
|
+
neutral: {},
|
|
5
|
+
curious: { eyeScaleY: 1.06, eyeOffsetY: -0.3, bodyRotate: 1.5 },
|
|
6
|
+
focused: { eyeScaleY: 0.9, bodyScaleY: 0.99 },
|
|
7
|
+
suspicious: { eyeScaleY: 0.58, eyeRotate: -8, bodyY: 0.6 },
|
|
8
|
+
sleepy: { eyeScaleY: 0.5, eyeShut: 0.3, bodyY: 1.2 },
|
|
9
|
+
proud: { eyeArcAmount: 1, bodyScaleY: 1.03 },
|
|
10
|
+
sad: { eyeScaleY: 0.8, eyeOffsetY: 1, bodyY: 2 },
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Blends any number of simultaneously-active moods, each 0..1, into one
|
|
14
|
+
* pose delta. Unlisted moods (weight 0 or absent) contribute nothing.
|
|
15
|
+
*/
|
|
16
|
+
export function blendMoods(weights, moods = builtinMoods) {
|
|
17
|
+
let eyeScaleX = 1;
|
|
18
|
+
let eyeScaleY = 1;
|
|
19
|
+
let eyeOffsetY = 0;
|
|
20
|
+
let eyeRotate = 0;
|
|
21
|
+
let eyeArcAmount = 0;
|
|
22
|
+
let eyeShut = 0;
|
|
23
|
+
let bodyY = 0;
|
|
24
|
+
let bodyScaleY = 1;
|
|
25
|
+
let bodyRotate = 0;
|
|
26
|
+
for (const [name, rawWeight] of Object.entries(weights)) {
|
|
27
|
+
const weight = clamp(rawWeight, 0, 1);
|
|
28
|
+
if (weight <= 0)
|
|
29
|
+
continue;
|
|
30
|
+
const mood = moods[name];
|
|
31
|
+
if (!mood)
|
|
32
|
+
continue;
|
|
33
|
+
eyeScaleX *= lerp(1, mood.eyeScaleX ?? 1, weight);
|
|
34
|
+
eyeScaleY *= lerp(1, mood.eyeScaleY ?? 1, weight);
|
|
35
|
+
eyeOffsetY += (mood.eyeOffsetY ?? 0) * weight;
|
|
36
|
+
eyeRotate += (mood.eyeRotate ?? 0) * weight;
|
|
37
|
+
eyeArcAmount = Math.max(eyeArcAmount, (mood.eyeArcAmount ?? 0) * weight);
|
|
38
|
+
eyeShut = Math.max(eyeShut, (mood.eyeShut ?? 0) * weight);
|
|
39
|
+
bodyY += (mood.bodyY ?? 0) * weight;
|
|
40
|
+
bodyScaleY *= lerp(1, mood.bodyScaleY ?? 1, weight);
|
|
41
|
+
bodyRotate += (mood.bodyRotate ?? 0) * weight;
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
eyes: { scaleX: eyeScaleX, scaleY: eyeScaleY, offsetY: eyeOffsetY, rotate: eyeRotate, arcAmount: eyeArcAmount, shut: eyeShut },
|
|
45
|
+
body: { y: bodyY, scaleY: bodyScaleY, rotate: bodyRotate },
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Smooths mood weights over time instead of snapping them, so switching
|
|
50
|
+
* which moods are "on" doesn't pop. Set target weights with `set`, read the
|
|
51
|
+
* current smoothed blend with `update`.
|
|
52
|
+
*/
|
|
53
|
+
export class MoodBlender {
|
|
54
|
+
current = {};
|
|
55
|
+
target = {};
|
|
56
|
+
rate;
|
|
57
|
+
moods;
|
|
58
|
+
constructor(options = {}) {
|
|
59
|
+
this.rate = options.rate ?? 5;
|
|
60
|
+
this.moods = options.moods ?? builtinMoods;
|
|
61
|
+
}
|
|
62
|
+
/** Sets (or clears, at weight 0 / omission) target weights for the named moods. Others are left as they are. */
|
|
63
|
+
set(weights) {
|
|
64
|
+
Object.assign(this.target, weights);
|
|
65
|
+
}
|
|
66
|
+
update(dt) {
|
|
67
|
+
const names = new Set([...Object.keys(this.current), ...Object.keys(this.target)]);
|
|
68
|
+
for (const name of names) {
|
|
69
|
+
const cur = this.current[name] ?? 0;
|
|
70
|
+
const target = this.target[name] ?? 0;
|
|
71
|
+
const next = lerp(cur, target, 1 - Math.exp(-this.rate * dt));
|
|
72
|
+
this.current[name] = Math.abs(next) < 1e-4 && target === 0 ? 0 : next;
|
|
73
|
+
}
|
|
74
|
+
return blendMoods(this.current, this.moods);
|
|
75
|
+
}
|
|
76
|
+
}
|
package/dist/noise.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sum of a few incommensurate sine waves so the output never visibly
|
|
3
|
+
* repeats over a normal viewing session, unlike a single `sin(t)`. Give
|
|
4
|
+
* each character instance on a page a different `seed` so they drift apart
|
|
5
|
+
* instead of moving in lockstep.
|
|
6
|
+
*/
|
|
7
|
+
export declare function neverRepeating(t: number, seed?: number): number;
|
|
8
|
+
export interface BreathingOptions {
|
|
9
|
+
/** Cycles per second. Default 0.26 (~1.65 rad/s, calibrated by ear). */
|
|
10
|
+
frequency?: number;
|
|
11
|
+
/** How much of `amplitude` a full breath moves, 0..1. Default 1. */
|
|
12
|
+
depthAmount?: number;
|
|
13
|
+
seed?: number;
|
|
14
|
+
}
|
|
15
|
+
/** A squash & stretch breathing multiplier, 1 at rest, oscillating by up to ±2% * `depthAmount`. Multiply directly onto `body.scaleY`/`scaleX`. */
|
|
16
|
+
export declare function breathing(t: number, opts?: BreathingOptions): number;
|
package/dist/noise.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sum of a few incommensurate sine waves so the output never visibly
|
|
3
|
+
* repeats over a normal viewing session, unlike a single `sin(t)`. Give
|
|
4
|
+
* each character instance on a page a different `seed` so they drift apart
|
|
5
|
+
* instead of moving in lockstep.
|
|
6
|
+
*/
|
|
7
|
+
export function neverRepeating(t, seed = 0) {
|
|
8
|
+
const a = Math.sin(t * 0.9 + seed * 1.7);
|
|
9
|
+
const b = Math.sin(t * 1.53 + seed * 0.4) * 0.6;
|
|
10
|
+
const c = Math.sin(t * 2.31 + seed * 2.9) * 0.35;
|
|
11
|
+
return (a + b + c) / 1.95;
|
|
12
|
+
}
|
|
13
|
+
/** A squash & stretch breathing multiplier, 1 at rest, oscillating by up to ±2% * `depthAmount`. Multiply directly onto `body.scaleY`/`scaleX`. */
|
|
14
|
+
export function breathing(t, opts = {}) {
|
|
15
|
+
const { frequency = 0.26, depthAmount = 1, seed = 0 } = opts;
|
|
16
|
+
return 1 + Math.sin(t * frequency * Math.PI * 2 + seed) * 0.02 * depthAmount;
|
|
17
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { PoseDelta } from "./types.js";
|
|
2
|
+
export interface ReactionDefinition {
|
|
3
|
+
durationSeconds: number;
|
|
4
|
+
/** `t` is 0..1 progress through the reaction. Returns the delta to layer on top of the base pose. */
|
|
5
|
+
curve(t: number): PoseDelta;
|
|
6
|
+
/** Higher wins when two reactions are both requested; see `ReactionPlayer`. Default 0. */
|
|
7
|
+
priority?: number;
|
|
8
|
+
}
|
|
9
|
+
/** A single hop with squash-on-takeoff and squash-on-landing, no real physics integration needed since the whole arc is a closed-form curve of `t`. */
|
|
10
|
+
export declare const bounce: ReactionDefinition;
|
|
11
|
+
/** Eyes widen fast, body flinches back, both settle — a startle reaction. */
|
|
12
|
+
export declare const fright: ReactionDefinition;
|
|
13
|
+
/** Two quick blinks in a row. */
|
|
14
|
+
export declare const doubleBlink: ReactionDefinition;
|
|
15
|
+
/** A small forward-back head nod, e.g. for acknowledging something. */
|
|
16
|
+
export declare const nod: ReactionDefinition;
|
|
17
|
+
export declare const builtinReactions: Record<string, ReactionDefinition>;
|
|
18
|
+
export interface ReactionPlayerOptions {
|
|
19
|
+
/** A request older than this (seconds) is dropped instead of starting once its turn comes. Default 1.6, matching DevBerry's calibration. */
|
|
20
|
+
maxQueueAgeSeconds?: number;
|
|
21
|
+
reactions?: Record<string, ReactionDefinition>;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Plays one reaction at a time. A second request while one is already
|
|
25
|
+
* playing doesn't cut it off: it waits as the single pending slot (a third
|
|
26
|
+
* request only overwrites the pending one if it has equal or higher
|
|
27
|
+
* priority), and starts when the current reaction ends — unless it's gone
|
|
28
|
+
* stale (older than `maxQueueAgeSeconds`), in which case it's dropped
|
|
29
|
+
* instead of surprising the user with a late reaction.
|
|
30
|
+
*/
|
|
31
|
+
export declare class ReactionPlayer {
|
|
32
|
+
private current;
|
|
33
|
+
private pending;
|
|
34
|
+
private clock;
|
|
35
|
+
private readonly maxQueueAgeSeconds;
|
|
36
|
+
private readonly reactions;
|
|
37
|
+
constructor(options?: ReactionPlayerOptions);
|
|
38
|
+
get isPlaying(): boolean;
|
|
39
|
+
get currentName(): string | null;
|
|
40
|
+
/** Requests `name` to play. Returns true if it started immediately, false if queued/dropped. */
|
|
41
|
+
play(name: string): boolean;
|
|
42
|
+
/** Advances the clock; returns the active reaction's pose delta, or `null` when nothing is playing. */
|
|
43
|
+
update(dt: number): PoseDelta | null;
|
|
44
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { clamp } from "./spring.js";
|
|
2
|
+
function squashLaunchLand(t, launchWindow = 0.15, landWindow = 0.15) {
|
|
3
|
+
const launch = clamp(1 - t / launchWindow, 0, 1);
|
|
4
|
+
const land = clamp((t - (1 - landWindow)) / landWindow, 0, 1);
|
|
5
|
+
return { squash: launch * 0.5 + land, stretch: 1 - launch - land * 0.3 };
|
|
6
|
+
}
|
|
7
|
+
/** A single hop with squash-on-takeoff and squash-on-landing, no real physics integration needed since the whole arc is a closed-form curve of `t`. */
|
|
8
|
+
export const bounce = {
|
|
9
|
+
durationSeconds: 0.55,
|
|
10
|
+
priority: 1,
|
|
11
|
+
curve(t) {
|
|
12
|
+
const { squash, stretch } = squashLaunchLand(t);
|
|
13
|
+
const flight = clamp((t - 0.12) / 0.76, 0, 1);
|
|
14
|
+
const y = -18 * Math.sin(Math.PI * flight);
|
|
15
|
+
return {
|
|
16
|
+
body: {
|
|
17
|
+
y,
|
|
18
|
+
scaleY: 1 - squash * 0.16 + (1 - squash) * (stretch - 1) * 0.1,
|
|
19
|
+
scaleX: 1 + squash * 0.1,
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
/** Eyes widen fast, body flinches back, both settle — a startle reaction. */
|
|
25
|
+
export const fright = {
|
|
26
|
+
durationSeconds: 0.5,
|
|
27
|
+
priority: 3,
|
|
28
|
+
curve(t) {
|
|
29
|
+
const attack = clamp(t / 0.08, 0, 1);
|
|
30
|
+
const release = 1 - clamp((t - 0.08) / 0.42, 0, 1);
|
|
31
|
+
const shakeEnvelope = Math.max(0, 1 - t / 0.35);
|
|
32
|
+
return {
|
|
33
|
+
eyes: { scaleY: 1 + attack * release * 0.3 },
|
|
34
|
+
body: { x: Math.sin(t * 55) * shakeEnvelope * 2.2, rotate: Math.sin(t * 40) * shakeEnvelope * 3 },
|
|
35
|
+
};
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
/** Two quick blinks in a row. */
|
|
39
|
+
export const doubleBlink = {
|
|
40
|
+
durationSeconds: 0.45,
|
|
41
|
+
curve(t) {
|
|
42
|
+
const cycle = (phase) => {
|
|
43
|
+
const local = clamp((t - phase) / 0.12, 0, 1);
|
|
44
|
+
return local < 1 ? Math.sin(Math.PI * local) : 0;
|
|
45
|
+
};
|
|
46
|
+
return { eyes: { shut: Math.max(cycle(0), cycle(0.2)) } };
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
/** A small forward-back head nod, e.g. for acknowledging something. */
|
|
50
|
+
export const nod = {
|
|
51
|
+
durationSeconds: 0.6,
|
|
52
|
+
curve(t) {
|
|
53
|
+
const envelope = Math.sin(Math.PI * t);
|
|
54
|
+
return { body: { rotate: Math.sin(t * Math.PI * 3) * envelope * 4 } };
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
export const builtinReactions = { bounce, fright, doubleBlink, nod };
|
|
58
|
+
/**
|
|
59
|
+
* Plays one reaction at a time. A second request while one is already
|
|
60
|
+
* playing doesn't cut it off: it waits as the single pending slot (a third
|
|
61
|
+
* request only overwrites the pending one if it has equal or higher
|
|
62
|
+
* priority), and starts when the current reaction ends — unless it's gone
|
|
63
|
+
* stale (older than `maxQueueAgeSeconds`), in which case it's dropped
|
|
64
|
+
* instead of surprising the user with a late reaction.
|
|
65
|
+
*/
|
|
66
|
+
export class ReactionPlayer {
|
|
67
|
+
current = null;
|
|
68
|
+
pending = null;
|
|
69
|
+
clock = 0;
|
|
70
|
+
maxQueueAgeSeconds;
|
|
71
|
+
reactions;
|
|
72
|
+
constructor(options = {}) {
|
|
73
|
+
this.maxQueueAgeSeconds = options.maxQueueAgeSeconds ?? 1.6;
|
|
74
|
+
this.reactions = options.reactions ?? builtinReactions;
|
|
75
|
+
}
|
|
76
|
+
get isPlaying() {
|
|
77
|
+
return this.current !== null;
|
|
78
|
+
}
|
|
79
|
+
get currentName() {
|
|
80
|
+
return this.current?.name ?? null;
|
|
81
|
+
}
|
|
82
|
+
/** Requests `name` to play. Returns true if it started immediately, false if queued/dropped. */
|
|
83
|
+
play(name) {
|
|
84
|
+
const def = this.reactions[name];
|
|
85
|
+
if (!def)
|
|
86
|
+
return false;
|
|
87
|
+
if (!this.current) {
|
|
88
|
+
this.current = { name, def, t: 0 };
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
const currentPriority = this.current.def.priority ?? 0;
|
|
92
|
+
const pendingPriority = this.pending ? this.pending.def.priority ?? 0 : -Infinity;
|
|
93
|
+
const requestedPriority = def.priority ?? 0;
|
|
94
|
+
if (requestedPriority >= currentPriority && requestedPriority >= pendingPriority) {
|
|
95
|
+
this.pending = { name, def, requestedAt: this.clock };
|
|
96
|
+
}
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
/** Advances the clock; returns the active reaction's pose delta, or `null` when nothing is playing. */
|
|
100
|
+
update(dt) {
|
|
101
|
+
this.clock += dt;
|
|
102
|
+
if (this.current) {
|
|
103
|
+
this.current.t += dt / this.current.def.durationSeconds;
|
|
104
|
+
if (this.current.t >= 1) {
|
|
105
|
+
this.current = null;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (!this.current && this.pending) {
|
|
109
|
+
const age = this.clock - this.pending.requestedAt;
|
|
110
|
+
const { name, def } = this.pending;
|
|
111
|
+
this.pending = null;
|
|
112
|
+
if (age <= this.maxQueueAgeSeconds) {
|
|
113
|
+
this.current = { name, def, t: 0 };
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (!this.current)
|
|
117
|
+
return null;
|
|
118
|
+
return this.current.def.curve(clamp(this.current.t, 0, 1));
|
|
119
|
+
}
|
|
120
|
+
}
|
package/dist/render.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { AvatarDefinitionLike, Pose } from "./types.js";
|
|
2
|
+
export interface RenderOptions {
|
|
3
|
+
color?: string;
|
|
4
|
+
eyeColor?: string;
|
|
5
|
+
/** Pixel size of the (square) mounted SVG. Default: fills the host via 100%/100%. */
|
|
6
|
+
size?: number;
|
|
7
|
+
}
|
|
8
|
+
export interface Bounds {
|
|
9
|
+
x: number;
|
|
10
|
+
y: number;
|
|
11
|
+
width: number;
|
|
12
|
+
height: number;
|
|
13
|
+
}
|
|
14
|
+
export interface MountedRig {
|
|
15
|
+
svg: SVGSVGElement;
|
|
16
|
+
/** The body silhouette's bounding box in viewBox units, read once after mount via `getBBox`. */
|
|
17
|
+
bounds: Bounds;
|
|
18
|
+
applyPose(pose: Pose): void;
|
|
19
|
+
destroy(): void;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Renders an Open-Bot-Avatar-shaped definition as our own SVG — one filled
|
|
23
|
+
* body path plus two independently posable eye groups — instead of going
|
|
24
|
+
* through `open-bot-avatar`'s own renderer/runtime. This is what lets the
|
|
25
|
+
* procedural engine (moods, reactions, gaze) deform the eyes and body pose
|
|
26
|
+
* every frame; Open Bot Avatar's JSON format is reused here only as the
|
|
27
|
+
* *shape* input.
|
|
28
|
+
*/
|
|
29
|
+
export declare function mountRig(host: HTMLElement, definition: AvatarDefinitionLike, options?: RenderOptions): MountedRig;
|
package/dist/render.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
const SVG_NS = "http://www.w3.org/2000/svg";
|
|
2
|
+
function createEyeGroup(eyeColor) {
|
|
3
|
+
const group = document.createElementNS(SVG_NS, "g");
|
|
4
|
+
// Neutral pill eye: ~4 wide, 11 tall at scale 1 (per the Open Bot Avatar
|
|
5
|
+
// contract's sizing) — a true stadium (flat sides, fully round caps, rx =
|
|
6
|
+
// half the width), not an ellipse, matching the "pill" eyes both Open Bot
|
|
7
|
+
// Avatar and DevBerry's own Berry use.
|
|
8
|
+
const pill = document.createElementNS(SVG_NS, "rect");
|
|
9
|
+
pill.setAttribute("x", "-2");
|
|
10
|
+
pill.setAttribute("y", "-5.5");
|
|
11
|
+
pill.setAttribute("width", "4");
|
|
12
|
+
pill.setAttribute("height", "11");
|
|
13
|
+
pill.setAttribute("rx", "2");
|
|
14
|
+
pill.setAttribute("fill", eyeColor);
|
|
15
|
+
// Happy arc: a simple upward stroke, same footprint as the pill.
|
|
16
|
+
const arc = document.createElementNS(SVG_NS, "path");
|
|
17
|
+
arc.setAttribute("d", "M -2.4 1.5 Q 0 -4.5 2.4 1.5");
|
|
18
|
+
arc.setAttribute("fill", "none");
|
|
19
|
+
arc.setAttribute("stroke", eyeColor);
|
|
20
|
+
arc.setAttribute("stroke-width", "2");
|
|
21
|
+
arc.setAttribute("stroke-linecap", "round");
|
|
22
|
+
arc.setAttribute("opacity", "0");
|
|
23
|
+
group.append(pill, arc);
|
|
24
|
+
return { group, pill, arc };
|
|
25
|
+
}
|
|
26
|
+
function applyEyeTransform(group, baseX, baseY, pose) {
|
|
27
|
+
const openness = 1 - pose.shut;
|
|
28
|
+
const sx = pose.scaleX;
|
|
29
|
+
const sy = pose.scaleY * Math.max(openness, 0.04);
|
|
30
|
+
group.setAttribute("transform", `translate(${baseX + pose.offsetX} ${baseY + pose.offsetY}) rotate(${pose.rotate}) scale(${sx} ${sy})`);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Renders an Open-Bot-Avatar-shaped definition as our own SVG — one filled
|
|
34
|
+
* body path plus two independently posable eye groups — instead of going
|
|
35
|
+
* through `open-bot-avatar`'s own renderer/runtime. This is what lets the
|
|
36
|
+
* procedural engine (moods, reactions, gaze) deform the eyes and body pose
|
|
37
|
+
* every frame; Open Bot Avatar's JSON format is reused here only as the
|
|
38
|
+
* *shape* input.
|
|
39
|
+
*/
|
|
40
|
+
export function mountRig(host, definition, options = {}) {
|
|
41
|
+
const { color = "#ff6a1a", eyeColor = "#151515" } = options;
|
|
42
|
+
const svg = document.createElementNS(SVG_NS, "svg");
|
|
43
|
+
svg.setAttribute("viewBox", "0 0 100 100");
|
|
44
|
+
svg.setAttribute("width", "100%");
|
|
45
|
+
svg.setAttribute("height", "100%");
|
|
46
|
+
if (options.size) {
|
|
47
|
+
svg.setAttribute("width", String(options.size));
|
|
48
|
+
svg.setAttribute("height", String(options.size));
|
|
49
|
+
}
|
|
50
|
+
const bodyGroup = document.createElementNS(SVG_NS, "g");
|
|
51
|
+
const bodyPath = document.createElementNS(SVG_NS, "path");
|
|
52
|
+
bodyPath.setAttribute("d", definition.body.path);
|
|
53
|
+
bodyPath.setAttribute("fill", color);
|
|
54
|
+
bodyGroup.appendChild(bodyPath);
|
|
55
|
+
const { eyes } = definition;
|
|
56
|
+
const halfSpacing = eyes.spacing / 2;
|
|
57
|
+
const leftBaseX = eyes.x - halfSpacing;
|
|
58
|
+
const rightBaseX = eyes.x + halfSpacing;
|
|
59
|
+
const baseY = eyes.y;
|
|
60
|
+
const left = createEyeGroup(eyeColor);
|
|
61
|
+
const right = createEyeGroup(eyeColor);
|
|
62
|
+
left.group.setAttribute("transform", `translate(${leftBaseX} ${baseY}) scale(${eyes.scale})`);
|
|
63
|
+
right.group.setAttribute("transform", `translate(${rightBaseX} ${baseY}) scale(${eyes.scale})`);
|
|
64
|
+
svg.append(bodyGroup, left.group, right.group);
|
|
65
|
+
host.appendChild(svg);
|
|
66
|
+
// getBBox needs the element attached to a rendered document; in a headless
|
|
67
|
+
// DOM (SSR, some test environments) this can throw — fall back to the
|
|
68
|
+
// viewBox itself rather than crash the mount.
|
|
69
|
+
let bounds;
|
|
70
|
+
try {
|
|
71
|
+
const box = bodyPath.getBBox();
|
|
72
|
+
bounds = { x: box.x, y: box.y, width: box.width, height: box.height };
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
bounds = { x: 0, y: 0, width: 100, height: 100 };
|
|
76
|
+
}
|
|
77
|
+
function applyPose(pose) {
|
|
78
|
+
const { body } = pose;
|
|
79
|
+
const pivotX = bounds.x + bounds.width / 2;
|
|
80
|
+
const pivotY = bounds.y + bounds.height; // ground pivot: bottom of the silhouette
|
|
81
|
+
bodyGroup.setAttribute("transform", `translate(${body.x} ${body.y}) translate(${pivotX} ${pivotY}) rotate(${body.rotate}) scale(${body.scaleX} ${body.scaleY}) translate(${-pivotX} ${-pivotY})`);
|
|
82
|
+
applyEyeTransform(left.group, leftBaseX, baseY, pose.leftEye);
|
|
83
|
+
applyEyeTransform(right.group, rightBaseX, baseY, pose.rightEye);
|
|
84
|
+
left.pill.setAttribute("opacity", String(1 - pose.leftEye.arcAmount));
|
|
85
|
+
left.arc.setAttribute("opacity", String(pose.leftEye.arcAmount));
|
|
86
|
+
right.pill.setAttribute("opacity", String(1 - pose.rightEye.arcAmount));
|
|
87
|
+
right.arc.setAttribute("opacity", String(pose.rightEye.arcAmount));
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
svg,
|
|
91
|
+
bounds,
|
|
92
|
+
applyPose,
|
|
93
|
+
destroy() {
|
|
94
|
+
host.removeChild(svg);
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
package/dist/rng.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Seedable PRNG (mulberry32). Deterministic by design: pass a fixed seed in
|
|
3
|
+
* tests or demos that need to reproduce a run; omit it for real randomness.
|
|
4
|
+
*/
|
|
5
|
+
export type Rng = () => number;
|
|
6
|
+
export declare function mulberry32(seed?: number): Rng;
|
|
7
|
+
/** Random float in [min, max). */
|
|
8
|
+
export declare function randRange(rng: Rng, min: number, max: number): number;
|
|
9
|
+
/** True with probability `p` (0..1). */
|
|
10
|
+
export declare function chance(rng: Rng, p: number): boolean;
|
package/dist/rng.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export function mulberry32(seed = Date.now() >>> 0) {
|
|
2
|
+
let a = seed >>> 0;
|
|
3
|
+
return function rng() {
|
|
4
|
+
a |= 0;
|
|
5
|
+
a = (a + 0x6d2b79f5) | 0;
|
|
6
|
+
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
|
7
|
+
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
8
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
/** Random float in [min, max). */
|
|
12
|
+
export function randRange(rng, min, max) {
|
|
13
|
+
return min + rng() * (max - min);
|
|
14
|
+
}
|
|
15
|
+
/** True with probability `p` (0..1). */
|
|
16
|
+
export function chance(rng, p) {
|
|
17
|
+
return rng() < p;
|
|
18
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export interface Slot {
|
|
2
|
+
name: string;
|
|
3
|
+
mood?: string;
|
|
4
|
+
/** Document-relative coordinates (`getBoundingClientRect()` plus `window.scrollY`/`scrollX`), not viewport-relative. */
|
|
5
|
+
rect: {
|
|
6
|
+
x: number;
|
|
7
|
+
y: number;
|
|
8
|
+
width: number;
|
|
9
|
+
height: number;
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
export interface TravelerFrame {
|
|
13
|
+
x: number;
|
|
14
|
+
y: number;
|
|
15
|
+
scale: number;
|
|
16
|
+
/** -1..1, which way the character is heading; feed into gaze/lean. */
|
|
17
|
+
directionX: number;
|
|
18
|
+
mood?: string;
|
|
19
|
+
/** 0 at rest near a slot, up to 1 mid-flight between two slots. */
|
|
20
|
+
flight: number;
|
|
21
|
+
}
|
|
22
|
+
export interface TravelerOptions {
|
|
23
|
+
/** Shrink at the midpoint of a flight, 0..1 of the slot size. Default 0.12. */
|
|
24
|
+
flightShrink?: number;
|
|
25
|
+
/** Upward arc at the midpoint of a flight, in the same units as the slots. Default 40. */
|
|
26
|
+
flightArc?: number;
|
|
27
|
+
/** Portion of each leg spent "parked" vs. flying, via smoothstep easing. Default [0.2, 0.8]. */
|
|
28
|
+
easeWindow?: [number, number];
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Computes one frame of the "character that travels between landing-page
|
|
32
|
+
* slots on scroll" pattern. Caller supplies the slots (e.g. from
|
|
33
|
+
* `getBoundingClientRect()` on `.slot[data-name]` elements, already
|
|
34
|
+
* ordered top to bottom) and which one is "active" (e.g. the last slot
|
|
35
|
+
* whose center has crossed above the viewport's midline) plus a 0..1
|
|
36
|
+
* progress toward the next one. This function has no DOM dependency so it
|
|
37
|
+
* is easy to unit test; wire the DOM reads yourself.
|
|
38
|
+
*/
|
|
39
|
+
export declare function travelerFrame(slots: Slot[], activeIndex: number, progress: number, opts?: TravelerOptions): TravelerFrame;
|
|
40
|
+
/** Finds the index of the last slot whose vertical center is above `viewportFraction` of `viewportHeight`. */
|
|
41
|
+
export declare function findActiveSlot(slots: Slot[], scrollY: number, viewportHeight: number, viewportFraction?: number): number;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { clamp, smooth } from "./spring.js";
|
|
2
|
+
/**
|
|
3
|
+
* Computes one frame of the "character that travels between landing-page
|
|
4
|
+
* slots on scroll" pattern. Caller supplies the slots (e.g. from
|
|
5
|
+
* `getBoundingClientRect()` on `.slot[data-name]` elements, already
|
|
6
|
+
* ordered top to bottom) and which one is "active" (e.g. the last slot
|
|
7
|
+
* whose center has crossed above the viewport's midline) plus a 0..1
|
|
8
|
+
* progress toward the next one. This function has no DOM dependency so it
|
|
9
|
+
* is easy to unit test; wire the DOM reads yourself.
|
|
10
|
+
*/
|
|
11
|
+
export function travelerFrame(slots, activeIndex, progress, opts = {}) {
|
|
12
|
+
const { flightShrink = 0.12, flightArc = 40, easeWindow = [0.2, 0.8] } = opts;
|
|
13
|
+
const current = slots[clamp(activeIndex, 0, slots.length - 1)];
|
|
14
|
+
const next = slots[clamp(activeIndex + 1, 0, slots.length - 1)];
|
|
15
|
+
const p = clamp(progress, 0, 1);
|
|
16
|
+
const eased = smooth(easeWindow[0], easeWindow[1], p);
|
|
17
|
+
const cx = current.rect.x + current.rect.width / 2;
|
|
18
|
+
const cy = current.rect.y + current.rect.height / 2;
|
|
19
|
+
const nx = next.rect.x + next.rect.width / 2;
|
|
20
|
+
const ny = next.rect.y + next.rect.height / 2;
|
|
21
|
+
const flight = Math.sin(p * Math.PI); // 0 at both ends, 1 at the midpoint
|
|
22
|
+
const arc = -flightArc * flight;
|
|
23
|
+
const scaleBase = current.rect.width / 2 + (next.rect.width / 2 - current.rect.width / 2) * eased;
|
|
24
|
+
return {
|
|
25
|
+
x: cx + (nx - cx) * eased,
|
|
26
|
+
y: cy + (ny - cy) * eased + arc,
|
|
27
|
+
scale: (scaleBase / (current.rect.width / 2)) * (1 - flightShrink * flight),
|
|
28
|
+
directionX: clamp((nx - cx) / 200, -1, 1),
|
|
29
|
+
mood: p > 0.5 ? next.mood : current.mood,
|
|
30
|
+
flight,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** Finds the index of the last slot whose vertical center is above `viewportFraction` of `viewportHeight`. */
|
|
34
|
+
export function findActiveSlot(slots, scrollY, viewportHeight, viewportFraction = 0.5) {
|
|
35
|
+
const line = scrollY + viewportHeight * viewportFraction;
|
|
36
|
+
let active = 0;
|
|
37
|
+
for (let i = 0; i < slots.length; i++) {
|
|
38
|
+
const center = slots[i].rect.y + slots[i].rect.height / 2;
|
|
39
|
+
if (center <= line)
|
|
40
|
+
active = i;
|
|
41
|
+
}
|
|
42
|
+
return active;
|
|
43
|
+
}
|
package/dist/spring.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Clamp `v` to the [a, b] range. */
|
|
2
|
+
export declare function clamp(v: number, a: number, b: number): number;
|
|
3
|
+
export declare function lerp(a: number, b: number, t: number): number;
|
|
4
|
+
/** Smoothstep of `x` between `a` and `b`. */
|
|
5
|
+
export declare function smooth(a: number, b: number, x: number): number;
|
|
6
|
+
/**
|
|
7
|
+
* Exponential damping toward `target` with no overshoot.
|
|
8
|
+
* Frame-rate independent: `rate` is in 1/seconds, `dt` in seconds.
|
|
9
|
+
*/
|
|
10
|
+
export declare function damp(current: number, target: number, rate: number, dt: number): number;
|
|
11
|
+
export interface SpringState {
|
|
12
|
+
value: number;
|
|
13
|
+
velocity: number;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Damped spring (critically-damped when `damping = 2 * sqrt(stiffness)`,
|
|
17
|
+
* overshoots when lower). Mutates and returns `state`.
|
|
18
|
+
*/
|
|
19
|
+
export declare function spring(state: SpringState, target: number, stiffness: number, damping: number, dt: number): SpringState;
|
|
20
|
+
/** Caps a frame delta so a tab coming back from sleep doesn't blow up springs. */
|
|
21
|
+
export declare function safeDt(rawDtMs: number, maxMs?: number): number;
|
package/dist/spring.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Clamp `v` to the [a, b] range. */
|
|
2
|
+
export function clamp(v, a, b) {
|
|
3
|
+
return v < a ? a : v > b ? b : v;
|
|
4
|
+
}
|
|
5
|
+
export function lerp(a, b, t) {
|
|
6
|
+
return a + (b - a) * t;
|
|
7
|
+
}
|
|
8
|
+
/** Smoothstep of `x` between `a` and `b`. */
|
|
9
|
+
export function smooth(a, b, x) {
|
|
10
|
+
const t = clamp((x - a) / (b - a), 0, 1);
|
|
11
|
+
return t * t * (3 - 2 * t);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Exponential damping toward `target` with no overshoot.
|
|
15
|
+
* Frame-rate independent: `rate` is in 1/seconds, `dt` in seconds.
|
|
16
|
+
*/
|
|
17
|
+
export function damp(current, target, rate, dt) {
|
|
18
|
+
return lerp(current, target, 1 - Math.exp(-rate * dt));
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Damped spring (critically-damped when `damping = 2 * sqrt(stiffness)`,
|
|
22
|
+
* overshoots when lower). Mutates and returns `state`.
|
|
23
|
+
*/
|
|
24
|
+
export function spring(state, target, stiffness, damping, dt) {
|
|
25
|
+
const force = stiffness * (target - state.value) - damping * state.velocity;
|
|
26
|
+
state.velocity += force * dt;
|
|
27
|
+
state.value += state.velocity * dt;
|
|
28
|
+
return state;
|
|
29
|
+
}
|
|
30
|
+
/** Caps a frame delta so a tab coming back from sleep doesn't blow up springs. */
|
|
31
|
+
export function safeDt(rawDtMs, maxMs = 50) {
|
|
32
|
+
return clamp(rawDtMs, 0, maxMs) / 1000;
|
|
33
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export interface StateDef<S extends string, Ctx> {
|
|
2
|
+
id: S;
|
|
3
|
+
/** Called once when the machine enters this state. */
|
|
4
|
+
onEnter?(ctx: Ctx): void;
|
|
5
|
+
/** Called once when the machine leaves this state. */
|
|
6
|
+
onExit?(ctx: Ctx): void;
|
|
7
|
+
/** Transition to `to` automatically after `ms` of being in this state, unless interrupted. */
|
|
8
|
+
after?: {
|
|
9
|
+
ms: number;
|
|
10
|
+
to: S;
|
|
11
|
+
};
|
|
12
|
+
/** States that may interrupt this one even mid-timer/mid-animation. Default: all. */
|
|
13
|
+
interruptibleBy?: S[] | "*";
|
|
14
|
+
/** Arbitrary data a binder (e.g. an avatar renderer) reads to decide mood/motion for this state. */
|
|
15
|
+
data?: Record<string, unknown>;
|
|
16
|
+
}
|
|
17
|
+
export interface TransitionDef<S extends string, E extends string, Ctx> {
|
|
18
|
+
from: S | "*";
|
|
19
|
+
event: E;
|
|
20
|
+
to: S;
|
|
21
|
+
guard?(ctx: Ctx): boolean;
|
|
22
|
+
}
|
|
23
|
+
export interface StateMachineConfig<S extends string, E extends string, Ctx> {
|
|
24
|
+
initial: S;
|
|
25
|
+
states: Record<S, StateDef<S, Ctx>>;
|
|
26
|
+
transitions: TransitionDef<S, E, Ctx>[];
|
|
27
|
+
context?: Ctx;
|
|
28
|
+
}
|
|
29
|
+
export interface BotStateMachine<S extends string, E extends string, Ctx> {
|
|
30
|
+
getState(): S;
|
|
31
|
+
getContext(): Ctx;
|
|
32
|
+
/** Fires `event`; returns true if a transition matched and ran. */
|
|
33
|
+
send(event: E): boolean;
|
|
34
|
+
/** Force a transition, bypassing `transitions` (still runs onExit/onEnter and schedules `after`). */
|
|
35
|
+
goto(state: S): void;
|
|
36
|
+
/** Advance internal timers (the `after` auto-transitions). Call every frame with a delta in ms. */
|
|
37
|
+
tick(dtMs: number): void;
|
|
38
|
+
/** Subscribe to state changes. Returns an unsubscribe function. */
|
|
39
|
+
subscribe(fn: (state: S, previous: S) => void): () => void;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* A small typed finite state machine for bot/mascot behavior (idle,
|
|
43
|
+
* thinking, success, error, loading, sleeping, or any custom set). Framework-
|
|
44
|
+
* and renderer-agnostic: it only tracks state and timers, you decide in
|
|
45
|
+
* `onEnter`/`onExit` or in a `bind*` helper what that means visually.
|
|
46
|
+
*/
|
|
47
|
+
export declare function createStateMachine<S extends string, E extends string, Ctx = Record<string, never>>(config: StateMachineConfig<S, E, Ctx>): BotStateMachine<S, E, Ctx>;
|
|
48
|
+
/** Common bot states, free to use as-is or as a starting point for your own `S` union. */
|
|
49
|
+
export type CommonBotState = "idle" | "thinking" | "success" | "error" | "loading" | "sleeping";
|