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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jp-mainieri
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,83 @@
1
- # Temporary Holding Version
1
+ # procedural-bot-animations
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ![Three Berry characters, each with a different personality, animated by this engine](skills/procedural-bot-animations/assets/cover.gif)
4
+
5
+ A procedural animation engine for a silhouette-plus-eyes avatar — the shape format from [Open Bot Avatar](https://github.com/DominikScholz/open-bot-avatar) — with weighted/blended moods, one-shot reaction timelines (bounce, fright, nod, double-blink), gaze with saccade/pursuit/microsaccade physics and a fake-3D turn, plus a typed state machine for tying it all to real app events.
6
+
7
+ Open Bot Avatar is used only to **model** the shape (its editor or `generate-avatar` skill produce the JSON). This package never calls Open Bot Avatar's own renderer or runtime — it renders the shape itself, so moods and reactions can actually deform the eyes and body frame to frame.
8
+
9
+ ```
10
+ npm install procedural-bot-animations
11
+ ```
12
+
13
+ ```ts
14
+ import { getExample } from "open-bot-avatar"; // optional: a source of example shapes
15
+ import { bindBrain, createStateMachine } from "procedural-bot-animations";
16
+
17
+ const host = document.querySelector("#bot")!;
18
+
19
+ const machine = createStateMachine({
20
+ initial: "idle",
21
+ states: {
22
+ idle: { id: "idle" },
23
+ thinking: { id: "thinking" },
24
+ success: { id: "success", after: { ms: 1800, to: "idle" } },
25
+ },
26
+ transitions: [
27
+ { from: "idle", event: "ask", to: "thinking" },
28
+ { from: "thinking", event: "resolve", to: "success" },
29
+ ],
30
+ });
31
+
32
+ const bot = bindBrain({ host, definition: getExample("mug")!, color: "#ff6a1a" });
33
+ machine.subscribe((state) => {
34
+ if (state === "thinking") bot.brain.setMood({ focused: 1 });
35
+ if (state === "success") { bot.brain.setMood({ proud: 1 }); bot.brain.react("bounce"); }
36
+ if (state === "idle") bot.brain.setMood({ focused: 0, proud: 0 });
37
+ });
38
+ bot.start();
39
+
40
+ // elsewhere in your app:
41
+ machine.send("ask");
42
+ ```
43
+
44
+ A full, running version of this — with buttons, a mood/reaction panel, a character picker, light/dark and reduced-motion support — is in [`examples/states-demo.html`](examples/states-demo.html).
45
+
46
+ ## What's in this repo
47
+
48
+ | Path | What |
49
+ |---|---|
50
+ | [`src/`](src) | The engine: `render.ts` (mounts a definition as this package's own SVG — body path + two posable eyes), `moods.ts` (weighted/blended named moods), `reactions.ts` (one-shot keyframe-free closed-form reaction curves with a priority queue), `gaze.ts` (pursuit/saccade/microsaccade physics, autonomous wander), `fake3d.ts` (the flat-silhouette "head turn" illusion), `blink.ts`, `brain.ts` (composes all of the above into one `Pose` per frame, no DOM), `bind.ts` (the DOM/`requestAnimationFrame` glue), `state-machine.ts` (generic FSM), `scroll-traveler.ts` (a character that travels between page sections on scroll) |
51
+ | [`skills/procedural-bot-animations/`](skills/procedural-bot-animations) | A [Claude Code](https://claude.com/claude-code) skill teaching an agent to use this engine, with a calibrated motion cookbook, a state-machine design guide, and a case study |
52
+ | [`examples/`](examples) | A runnable states demo (Open Bot Avatar example shapes) and [`examples/berry-live/`](examples/berry-live) — see below |
53
+ | [`docs/architecture.md`](docs/architecture.md) | How the layers fit together, and how to point this at a different renderer |
54
+ | [`tests/`](tests) | Vitest unit tests (no DOM required — `render.ts`/`bind.ts` are the only DOM-dependent modules, verified by hand via the examples) |
55
+
56
+ ## Berry: a case study, not a toy example
57
+
58
+ [`examples/berry-live/`](examples/berry-live) is a faithful, working port of [DevBerry](https://devberry.app)'s actual mascot — real body-and-leaf geometry, real spring/leaf-bend physics, real keyframed personality reactions (wink, flatten, somersault), ported line-for-line from its production engine (credit and detail in [`skills/procedural-bot-animations/references/berry-case-study.md`](skills/procedural-bot-animations/references/berry-case-study.md)). It's **not** part of the installable package — Berry has a multi-part rig (three independently-sprung leaves), a different shape than the single silhouette `src/` targets. It's here so the gap between "a generic single-silhouette engine" and "a production multi-part character" is something you can see and copy from, not just a sentence in a README.
59
+
60
+ ## Relationship to Open Bot Avatar
61
+
62
+ This is an independent, unofficial companion project — not affiliated with or published by Open Bot Avatar's author. It depends on nothing from `open-bot-avatar` at runtime: the engine only needs a `{ body: { path }, eyes: { x, y, spacing, scale } }` definition, which you can get from Open Bot Avatar's editor/skill, hand-write, or generate any other way.
63
+
64
+ Open Bot Avatar is MIT-licensed by Dominik Scholz. This repo is also MIT-licensed; see [LICENSE](LICENSE). Berry is DevBerry's mascot, included in `examples/berry-live/` with its owner's permission (see the case study for exactly what's ported and what isn't).
65
+
66
+ ## Development
67
+
68
+ ```bash
69
+ npm install
70
+ npm run typecheck
71
+ npm test
72
+ npm run build
73
+ ```
74
+
75
+ `npm run check` runs all three in sequence — the same thing CI runs on every push.
76
+
77
+ ## Contributing
78
+
79
+ Issues and PRs are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md).
80
+
81
+ ## License
82
+
83
+ [MIT](LICENSE)
package/dist/bind.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ import { Brain, type BrainOptions } from "./brain.js";
2
+ import type { GazeTarget } from "./gaze.js";
3
+ import type { AvatarDefinitionLike } from "./types.js";
4
+ import { type MountedRig, type RenderOptions } from "./render.js";
5
+ export interface BoundBot {
6
+ readonly brain: Brain;
7
+ readonly rig: MountedRig;
8
+ /** Advance one frame. `nowMs` should be monotonically increasing, e.g. from `requestAnimationFrame`. */
9
+ tick(nowMs: number): void;
10
+ /** Runs `tick` on `requestAnimationFrame` until `stop()`. */
11
+ start(): void;
12
+ stop(): void;
13
+ destroy(): void;
14
+ }
15
+ export interface BindOptions extends RenderOptions {
16
+ host: HTMLElement;
17
+ definition: AvatarDefinitionLike;
18
+ brain?: BrainOptions;
19
+ /** Returns the live gaze target (e.g. pointer position relative to the host, -1..1) or `null` for autonomous wandering. */
20
+ getGazeTarget?: () => GazeTarget | null;
21
+ }
22
+ /**
23
+ * Mounts a definition with `mountRig` and wires a `Brain` to it: every
24
+ * frame it reads the gaze target, advances mood/gaze/blink/reactions, and
25
+ * applies the resulting pose to the rendered SVG.
26
+ */
27
+ export declare function bindBrain(options: BindOptions): BoundBot;
package/dist/bind.js ADDED
@@ -0,0 +1,42 @@
1
+ import { Brain } from "./brain.js";
2
+ import { safeDt } from "./spring.js";
3
+ import { mountRig } from "./render.js";
4
+ /**
5
+ * Mounts a definition with `mountRig` and wires a `Brain` to it: every
6
+ * frame it reads the gaze target, advances mood/gaze/blink/reactions, and
7
+ * applies the resulting pose to the rendered SVG.
8
+ */
9
+ export function bindBrain(options) {
10
+ const rig = mountRig(options.host, options.definition, options);
11
+ const brain = new Brain(options.brain);
12
+ let lastMs = null;
13
+ let rafId = null;
14
+ function tick(nowMs) {
15
+ const dt = safeDt(lastMs === null ? 16 : nowMs - lastMs);
16
+ lastMs = nowMs;
17
+ const target = options.getGazeTarget?.() ?? null;
18
+ rig.applyPose(brain.update(dt, target));
19
+ }
20
+ return {
21
+ brain,
22
+ rig,
23
+ tick,
24
+ start() {
25
+ const loop = (nowMs) => {
26
+ tick(nowMs);
27
+ rafId = requestAnimationFrame(loop);
28
+ };
29
+ rafId = requestAnimationFrame(loop);
30
+ },
31
+ stop() {
32
+ if (rafId !== null)
33
+ cancelAnimationFrame(rafId);
34
+ rafId = null;
35
+ lastMs = null;
36
+ },
37
+ destroy() {
38
+ this.stop();
39
+ rig.destroy();
40
+ },
41
+ };
42
+ }
@@ -0,0 +1,25 @@
1
+ import { type Rng } from "./rng.js";
2
+ export interface BlinkOptions {
3
+ /** Min/max seconds between blinks. Default [1.8, 6]. */
4
+ intervalSeconds?: [number, number];
5
+ /** Blink duration in seconds. Default 0.15. */
6
+ durationSeconds?: number;
7
+ /** Chance a blink is a double-blink. Default 0.2. */
8
+ doubleChance?: number;
9
+ rng?: Rng;
10
+ }
11
+ /**
12
+ * Schedules blinks and reports how shut the eyes should be (0 open, 1 shut)
13
+ * at the current time. Since this engine renders its own eyes instead of
14
+ * going through Open Bot Avatar's runtime (which blinks on its own),
15
+ * driving the blink is this package's job now.
16
+ */
17
+ export declare class BlinkScheduler {
18
+ private nextAt;
19
+ private closedUntil;
20
+ private pendingSecondBlink;
21
+ private readonly opts;
22
+ constructor(opts?: BlinkOptions);
23
+ /** Call every frame with the running clock `t` (seconds). Returns shut-ness, 0 (open) to 1 (shut). */
24
+ update(t: number): number;
25
+ }
package/dist/blink.js ADDED
@@ -0,0 +1,48 @@
1
+ import { chance, mulberry32, randRange } from "./rng.js";
2
+ /**
3
+ * Schedules blinks and reports how shut the eyes should be (0 open, 1 shut)
4
+ * at the current time. Since this engine renders its own eyes instead of
5
+ * going through Open Bot Avatar's runtime (which blinks on its own),
6
+ * driving the blink is this package's job now.
7
+ */
8
+ export class BlinkScheduler {
9
+ nextAt;
10
+ closedUntil = -1;
11
+ pendingSecondBlink = false;
12
+ opts;
13
+ constructor(opts = {}) {
14
+ this.opts = {
15
+ intervalSeconds: opts.intervalSeconds ?? [1.8, 6],
16
+ durationSeconds: opts.durationSeconds ?? 0.15,
17
+ doubleChance: opts.doubleChance ?? 0.2,
18
+ rng: opts.rng ?? mulberry32(),
19
+ };
20
+ this.nextAt = randRange(this.opts.rng, ...this.opts.intervalSeconds);
21
+ }
22
+ /** Call every frame with the running clock `t` (seconds). Returns shut-ness, 0 (open) to 1 (shut). */
23
+ update(t) {
24
+ const { intervalSeconds, durationSeconds, doubleChance, rng } = this.opts;
25
+ if (this.closedUntil < 0 && t >= this.nextAt) {
26
+ this.closedUntil = t + durationSeconds;
27
+ }
28
+ if (this.closedUntil >= 0 && t >= this.closedUntil) {
29
+ this.closedUntil = -1;
30
+ if (this.pendingSecondBlink) {
31
+ this.pendingSecondBlink = false;
32
+ this.nextAt = t + durationSeconds * 1.6;
33
+ }
34
+ else if (chance(rng, doubleChance)) {
35
+ this.pendingSecondBlink = true;
36
+ this.nextAt = t + durationSeconds * 1.6;
37
+ }
38
+ else {
39
+ this.nextAt = t + randRange(rng, ...intervalSeconds);
40
+ }
41
+ }
42
+ if (this.closedUntil < 0)
43
+ return 0;
44
+ const remaining = this.closedUntil - t;
45
+ const half = durationSeconds / 2;
46
+ return remaining > half ? 1 - (remaining - half) / half : remaining / half;
47
+ }
48
+ }
@@ -0,0 +1,39 @@
1
+ import { BlinkScheduler, type BlinkOptions } from "./blink.js";
2
+ import { type FakeTurnOptions } from "./fake3d.js";
3
+ import { GazeEngine, type GazeEngineOptions, type GazeTarget } from "./gaze.js";
4
+ import { MoodBlender, type MoodBlenderOptions, type MoodWeights } from "./moods.js";
5
+ import { ReactionPlayer, type ReactionPlayerOptions } from "./reactions.js";
6
+ import { type Pose } from "./types.js";
7
+ export interface BrainOptions {
8
+ gaze?: GazeEngineOptions;
9
+ moods?: MoodBlenderOptions;
10
+ reactions?: ReactionPlayerOptions;
11
+ blink?: BlinkOptions;
12
+ fakeTurn?: FakeTurnOptions;
13
+ /** How much of the gaze's vertical offset becomes eye slide, in viewBox units. Default 2.5. */
14
+ gazeRangeY?: number;
15
+ /** Breathing cycles/sec and amount; see `noise.ts#breathing`. */
16
+ breathing?: {
17
+ frequency?: number;
18
+ depthAmount?: number;
19
+ };
20
+ }
21
+ /**
22
+ * The pure, DOM-free core: combines mood blending, gaze (with the fake-3D
23
+ * turn), blinking and one-shot reactions into a single `Pose` every frame.
24
+ * No rendering, no `requestAnimationFrame` — a DOM binder (see
25
+ * `examples/states-demo.html` or write your own) reads `update()`'s output
26
+ * and calls `MountedRig.applyPose`.
27
+ */
28
+ export declare class Brain {
29
+ readonly gazeEngine: GazeEngine;
30
+ readonly moodBlender: MoodBlender;
31
+ readonly reactionPlayer: ReactionPlayer;
32
+ readonly blinkScheduler: BlinkScheduler;
33
+ private clock;
34
+ private readonly opts;
35
+ constructor(options?: BrainOptions);
36
+ setMood(weights: MoodWeights): void;
37
+ react(name: string): boolean;
38
+ update(dt: number, gazeTarget: GazeTarget | null): Pose;
39
+ }
package/dist/brain.js ADDED
@@ -0,0 +1,57 @@
1
+ import { BlinkScheduler } from "./blink.js";
2
+ import { fakeTurn } from "./fake3d.js";
3
+ import { GazeEngine } from "./gaze.js";
4
+ import { MoodBlender } from "./moods.js";
5
+ import { breathing } from "./noise.js";
6
+ import { ReactionPlayer } from "./reactions.js";
7
+ import { addPose, neutralPose, resolveDelta } from "./types.js";
8
+ /**
9
+ * The pure, DOM-free core: combines mood blending, gaze (with the fake-3D
10
+ * turn), blinking and one-shot reactions into a single `Pose` every frame.
11
+ * No rendering, no `requestAnimationFrame` — a DOM binder (see
12
+ * `examples/states-demo.html` or write your own) reads `update()`'s output
13
+ * and calls `MountedRig.applyPose`.
14
+ */
15
+ export class Brain {
16
+ gazeEngine;
17
+ moodBlender;
18
+ reactionPlayer;
19
+ blinkScheduler;
20
+ clock = 0;
21
+ opts;
22
+ constructor(options = {}) {
23
+ this.opts = options;
24
+ this.gazeEngine = new GazeEngine(options.gaze);
25
+ this.moodBlender = new MoodBlender(options.moods);
26
+ this.reactionPlayer = new ReactionPlayer(options.reactions);
27
+ this.blinkScheduler = new BlinkScheduler(options.blink);
28
+ }
29
+ setMood(weights) {
30
+ this.moodBlender.set(weights);
31
+ }
32
+ react(name) {
33
+ return this.reactionPlayer.play(name);
34
+ }
35
+ update(dt, gazeTarget) {
36
+ this.clock += dt;
37
+ const t = this.clock;
38
+ let pose = neutralPose();
39
+ const moodDelta = this.moodBlender.update(dt);
40
+ pose = addPose(pose, resolveDelta(moodDelta));
41
+ const gaze = this.gazeEngine.update(dt, gazeTarget, t);
42
+ const turnDelta = fakeTurn(gaze.offset.x, this.opts.fakeTurn);
43
+ pose = addPose(pose, resolveDelta(turnDelta));
44
+ pose = addPose(pose, resolveDelta({ eyes: { offsetY: gaze.offset.y * (this.opts.gazeRangeY ?? 2.5) } }));
45
+ const attentionScale = 1 + gaze.attention * 0.15;
46
+ const boredomScale = 1 - gaze.boredom * 0.3;
47
+ pose = addPose(pose, resolveDelta({ eyes: { scaleX: attentionScale * boredomScale, scaleY: attentionScale * boredomScale, shut: gaze.boredom * 0.25 } }));
48
+ const blinkShut = this.blinkScheduler.update(t);
49
+ pose = addPose(pose, resolveDelta({ eyes: { shut: blinkShut } }));
50
+ const breathe = breathing(t, this.opts.breathing);
51
+ pose = addPose(pose, resolveDelta({ body: { scaleY: breathe, scaleX: 1 + (1 - breathe) * 0.5 } }));
52
+ const reactionDelta = this.reactionPlayer.update(dt);
53
+ if (reactionDelta)
54
+ pose = addPose(pose, resolveDelta(reactionDelta));
55
+ return pose;
56
+ }
57
+ }
@@ -0,0 +1,20 @@
1
+ import type { PoseDelta } from "./types.js";
2
+ export interface FakeTurnOptions {
3
+ /** Max eye slide, in viewBox units, at `turn = ±1`. Default 6. */
4
+ maxSlide?: number;
5
+ /** How much the far eye shrinks in width at `turn = ±1`, 0..1. Default 0.4. */
6
+ farShrink?: number;
7
+ /** How much the near eye grows in width at `turn = ±1`, 0..1. Default 0.12. */
8
+ nearGrow?: number;
9
+ /** Body lean, degrees at `turn = ±1`. Default 2. */
10
+ bodyLeanDeg?: number;
11
+ }
12
+ /**
13
+ * The Pumpy/Open-Bot-Avatar-style "fake 3D turn": on a flat silhouette with
14
+ * no real depth, sliding both eyes toward the turn direction and shrinking
15
+ * the eye on the far side (while the near one grows slightly) reads as the
16
+ * head rotating, the same illusion Open Bot Avatar gets from projecting
17
+ * stacked cross-sections — reproduced here directly on the eyes since this
18
+ * engine draws its own flat silhouette instead of that projection.
19
+ */
20
+ export declare function fakeTurn(turn: number, options?: FakeTurnOptions): PoseDelta;
package/dist/fake3d.js ADDED
@@ -0,0 +1,24 @@
1
+ import { clamp } from "./spring.js";
2
+ /**
3
+ * The Pumpy/Open-Bot-Avatar-style "fake 3D turn": on a flat silhouette with
4
+ * no real depth, sliding both eyes toward the turn direction and shrinking
5
+ * the eye on the far side (while the near one grows slightly) reads as the
6
+ * head rotating, the same illusion Open Bot Avatar gets from projecting
7
+ * stacked cross-sections — reproduced here directly on the eyes since this
8
+ * engine draws its own flat silhouette instead of that projection.
9
+ */
10
+ export function fakeTurn(turn, options = {}) {
11
+ const { maxSlide = 6, farShrink = 0.4, nearGrow = 0.12, bodyLeanDeg = 2 } = options;
12
+ const t = clamp(turn, -1, 1);
13
+ const slide = t * maxSlide;
14
+ // t > 0: turning toward the right eye (near side), away from the left eye (far side).
15
+ const leftScaleX = 1 - Math.max(0, t) * farShrink - Math.max(0, -t) * 0; // left shrinks when turning right
16
+ const rightScaleX = 1 - Math.max(0, -t) * farShrink; // right shrinks when turning left
17
+ const leftGrow = 1 + Math.max(0, -t) * nearGrow; // left grows when turning left (left becomes near)
18
+ const rightGrow = 1 + Math.max(0, t) * nearGrow; // right grows when turning right
19
+ return {
20
+ leftEye: { offsetX: slide, scaleX: leftScaleX * leftGrow },
21
+ rightEye: { offsetX: slide, scaleX: rightScaleX * rightGrow },
22
+ body: { rotate: t * bodyLeanDeg },
23
+ };
24
+ }
package/dist/gaze.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ import { type Rng } from "./rng.js";
2
+ export interface Point2D {
3
+ x: number;
4
+ y: number;
5
+ }
6
+ export type ArrivalStyle = "saccade" | "pursuit";
7
+ export interface GazeTarget {
8
+ point: Point2D;
9
+ /** How the eye should get there. Default "pursuit" (smooth, no overshoot) for a moving target, "saccade" (snap + settle) for a newly-appeared one — pass explicitly when you know which. */
10
+ arrival?: ArrivalStyle;
11
+ }
12
+ export interface GazeOutput {
13
+ offset: Point2D;
14
+ /** 0..1: recently had a big saccade or a fast-moving target. Widens the eyes. */
15
+ attention: number;
16
+ /** 0..1: no target/motion for a while. Heavies the eyelids. */
17
+ boredom: number;
18
+ }
19
+ export interface GazeEngineOptions {
20
+ /** Damp rate for smooth pursuit. Default 9. */
21
+ pursuitRate?: number;
22
+ /** Spring for a saccade — the default slightly overshoots, then settles. */
23
+ saccadeSpring?: {
24
+ stiffness: number;
25
+ damping: number;
26
+ };
27
+ /** Constant small jitter amplitude so the eye never looks perfectly frozen. Default 0.015. */
28
+ microsaccadeAmplitude?: number;
29
+ /** Seconds with no target before boredom starts rising. Default 4. */
30
+ boredomAfterSeconds?: number;
31
+ /** Seconds between autonomous wander targets, used when no explicit target is given. Default [1.2, 3.8]. */
32
+ wanderIntervalSeconds?: [number, number];
33
+ wanderRange?: number;
34
+ recenterChance?: number;
35
+ rng?: Rng;
36
+ }
37
+ /**
38
+ * Drives one `(x, y)` gaze offset (-1..1 ish) from either an explicit target
39
+ * (pointer position, a focus anchor) or autonomous wandering, with two
40
+ * distinct arrival feels — `pursuit` (critically damped, used for a target
41
+ * that is itself moving, like a cursor) and `saccade` (slightly
42
+ * underdamped, used for a target that just appeared) — plus a constant
43
+ * microsaccade jitter and an attention/boredom scalar a caller can map onto
44
+ * eye size and eyelid openness.
45
+ */
46
+ export declare class GazeEngine {
47
+ private pos;
48
+ private posY;
49
+ private pursuit;
50
+ private usingSaccade;
51
+ private lastTargetPoint;
52
+ private attention;
53
+ private idleSeconds;
54
+ private wanderTarget;
55
+ private nextWanderAt;
56
+ private readonly opts;
57
+ constructor(options?: GazeEngineOptions);
58
+ /** Call every frame. Pass `null` for an explicit target to fall back to autonomous wandering. */
59
+ update(dt: number, explicitTarget: GazeTarget | null, t: number): GazeOutput;
60
+ }
package/dist/gaze.js ADDED
@@ -0,0 +1,90 @@
1
+ import { damp, spring } from "./spring.js";
2
+ import { neverRepeating } from "./noise.js";
3
+ import { chance, mulberry32, randRange } from "./rng.js";
4
+ const DEFAULT_SACCADE_SPRING = { stiffness: 260, damping: 16 };
5
+ /**
6
+ * Drives one `(x, y)` gaze offset (-1..1 ish) from either an explicit target
7
+ * (pointer position, a focus anchor) or autonomous wandering, with two
8
+ * distinct arrival feels — `pursuit` (critically damped, used for a target
9
+ * that is itself moving, like a cursor) and `saccade` (slightly
10
+ * underdamped, used for a target that just appeared) — plus a constant
11
+ * microsaccade jitter and an attention/boredom scalar a caller can map onto
12
+ * eye size and eyelid openness.
13
+ */
14
+ export class GazeEngine {
15
+ pos = { value: 0, velocity: 0 }; // x, driven by whichever arrival style is active
16
+ posY = { value: 0, velocity: 0 };
17
+ pursuit = { x: 0, y: 0 };
18
+ usingSaccade = false;
19
+ lastTargetPoint = null;
20
+ attention = 0;
21
+ idleSeconds = 0;
22
+ wanderTarget = { x: 0, y: 0 };
23
+ nextWanderAt = 0;
24
+ opts;
25
+ constructor(options = {}) {
26
+ this.opts = {
27
+ pursuitRate: options.pursuitRate ?? 9,
28
+ saccadeSpring: options.saccadeSpring ?? DEFAULT_SACCADE_SPRING,
29
+ microsaccadeAmplitude: options.microsaccadeAmplitude ?? 0.015,
30
+ boredomAfterSeconds: options.boredomAfterSeconds ?? 4,
31
+ wanderIntervalSeconds: options.wanderIntervalSeconds ?? [1.2, 3.8],
32
+ wanderRange: options.wanderRange ?? 0.6,
33
+ recenterChance: options.recenterChance ?? 0.3,
34
+ rng: options.rng ?? mulberry32(),
35
+ };
36
+ }
37
+ /** Call every frame. Pass `null` for an explicit target to fall back to autonomous wandering. */
38
+ update(dt, explicitTarget, t) {
39
+ const { rng, wanderIntervalSeconds, wanderRange, recenterChance, boredomAfterSeconds } = this.opts;
40
+ let target = explicitTarget;
41
+ if (!target) {
42
+ this.idleSeconds += dt;
43
+ this.nextWanderAt -= dt;
44
+ if (this.nextWanderAt <= 0) {
45
+ this.nextWanderAt = randRange(rng, wanderIntervalSeconds[0], wanderIntervalSeconds[1]);
46
+ const newTarget = chance(rng, recenterChance)
47
+ ? { x: 0, y: 0 }
48
+ : { x: randRange(rng, -wanderRange, wanderRange), y: randRange(rng, -wanderRange, wanderRange) };
49
+ this.wanderTarget = newTarget;
50
+ target = { point: newTarget, arrival: "saccade" };
51
+ }
52
+ else {
53
+ target = { point: this.wanderTarget, arrival: "pursuit" };
54
+ }
55
+ }
56
+ else {
57
+ this.idleSeconds = 0;
58
+ }
59
+ const isNewPoint = !this.lastTargetPoint || this.lastTargetPoint.x !== target.point.x || this.lastTargetPoint.y !== target.point.y;
60
+ this.lastTargetPoint = target.point;
61
+ const arrival = target.arrival ?? "pursuit";
62
+ this.usingSaccade = arrival === "saccade" && isNewPoint ? true : this.usingSaccade;
63
+ let x;
64
+ let y;
65
+ if (arrival === "saccade") {
66
+ spring(this.pos, target.point.x, this.opts.saccadeSpring.stiffness, this.opts.saccadeSpring.damping, dt);
67
+ spring(this.posY, target.point.y, this.opts.saccadeSpring.stiffness, this.opts.saccadeSpring.damping, dt);
68
+ x = this.pos.value;
69
+ y = this.posY.value;
70
+ if (isNewPoint)
71
+ this.attention = Math.min(1, this.attention + 0.6);
72
+ }
73
+ else {
74
+ this.pursuit = { x: damp(this.pursuit.x, target.point.x, this.opts.pursuitRate, dt), y: damp(this.pursuit.y, target.point.y, this.opts.pursuitRate, dt) };
75
+ // Keep the saccade spring following too, at rest, so a later saccade doesn't jump from a stale position.
76
+ this.pos.value = this.pursuit.x;
77
+ this.pos.velocity = 0;
78
+ this.posY.value = this.pursuit.y;
79
+ this.posY.velocity = 0;
80
+ x = this.pursuit.x;
81
+ y = this.pursuit.y;
82
+ }
83
+ this.attention = damp(this.attention, 0, 1.5, dt);
84
+ const boredom = this.idleSeconds > boredomAfterSeconds ? Math.min(1, (this.idleSeconds - boredomAfterSeconds) / 3) : 0;
85
+ const jitter = this.opts.microsaccadeAmplitude;
86
+ x += neverRepeating(t, 7) * jitter;
87
+ y += neverRepeating(t, 13) * jitter * 0.6;
88
+ return { offset: { x, y }, attention: this.attention, boredom };
89
+ }
90
+ }
@@ -0,0 +1,14 @@
1
+ export * from "./spring.js";
2
+ export * from "./rng.js";
3
+ export * from "./noise.js";
4
+ export * from "./types.js";
5
+ export * from "./render.js";
6
+ export * from "./moods.js";
7
+ export * from "./reactions.js";
8
+ export * from "./gaze.js";
9
+ export * from "./fake3d.js";
10
+ export * from "./blink.js";
11
+ export * from "./brain.js";
12
+ export * from "./bind.js";
13
+ export * from "./state-machine.js";
14
+ export * from "./scroll-traveler.js";
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ export * from "./spring.js";
2
+ export * from "./rng.js";
3
+ export * from "./noise.js";
4
+ export * from "./types.js";
5
+ export * from "./render.js";
6
+ export * from "./moods.js";
7
+ export * from "./reactions.js";
8
+ export * from "./gaze.js";
9
+ export * from "./fake3d.js";
10
+ export * from "./blink.js";
11
+ export * from "./brain.js";
12
+ export * from "./bind.js";
13
+ export * from "./state-machine.js";
14
+ export * from "./scroll-traveler.js";
@@ -0,0 +1,48 @@
1
+ import type { PoseDelta } from "./types.js";
2
+ /**
3
+ * One mood's fully-applied (weight = 1) look. Scale-like fields are lerped
4
+ * from neutral (1 or 0) by the mood's weight and then multiplied across
5
+ * active moods, so e.g. `curious` and `sleepy` can be mixed instead of one
6
+ * replacing the other outright — the thing Open Bot Avatar's three-string
7
+ * `mood` can't do.
8
+ */
9
+ export interface MoodDefinition {
10
+ eyeScaleX?: number;
11
+ eyeScaleY?: number;
12
+ eyeOffsetY?: number;
13
+ eyeRotate?: number;
14
+ eyeArcAmount?: number;
15
+ eyeShut?: number;
16
+ bodyY?: number;
17
+ bodyScaleY?: number;
18
+ bodyRotate?: number;
19
+ }
20
+ /** A starting set covering most app states; add your own with the same shape. */
21
+ export declare const builtinMoods: Record<string, MoodDefinition>;
22
+ export type MoodWeights = Record<string, number>;
23
+ /**
24
+ * Blends any number of simultaneously-active moods, each 0..1, into one
25
+ * pose delta. Unlisted moods (weight 0 or absent) contribute nothing.
26
+ */
27
+ export declare function blendMoods(weights: MoodWeights, moods?: Record<string, MoodDefinition>): PoseDelta;
28
+ export interface MoodBlenderOptions {
29
+ /** How fast each mood's weight eases toward its target, 1/seconds. Default 5 (matches DevBerry's calibration). */
30
+ rate?: number;
31
+ }
32
+ /**
33
+ * Smooths mood weights over time instead of snapping them, so switching
34
+ * which moods are "on" doesn't pop. Set target weights with `set`, read the
35
+ * current smoothed blend with `update`.
36
+ */
37
+ export declare class MoodBlender {
38
+ private current;
39
+ private target;
40
+ private readonly rate;
41
+ private readonly moods;
42
+ constructor(options?: MoodBlenderOptions & {
43
+ moods?: Record<string, MoodDefinition>;
44
+ });
45
+ /** Sets (or clears, at weight 0 / omission) target weights for the named moods. Others are left as they are. */
46
+ set(weights: MoodWeights): void;
47
+ update(dt: number): PoseDelta;
48
+ }