open-bot-avatar 0.2.1 → 0.3.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 (54) hide show
  1. package/README.md +25 -6
  2. package/dist/animator.d.ts +9 -4
  3. package/dist/animator.d.ts.map +1 -1
  4. package/dist/animator.js +32 -17
  5. package/dist/animator.js.map +1 -1
  6. package/dist/color.d.ts +4 -0
  7. package/dist/color.d.ts.map +1 -1
  8. package/dist/color.js +45 -0
  9. package/dist/color.js.map +1 -1
  10. package/dist/dom/mount.d.ts +8 -2
  11. package/dist/dom/mount.d.ts.map +1 -1
  12. package/dist/dom/mount.js +29 -8
  13. package/dist/dom/mount.js.map +1 -1
  14. package/dist/dom/paint.d.ts.map +1 -1
  15. package/dist/dom/paint.js +18 -5
  16. package/dist/dom/paint.js.map +1 -1
  17. package/dist/effects.d.ts +82 -0
  18. package/dist/effects.d.ts.map +1 -0
  19. package/dist/effects.js +352 -0
  20. package/dist/effects.js.map +1 -0
  21. package/dist/eyes.d.ts +29 -0
  22. package/dist/eyes.d.ts.map +1 -0
  23. package/dist/eyes.js +128 -0
  24. package/dist/eyes.js.map +1 -0
  25. package/dist/index.d.ts +3 -3
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +1 -1
  28. package/dist/index.js.map +1 -1
  29. package/dist/mood.d.ts +10 -5
  30. package/dist/mood.d.ts.map +1 -1
  31. package/dist/mood.js +3 -2
  32. package/dist/mood.js.map +1 -1
  33. package/dist/motion.d.ts +63 -10
  34. package/dist/motion.d.ts.map +1 -1
  35. package/dist/motion.js +239 -41
  36. package/dist/motion.js.map +1 -1
  37. package/dist/render.d.ts +68 -4
  38. package/dist/render.d.ts.map +1 -1
  39. package/dist/render.js +265 -34
  40. package/dist/render.js.map +1 -1
  41. package/dist/types.d.ts +35 -7
  42. package/dist/types.d.ts.map +1 -1
  43. package/package.json +1 -1
  44. package/src/animator.ts +40 -20
  45. package/src/color.ts +48 -0
  46. package/src/dom/mount.ts +38 -11
  47. package/src/dom/paint.ts +17 -5
  48. package/src/effects.ts +405 -0
  49. package/src/eyes.ts +157 -0
  50. package/src/index.ts +3 -3
  51. package/src/mood.ts +13 -7
  52. package/src/motion.ts +270 -48
  53. package/src/render.ts +335 -42
  54. package/src/types.ts +42 -7
package/src/render.ts CHANGED
@@ -14,11 +14,20 @@
14
14
  * does projection and occlusion. Each visible slice costs a compositor layer,
15
15
  * so mountAvatar paints live avatars to one canvas by default and only uses
16
16
  * the scene with `renderer: 'scene'`.
17
+ *
18
+ * A state can draw more than the body (see effects.ts): ribbons behind and in front of it, and
19
+ * the marks a thinking or blocked bot turns into. Those stay where they are while the body hops
20
+ * and rolls.
17
21
  */
18
- import { parseHex, toHex } from './color.ts';
22
+ import { mix, oklch, parseHex, toHex, toOklch } from './color.ts';
19
23
  import type { Rgb } from './color.ts';
20
- import { computePose, hashString } from './motion.ts';
21
- import type { Pose } from './motion.ts';
24
+ import { bodyScale, markParts, ribbonPieces, ribbonReach, rimOf } from './effects.ts';
25
+ import type { Rim } from './effects.ts';
26
+ import type { Box } from './effects.ts';
27
+ import { eyePath, plainLook } from './eyes.ts';
28
+ import type { EyeSpot } from './eyes.ts';
29
+ import { computePose, hashString, noise } from './motion.ts';
30
+ import type { EyeLook, Pose } from './motion.ts';
22
31
  import type { Bounds, Point } from './path.ts';
23
32
  import { EYE_H, EYE_W, GAZE_X, GAZE_Y, HAPPY_ARC, analyzeBody, eyeCenters, gazeRange, validateAvatar } from './validate.ts';
24
33
  import type { GazeRange } from './validate.ts';
@@ -50,6 +59,8 @@ interface Prepared {
50
59
  ids: Map<string, string>;
51
60
  /** Slices kept at a rendered size, per stack, keyed by stack and rounded size. */
52
61
  detail: Map<string, boolean[]>;
62
+ /** Where the ribbons' hoops are centred and how far the body reaches from there (see ribbonRims). */
63
+ rims: () => { work: Rim; cage: Rim };
53
64
  }
54
65
 
55
66
  const cache = new Map<string, Prepared>();
@@ -65,6 +76,48 @@ function depthOption(options: RenderOptions): number {
65
76
  return Math.round(d * 2) / 2;
66
77
  }
67
78
 
79
+ const lazy = <T>(make: () => T): (() => T) => {
80
+ let value: T | undefined;
81
+ return () => (value ??= make());
82
+ };
83
+
84
+ /**
85
+ * How far the body reaches from the middle of its box, for a working turn's hoop and for a
86
+ * celebration's cage. The hoops' centre hops and stretches with the body (see ribbonsFollow) but
87
+ * does not lean or sway with it, so each is measured over the leans its state takes, the body
88
+ * stretched about the centre: a working bot leans 2.4° to 6.6° and squashes to 98%; a celebrating
89
+ * one sways ±1.7° and stretches up to 5.5%. The hoops stand just outside that, so the body never
90
+ * moves through a point where a ribbon passes behind it.
91
+ */
92
+ export function ribbonRims(polys: Point[][], b: Bounds): { work: Rim; cage: Rim } {
93
+ const [cx, cy] = pivotOf(b);
94
+ const bx = (b.minX + b.maxX) / 2, by = b.maxY;
95
+ /** The body leaned by each of `rolls` (degrees, about its base) and stretched by each of `sys` about the centre. */
96
+ const posed = (rolls: number[], sys: number[]) => {
97
+ const out: Point[][][] = [];
98
+ for (const roll of rolls) {
99
+ const r = (roll * Math.PI) / 180, c = Math.cos(r), sn = Math.sin(r);
100
+ for (const k of sys) {
101
+ out.push(polys.map((poly) => poly.map(([x, y]): Point => {
102
+ const lx = bx + c * (x - bx) - sn * (y - by), ly = by + sn * (x - bx) + c * (y - by);
103
+ return [cx + 1.01 * (lx - cx), cy + k * (ly - cy)];
104
+ })));
105
+ }
106
+ }
107
+ return out;
108
+ };
109
+ return { work: rimOf(posed([2.4, 4.5, 6.6], [0.98, 1]), cx, cy), cage: rimOf(posed([-1.7, 0, 1.7], [0.99, 1.055]), cx, cy) };
110
+ }
111
+
112
+ /**
113
+ * The rim moved to where the hoops' centre is in this pose: it hops and stretches with the body
114
+ * (the root motion's lift and scale about the base) but does not lean or sway with it.
115
+ */
116
+ export function ribbonsFollow(rim: Rim, pose: Pick<Pose, 'lift' | 'sx' | 'sy'>, b: Bounds): Rim {
117
+ const bx = (b.minX + b.maxX) / 2, by = b.maxY;
118
+ return { ...rim, cx: bx + pose.sx * (rim.cx - bx), cy: by + pose.sy * (rim.cy - by) + pose.lift };
119
+ }
120
+
68
121
  function prepare(definition: AvatarDefinition, depth: number): Prepared {
69
122
  const key = JSON.stringify([definition?.id, definition?.name, definition?.body?.path, definition?.eyes, depth]);
70
123
  const hit = cache.get(key);
@@ -85,6 +138,7 @@ function prepare(definition: AvatarDefinition, depth: number): Prepared {
85
138
  id,
86
139
  ids,
87
140
  detail: new Map(),
141
+ rims: lazy(() => ribbonRims(body.polys, vol.bounds)),
88
142
  };
89
143
  if (cache.size >= 64) cache.delete(cache.keys().next().value as string);
90
144
  cache.set(key, prepared);
@@ -98,11 +152,13 @@ export function preparedVolume(definition: AvatarDefinition, depth?: number): {
98
152
  }
99
153
 
100
154
  function poseOf(p: Prepared, options: RenderOptions): Pose {
101
- const motion = options.motion === 'thinking' || options.motion === 'happy' ? options.motion : 'idle';
102
155
  return computePose({
103
156
  seed: p.seed,
104
157
  time: Number.isFinite(options.time) ? (options.time as number) : 0,
105
- motion,
158
+ state: options.state,
159
+ mood: options.mood,
160
+ motion: options.motion,
161
+ stateAge: options.stateAge,
106
162
  gaze: options.gaze,
107
163
  reducedMotion: options.reducedMotion === true,
108
164
  view: options.view,
@@ -125,6 +181,10 @@ const mul = (m: M, n: M): M => [
125
181
  ];
126
182
  const translate = (x: number, y: number): M => [1, 0, 0, 1, x, y];
127
183
  const about = (x: number, y: number, m: M): M => mul(translate(x, y), mul(m, translate(-x, -y)));
184
+ const invert = ([a, b, c, d, e, g]: M): M => {
185
+ const det = a * d - b * c;
186
+ return [d / det, -b / det, -c / det, a / det, (c * g - d * e) / det, (b * e - a * g) / det];
187
+ };
128
188
  const mat = (m: M) => `matrix(${m.map((v, i) => (i < 4 ? (Math.round(v * 10000) / 10000).toString() : f(v))).join(' ')})`;
129
189
 
130
190
  export interface ViewBasis {
@@ -203,11 +263,20 @@ const POSE_SWAY = 0.2;
203
263
  * canvas renderer uses it only as an upper bound: it sizes each bitmap to what is actually painted.
204
264
  */
205
265
  export function avatarExtent(definition: AvatarDefinition, depth?: number): { x: number; y: number; size: number } {
206
- const { vol } = prepare(definition, depthOption({ depth }));
266
+ const p = prepare(definition, depthOption({ depth }));
267
+ const { vol } = p;
207
268
  const b = vol.bounds;
208
269
  const [cx, cy] = pivotOf(b);
209
270
  const radius = Math.hypot(b.maxX - b.minX, b.maxY - b.minY, Math.max(...vol.parts.map((part) => part.depth)) + 2 * EYE_LIFT) / 2;
210
- const half = radius + POSE_LIFT + POSE_SWAY * (radius + b.maxY - cy);
271
+ // Ribbons reach their hoop plus their band from the middle of the body's box, and keep the
272
+ // canvas's antialiasing margin (FIT_PAD) inside.
273
+ const { work, cage } = p.rims();
274
+ // The hoops' centre also hops and stretches with the body: as far as the body's own pose moves it.
275
+ const reach = (rim: Rim) => {
276
+ const r = ribbonReach(rim.max);
277
+ return Math.hypot(rim.cx - cx, rim.cy - cy) + POSE_LIFT + POSE_SWAY * Math.abs(b.maxY - rim.cy) + r.radius + r.band + 1.2;
278
+ };
279
+ const half = Math.max(radius + POSE_LIFT + POSE_SWAY * (radius + b.maxY - cy), reach(work), reach(cage));
211
280
  return { x: cx - half, y: cy - half, size: 2 * half };
212
281
  }
213
282
 
@@ -254,7 +323,9 @@ interface EyeState {
254
323
  /** Drawn pill height after blink/squint, and its downward shift (lids close toward a point below center). */
255
324
  open: number;
256
325
  shift: number;
257
- happy: boolean;
326
+ look: EyeLook;
327
+ /** The plain pill or the plain happy arc, drawn as such; null for every other look (a path). */
328
+ plain: 'pill' | 'arc' | null;
258
329
  }
259
330
 
260
331
  function eyeStates(p: Prepared, pose: Pose): [EyeState, EyeState] {
@@ -264,13 +335,19 @@ function eyeStates(p: Prepared, pose: Pose): [EyeState, EyeState] {
264
335
  const dx = pose.gazeX * (pose.gazeX >= 0 ? r.right : r.left) * GAZE_X * s;
265
336
  const dy = pose.gazeY * (pose.gazeY >= 0 ? r.down : r.up) * GAZE_Y * s;
266
337
  const centers = eyeCenters(p.def.eyes);
338
+ const plain = plainLook(pose.eyes);
267
339
  return ([0, 1] as const).map((i) => {
268
340
  const squint = i === 0 ? pose.squintL : pose.squintR;
269
341
  const open = Math.max(h * Math.max(0.09, (1 - pose.blink) * (1 - squint * 0.4)), w * 0.55);
270
- return { x: centers[i][0], y: centers[i][1], w, h, dx, dy, open, shift: (h - open) * 0.18, happy: pose.eyeShape === 'happy' };
342
+ return { x: centers[i][0], y: centers[i][1], w, h, dx, dy, open, shift: (h - open) * 0.18, look: pose.eyes, plain };
271
343
  }) as [EyeState, EyeState];
272
344
  }
273
345
 
346
+ /** Where an eye is drawn: with its gaze offset, or without it where a transform applies the gaze. */
347
+ function eyeSpot(e: EyeState, gaze: boolean): EyeSpot {
348
+ return { x: e.x + (gaze ? e.dx : 0), y: e.y + (gaze ? e.dy : 0), w: e.w, h: e.h, open: e.open, shift: e.shift };
349
+ }
350
+
274
351
  function happyArc(e: EyeState): string {
275
352
  const ex = e.x + e.dx, ey = e.y + e.dy;
276
353
  const hw = e.w * HAPPY_ARC.halfWidth, base = ey + e.h * HAPPY_ARC.base;
@@ -278,7 +355,8 @@ function happyArc(e: EyeState): string {
278
355
  }
279
356
 
280
357
  function eyeMark(e: EyeState): EyeMark {
281
- if (e.happy) return { shape: 'arc', d: happyArc(e), strokeWidth: e.w * HAPPY_ARC.stroke };
358
+ if (e.plain === 'arc') return { shape: 'arc', d: happyArc(e), strokeWidth: e.w * HAPPY_ARC.stroke };
359
+ if (e.plain === null) return { shape: 'path', d: eyePath(e.look, eyeSpot(e, true)) };
282
360
  const cx = e.x + e.dx, cy = e.y + e.dy + e.shift;
283
361
  return { shape: 'pill', x: cx - e.w / 2, y: cy - e.open / 2, width: e.w, height: e.open, radius: Math.min(e.w, e.open) / 2 };
284
362
  }
@@ -296,10 +374,15 @@ function colors(options: RenderOptions): { color: string; ink: string } {
296
374
  /** 2D affine matrix in SVG order (a b c d e f). */
297
375
  export type Matrix = [number, number, number, number, number, number];
298
376
 
299
- /** How one eye is drawn, in its face plane's coordinates (viewBox units). */
377
+ /**
378
+ * How one eye is drawn, in its face plane's coordinates (viewBox units): the plain pill, the
379
+ * plain happy arc (stroked, round caps), or for every other look a filled outline (a waiting
380
+ * bot's slits, and every shape on the way from one look to the next).
381
+ */
300
382
  export type EyeMark =
301
383
  | { shape: 'pill'; x: number; y: number; width: number; height: number; radius: number }
302
- | { shape: 'arc'; d: string; strokeWidth: number };
384
+ | { shape: 'arc'; d: string; strokeWidth: number }
385
+ | { shape: 'path'; d: string };
303
386
 
304
387
  export type FrameShape =
305
388
  | {
@@ -310,7 +393,26 @@ export type FrameShape =
310
393
  path: string;
311
394
  matrix: Matrix;
312
395
  }
313
- | { kind: 'eye'; key: 'eye-0' | 'eye-1'; matrix: Matrix; mark: EyeMark };
396
+ | { kind: 'eye'; key: 'eye-0' | 'eye-1'; matrix: Matrix; mark: EyeMark }
397
+ | {
398
+ /**
399
+ * A piece of a ribbon: fill `d` in `fill`. Each ribbon has a hue of its own, set apart from
400
+ * the body's; a piece `front` of the body is lighter than one behind it.
401
+ */
402
+ kind: 'ribbon';
403
+ key: string;
404
+ d: string;
405
+ box: { x: number; y: number; w: number; h: number };
406
+ matrix: Matrix;
407
+ front: boolean;
408
+ /** The ribbon's colour where it is plainest (the middle of its gradient). */
409
+ fill: string;
410
+ /**
411
+ * A linear gradient along the whole ribbon, in the same coordinates as `d`: from its tail
412
+ * (x1, y1) to its head (x2, y2), the stops evenly spaced. Every piece of a ribbon shares it.
413
+ */
414
+ gradient: { x1: number; y1: number; x2: number; y2: number; stops: string[] };
415
+ };
314
416
 
315
417
  /** One cross-section outline, shared by every shape that draws it. */
316
418
  export interface FramePath {
@@ -322,7 +424,9 @@ export interface FramePath {
322
424
 
323
425
  /**
324
426
  * One frame of the avatar flattened onto the screen: every cross-section the
325
- * view draws with its projection, and the visible eyes, sorted back to front.
427
+ * view draws with its projection, and the visible eyes, sorted back to front,
428
+ * between the ribbons behind the body and those in front of it. The marks of
429
+ * `thinking` and `blocked` are listed as slices too, in place of the body.
326
430
  * Painting them in order (body paths in `color`, eyes in `ink`) inside the
327
431
  * `root` transform and a 0 0 100 100 viewBox gives the avatar exactly as
328
432
  * renderAvatarSvg draws it. Plain numbers and path strings, so any vector
@@ -357,6 +461,133 @@ export function liveFrame(definition: AvatarDefinition, options: RenderOptions =
357
461
  return flatFrame(definition, options, options.size);
358
462
  }
359
463
 
464
+ /**
465
+ * The ribbons are steps along a ramp of the body's own color, painter's style: each step is
466
+ * RAMP_LIGHT lighter or darker in OKLCH and turns RAMP_HUE degrees with it, toward yellow as it
467
+ * lightens and toward blue as it darkens. Steps run +1, -1, +2, -2 and so on, skipping any that
468
+ * would leave RAMP_RANGE, so a working bot's three are one lighter, one darker and one lighter
469
+ * still on most bodies. A body lighter or darker than the range steps from its edge instead, so
470
+ * a white body's ribbons are all well darker than it, and a black one's well lighter.
471
+ */
472
+ const RAMP_LIGHT = 0.09;
473
+ const RAMP_HUE = 14;
474
+ // Six steps wide: room for five besides the body's own, wherever it starts. Past it shades wash
475
+ // out toward white or sink toward black.
476
+ const RAMP_RANGE = [0.36, 0.9] as const;
477
+ const WARM = 100;
478
+ const palettes = new Map<string, Rgb[][]>();
479
+ /**
480
+ * How far a ribbon's colour runs from its tail (its shade) to its head: further from the body's
481
+ * lightness by GRADIENT_LIGHT, turning GRADIENT_HUE degrees with it (warmer as it lightens,
482
+ * cooler as it darkens). GRADIENT_STOPS colours along the way.
483
+ */
484
+ const GRADIENT_LIGHT = 0.13;
485
+ const GRADIENT_HUE = 25;
486
+ const GRADIENT_STOPS = 5;
487
+ /** Below this chroma a body counts as white, gray or black, and its ribbons are grays with this much tint. */
488
+ const NEUTRAL = 0.04;
489
+ const NEUTRAL_TINT = 0.025;
490
+ /**
491
+ * Which shades (by their order along the ramp: +1, -1, +2, -2, +3 on most bodies) each band's lanes
492
+ * take, a working bot's band first. A celebration's two bands lean to the lighter shades, so the
493
+ * cage stays bright against a dark page.
494
+ */
495
+ const BAND_SHADES = [[0, 1, 2], [2, 0, 3], [1, 2, 0]] as const;
496
+
497
+ /** Turn hue `h` by up to `by` degrees toward hue `to`, never past it. */
498
+ function turnToward(h: number, to: number, by: number): number {
499
+ const d = ((to - h + 540) % 360) - 180;
500
+ return (h + Math.sign(d) * Math.min(Math.abs(d), by) + 360) % 360;
501
+ }
502
+
503
+ /**
504
+ * The colors of the ribbons on a body this color, one per band and lane (see BAND_SHADES): five
505
+ * steps along its own ramp (see RAMP_LIGHT), at least as vivid as the body. A white, gray or
506
+ * black body gets grays: lighter or darker than it, with just a hint of a hue its seed picks.
507
+ * A piece behind the body is a shade deeper than one in front of it.
508
+ */
509
+ /** The colour `t` (0..1) of the way along a colour run, in sRGB between its stops. */
510
+ function runAt(run: Rgb[], t: number): string {
511
+ const x = clamp(t, 0, 1) * (run.length - 1), n = Math.min(Math.floor(x), run.length - 2);
512
+ return toHex(mix(run[n], run[n + 1], x - n));
513
+ }
514
+
515
+ function ribbonPalette(color: string | undefined, seed: number): Rgb[][] {
516
+ const key = `${color}|${seed}`;
517
+ let palette = palettes.get(key);
518
+ if (palette) return palette;
519
+ const [light, chroma, hue] = toOklch(parseHex(color) ?? (parseHex(DEFAULT_COLOR) as Rgb));
520
+ // A seed's hue skips the yellows (80 to 130), whose darker steps turn olive.
521
+ const neutral = chroma < NEUTRAL;
522
+ const base = neutral ? (130 + noise(seed, 500) * 310) % 360 : hue;
523
+ const c = neutral ? NEUTRAL_TINT : Math.max(chroma, 0.17);
524
+ const from = Math.min(RAMP_RANGE[1], Math.max(RAMP_RANGE[0], light));
525
+ const steps: number[] = [];
526
+ for (let k = 1; steps.length < 5 && k < 10; k++) {
527
+ for (const step of [k, -k]) {
528
+ const l = from + step * RAMP_LIGHT;
529
+ if (steps.length < 5 && l >= RAMP_RANGE[0] - 1e-9 && l <= RAMP_RANGE[1] + 1e-9) steps.push(step);
530
+ }
531
+ }
532
+ while (steps.length < 5) steps.push(steps[steps.length - 1] ?? 1);
533
+ const shades = steps.map((step) => {
534
+ const l = from + step * RAMP_LIGHT;
535
+ const h = turnToward(base, step > 0 ? WARM : WARM + 180, RAMP_HUE * Math.abs(step));
536
+ // Tail to head, away from the body's lightness: lighter and warmer, or darker and cooler.
537
+ const away = step > 0 ? 1 : -1;
538
+ const run = Array.from({ length: GRADIENT_STOPS }, (_, n) => {
539
+ const t = n / (GRADIENT_STOPS - 1);
540
+ const hue = turnToward(h, away > 0 ? WARM : WARM + 180, GRADIENT_HUE * t);
541
+ return oklch(clamp(l + away * GRADIENT_LIGHT * t, 0.26, 0.9), c, hue);
542
+ });
543
+ return { step, run };
544
+ });
545
+ // Each band takes three of the shades, lightest on the inside lane to darkest on the outside.
546
+ palette = BAND_SHADES.flatMap((pick) => pick.map((n) => shades[n]).sort((x, y) => y.step - x.step).map(({ run }) => run));
547
+ if (palettes.size >= 64) palettes.clear();
548
+ palettes.set(key, palette);
549
+ return palette;
550
+ }
551
+
552
+ /** What a frame draws besides the body, in viewBox units outside the body's own motion. */
553
+ interface Effects {
554
+ /** How much of its size the body keeps while it gives way to a mark (0 = gone). */
555
+ body: number;
556
+ ribbons: { d: string; box: Box; front: boolean; fill: string; gradient: RibbonGradient }[];
557
+ marks: { id: string; d: string; box: Box; matrix: M }[];
558
+ }
559
+
560
+ function effectsOf(p: Prepared, pose: Pose, options: RenderOptions): Effects {
561
+ const b = p.vol.bounds;
562
+ const time = Number.isFinite(options.time) ? (options.time as number) : 0;
563
+ const still = options.reducedMotion === true;
564
+ const [cx, cy] = pivotOf(b);
565
+ return {
566
+ body: bodyScale(pose.bang, pose.dots),
567
+ ribbons: still ? [] : ribbonPieces(b, pose.ribbons, p.seed, time, pose.sweep, pose.cage, ribbonsFollow(pose.cage >= 0.5 ? p.rims().cage : p.rims().work, pose, b)).map((r) => {
568
+ const hue = ribbonPalette(options.color, p.seed)[r.ribbon];
569
+ // The piece's stretch of its ribbon's colour run, front and back alike.
570
+ const [s0, s1] = r.along;
571
+ const stops = [s0, (s0 + s1) / 2, s1].map((t) => runAt(hue, t));
572
+ // A gradient needs some length; a piece too short to have one takes its middle colour.
573
+ const long = Math.hypot(r.to[0] - r.from[0], r.to[1] - r.from[1]) > 0.01;
574
+ return {
575
+ d: r.d, box: r.box, front: r.front, fill: stops[1],
576
+ gradient: long ? { x1: r.from[0], y1: r.from[1], x2: r.to[0], y2: r.to[1], stops } : { x1: r.from[0], y1: r.from[1], x2: r.from[0] + 0.01, y2: r.from[1], stops: [stops[1], stops[1], stops[1]] },
577
+ };
578
+ }),
579
+ marks: markParts(b, pose.bang, pose.dots, p.seed, time, still).map((part) => {
580
+ const turn: M = [Math.cos(part.turn), Math.sin(part.turn), -Math.sin(part.turn), Math.cos(part.turn), 0, 0];
581
+ return {
582
+ id: `${p.id}-${part.shape}`,
583
+ d: part.d,
584
+ box: part.box,
585
+ matrix: mul(about(cx, cy, turn), mul(translate(part.x, part.y), [part.scale, 0, 0, part.scale, 0, 0])),
586
+ };
587
+ }),
588
+ };
589
+ }
590
+
360
591
  function flatFrame(definition: AvatarDefinition, options: RenderOptions, size: number | undefined): AvatarFrame {
361
592
  const p = prepare(definition, depthOption(options));
362
593
  const { vol } = p;
@@ -367,51 +598,91 @@ function flatFrame(definition: AvatarDefinition, options: RenderOptions, size: n
367
598
  const v = viewBasis(pose.yaw, pose.pitch);
368
599
  const stack = activeStack(v);
369
600
  const eyesMid: Point = [p.def.eyes.x, p.def.eyes.y];
601
+ const fx = effectsOf(p, pose, options);
602
+ const root = rootMatrix(pose, b);
603
+ // The body shrinks toward its center as it gives way to a mark.
604
+ const shrink = (m: M): M => (fx.body < 1 ? mul(about(pivot[0], pivot[1], [fx.body, 0, 0, fx.body, 0, 0]), m) : m);
370
605
 
371
606
  // Only the cross-sections this view draws are listed; ids are stable across frames.
372
607
  const paths = new Map<string, FramePath>();
373
608
  const items: { depth: number; shape: FrameShape }[] = [];
374
- drawnSlices(p, v, size, (s, m, i, j) => {
375
- let path = paths.get(s.d);
376
- if (!path) {
377
- path = { id: p.ids.get(s.d) as string, d: s.d, evenOdd: s.evenOdd, box: { ...s.box } };
378
- paths.set(s.d, path);
379
- }
380
- // Depth keys are taken under the eyes for the eye part, so only depth decides eye-vs-body order there.
381
- const [rx, ry] = i === vol.eyePart ? eyesMid : vol.parts[i].center;
382
- const depth = stack === 'z' ? projectPoint(v, [rx, ry, s.at], pivot)[2] : projectPoint(v, [s.at, ry, 0], pivot)[2];
383
- items.push({ depth, shape: { kind: 'slice', key: `${i}${stack}${j}`, path: path.id, matrix: m } });
384
- });
385
- // Painted on the surface; each eye goes once the surface under it turns away.
386
- eyeStates(p, pose).forEach((e, idx) => {
387
- if (eyeVisible(vol, v, idx)) {
388
- const z = vol.eyeZ[idx] + EYE_LIFT;
389
- items.push({
390
- depth: projectPoint(v, [eyesMid[0], eyesMid[1], z], pivot)[2] + 1e-6,
391
- shape: { kind: 'eye', key: idx === 0 ? 'eye-0' : 'eye-1', matrix: planeMatrix(v, z, pivot), mark: eyeMark(e) },
392
- });
393
- }
609
+ if (fx.body > 0) {
610
+ drawnSlices(p, v, size, (s, m, i, j) => {
611
+ let path = paths.get(s.d);
612
+ if (!path) {
613
+ path = { id: p.ids.get(s.d) as string, d: s.d, evenOdd: s.evenOdd, box: { ...s.box } };
614
+ paths.set(s.d, path);
615
+ }
616
+ // Depth keys are taken under the eyes for the eye part, so only depth decides eye-vs-body order there.
617
+ const [rx, ry] = i === vol.eyePart ? eyesMid : vol.parts[i].center;
618
+ const depth = stack === 'z' ? projectPoint(v, [rx, ry, s.at], pivot)[2] : projectPoint(v, [s.at, ry, 0], pivot)[2];
619
+ items.push({ depth, shape: { kind: 'slice', key: `${i}${stack}${j}`, path: path.id, matrix: shrink(m) } });
620
+ });
621
+ // Painted on the surface; each eye goes once the surface under it turns away.
622
+ eyeStates(p, pose).forEach((e, idx) => {
623
+ if (eyeVisible(vol, v, idx)) {
624
+ const z = vol.eyeZ[idx] + EYE_LIFT;
625
+ items.push({
626
+ depth: projectPoint(v, [eyesMid[0], eyesMid[1], z], pivot)[2] + 1e-6,
627
+ shape: { kind: 'eye', key: idx === 0 ? 'eye-0' : 'eye-1', matrix: shrink(planeMatrix(v, z, pivot)), mark: eyeMark(e) },
628
+ });
629
+ }
630
+ });
631
+ items.sort((a, c) => a.depth - c.depth);
632
+ }
633
+
634
+ // Ribbons and marks stay put while the body moves: their matrices undo the root's motion.
635
+ const fixed = fx.ribbons.length || fx.marks.length ? invert(root) : null;
636
+ const ribbon = (front: boolean): FrameShape[] =>
637
+ fx.ribbons.flatMap((r, i) =>
638
+ r.front === front ? [{ kind: 'ribbon' as const, key: `ribbon-${i}`, d: r.d, box: r.box, matrix: fixed as M, front, fill: r.fill, gradient: r.gradient }] : [],
639
+ );
640
+ const marks = fx.marks.map((mark, i): FrameShape => {
641
+ if (!paths.has(mark.id)) paths.set(mark.id, { id: mark.id, d: mark.d, evenOdd: false, box: mark.box });
642
+ return { kind: 'slice', key: `mark-${i}`, path: mark.id, matrix: mul(fixed as M, mark.matrix) };
394
643
  });
395
- items.sort((a, c) => a.depth - c.depth);
396
- return { name: p.def.name, color, ink, paths: [...paths.values()], root: rootMatrix(pose, b), shapes: items.map((it) => it.shape) };
644
+ return {
645
+ name: p.def.name, color, ink, paths: [...paths.values()], root,
646
+ shapes: [...ribbon(false), ...items.map((it) => it.shape), ...ribbon(true), ...marks],
647
+ };
397
648
  }
398
649
 
399
650
  // ---------------------------------------------------------------------------
400
651
  // Standalone SVG still
401
652
 
402
653
  function eyeSvg(mark: EyeMark, ink: string): string {
654
+ if (mark.shape === 'path') return `<path d="${mark.d}" fill="${ink}"/>`;
403
655
  if (mark.shape === 'arc') {
404
656
  return `<path d="${mark.d}" fill="none" stroke="${ink}" stroke-width="${f(mark.strokeWidth)}" stroke-linecap="round"/>`;
405
657
  }
406
658
  return `<rect x="${f(mark.x)}" y="${f(mark.y)}" width="${f(mark.width)}" height="${f(mark.height)}" rx="${f(mark.radius)}" fill="${ink}"/>`;
407
659
  }
408
660
 
661
+ type RibbonGradient = { x1: number; y1: number; x2: number; y2: number; stops: string[] };
662
+
663
+ /**
664
+ * A ribbon piece with its gradient alongside it. The id is taken from the gradient itself, so
665
+ * repeats on a page (the same avatar at the same moment) share one harmlessly.
666
+ */
667
+ function ribbonSvg(d: string, g: RibbonGradient): string {
668
+ const id = `oba-g${hashString(`${f(g.x1)},${f(g.y1)},${f(g.x2)},${f(g.y2)},${g.stops.join()}`).toString(36)}`;
669
+ const stops = g.stops.map((c, i) => `<stop offset="${f(i / (g.stops.length - 1))}" stop-color="${c}"/>`).join('');
670
+ return (
671
+ `<linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="${f(g.x1)}" y1="${f(g.y1)}" x2="${f(g.x2)}" y2="${f(g.y2)}">${stops}</linearGradient>` +
672
+ `<path d="${d}" fill="url(#${id})"/>`
673
+ );
674
+ }
675
+
409
676
  /** Render a definition to a standalone SVG string. Throws if the definition is invalid. */
410
677
  export function renderAvatarSvg(definition: AvatarDefinition, options: RenderOptions = {}): string {
411
678
  const frame = avatarFrame(definition, options);
412
679
  const defsMarkup = frame.paths.map((d) => `<path id="${d.id}" d="${d.d}"${d.evenOdd ? ' fill-rule="evenodd"' : ''}/>`).join('');
413
680
  const body = frame.shapes
414
- .map((s) => (s.kind === 'slice' ? `<use href="#${s.path}" transform="${mat(s.matrix)}"/>` : `<g transform="${mat(s.matrix)}">${eyeSvg(s.mark, frame.ink)}</g>`))
681
+ .map((s) =>
682
+ s.kind === 'slice' ? `<use href="#${s.path}" transform="${mat(s.matrix)}"/>`
683
+ : s.kind === 'eye' ? `<g transform="${mat(s.matrix)}">${eyeSvg(s.mark, frame.ink)}</g>`
684
+ : `<g transform="${mat(s.matrix)}">${ribbonSvg(s.d, s.gradient)}</g>`,
685
+ )
415
686
  .join('');
416
687
  const size = Number.isFinite(options.size) && (options.size as number) > 0 ? f(clamp(options.size as number, 8, 4096)) : null;
417
688
  const dims = size ? ` width="${size}" height="${size}"` : '';
@@ -448,6 +719,9 @@ function sliceMarkup(s: VolumeSlice): string {
448
719
  );
449
720
  }
450
721
 
722
+ const overlay = (side: 'back' | 'front') =>
723
+ `<svg data-fx="${side}" viewBox="0 0 100 100" style="${FILL}overflow:visible;pointer-events:none" fill="currentColor" aria-hidden="true"></svg>`;
724
+
451
725
  /**
452
726
  * Static markup of the live scene for a definition and depth. Mount it once,
453
727
  * then apply `sceneFrame` every frame. Body color comes from CSS `color` on
@@ -470,16 +744,23 @@ export function renderAvatarScene(definition: AvatarDefinition, options: Pick<Re
470
744
  `<i style="position:absolute;inset:0;border-radius:999px;background:${ink}"></i>` +
471
745
  `<svg viewBox="${f(e.x - e.w / 2)} ${f(e.y - e.h / 2)} ${f(e.w)} ${f(e.h)}" style="${FILL}overflow:visible;display:none" aria-hidden="true">` +
472
746
  `<path d="${happyArc(e)}" fill="none" stroke="${ink}" stroke-width="${f(e.w * HAPPY_ARC.stroke)}" stroke-linecap="round"/></svg>` +
747
+ // Every look between the pill and the arc: its outline is written each frame it changes.
748
+ `<svg data-morph viewBox="${f(e.x - e.w / 2)} ${f(e.y - e.h / 2)} ${f(e.w)} ${f(e.h)}" style="${FILL}overflow:visible;display:none" aria-hidden="true">` +
749
+ `<path fill="${ink}"/></svg>` +
473
750
  `</div>`
474
751
  );
475
752
  });
476
753
  return (
477
754
  `<div data-avatar-scene="${p.id}" style="position:relative;width:100%;height:100%;container-type:size">` +
755
+ // Ribbons behind the body; they and the marks are written each frame they show.
756
+ overlay('back') +
478
757
  // will-change pins the slices' raster scale: without it every hop and squash re-rasterizes each slice.
479
758
  `<div data-motion style="${FILL}will-change:transform;transform-origin:${u((b.minX + b.maxX) / 2)} ${u(b.maxY)}">` +
480
759
  `<div data-view style="${FILL}transform-style:preserve-3d;transform-origin:${u(cx)} ${u(cy)}">` +
481
760
  stack('z') + stack('x') + eyes.join('') +
482
- `</div></div></div>`
761
+ `</div></div>` +
762
+ overlay('front') +
763
+ `</div>`
483
764
  );
484
765
  }
485
766
 
@@ -488,12 +769,18 @@ export interface SceneFrame {
488
769
  scene: string;
489
770
  /** 2D motion (hop, roll, squash) about the base of the body. */
490
771
  motion: string;
491
- /** 3D view rotation about the body center. */
772
+ /** 3D view rotation about the body center, scaled down while the body gives way to a mark. */
492
773
  view: string;
774
+ /** How much of its size the body keeps, 0..1; at 0 the view needs no layers. */
775
+ body: number;
776
+ /** Markup for the scene's two overlays (`data-fx`): ribbons behind the body; ribbons and marks in front. */
777
+ back: string;
778
+ front: string;
493
779
  stack: 'z' | 'x';
494
780
  /** Per slice of the active stack, in markup order: whether it shows. Hidden ones need no layer. */
495
781
  slices: boolean[];
496
- eyes: { visible: boolean; happy: boolean; transform: string; pill: string }[];
782
+ /** `d` is set while the eye is between the pill and the arc: it then shows the `data-morph` path alone. */
783
+ eyes: { visible: boolean; happy: boolean; transform: string; pill: string; d: string }[];
497
784
  }
498
785
 
499
786
  const r4 = (n: number) => Math.round(n * 10000) / 10000;
@@ -536,18 +823,24 @@ export function sceneFrame(definition: AvatarDefinition, options: RenderOptions
536
823
  const stack = activeStack(v);
537
824
  const drawn = sliceCull(v);
538
825
  const kept = sliceDetail(p, stack, options.size);
826
+ const fx = effectsOf(p, pose, options);
827
+ const piece = (front: boolean) => fx.ribbons.filter((r) => r.front === front).map((r) => ribbonSvg(r.d, r.gradient)).join('');
539
828
  let k = 0;
540
829
  return {
541
830
  scene: p.id,
542
831
  motion: `translate(0,${u(pose.lift)}) rotate(${f(pose.roll)}deg) scale(${r4(pose.sx)},${r4(pose.sy)})`,
543
- view: `rotateX(${r4(pose.pitch)}rad) rotateY(${r4(pose.yaw)}rad)`,
832
+ view: (fx.body < 1 ? `scale(${r4(fx.body)}) ` : '') + `rotateX(${r4(pose.pitch)}rad) rotateY(${r4(pose.yaw)}rad)`,
833
+ body: fx.body,
834
+ back: piece(false),
835
+ front: piece(true) + fx.marks.map((mark) => `<path d="${mark.d}" transform="${mat(mark.matrix)}"/>`).join(''),
544
836
  stack,
545
837
  slices: p.vol.parts.flatMap((part) => (stack === 'z' ? part.zSlices : part.xSlices).map((s) => kept[k++] && drawn(s))),
546
838
  eyes: states.map((e, i) => ({
547
839
  visible: eyeVisible(p.vol, v, i),
548
- happy: e.happy,
840
+ happy: e.plain === 'arc',
549
841
  transform: `translateZ(${u(p.vol.eyeZ[i] + EYE_LIFT)}) translate(${u(e.dx)},${u(e.dy)})`,
550
842
  pill: `translateY(${u(e.shift)}) scaleY(${r4(e.open / e.h)})`,
843
+ d: e.plain === null ? eyePath(e.look, eyeSpot(e, false)) : '',
551
844
  })),
552
845
  };
553
846
  }
package/src/types.ts CHANGED
@@ -28,14 +28,39 @@ export interface AvatarDefinition {
28
28
  eyes: AvatarEyes;
29
29
  }
30
30
 
31
+ /**
32
+ * What the bot is doing. `thinking` and `blocked` replace the body with a mark (three dots, an
33
+ * exclamation mark); `working` sweeps a band of ribbons round the body every few seconds; `done`
34
+ * celebrates: it turns a few times with ribbons flying, rests, and after a while does it again.
35
+ */
36
+ export type AvatarState = 'idle' | 'thinking' | 'working' | 'waiting' | 'blocked' | 'done';
37
+
38
+ /** How the bot feels. It shapes the eyes on top of any state; in `idle` a happy bot also hops. */
39
+ export type AvatarMood = 'neutral' | 'happy';
40
+
41
+ /**
42
+ * The single option that came before `state` and `mood`, still accepted: `idle` and `thinking`
43
+ * are states, `happy` is the idle state in a happy mood.
44
+ * @deprecated Use `state` and `mood`.
45
+ */
31
46
  export type AvatarMotion = 'idle' | 'thinking' | 'happy';
32
47
 
33
48
  /**
34
- * A mood easing in over what was shown before it: a plain mood, or a mood that
35
- * was itself still easing in (its progress frozen where it was). `t` 0..1.
49
+ * A change easing in over what was shown before it: a plain legacy motion, or a state and mood
50
+ * that were themselves still easing in (their progress frozen where it was). `t` 0..1.
36
51
  */
37
52
  export interface AvatarMotionBlend {
38
- from: AvatarMotion | { motion: AvatarMotion; blend?: AvatarMotionBlend };
53
+ from:
54
+ | AvatarMotion
55
+ | {
56
+ state?: AvatarState;
57
+ mood?: AvatarMood;
58
+ /** @deprecated Use `state` and `mood`. */
59
+ motion?: AvatarMotion;
60
+ /** Seconds that state had been showing when the change began (see RenderOptions.stateAge). */
61
+ age?: number;
62
+ blend?: AvatarMotionBlend;
63
+ };
39
64
  t: number;
40
65
  }
41
66
 
@@ -61,14 +86,24 @@ export interface RenderOptions {
61
86
  * over the idle pose so following can start and stop without a jump.
62
87
  */
63
88
  gaze?: { x: number; y: number; weight?: number };
89
+ /** What the bot is doing (default `idle`). */
90
+ state?: AvatarState;
91
+ /** How the bot feels (default `neutral`). */
92
+ mood?: AvatarMood;
93
+ /** @deprecated Use `state` and `mood`; they win when given. */
64
94
  motion?: AvatarMotion;
65
95
  /**
66
- * Ease into `motion` from the mood shown before: the pose blends between the
67
- * two, and eyes that change shape close and reopen. Hosts leave it out once
68
- * `t` reaches 1 (and under reduced motion).
96
+ * Seconds since `state` began. `done` celebrates from the moment it begins, so hosts that
97
+ * animate pass this (createAnimator returns it); without it the state is drawn at rest.
98
+ */
99
+ stateAge?: number;
100
+ /**
101
+ * Ease into `state` and `mood` from what was shown before: the pose blends between the two
102
+ * and the eyes morph from one shape to the other. Hosts leave it out once `t` reaches 1 (and
103
+ * under reduced motion).
69
104
  */
70
105
  motionBlend?: AvatarMotionBlend;
71
- /** Freeze body motion and blinking at a calm pose; gaze still applies. */
106
+ /** Freeze body motion, blinking, ribbons and marks at a calm pose; gaze still applies. */
72
107
  reducedMotion?: boolean;
73
108
  }
74
109