procedural-bot-animations 0.1.0 → 0.2.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.
Files changed (59) hide show
  1. package/README.md +167 -47
  2. package/dist/animation.d.ts +90 -0
  3. package/dist/animation.js +396 -0
  4. package/dist/brain.d.ts +194 -35
  5. package/dist/brain.js +578 -54
  6. package/dist/character.d.ts +123 -0
  7. package/dist/character.js +916 -0
  8. package/dist/characters/berry.d.ts +2 -0
  9. package/dist/characters/berry.js +38 -0
  10. package/dist/characters/flame.d.ts +2 -0
  11. package/dist/characters/flame.js +46 -0
  12. package/dist/delta.d.ts +16 -0
  13. package/dist/delta.js +146 -0
  14. package/dist/examples.d.ts +4 -0
  15. package/dist/examples.js +208 -0
  16. package/dist/focus.d.ts +46 -0
  17. package/dist/focus.js +284 -0
  18. package/dist/gaze.d.ts +41 -53
  19. package/dist/gaze.js +125 -82
  20. package/dist/index.d.ts +18 -11
  21. package/dist/index.js +18 -11
  22. package/dist/interactions.d.ts +30 -0
  23. package/dist/interactions.js +100 -0
  24. package/dist/library.d.ts +18 -0
  25. package/dist/library.js +14 -0
  26. package/dist/moods.d.ts +78 -46
  27. package/dist/moods.js +48 -73
  28. package/dist/motion.d.ts +93 -0
  29. package/dist/motion.js +167 -0
  30. package/dist/mount.d.ts +90 -0
  31. package/dist/mount.js +707 -0
  32. package/dist/parts.d.ts +36 -0
  33. package/dist/parts.js +131 -0
  34. package/dist/reactions.d.ts +184 -44
  35. package/dist/reactions.js +1851 -116
  36. package/dist/rig.d.ts +119 -0
  37. package/dist/rig.js +59 -0
  38. package/dist/scroll-traveler.js +1 -1
  39. package/dist/ticker.d.ts +10 -0
  40. package/dist/ticker.js +42 -0
  41. package/dist/transformations.d.ts +21 -0
  42. package/dist/transformations.js +306 -0
  43. package/package.json +7 -11
  44. package/dist/bind.d.ts +0 -27
  45. package/dist/bind.js +0 -42
  46. package/dist/blink.d.ts +0 -25
  47. package/dist/blink.js +0 -48
  48. package/dist/fake3d.d.ts +0 -20
  49. package/dist/fake3d.js +0 -24
  50. package/dist/noise.d.ts +0 -16
  51. package/dist/noise.js +0 -17
  52. package/dist/render.d.ts +0 -29
  53. package/dist/render.js +0 -97
  54. package/dist/rng.d.ts +0 -10
  55. package/dist/rng.js +0 -18
  56. package/dist/spring.d.ts +0 -21
  57. package/dist/spring.js +0 -33
  58. package/dist/types.d.ts +0 -63
  59. package/dist/types.js +0 -46
@@ -0,0 +1,396 @@
1
+ /*
2
+ * Animation definitions: plain JSON for reactions (one-shot), activities
3
+ * (loops) and moods (static poses), validated and compiled into the same
4
+ * objects the built-in library uses.
5
+ */
6
+ import { FIELDS } from "./delta.js";
7
+ import { CURVES, fromTracks } from "./motion.js";
8
+ const f = (group, unit, min, max, description) => ({
9
+ group,
10
+ unit,
11
+ min,
12
+ max,
13
+ rest: 0,
14
+ description,
15
+ });
16
+ /**
17
+ * One entry per delta field. The hard ranges come from the extreme values the
18
+ * built-in reactions, activities and moods actually reach, widened about 1.5×.
19
+ * 0 is always the character at rest.
20
+ */
21
+ export const FIELD_INFO = {
22
+ rootY: f("body", "px", -400, 650, "Raises (negative) or lowers the whole character; the shadow stays on the ground."),
23
+ opacity: f("body", "-1..1", -1, 0, "Added to the opacity (-1 disappears)."),
24
+ bodyRotate: f("body", "deg", -45, 45, "Rotation around the ground (leaning)."),
25
+ centerRotate: f("body", "deg", -720, 720, "Rotation around the body center (somersault)."),
26
+ bodySx: f("body", "scale", -0.5, 0.6, "Horizontal stretch of the body from the ground (0.2 = 20% wider)."),
27
+ bodySy: f("body", "scale", -0.8, 0.8, "Vertical stretch of the body from the ground (-0.2 = 20% shorter). Keep bodySx near -bodySy to preserve volume."),
28
+ scale: f("body", "scale", -1, 0.5, "Uniform scale of the character, from the ground (-1 vanishes)."),
29
+ partC: f("parts", "deg", -50, 50, "Middle appendage rotation."),
30
+ partL: f("parts", "deg", -50, 50, "Left appendage: positive raises it."),
31
+ partR: f("parts", "deg", -50, 50, "Right appendage: negative raises it (mirrored)."),
32
+ partAmp: f("parts", "scale", -1, 1.5, "Multiplies the amplitude of the appendage sway (-1 freezes it)."),
33
+ eyeX: f("eyes", "px", -40, 40, "Eyes move horizontally."),
34
+ eyeY: f("eyes", "px", -40, 40, "Eyes move vertically (positive looks down)."),
35
+ eyeSx: f("eyes", "scale", -1, 0.6, "Eye width, increment over 1."),
36
+ eyeSy: f("eyes", "scale", -1, 0.6, "Eye height, increment over 1 (-0.5 leaves the eye at half its height)."),
37
+ turn: f("eyes", "-1..1", -1.6, 1.6, "Fake 3D turn: -1 to 1 turns the face; up to +-1.6 is a profile."),
38
+ happy: f("eyes", "0..1", 0, 1, "Both eyes become arcs (^)."),
39
+ happyLeft: f("eyes", "0..1", 0, 1, "Only the left eye becomes an arc (^)."),
40
+ happyRight: f("eyes", "0..1", 0, 1, "Only the right eye becomes an arc (^)."),
41
+ holdGaze: f("eyes", "0..1", 0, 1, "How much the reaction takes over the gaze (0 follows the target, 1 only the reaction rules)."),
42
+ lidTop: f("lids", "0..1", 0, 1, "Top eyelid (0 open, 1 closes the eye from the top down)."),
43
+ lidBottom: f("lids", "0..1", 0, 1, "Bottom eyelid (0 open, 1 closes from the bottom up): a smiling look."),
44
+ lidAngle: f("lids", "deg", -40, 40, "Eyelid tilt: positive slopes down toward the inside (angry, suspicious), negative toward the outside (worried)."),
45
+ closeLeft: f("lids", "0..1", 0, 1, "Closes just the left eye (a wink)."),
46
+ closeRight: f("lids", "0..1", 0, 1, "Closes just the right eye (a wink)."),
47
+ shadow: f("body", "-1..1", -1, 0, "Shadow opacity, added to 1 (-1 hides the shadow; it cannot get stronger than normal)."),
48
+ lamp: f("accessories", "0..1", 0, 1, "Light bulb accessory (0 hidden, 1 visible)."),
49
+ exclaim: f("accessories", "0..1", 0, 1, "Exclamation mark (0 hidden, 1 visible)."),
50
+ question: f("accessories", "0..1", 0, 1, "Question mark (0 hidden, 1 visible)."),
51
+ ellipsis: f("accessories", "0..1", 0, 1, "Three dots (0 hidden, 1 visible)."),
52
+ zzz: f("accessories", "0..1", 0, 1, "Sleeping Z's (0 hidden, 1 visible)."),
53
+ rays: f("accessories", "0..1", 0, 1, "Light rays (0 hidden, 1 visible)."),
54
+ sparks: f("accessories", "0..1", 0, 1, "Progress of the sparks of a hit (0 to 1); 0 when there are none."),
55
+ gray: f("flame", "0..1", 0, 1, "Loses its color: 0 normal, 1 gray (flame characters)."),
56
+ core: f("flame", "0..1", 0, 1, "Lit yellow core (flame characters)."),
57
+ embers: f("flame", "0..1", 0, 1, "Embers rising from the tongues (intensity)."),
58
+ smoke: f("flame", "0..1", 0, 1, "Smoke coming off the tip (intensity)."),
59
+ morph: f("morph", "0..1", 0, 1, "Starts the transformation: scaling becomes relative to the anchor and the idle goes quiet."),
60
+ round: f("morph", "0..1", 0, 1, "The silhouette becomes a circle."),
61
+ retract: f("morph", "-1..1", -0.5, 1, "Appendages retract into the body (negative: they pop out bigger)."),
62
+ eyesVanish: f("morph", "0..1", 0, 1, "The eyes shrink until they vanish."),
63
+ swap: f("morph", "0..1", 0, 1, "At 0.5 or more shows the object in place of the body."),
64
+ bubbleR: f("morph", "px", 0, 200, "Outer radius of the bubble (a disc when bubbleHole is 0)."),
65
+ bubbleHole: f("morph", "px", 0, 130, "Radius of the hole: with a hole, the bubble becomes a ring."),
66
+ bubbleArc: f("morph", "0..1", 0, 1, "Fraction of the ring that is missing (0 = whole ring)."),
67
+ bubbleX: f("morph", "px", -200, 200, "Horizontal offset of the bubble."),
68
+ bubbleY: f("morph", "px", -200, 200, "Vertical offset of the bubble."),
69
+ dotsDist: f("morph", "px", 0, 260, "Distance from the side dots to the bubble; they are born underneath it."),
70
+ dotsBounce: f("morph", "0..1", 0, 1, "How much the dots bounce."),
71
+ checkDraw: f("morph", "0..1", 0, 1, "How much of the check mark has been drawn, from the bubble."),
72
+ codeDraw: f("morph", "0..1", 0, 1, "How much of the </> has been drawn, from the three dots."),
73
+ orbitOpen: f("morph", "0..1", 0, 1, "The orbit dots come out from under the bubble up to the full radius."),
74
+ objScale: f("morph", "scale", -0.5, 0.5, "Added to the object's scale (pulse)."),
75
+ objRotate: f("morph", "deg", -2200, 2200, "Rotation of the object, in degrees."),
76
+ };
77
+ /** Group of every field, in the order of `FIELDS`. */
78
+ export const FIELD_GROUPS = ["body", "parts", "eyes", "lids", "accessories", "flame", "morph"];
79
+ export const CURVE_NAMES = Object.keys(CURVES);
80
+ export const ANIMATION_LIMITS = {
81
+ reactionDuration: [0.2, 10],
82
+ activityPeriod: [0.3, 20],
83
+ maxTracks: 24,
84
+ maxKeyframes: 40,
85
+ nameMax: 60,
86
+ };
87
+ /** Fields a mood may not set: transformations, sparks, and anything that changes opacity or size. */
88
+ const MOOD_FORBIDDEN = new Set(["sparks", "opacity", "scale"]);
89
+ /* ---------- helpers ---------- */
90
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
91
+ const isNum = (v) => typeof v === "number" && Number.isFinite(v);
92
+ const ID_RE = /^[a-z][a-zA-Z0-9]{1,39}$/;
93
+ const isField = (k) => Object.prototype.hasOwnProperty.call(FIELD_INFO, k);
94
+ function distance(a, b) {
95
+ const prev = Array.from({ length: b.length + 1 }, (_, j) => j);
96
+ for (let i = 1; i <= a.length; i++) {
97
+ let diag = prev[0];
98
+ prev[0] = i;
99
+ for (let j = 1; j <= b.length; j++) {
100
+ const tmp = prev[j];
101
+ prev[j] = Math.min(prev[j] + 1, prev[j - 1] + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));
102
+ diag = tmp;
103
+ }
104
+ }
105
+ return prev[b.length];
106
+ }
107
+ /** The valid field names closest to `name` (case-insensitive edit distance, substring matches first). */
108
+ export function closestFields(name, count = 3) {
109
+ const low = name.toLowerCase();
110
+ return [...FIELDS]
111
+ .map((k) => {
112
+ const kl = k.toLowerCase();
113
+ const sub = kl.includes(low) || low.includes(kl) ? -2 : 0;
114
+ return { k, score: distance(low, kl) + sub };
115
+ })
116
+ .sort((a, b) => a.score - b.score)
117
+ .slice(0, count)
118
+ .map((x) => x.k);
119
+ }
120
+ const num = (n) => Number(n.toFixed(3)).toString();
121
+ /* ---------- validation ---------- */
122
+ function checkTrack(at, field, kfs, errors) {
123
+ if (!Array.isArray(kfs)) {
124
+ errors.push(`${at}: must be an array of keyframes [t, value] or [t, value, curve]`);
125
+ return null;
126
+ }
127
+ if (kfs.length < 2) {
128
+ errors.push(`${at}: needs at least 2 keyframes`);
129
+ return null;
130
+ }
131
+ if (kfs.length > ANIMATION_LIMITS.maxKeyframes) {
132
+ errors.push(`${at}: ${kfs.length} keyframes, the limit is ${ANIMATION_LIMITS.maxKeyframes}`);
133
+ return null;
134
+ }
135
+ const info = FIELD_INFO[field];
136
+ const before = errors.length;
137
+ const out = [];
138
+ let last = -1;
139
+ kfs.forEach((kf, i) => {
140
+ const k = `${at}[${i}]`;
141
+ if (!Array.isArray(kf) || (kf.length !== 2 && kf.length !== 3)) {
142
+ errors.push(`${k}: must be [t, value] or [t, value, curve]`);
143
+ return;
144
+ }
145
+ const [t, v, curve] = kf;
146
+ let ok = true;
147
+ if (!isNum(t) || t < 0 || t > 1) {
148
+ errors.push(`${k}: t must be a number between 0 and 1`);
149
+ ok = false;
150
+ }
151
+ else {
152
+ if (i === 0 && t !== 0) {
153
+ errors.push(`${k}: the first keyframe must have t = 0`);
154
+ ok = false;
155
+ }
156
+ if (t < last) {
157
+ errors.push(`${k}: t = ${t} is smaller than the previous keyframe's (${last}); times must not decrease`);
158
+ ok = false;
159
+ }
160
+ last = t;
161
+ }
162
+ if (!isNum(v) || v < info.min || v > info.max) {
163
+ errors.push(`${k}: value for ${field} must be a number between ${info.min} and ${info.max} (${info.unit})`);
164
+ ok = false;
165
+ }
166
+ if (curve !== undefined && (typeof curve !== "string" || !CURVE_NAMES.includes(curve))) {
167
+ errors.push(`${k}: curve must be one of ${CURVE_NAMES.map((c) => `"${c}"`).join(", ")}`);
168
+ ok = false;
169
+ }
170
+ if (ok)
171
+ out.push(curve === undefined ? [t, v] : [t, v, curve]);
172
+ });
173
+ return errors.length > before ? null : out;
174
+ }
175
+ /** Checks the shape shared by reactions and activities; returns the tracks that are individually valid. */
176
+ function checkTracks(raw, errors) {
177
+ if (!isRecord(raw)) {
178
+ errors.push("tracks: must be an object { fieldName: [[t, value], ...] }");
179
+ return null;
180
+ }
181
+ const names = Object.keys(raw);
182
+ if (names.length === 0) {
183
+ errors.push("tracks: needs at least one track");
184
+ return null;
185
+ }
186
+ if (names.length > ANIMATION_LIMITS.maxTracks)
187
+ errors.push(`tracks: ${names.length} tracks, the limit is ${ANIMATION_LIMITS.maxTracks}`);
188
+ const tracks = {};
189
+ for (const name of names) {
190
+ if (!isField(name)) {
191
+ errors.push(`tracks.${name}: unknown field; closest valid names: ${closestFields(name).join(", ")}`);
192
+ continue;
193
+ }
194
+ const t = checkTrack(`tracks.${name}`, name, raw[name], errors);
195
+ if (t)
196
+ tracks[name] = t;
197
+ }
198
+ // Valid tracks are returned even when others failed, so the later rules still report on them.
199
+ return tracks;
200
+ }
201
+ const first = (t) => t[0];
202
+ const lastKf = (t) => t[t.length - 1];
203
+ /** Share of the duration (0..1) in which a track is not exactly zero, sampled 200 times. */
204
+ function activeShare(kfs) {
205
+ const fn = fromTracks({ holdGaze: kfs });
206
+ let n = 0;
207
+ for (let i = 0; i <= 200; i++)
208
+ if (Math.abs(fn(i / 200).holdGaze ?? 0) > 1e-6)
209
+ n++;
210
+ return n / 201;
211
+ }
212
+ /** Checks any JSON value as an animation definition. Collects every problem; warnings never block. */
213
+ export function validateAnimation(input) {
214
+ const errors = [];
215
+ const warnings = [];
216
+ if (!isRecord(input))
217
+ return { ok: false, errors: ["(root): must be a JSON object"] };
218
+ if (input.version !== 1)
219
+ errors.push("version: must be the number 1");
220
+ const kind = input.kind;
221
+ if (kind !== "reaction" && kind !== "activity" && kind !== "mood")
222
+ errors.push('kind: must be "reaction", "activity" or "mood"');
223
+ if (typeof input.id !== "string" || !ID_RE.test(input.id))
224
+ errors.push("id: must be camelCase letters and digits, 2 to 40 characters, starting with a lowercase letter (for example sideEye)");
225
+ let name = "";
226
+ if (typeof input.name !== "string")
227
+ errors.push("name: must be a string");
228
+ else {
229
+ name = input.name.trim();
230
+ // eslint-disable-next-line no-control-regex
231
+ if (name.length < 1 || name.length > ANIMATION_LIMITS.nameMax || /[\u0000-\u001f<>]/.test(name))
232
+ errors.push(`name: must be 1 to ${ANIMATION_LIMITS.nameMax} printable characters, without < or >`);
233
+ }
234
+ const allowed = kind === "reaction"
235
+ ? ["version", "kind", "id", "name", "duration", "tracks"]
236
+ : kind === "activity"
237
+ ? ["version", "kind", "id", "name", "period", "tracks"]
238
+ : ["version", "kind", "id", "name", "pose"];
239
+ if (kind === "reaction" || kind === "activity" || kind === "mood")
240
+ for (const k of Object.keys(input))
241
+ if (!allowed.includes(k))
242
+ warnings.push(`${k}: unknown key for a ${kind}, ignored`);
243
+ let value = null;
244
+ if (kind === "reaction" || kind === "activity") {
245
+ const key = kind === "reaction" ? "duration" : "period";
246
+ const [lo, hi] = kind === "reaction" ? ANIMATION_LIMITS.reactionDuration : ANIMATION_LIMITS.activityPeriod;
247
+ const secs = input[key];
248
+ if (!isNum(secs) || secs < lo || secs > hi)
249
+ errors.push(`${key}: must be a number of seconds between ${lo} and ${hi}`);
250
+ const tracks = checkTracks(input.tracks, errors);
251
+ if (tracks) {
252
+ for (const [field, kfs] of Object.entries(tracks)) {
253
+ const at = `tracks.${field}`;
254
+ const a = first(kfs)[1];
255
+ const b = lastKf(kfs)[1];
256
+ if (kind === "reaction") {
257
+ if (a !== 0 || b !== 0)
258
+ errors.push(`${at}: must start and end at 0 so the character returns to neutral (first value ${num(a)}, last value ${num(b)}); add a final keyframe back to 0`);
259
+ }
260
+ else {
261
+ if (a !== b)
262
+ errors.push(`${at}: the first and last values must be equal for a seamless loop (first ${num(a)}, last ${num(b)})`);
263
+ if (lastKf(kfs)[0] !== 1)
264
+ errors.push(`${at}: the last keyframe must have t = 1 (it is ${num(lastKf(kfs)[0])}) so the loop closes`);
265
+ }
266
+ }
267
+ if (kind === "reaction") {
268
+ const morph = Object.keys(tracks).filter((k) => FIELD_INFO[k].group === "morph");
269
+ if (morph.length)
270
+ warnings.push(`tracks use morph-group fields (${morph.join(", ")}); these belong to the transformation grammar (bubble, ring, check) and only look right when several of them are choreographed together`);
271
+ const groups = new Set(Object.keys(tracks).map((k) => FIELD_INFO[k].group));
272
+ if (!groups.has("body") && !groups.has("eyes") && !groups.has("lids"))
273
+ warnings.push("tracks: no body, eyes or lids track, so the reaction will barely be noticeable");
274
+ const hg = tracks.holdGaze;
275
+ if (hg && activeShare(hg) > 0.8)
276
+ warnings.push("tracks.holdGaze: above 0 for more than 80% of the duration; the character will ignore what it is looking at for most of the reaction");
277
+ }
278
+ }
279
+ if (!errors.length && tracks && isNum(secs))
280
+ value = kind === "reaction"
281
+ ? { version: 1, kind, id: input.id, name, duration: secs, tracks }
282
+ : { version: 1, kind, id: input.id, name, period: secs, tracks };
283
+ }
284
+ else if (kind === "mood") {
285
+ const pose = input.pose;
286
+ if (!isRecord(pose))
287
+ errors.push("pose: must be an object { fieldName: number }");
288
+ else {
289
+ const names = Object.keys(pose);
290
+ if (names.length === 0)
291
+ errors.push("pose: needs at least one field");
292
+ const clean = {};
293
+ for (const k of names) {
294
+ if (!isField(k)) {
295
+ errors.push(`pose.${k}: unknown field; closest valid names: ${closestFields(k).join(", ")}`);
296
+ continue;
297
+ }
298
+ const info = FIELD_INFO[k];
299
+ if (info.group === "morph" || MOOD_FORBIDDEN.has(k)) {
300
+ errors.push(`pose.${k}: not allowed in a mood (moods cannot use the morph group, sparks, opacity or scale)`);
301
+ continue;
302
+ }
303
+ const v = pose[k];
304
+ if (!isNum(v) || v < info.min || v > info.max)
305
+ errors.push(`pose.${k}: must be a number between ${info.min} and ${info.max} (${info.unit})`);
306
+ else
307
+ clean[k] = v;
308
+ }
309
+ if (!errors.length)
310
+ value = { version: 1, kind, id: input.id, name, pose: clean };
311
+ }
312
+ }
313
+ if (errors.length || !value)
314
+ return { ok: false, errors: errors.length ? errors : ["(root): invalid animation"] };
315
+ return { ok: true, value, warnings };
316
+ }
317
+ /* ---------- compile ---------- */
318
+ /** Turns a validated definition into what the library stores. */
319
+ export function compileAnimation(def) {
320
+ if (def.kind === "mood")
321
+ return { kind: "mood", id: def.id, name: def.name, def: { ...def.pose } };
322
+ const sample = fromTracks(def.tracks);
323
+ if (def.kind === "reaction")
324
+ return { kind: "reaction", id: def.id, name: def.name, def: { duration: def.duration, sample } };
325
+ const period = def.period;
326
+ return {
327
+ kind: "activity",
328
+ id: def.id,
329
+ name: def.name,
330
+ // Loop: t = (seconds % period) / period, kept positive for negative times.
331
+ def: (seconds) => sample((((seconds % period) + period) % period) / period),
332
+ };
333
+ }
334
+ /** JSON text → validated definition plus compiled entry. Never throws. */
335
+ export function parseAnimation(json) {
336
+ let raw;
337
+ try {
338
+ raw = JSON.parse(json);
339
+ }
340
+ catch (err) {
341
+ return { ok: false, errors: [`(root): not valid JSON (${err instanceof Error ? err.message : String(err)})`] };
342
+ }
343
+ const v = validateAnimation(raw);
344
+ if (!v.ok)
345
+ return v;
346
+ try {
347
+ return { ok: true, value: { definition: v.value, compiled: compileAnimation(v.value) }, warnings: v.warnings };
348
+ }
349
+ catch (err) {
350
+ return { ok: false, errors: [`(root): could not compile (${err instanceof Error ? err.message : String(err)})`] };
351
+ }
352
+ }
353
+ /** Structural type so this file does not depend on library.ts. */
354
+ export function addToLibrary(lib, a) {
355
+ if (a.kind === "reaction")
356
+ lib.reactions[a.id] = a.def;
357
+ else if (a.kind === "activity")
358
+ lib.activities[a.id] = a.def;
359
+ else
360
+ lib.moods[a.id] = a.def;
361
+ }
362
+ /* ---------- description ---------- */
363
+ const GROUP_LABEL = {
364
+ body: "the body",
365
+ parts: "the parts",
366
+ eyes: "the eyes",
367
+ lids: "the eyelids",
368
+ accessories: "the accessories",
369
+ flame: "the flame effects",
370
+ morph: "the transformation",
371
+ };
372
+ /** One-paragraph plain-English summary: length, which groups move and the peak values. */
373
+ export function describeAnimation(def) {
374
+ const peaks = (values) => {
375
+ const byGroup = new Map();
376
+ for (const [field, peak] of values) {
377
+ const info = FIELD_INFO[field];
378
+ const list = byGroup.get(info.group) ?? [];
379
+ list.push(`${field} reaches ${num(peak)}${info.unit === "px" ? " px" : info.unit === "deg" ? "°" : ""}`);
380
+ byGroup.set(info.group, list);
381
+ }
382
+ return FIELD_GROUPS.filter((g) => byGroup.has(g))
383
+ .map((g) => `${GROUP_LABEL[g]} (${byGroup.get(g).join(", ")})`)
384
+ .join("; ");
385
+ };
386
+ const peakOf = (kfs) => kfs.reduce((p, k) => (Math.abs(k[1]) > Math.abs(p) ? k[1] : p), 0);
387
+ if (def.kind === "mood") {
388
+ const entries = Object.entries(def.pose).filter(([, v]) => v !== 0);
389
+ return `"${def.name}" is a mood: a held pose that blends with the other moods. It sets ${peaks(entries) || "nothing"}.`;
390
+ }
391
+ const entries = Object.entries(def.tracks).map(([k, v]) => [k, peakOf(v)]);
392
+ const moving = peaks(entries);
393
+ if (def.kind === "reaction")
394
+ return `"${def.name}" is a one-shot reaction of ${num(def.duration)} s that starts and ends at rest. It moves ${moving || "nothing"}.`;
395
+ return `"${def.name}" is a loop that repeats every ${num(def.period)} s and joins up seamlessly. It moves ${moving || "nothing"}.`;
396
+ }
package/dist/brain.d.ts CHANGED
@@ -1,39 +1,198 @@
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
- }
1
+ import { type Delta } from "./delta.js";
2
+ import { type Gesture, type Interactions } from "./interactions.js";
3
+ import { type Library } from "./library.js";
4
+ import { type Rng } from "./motion.js";
5
+ import type { Rig, Role } from "./rig.js";
6
+ export type BrainInput = {
7
+ /** Gaze target, normalised from −1 to 1 relative to the character. `null` makes it wander. */
8
+ gaze: {
9
+ x: number;
10
+ y: number;
11
+ } | null;
12
+ hover: boolean;
13
+ /** Reduced motion: no idle, no jump; only changes of expression. */
14
+ reduced: boolean;
15
+ /** Mood weights by name (names unknown to the library are ignored). */
16
+ mood: Record<string, number>;
17
+ /** Activity name, or `null`. */
18
+ activity: string | null;
19
+ /** `simple` (small sizes): no appendage sway and no accessories. */
20
+ detail: "full" | "simple";
21
+ /** Appendage tips bend with physics. Default: on. */
22
+ bend?: boolean;
23
+ /** Something new on the page caught the attention this frame (0 to 1). */
24
+ interest?: number;
25
+ /** How close the cursor is (0 far, 1 right on top). */
26
+ proximity?: number;
27
+ /** Seconds for the eye to glide to the target; absent = saccade (see `GazeInput`). */
28
+ glide?: number;
29
+ };
30
+ export type EyePose = {
31
+ x: number;
32
+ y: number;
33
+ sx: number;
34
+ sy: number;
35
+ /** Eyelids: 0 to 1, and the tilt in degrees (already mirrored for this eye). */
36
+ lidTop: number;
37
+ lidBottom: number;
38
+ lidAngle: number;
39
+ /** 0 open eye, 1 happy arc (^). */
40
+ happy: number;
41
+ /** Extra tilt of the eye, in degrees (added to the style's). */
42
+ rot: number;
43
+ };
44
+ /** Transformation fields, passed straight through to the renderer. */
45
+ declare const OBJECT_FIELDS: readonly ["morph", "round", "retract", "swap", "bubbleR", "bubbleHole", "bubbleArc", "bubbleX", "bubbleY", "dotsDist", "dotsBounce", "checkDraw", "codeDraw", "orbitOpen", "objScale", "objRotate"];
46
+ type Objects = Pick<Delta, (typeof OBJECT_FIELDS)[number]>;
47
+ export type Pose = Objects & {
48
+ rootY: number;
49
+ opacity: number;
50
+ bodyRotate: number;
51
+ centerRotate: number;
52
+ bodySx: number;
53
+ bodySy: number;
54
+ scale: number;
55
+ partsX: number;
56
+ partC: number;
57
+ partL: number;
58
+ partR: number;
59
+ /** How much each appendage tip bends, in degrees (0 = straight). */
60
+ bendC: number;
61
+ bendL: number;
62
+ bendR: number;
63
+ leftEye: EyePose;
64
+ rightEye: EyePose;
65
+ shadowScale: number;
66
+ shadowOpacity: number;
67
+ /** 0 = no sparks; otherwise, progress of the burst (0 to 1). */
68
+ sparks: number;
69
+ lamp: number;
70
+ exclaim: number;
71
+ question: number;
72
+ ellipsis: number;
73
+ zzz: number;
74
+ rays: number;
75
+ /** Gaze state, for debugging and for anyone who wants to react to it. */
76
+ attention: number;
77
+ boredom: number;
78
+ gray: number;
79
+ core: number;
80
+ embers: number;
81
+ smoke: number;
82
+ /** Seconds since the page started, for the accessories' loops. */
83
+ time: number;
84
+ };
21
85
  /**
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`.
86
+ * What the brain needs from a rig. `appendages` is optional: without it, the
87
+ * three roles (C, L, R) are assumed; with it, only the roles present are
88
+ * simulated (a rig may have fewer than three, or none).
27
89
  */
90
+ export type BrainConfig = Pick<Rig, "id" | "baseHeight" | "idleAppendage" | "flicker"> & {
91
+ appendages?: readonly {
92
+ role: Role;
93
+ }[];
94
+ };
95
+ export declare const DEFAULT_BRAIN_CONFIG: BrainConfig;
96
+ export type BrainOptions = {
97
+ /** What can be played, by name. Default: `DEFAULT_LIBRARY`. */
98
+ library?: Library;
99
+ /** Hover/click/cuddle/nap behaviour. Default: `INTERACTIONS[config.id] ?? INTERACTIONS.berry`. */
100
+ interactions?: Interactions;
101
+ rng?: Rng;
102
+ /** Initial time (ms), the first blink is scheduled relative to it. Default: `performance.now()`. */
103
+ now?: number;
104
+ };
28
105
  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;
106
+ private readonly rng;
107
+ private cfg;
108
+ private library;
109
+ private interactions;
110
+ /** True when the caller passed their own interactions (they then ignore `config.id`). */
111
+ private customInteractions;
112
+ /** Roles simulated (those the rig has). */
113
+ private roles;
114
+ private last;
115
+ private blink;
116
+ private gaze;
117
+ private wander;
118
+ private parts;
119
+ /** Tip link of each appendage (a two-link chain). */
120
+ private tips;
121
+ private targets;
122
+ /** Velocities of the previous frame, to measure acceleration. */
123
+ private previous;
124
+ private jumpState;
125
+ private squash;
126
+ private hover;
127
+ private moodSprings;
128
+ private moodWeights;
129
+ private activitySprings;
130
+ private activityWeights;
131
+ private reaction;
132
+ private leaving;
133
+ /** Requested during a transformation: starts when it ends. */
134
+ private queue;
135
+ /** Last value of `morph`: during the transformation, it does not jump. */
136
+ private morph;
137
+ private chain;
138
+ private lastTap;
139
+ private lastGesture;
140
+ private lastHover;
141
+ private hoverSince;
142
+ private pending;
143
+ private cuddle;
144
+ private nap;
145
+ private smoothed;
146
+ private hoverHold;
147
+ private nearHold;
148
+ private attentionHold;
149
+ private sv;
150
+ constructor(config?: BrainConfig, options?: BrainOptions);
151
+ /**
152
+ * Swaps the physical configuration (another rig) keeping the state: reaction
153
+ * in progress, mood weights, gaze. Appendages that no longer exist are zeroed.
154
+ */
155
+ setConfig(config: BrainConfig): void;
156
+ /** Swaps what can be played (reactions, activities, moods). Default: `DEFAULT_LIBRARY`. */
157
+ setLibrary(library?: Library): void;
158
+ /** Swaps the interactions; `undefined` goes back to the one for `config.id`. */
159
+ setInteractions(interactions?: Interactions): void;
160
+ /**
161
+ * Forget the last frame time. Call it when frames stop for a while (the
162
+ * character left the screen, the tab was hidden): the next `step` then
163
+ * treats the gap as a fresh start instead of integrating across it.
164
+ */
165
+ resume(): void;
166
+ /** Name of the reaction in progress, or `null`. */
167
+ get currentReaction(): string | null;
168
+ /** Progress (0 to 1+) of a reaction; 1 if its definition no longer exists. */
169
+ private progress;
170
+ /**
171
+ * Fires a reaction. A new one replaces the previous one, which fades out in
172
+ * 350 ms instead of cutting off. During a transformation (the body does not
173
+ * even exist), the new one waits in the queue. An unknown name is ignored
174
+ * and returns `false`.
175
+ */
176
+ react(name: string, now: number): boolean;
177
+ jump(vy?: number): void;
178
+ /**
179
+ * Busy: a reaction playing or the body in the air. Hover and click gestures
180
+ * do not cut what is happening (that is what made the character shake with
181
+ * fast clicks): they wait their turn. App reactions (`react`) still enter at once.
182
+ */
183
+ busy(now: number): boolean;
184
+ /** Gesture waiting, for debugging. */
185
+ get pendingGesture(): Gesture | null;
186
+ private perform;
187
+ /** Cursor entered: a drawn gesture, if not in the middle of another. */
188
+ hoverEnter(now: number): Gesture | null;
189
+ /**
190
+ * Click or tap. A single click draws a gesture; successive clicks (less than
191
+ * 0.7 s apart) hop until the sequence asks for something else: the character
192
+ * table's reactions come on the 3rd, 5th and 8th. It also wakes whoever was
193
+ * dozing under the cursor.
194
+ */
195
+ tap(now: number): Gesture;
196
+ step(now: number, e: BrainInput): Pose;
39
197
  }
198
+ export {};