@kodax-ai/botui 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.
@@ -0,0 +1,579 @@
1
+ // The solids theme: a shaded 3D solid with eyes on its surface, drawn as SVG.
2
+ //
3
+ // One instance owns one <span> with one <svg>. Nothing here reads the wall
4
+ // clock: `step(dt)` advances an avatar by exactly dt seconds, so motion can be
5
+ // driven by hand for tests and film strips.
6
+
7
+ import {TAU, ease, clamp, smooth, bump, hash, random, pointer, world, join, leave, joined, prefersDark} from '../../core/core.js';
8
+ import {STATES, resolveState} from '../../core/states.js';
9
+ import {solid, SHAPES} from './geometry.js';
10
+ import {EYE_STYLES, EXPRESSIONS, eyeShape} from './face.js';
11
+ import {REST, POSES, GESTURES, FIDGETS} from './motion.js';
12
+ import {SYMBOLS} from './symbols.js';
13
+
14
+ const NS = 'http://www.w3.org/2000/svg';
15
+ const LIGHT = [-0.42, -0.82, 0.39];
16
+ const CY = 50, UNIT = 23, PERSPECTIVE = 0.07, GROUND = 90, RING = 42;
17
+ const STAR = 'M0,-1L.26,-.26L1,0L.26,.26L0,1L-.26,.26L-1,0L-.26,-.26Z';
18
+ const HEART = 'M0,1C-1.3,0 -1.1,-1 -.5,-1C-.2,-1 0,-.8 0,-.6C0,-.8 .2,-1 .5,-1C1.1,-1 1.3,0 0,1Z';
19
+
20
+ /**
21
+ * Body colours. `chroma`, `base` and `span` default to a saturated mid tone; `eye`
22
+ * overrides the eye colour; `dark` holds what changes on a dark background
23
+ * (without it the colour is simply a little lighter there).
24
+ */
25
+ export const COLORS = {
26
+ red: {hue: 25}, orange: {hue: 55}, amber: {hue: 85}, lime: {hue: 120}, green: {hue: 150}, teal: {hue: 175},
27
+ cyan: {hue: 200}, sky: {hue: 235}, blue: {hue: 265}, violet: {hue: 290}, magenta: {hue: 330}, pink: {hue: 0, chroma: 0.13, base: 0.68},
28
+ brown: {hue: 60, chroma: 0.06, base: 0.5, dark: {base: 0.58}}, gray: {hue: 260, chroma: 0.012, base: 0.58, dark: {base: 0.67}},
29
+ black: {hue: 260, chroma: 0.012, base: 0.3, span: 0.15, dark: {base: 0.45, span: 0.17, chroma: 0.02}},
30
+ white: {hue: 260, chroma: 0.006, base: 0.83, span: 0.13, eye: 'oklch(0.3 0.03 260)', dark: {}},
31
+ };
32
+ /** The colours a Bot ID can be born with: the twelve saturated ones. */
33
+ export const BIRTH_COLORS = Object.keys(COLORS).slice(0, 12);
34
+ export const HUES = BIRTH_COLORS.map(name => COLORS[name].hue);
35
+
36
+ // Glyphs shown beside the head. `d` is stroked, `dot` is a filled circle [x, y, r].
37
+ const MARKS = {
38
+ ask: {d: 'M-4,-6Q-4,-11 0,-11Q4.5,-11 4.5,-6.5Q4.5,-3.5 0,-2L0,1', dot: [0, 6.5, 2]},
39
+ bang: {d: 'M0,-11L0,0', dot: [0, 6.5, 2.1]},
40
+ dots: {d: 'M-7,0L-7,0M0,0L0,0M7,0L7,0', wide: true},
41
+ check: {d: 'M-7,0L-2,5L7,-6'},
42
+ up: {d: 'M0,8L0,-9M-6,-3L0,-9L6,-3'},
43
+ code: {d: 'M-4,-6L-10,0L-4,6M4,-6L10,0L4,6'},
44
+ search: {d: 'M-8,-2a6,6 0 1,0 12,0a6,6 0 1,0 -12,0M3,3L9,9'},
45
+ cursor: {d: 'M-5,-9L-5,7L-1,3L2,9L5,7.5L2,2L7,2Z', fill: true},
46
+ pen: {d: 'M-7,8L-6,3L4,-8L8,-4L-2,7ZM-9,10L8,10'},
47
+ anger: {d: 'M-6,-2Q-2,-2 -2,-6M6,-2Q2,-2 2,-6M-6,2Q-2,2 -2,6M6,2Q2,2 2,6', paint: 'oklch(0.62 0.22 25)'},
48
+ sweat: {d: 'M0,-8Q6,2 0,6Q-6,2 0,-8Z', paint: 'oklch(0.78 0.1 230)'},
49
+ badge: {d: '', dot: [0, 0, 5.5], paint: 'oklch(0.64 0.22 25)'},
50
+ };
51
+
52
+ const known = name => SHAPES.some(s => s.name === name);
53
+ const r1 = v => Math.round(v * 10) / 10;
54
+ function el(name, attrs, parent) {
55
+ const node = document.createElementNS(NS, name);
56
+ for (const key in attrs) node.setAttribute(key, attrs[key]);
57
+ if (parent) parent.append(node);
58
+ return node;
59
+ }
60
+
61
+ /**
62
+ * The look a Bot ID maps to: one solid, one colour, one eye style. `pool` can
63
+ * limit the choice: {shapes, colors, eyes}, each a list of names.
64
+ */
65
+ export function identityFrom(identity, pool) {
66
+ const h = hash(identity), pick = (given, test, all) => { const kept = (given || []).filter(test); return kept.length ? kept : all; };
67
+ const shapes = pick(pool?.shapes, known, SHAPES.map(s => s.name)), colors = pick(pool?.colors, name => COLORS[name], BIRTH_COLORS), eyes = pick(pool?.eyes, name => EYE_STYLES[name], Object.keys(EYE_STYLES));
68
+ return {shape: shapes[h % shapes.length], color: colors[(h >>> 8) % colors.length], eyes: eyes[(h >>> 16) % eyes.length]};
69
+ }
70
+
71
+ // Attribution carried by every avatar: invisibly in the SVG, and as a visible mark from WATERMARK_FROM pixels up.
72
+ export const WATERMARK = 'KodaX-AI', WATERMARK_FROM = 48;
73
+ const CREDIT = 'BotUI. Copyright (c) 2026 Wei Zhang (icetomoyo) / KodaX-AI. KodaX-AI BotUI License 1.0. https://github.com/icetomoyo/BotUI';
74
+
75
+ export class SolidAvatar {
76
+ /**
77
+ * @param {object} options
78
+ * @param {string} [options.identity] Bot ID. Picks shape, colour and eyes unless given.
79
+ * @param {{shapes?: string[], colors?: string[], eyes?: string[]}} [options.pool] Limits what an identity can be born as.
80
+ * @param {number} [options.size=36] Width and height in CSS pixels.
81
+ * @param {string} [options.shape] A name from SHAPES.
82
+ * @param {string} [options.color] A name from COLORS.
83
+ * @param {number} [options.hue] An OKLCH hue, 0..360, instead of a named colour.
84
+ * @param {string} [options.eyes] A name from EYE_STYLES.
85
+ * @param {string} [options.eyeColor] Any CSS colour for the eyes.
86
+ * @param {string} [options.state='idle'] A name from STATES.
87
+ * @param {number} [options.progress] 0..1, shown by the `progress` state. Without it the ring loops.
88
+ * @param {'light'|'dark'|'auto'} [options.scheme='light'] The background it sits on; 'auto' follows the system.
89
+ * @param {'around'|'morph'} [options.signals='around'] How signal states show: effects around the body, or the body turning into a symbol.
90
+ * @param {boolean} [options.emphasized=false] Mark this one as the active Bot: slightly larger, with a halo on the ground.
91
+ * @param {boolean} [options.interactive=true] React to hover, press, click and drag.
92
+ * @param {boolean} [options.track=true] Follow the pointer with head and eyes.
93
+ * @param {boolean} [options.static=false] Show only the resting pose. Reduced-motion users always get this.
94
+ * @param {boolean} [options.playing=true] False pauses the animation.
95
+ * @param {number} [options.maxFrameRate=60]
96
+ * @param {boolean} [options.autoplay=true] Animate on the shared frame loop. With false, call step() yourself.
97
+ * @param {string} [options.label] Accessible name. Without it the avatar is decorative.
98
+ * @param {boolean} [options.watermark=true] Show the KodaX-AI mark (drawn from 48 px up). The licence allows turning it off only for Community Use or under a Customer Agreement; see LICENSE.
99
+ */
100
+ constructor(options = {}) {
101
+ this.identity = options.identity ?? 'bot';
102
+ this.pool = options.pool ?? null;
103
+ const born = identityFrom(this.identity, this.pool);
104
+ this.size = options.size ?? 36; this.shape = known(options.shape) ? options.shape : born.shape;
105
+ this.eyes = EYE_STYLES[options.eyes] ? options.eyes : born.eyes; this.eyeColor = options.eyeColor ?? null;
106
+ this.scheme = options.scheme ?? 'light'; this.signals = options.signals ?? 'around'; this.emphasized = !!options.emphasized;
107
+ this.paint(options.color, options.hue, born.color);
108
+ this.state = resolveState(options.state) || 'idle'; this.progress = options.progress ?? null;
109
+ this.watermark = options.watermark ?? true;
110
+ this.track = options.track ?? true; this.static = !!options.static; this.playing = options.playing ?? true; this.maxFrameRate = options.maxFrameRate ?? 60;
111
+ this.visible = true; this.settled = false;
112
+ this.rng = random(hash(this.identity)); this.t = this.rng() * 10; this.since = 0; this.dt = 0; this.beat = 0;
113
+ this.p = {yaw: 0.2, pitch: -0.26, roll: 0, sy: 1, lift: 0, scale: 1, sat: 1, open: 1, blush: 0};
114
+ this.vel = {sy: 0, lift: 0, scale: 0, roll: 0};
115
+ this.omega = 0; this.spun = 0; this.dizzy = 0; this.tug = 0; this.phase = 0;
116
+ this.aim = {x: 0, y: 0}; this.gazeAt = {x: 0, y: 0}; this.focus = null; this.fixed = null; this.stray = {x: 0, y: 0}; this.strayIn = 0;
117
+ this.shown = 'neutral'; this.override = null;
118
+ this.blinkIn = 1 + this.rng() * 3; this.blinkFor = 0; this.fidgetIn = 4 + this.rng() * 6;
119
+ this.gestures = []; this.particles = []; this.swap = null;
120
+ this.aura = {orbit: 0, mark: 0, stars: 0, ring: 0, bars: 0, morph: 0, emph: 0}; this.markName = 'ask'; this.ringKind = 'spin';
121
+ this.hover = false; this.press = false; this.dragging = false; this.rectAge = 99; this.center = {x: 0, y: 0};
122
+
123
+ this.el = document.createElement('span');
124
+ this.el.className = 'botui-avatar botui-solid'; this.el.botAvatar = this; this.el.dataset.state = this.state;
125
+ this.el.style.cssText = 'display:inline-block;line-height:0;vertical-align:middle;user-select:none;-webkit-user-select:none';
126
+ this.name(options.label);
127
+ this.svg = el('svg', {viewBox: '0 0 100 100', width: this.size, height: this.size, overflow: 'visible'}, this.el);
128
+ el('metadata', {}, this.svg).textContent = CREDIT;
129
+ this.shadow = el('ellipse', {cx: 50, cy: GROUND, ry: 3.6}, this.svg);
130
+ this.back = el('g', {}, this.svg);
131
+ this.haloNode = el('ellipse', {cx: 50, cy: GROUND, fill: 'none', display: 'none'}, this.back);
132
+ this.ringNode = el('circle', {cx: 50, r: RING, fill: 'none', 'stroke-linecap': 'round', display: 'none'}, this.back);
133
+ this.body = el('g', {'stroke-linejoin': 'round', 'stroke-width': 2.4}, this.svg);
134
+ this.blushNodes = [-1, 1].map(() => el('path', {fill: 'none', 'stroke-linecap': 'round', stroke: 'oklch(0.74 0.17 15)', display: 'none'}, this.svg));
135
+ this.eyeNodes = [-1, 1].map(() => el('path', {'stroke-linecap': 'round', 'stroke-linejoin': 'round'}, this.svg));
136
+ this.symbolNode = el('g', {display: 'none'}, this.svg);
137
+ el('path', {fill: 'none', 'stroke-linecap': 'round', 'stroke-linejoin': 'round'}, this.symbolNode);
138
+ this.front = el('g', {}, this.svg);
139
+ this.barsNode = el('path', {fill: 'none', 'stroke-linecap': 'round', display: 'none'}, this.front);
140
+ this.markNode = el('text', {x: 99, y: 98, 'text-anchor': 'end', 'font-family': "system-ui, 'Segoe UI', sans-serif", 'font-weight': 600, fill: '#8b8b8b', 'fill-opacity': 0.75, 'pointer-events': 'none', display: 'none'}, this.svg);
141
+ this.markNode.textContent = WATERMARK;
142
+ this.facePaths = []; this.used = 0;
143
+ this.build();
144
+ if (options.interactive ?? true) this.listen();
145
+ this.settle();
146
+ this.auto = options.autoplay ?? true;
147
+ if (this.auto) join(this);
148
+ }
149
+
150
+ // ---- public API ----
151
+ /** Change any of: label, size, shape, color, hue, eyes, eyeColor, scheme, signals, emphasized, state, progress, track, static, playing, maxFrameRate, identity. */
152
+ update(options) {
153
+ let born = null;
154
+ if (options.identity !== undefined && options.identity !== this.identity) { this.identity = options.identity; born = identityFrom(this.identity, this.pool); this.eyes = born.eyes; this.paint(born.color); }
155
+ if (options.color !== undefined || options.hue !== undefined) this.paint(options.color, options.hue, this.color);
156
+ if (options.eyes !== undefined && EYE_STYLES[options.eyes]) this.eyes = options.eyes;
157
+ for (const key of ['eyeColor', 'track', 'progress', 'playing', 'maxFrameRate', 'signals', 'emphasized', 'watermark']) if (options[key] !== undefined) { this[key] = options[key]; this.settled = false; }
158
+ if (options.scheme !== undefined) { this.scheme = options.scheme; this.retone(); }
159
+ if (options.label !== undefined) this.name(options.label);
160
+ if (options.static !== undefined) { this.static = !!options.static; this.settled = false; }
161
+ if (options.size !== undefined) { this.size = Number(options.size); this.svg.setAttribute('width', this.size); this.svg.setAttribute('height', this.size); }
162
+ const shape = known(options.shape) ? options.shape : born?.shape;
163
+ // A new shape arrives with a quick turn: it shrinks, swaps and pops back.
164
+ if (shape && shape !== (this.swap?.to || this.shape)) { if (joined(this) && !this.static) this.swap = {to: shape, age: 0}; else this.shape = shape; }
165
+ this.build();
166
+ if (options.state !== undefined) this.setState(options.state);
167
+ if (!joined(this)) this.render();
168
+ return this;
169
+ }
170
+ setState(name) {
171
+ const state = resolveState(name);
172
+ if (!state || state === this.state) return this;
173
+ this.state = state; this.since = 0; this.el.dataset.state = state; this.vel.scale += 1.2; this.settled = false;
174
+ if (!this.morphing) POSES[state]?.enter?.(this);
175
+ return this;
176
+ }
177
+ /** Play a one-shot gesture from GESTURES. */
178
+ play(name) {
179
+ const def = GESTURES[name];
180
+ if (!def) return this;
181
+ this.gestures = this.gestures.filter(g => g.def !== def);
182
+ this.gestures.push({def, age: 0}); def.start?.(this);
183
+ return this;
184
+ }
185
+ /** Show an expression from EXPRESSIONS for `ms` milliseconds, over whatever the state shows. */
186
+ express(name, ms = 1500) { this.override = name && EXPRESSIONS[name] ? {name, left: ms / 1000} : null; return this; }
187
+ /** Watch a client-space point; lookAt(null) hands control back to the pointer. */
188
+ lookAt(x, y) { this.focus = x == null ? null : {x, y}; return this; }
189
+ /** Hold a direction, each axis -1..1; look(null) releases it. */
190
+ look(direction) { this.fixed = direction ? {x: clamp(direction.x ?? 0, -1, 1), y: clamp(direction.y ?? 0, -1, 1)} : null; return this; }
191
+ blink() { this.blinkFor = 0.13; return this; }
192
+ /** A small acknowledging bob, e.g. on each keystroke. */
193
+ nudge() { this.vel.sy -= 1.4; return this; }
194
+ /**
195
+ * React to a touch. `poke('spin', {turns})`, `poke('bounce')`, `poke('nod')` or
196
+ * any gesture name; with no action it picks a reaction itself.
197
+ */
198
+ poke(action, {turns = 1} = {}) {
199
+ this.pulse();
200
+ if (action === 'spin') { this.omega += 3 * TAU * turns; this.hop(170); return this; }
201
+ if (action) return this.play(action);
202
+ if (this.state === 'blocked' || this.state === 'sleeping' || this.state === 'powering-down') { this.hop(40); return this; }
203
+ const r = this.rng();
204
+ if (r < 0.4) { this.omega += r < 0.2 ? 19 : -19; this.hop(170); this.express('happy', 800); }
205
+ else this.play(r < 0.6 ? 'jump' : r < 0.75 ? 'wobble' : r < 0.9 ? 'flip' : 'roll');
206
+ return this;
207
+ }
208
+ /** Advance by dt seconds and redraw. Long steps are simulated in slices so the springs stay stable at any frame rate. */
209
+ step(dt) {
210
+ const slices = Math.max(1, Math.ceil(dt / 0.017 - 1e-6));
211
+ for (let i = 1; i <= slices; i++) this.advance(dt / slices, i === slices);
212
+ return this;
213
+ }
214
+ /** Start the current state again from its resting pose. */
215
+ restart() { this.since = 0; this.settle(); this.settled = false; return this; }
216
+ /** Leave the frame loop, e.g. while detached from the page; resume() joins it again. */
217
+ suspend() { leave(this); return this; }
218
+ resume() { if (this.auto) join(this); return this; }
219
+ /** The current frame as standalone SVG markup, for a favicon, an export or server-rendered HTML. */
220
+ toSVG() {
221
+ const copy = this.svg.cloneNode(true);
222
+ copy.setAttribute('xmlns', NS);
223
+ for (const node of copy.querySelectorAll('[display="none"]')) node.remove();
224
+ return copy.outerHTML;
225
+ }
226
+ dispose() { leave(this); this.el.botAvatar = null; this.el.remove(); }
227
+ // Names used by RSIBot's existing component.
228
+ gaze(point) { return point ? this.lookAt(point.x, point.y) : this.lookAt(null); }
229
+ setExpression(name, {duration = 1200} = {}) { return this.express(name, duration); }
230
+
231
+ // ---- building blocks used by states and gestures ----
232
+ hop(strength) { this.vel.lift -= strength; }
233
+ squash(strength) { this.vel.sy -= strength; }
234
+ every(period) { return Math.floor(this.since / period) !== Math.floor((this.since - this.dt) / period); }
235
+ pulse() { this.spawn({type: 'ring', life: 0.6, node: el('ellipse', {cx: 50, cy: GROUND, fill: 'none'}, this.back)}); }
236
+ emit(type) {
237
+ const rng = this.rng, dot = () => el('circle', {r: 1}, this.front), line = d => el('path', {d, fill: 'none', 'stroke-width': 0.62, 'stroke-linecap': 'round', 'stroke-linejoin': 'round'}, this.front);
238
+ if (type === 'z') this.spawn({life: 2.2, x: 0.9, y: -1.0, vx: 0.32, vy: -0.42, size: 2.2, turn: -12, grow: 1, stroked: true, node: line('M-1,-1H1L-1,1H1')});
239
+ else if (type === 'note') this.spawn({life: 1.8, x: 0.7 + rng() * 0.5, y: -0.9, vx: 0.3 * (rng() - 0.3), vy: -0.6, size: 4.6, turn: rng() * 24 - 12, grow: 0.3, stroked: true, node: line('M-.8,1.4L-.8,-1.6L1.2,-1.1L1.2,.9M-1.3,1.5L-.8,1.4M.7,1L1.2,.9')});
240
+ else if (type === 'heart') this.spawn({life: 1.4, x: (rng() - 0.5) * 1.6, y: -0.9, vx: (rng() - 0.5) * 0.5, vy: -0.9, size: 2.6 + rng() * 1.6, paint: 'oklch(0.7 0.19 10)', node: el('path', {d: HEART}, this.front)});
241
+ else if (type === 'tear') this.spawn({life: 0.9, x: (rng() < 0.5 ? -0.42 : 0.42), y: 0.25, vy: 0.3, g: 5, size: 1.5, paint: 'oklch(0.8 0.1 230)', node: dot()});
242
+ else if (type === 'dust') this.spawn({life: 0.5, x: -0.5 - rng() * 0.3, y: 1.7, vx: -1.6 - rng(), vy: -0.5, size: 3 + rng() * 1.6, paint: 'oklch(0.8 0.01 260)', node: dot()});
243
+ else if (type === 'out') this.spawn({life: 0.7, x: (rng() - 0.5) * 0.6, y: -0.7, vx: 1.6 + rng() * 1.2, vy: -2 - rng() * 1.4, size: 2.4 + rng() * 1.2, node: dot()});
244
+ else if (type === 'up') this.spawn({life: 0.9, x: (rng() - 0.5) * 2.2, y: 0.8, vy: -2.4, size: 2.2 + rng() * 1.2, node: dot()});
245
+ else if (type === 'in') { const a = rng() * TAU, life = 0.6; this.spawn({life, x: 2.3 * Math.cos(a), y: 2.3 * Math.sin(a), vx: -2.3 * Math.cos(a) / life, vy: -2.3 * Math.sin(a) / life, size: 3.2 + rng() * 1.6, node: dot()}); }
246
+ }
247
+ burst(type, count) {
248
+ const rng = this.rng;
249
+ for (let i = 0; i < count; i++) {
250
+ const a = (i + rng()) / count * TAU;
251
+ if (type === 'spark') this.spawn({life: 0.55 + rng() * 0.4, x: Math.cos(a), y: Math.sin(a) * 0.9 - 0.1, vx: Math.cos(a) * (1.3 + rng()), vy: Math.sin(a) * (1.3 + rng()), drag: 2, size: 4 + rng() * 4, turn: rng() * 90, spin: 90, bright: true, node: el('path', {d: STAR}, this.front)});
252
+ else this.spawn({life: 1 + rng() * 0.5, x: (rng() - 0.5) * 0.8, y: -0.9, vx: (rng() - 0.5) * 4.6, vy: -2.4 - rng() * 2.4, g: 9, size: 2.4 + rng() * 1.6, turn: rng() * 360, spin: 520, paint: `oklch(0.78 0.17 ${HUES[Math.floor(rng() * HUES.length)]})`, node: el('rect', {x: -1, y: -0.6, width: 2, height: 1.2, rx: 0.3}, this.front)});
253
+ }
254
+ }
255
+ spawn(particle) {
256
+ if (this.particles.length >= 40) { particle.node.remove(); return; }
257
+ particle.node.setAttribute('transform', 'scale(0)');
258
+ this.particles.push({age: 0, x: 0, y: 0, vx: 0, vy: 0, size: 1, turn: 0, spin: 0, ...particle});
259
+ }
260
+
261
+ // ---- internals ----
262
+ name(label) {
263
+ if (label) { this.el.setAttribute('role', 'img'); this.el.setAttribute('aria-label', label); this.el.removeAttribute('aria-hidden'); }
264
+ else { this.el.removeAttribute('role'); this.el.removeAttribute('aria-label'); this.el.setAttribute('aria-hidden', 'true'); }
265
+ }
266
+ paint(color, hue, fallback) {
267
+ const given = hue != null && hue !== '' && Number.isFinite(Number(hue)), named = COLORS[color] ? color : given ? null : fallback;
268
+ if (!named && !given) return; // neither a known colour nor a usable hue: keep what it has
269
+ this.color = named ?? null;
270
+ this.spec = named ? COLORS[named] : {hue: Number(hue)};
271
+ this.retone();
272
+ }
273
+ retone() {
274
+ const spec = this.spec;
275
+ this.dark = this.scheme === 'dark' || (this.scheme === 'auto' && prefersDark());
276
+ this.tone = {chroma: 0.15, base: 0.6, span: 0.26, eye: null, ...spec, ...(this.dark ? spec.dark ?? {base: (spec.base ?? 0.6) + 0.05} : null)};
277
+ this.hue = this.tone.hue; this.settled = false;
278
+ }
279
+ get morphing() { return this.signals === 'morph' && !!SYMBOLS[this.state]; }
280
+ build() {
281
+ // The mark keeps a readable pixel size, so it takes more of a small avatar; below 48 px it would not be legible at all.
282
+ const marked = this.watermark !== false && this.size >= WATERMARK_FROM;
283
+ if (marked) { this.markNode.setAttribute('font-size', (clamp(this.size * 0.075, 5.5, 10) * 100 / this.size).toFixed(2)); this.markNode.removeAttribute('display'); }
284
+ else this.markNode.setAttribute('display', 'none');
285
+ const geo = solid(this.shape, this.size <= 40 ? 12 : this.size <= 110 ? 18 : 28);
286
+ if (geo !== this.geo) {
287
+ this.geo = geo; this.points = new Float32Array(geo.verts.length * 3);
288
+ while (this.facePaths.length < geo.faces.length) this.facePaths.push(el('path', {display: 'none'}, this.body));
289
+ for (let i = geo.faces.length; i < this.facePaths.length; i++) this.facePaths[i].setAttribute('display', 'none');
290
+ this.used = Math.min(this.used, geo.faces.length);
291
+ }
292
+ this.el.dataset.shape = this.shape;
293
+ // How far it may turn before the far eye slips round the side. Narrow and
294
+ // strongly curved solids get less.
295
+ const gap = EYE_STYLES[this.eyes].gap * geo.k, n = geo.nrm(gap, 0.02 * geo.k);
296
+ this.turnLimit = clamp(1.2 - Math.atan2(Math.abs(n[0]), -n[2]), 0.3, 1.2);
297
+ this.shadow.setAttribute('fill', this.dark ? 'oklch(0 0 0)' : `oklch(0.25 0.06 ${this.hue})`);
298
+ }
299
+
300
+ listen() {
301
+ const host = this.el;
302
+ host.style.cursor = 'grab'; host.style.touchAction = 'pan-y';
303
+ host.addEventListener('pointerenter', () => { this.hover = true; });
304
+ host.addEventListener('pointerleave', () => { this.hover = false; });
305
+ host.addEventListener('pointerdown', e => {
306
+ this.press = true; this.dragging = false; this.drag = {x: e.clientX, y: e.clientY, travel: 0, at: performance.now(), speed: 0};
307
+ host.setPointerCapture?.(e.pointerId);
308
+ });
309
+ host.addEventListener('pointermove', e => {
310
+ if (!this.press) return;
311
+ const d = this.drag, dx = e.clientX - d.x, dy = e.clientY - d.y, now = performance.now(), dt = Math.max(0.004, (now - d.at) / 1000);
312
+ d.x = e.clientX; d.y = e.clientY; d.at = now; d.travel += Math.abs(dx) + Math.abs(dy);
313
+ if (d.travel < 5) return;
314
+ // Dragging across the avatar's own width turns it half a revolution.
315
+ this.dragging = true; host.style.cursor = 'grabbing';
316
+ const turn = dx / this.size * Math.PI;
317
+ this.p.yaw += turn; this.spun += Math.abs(turn); d.speed = d.speed * 0.5 + turn / dt * 0.5;
318
+ this.tug = clamp(this.tug - dy / this.size * 1.4, -0.7, 0.7);
319
+ });
320
+ host.addEventListener('pointerup', () => {
321
+ if (!this.press) return;
322
+ if (this.dragging) this.omega = clamp(this.drag.speed, -34, 34);
323
+ else { this.poke(); host.dispatchEvent(new CustomEvent('bot-poke', {bubbles: true, detail: {avatar: this}})); }
324
+ this.press = false; this.dragging = false; host.style.cursor = 'grab';
325
+ });
326
+ host.addEventListener('pointercancel', () => { this.press = false; this.dragging = false; host.style.cursor = 'grab'; });
327
+ }
328
+
329
+ // Where to look, as a vector that saturates with distance.
330
+ attend(dt) {
331
+ let x = 0, y = 0;
332
+ const target = this.focus || world.attention || (this.track && performance.now() - pointer.at < 6000 ? pointer : null);
333
+ if (this.fixed) { x = this.fixed.x; y = this.fixed.y; }
334
+ else if (target) {
335
+ if ((this.rectAge += dt) > 0.4) { const r = this.el.getBoundingClientRect(); this.center = {x: r.left + r.width / 2, y: r.top + r.height / 2}; this.rectAge = 0; }
336
+ const dx = target.x - this.center.x, dy = target.y - this.center.y, d = Math.hypot(dx, dy) + 60 + this.size;
337
+ x = dx / d; y = dy / d;
338
+ } else {
339
+ // Nobody to look at: glance around, and come back to the viewer now and then.
340
+ if ((this.strayIn -= dt) < 0) { this.strayIn = 1.2 + this.rng() * 2.6; this.stray = this.rng() < 0.35 ? {x: 0, y: 0} : {x: (this.rng() - 0.5) * 0.7, y: (this.rng() - 0.5) * 0.35}; }
341
+ x = this.stray.x; y = this.stray.y;
342
+ }
343
+ this.aim.x = ease(this.aim.x, x, dt, 7); this.aim.y = ease(this.aim.y, y, dt, 7);
344
+ return this.aim;
345
+ }
346
+
347
+ spring(key, target, stiff, damp, dt) {
348
+ this.vel[key] += (stiff * (target - this.p[key]) - damp * this.vel[key]) * dt;
349
+ this.p[key] += this.vel[key] * dt;
350
+ }
351
+ wanted(look) {
352
+ // As a symbol the body only floats; the symbol does the talking.
353
+ const want = this.morphing ? {...REST, lift: 1.5 * Math.sin(this.t * 2), still: true} : {...REST, ...(POSES[this.state] || POSES.idle).pose(this, this.t, look)};
354
+ if (this.emphasized) want.scale *= 1.1;
355
+ // Turns short of a profile are eased back so both eyes stay in view; real turn-arounds pass through.
356
+ const limit = this.turnLimit, knee = 0.6 * limit, turn = Math.abs(want.yaw);
357
+ if (turn > knee && turn < 1.6) want.yaw = Math.sign(want.yaw) * (knee + (limit - knee) * Math.tanh((turn - knee) / (limit - knee)));
358
+ return want;
359
+ }
360
+
361
+ /** Jump straight to the resting pose of the current state and draw it. */
362
+ settle() {
363
+ const p = this.p; this.dt = 0;
364
+ const want = this.wanted({x: 0, y: 0});
365
+ Object.assign(p, {yaw: want.yaw, pitch: want.pitch, roll: want.roll, sy: want.sy, lift: want.lift, scale: want.scale, sat: want.sat, blush: want.blush, open: 1});
366
+ this.vel = {sy: 0, lift: 0, scale: 0, roll: 0}; this.omega = 0; this.dizzy = 0; this.tug = 0; this.gestures = []; this.swap = null;
367
+ this.gazeAt = {x: want.gx, y: want.gy}; this.shown = want.expr;
368
+ if (want.mark) this.markName = want.mark; if (want.ring) this.ringKind = want.ring;
369
+ this.aura = {orbit: +(want.orbit > 0), mark: +!!want.mark, stars: 0, ring: +!!want.ring, bars: +want.bars, morph: +this.morphing, emph: +this.emphasized};
370
+ for (const q of this.particles) q.node.remove();
371
+ this.particles = [];
372
+ this.render(); this.settled = true;
373
+ }
374
+
375
+ advance(dt, draw = true) {
376
+ const p = this.p; this.dt = dt; this.t += dt; this.since += dt; this.settled = false;
377
+ const want = this.wanted(this.attend(dt));
378
+
379
+ if (this.state === 'idle' && !this.hover && !this.press && (this.fidgetIn -= dt) < 0) { this.fidgetIn = 5 + this.rng() * 7; this.play(FIDGETS[Math.floor(this.rng() * FIDGETS.length)]); }
380
+ if (this.hover) want.scale *= 1.08;
381
+ if (this.press && !this.dragging) { want.sy = Math.min(want.sy, 0.55); want.lift += 10; }
382
+
383
+ const g = {yaw: 0, pitch: 0, roll: 0, sy: 0, lift: 0, scale: 0, gx: 0, gy: 0};
384
+ let acted = null;
385
+ this.gestures = this.gestures.filter(item => {
386
+ item.age += dt;
387
+ if (item.age >= item.def.dur) { item.def.end?.(this); return false; }
388
+ item.def.move(item.age / item.def.dur, g); acted = item.def.expr || acted;
389
+ return true;
390
+ });
391
+ if (this.swap) {
392
+ const s = this.swap, u = (s.age += dt) / 0.36;
393
+ if (u >= 0.5 && s.to) { this.shape = s.to; s.to = null; this.build(); }
394
+ g.scale -= 0.5 * bump(u); g.yaw += TAU * smooth(Math.min(1, u));
395
+ if (u >= 1) this.swap = null;
396
+ }
397
+
398
+ // Spin too much and it gets dizzy.
399
+ this.spun = Math.max(0, this.spun + Math.abs(this.omega) * dt - 2.5 * dt);
400
+ if (this.spun > 15 && this.dizzy <= 0) { this.dizzy = 2.8; this.spun = 0; }
401
+ this.dizzy = Math.max(0, this.dizzy - dt);
402
+ if (this.dizzy > 0) g.roll += 0.16 * Math.sin(this.t * 9) * Math.min(1, this.dizzy);
403
+
404
+ this.omega = ease(this.omega, 0, dt, 3);
405
+ if (!this.dragging) { p.yaw = ease(p.yaw, want.yaw + Math.round((p.yaw - want.yaw) / TAU) * TAU, dt, want.rate) + this.omega * dt; this.tug = ease(this.tug, 0, dt, 4); }
406
+ p.pitch = ease(p.pitch, want.pitch + this.tug, dt, want.rate);
407
+ this.spring('sy', want.sy, want.stiff, Math.sqrt(want.stiff), dt);
408
+ this.spring('lift', want.lift, 180, 12, dt);
409
+ this.spring('scale', want.scale, 220, 18, dt);
410
+ this.spring('roll', want.roll, 120, 12, dt);
411
+ p.sat = ease(p.sat, want.sat, dt, 5); p.blush = ease(p.blush, want.blush, dt, 6);
412
+ this.gazeAt.x = ease(this.gazeAt.x, want.gx + g.gx, dt, 10); this.gazeAt.y = ease(this.gazeAt.y, want.gy + g.gy, dt, 10);
413
+
414
+ // Expressions change behind a blink.
415
+ if (this.override && (this.override.left -= dt) <= 0) this.override = null;
416
+ const expr = this.override?.name || (this.dizzy > 0 && 'dizzy') || acted || (this.press && !this.dragging && 'squint') || (this.hover && want.expr === 'neutral' ? 'wide' : want.expr);
417
+ if (expr !== this.shown && p.open < 0.2) this.shown = expr;
418
+ if ((this.blinkIn -= dt) < 0) { this.blinkFor = want.still ? 0 : 0.13; this.blinkIn = this.rng() < 0.2 ? 0.3 : 2 + this.rng() * 3.5; }
419
+ this.blinkFor = Math.max(0, this.blinkFor - dt);
420
+ p.open = ease(p.open, expr !== this.shown || this.blinkFor > 0 ? 0 : 1, dt, 32);
421
+
422
+ if (want.mark) this.markName = want.mark; if (want.ring) this.ringKind = want.ring;
423
+ this.phase += dt * 2.6 * (want.orbit || 1);
424
+ const goal = {orbit: +(want.orbit > 0), mark: +!!want.mark, stars: +(this.dizzy > 0), ring: +!!want.ring, bars: +want.bars, morph: +this.morphing, emph: +this.emphasized};
425
+ for (const key in goal) this.aura[key] = ease(this.aura[key], goal[key], dt, 7);
426
+ this.particles = this.particles.filter(q => {
427
+ q.age += dt;
428
+ if (q.age >= q.life) { q.node.remove(); return false; }
429
+ if (q.g) q.vy += q.g * dt;
430
+ if (q.drag) { q.vx *= 1 - q.drag * dt; q.vy *= 1 - q.drag * dt; }
431
+ q.x += q.vx * dt; q.y += q.vy * dt;
432
+ return true;
433
+ });
434
+ if (draw) this.render(g);
435
+ }
436
+
437
+ render(g = {yaw: 0, pitch: 0, roll: 0, sy: 0, lift: 0, scale: 0}) {
438
+ if (this.scheme === 'auto' && prefersDark() !== this.dark) { this.retone(); this.build(); }
439
+ const p = this.p, geo = this.geo, P = this.points, tone = this.tone, hue = tone.hue, morph = smooth(clamp(this.aura.morph, 0, 1)), gone = morph > 0.9;
440
+ const sy = clamp(p.sy + g.sy, 0.3, 1.7), sx = 1 + (1 - sy) * 0.3, lift = p.lift + g.lift, S = UNIT * Math.max(0.1, p.scale * (1 + g.scale)) * (1 - morph);
441
+ if (gone !== this.gone) { this.gone = gone; if (gone) this.body.setAttribute('display', 'none'); else this.body.removeAttribute('display'); }
442
+ const ca = Math.cos(p.yaw + g.yaw), sa = Math.sin(p.yaw + g.yaw), cb = Math.cos(p.pitch + g.pitch), sb = Math.sin(p.pitch + g.pitch), cr = Math.cos(p.roll + g.roll), sr = Math.sin(p.roll + g.roll);
443
+ // Yaw, then pitch, then roll.
444
+ const turn = (x, y, z) => { const x1 = x * ca + z * sa, z1 = -x * sa + z * ca, y2 = y * cb - z1 * sb; return [x1 * cr - y2 * sr, x1 * sr + y2 * cr, y * sb + z1 * cb]; };
445
+ const place = v => { const q = turn(v[0] * sx, v[1] * sy + 1 - sy, v[2] * sx), w = S * (1 - q[2] * PERSPECTIVE); return [50 + q[0] * w, CY + lift + q[1] * w, q[2]]; };
446
+
447
+ geo.verts.forEach((v, i) => { const q = place(v); P[i * 3] = q[0]; P[i * 3 + 1] = q[1]; P[i * 3 + 2] = q[2]; });
448
+
449
+ // Faces that point at the viewer, far ones first.
450
+ const seen = [], chroma = (tone.chroma * p.sat).toFixed(3);
451
+ geo.faces.forEach(face => {
452
+ const n = turn(face.n[0], face.n[1], face.n[2]);
453
+ if (n[2] > 0.02) return;
454
+ let depth = 0; for (const m of face.idx) depth += P[m * 3 + 2];
455
+ seen.push({face, order: face.layer * 1000 - depth / face.idx.length, lit: n[0] * LIGHT[0] + n[1] * LIGHT[1] + n[2] * LIGHT[2]});
456
+ });
457
+ seen.sort((a, b) => a.order - b.order);
458
+ seen.forEach(({face, lit}, i) => {
459
+ let d = '';
460
+ for (const m of face.idx) d += (d ? 'L' : 'M') + r1(P[m * 3]) + ',' + r1(P[m * 3 + 1]);
461
+ const shade = `oklch(${(tone.base + tone.span * clamp(lit, -1, 1)).toFixed(3)} ${chroma} ${hue})`, node = this.facePaths[i];
462
+ node.setAttribute('d', d + 'Z'); node.setAttribute('fill', shade); node.setAttribute('stroke', shade);
463
+ if (i >= this.used) node.removeAttribute('display');
464
+ });
465
+ for (let i = seen.length; i < this.used; i++) this.facePaths[i].setAttribute('display', 'none');
466
+ this.used = seen.length;
467
+
468
+ // Eyes, drawn on the surface so they turn with the solid. Small avatars get slightly larger eyes.
469
+ const style = EYE_STYLES[this.eyes], k = this.size <= 28 ? Math.max(geo.k * 1.18, 0.74) : this.size <= 40 ? Math.max(geo.k * 1.08, 0.68) : geo.k, minWidth = 110 / this.size;
470
+ const ink = this.eyeColor || tone.eye || `oklch(0.975 0.03 ${hue})`;
471
+ this.eyeNodes.forEach((node, i) => {
472
+ const side = i ? 1 : -1, ex = side * style.gap + this.gazeAt.x, ey = 0.02 + this.gazeAt.y, blush = this.blushNodes[i];
473
+ const n = geo.nrm(ex * k, ey * k), toward = -turn(n[0], n[1], n[2])[2];
474
+ if (toward < 0.12 || gone) { node.setAttribute('display', 'none'); blush.setAttribute('display', 'none'); return; }
475
+ const shape = eyeShape(this.shown, side, style, p.open), fade = clamp(toward * 1.5, 0.45, 1);
476
+ let d = '';
477
+ for (const line of shape.lines) {
478
+ line.forEach(([x, y], j) => { const q = place(geo.at((ex + x) * k, (ey + y) * k)); d += (j ? 'L' : 'M') + r1(q[0]) + ',' + r1(q[1]); });
479
+ if (shape.fill) d += 'Z';
480
+ }
481
+ node.setAttribute('d', d); node.removeAttribute('display'); node.setAttribute('stroke', ink);
482
+ node.setAttribute('fill', shape.fill ? ink : 'none');
483
+ node.setAttribute('stroke-width', Math.max(shape.fill ? 0 : minWidth, shape.w * S * k * fade).toFixed(2));
484
+ node.setAttribute('opacity', (0.55 + 0.45 * p.sat).toFixed(2));
485
+ if (p.blush < 0.03) { blush.setAttribute('display', 'none'); return; }
486
+ const bx = ex + side * 0.2, by = ey + 0.3, a = place(geo.at((bx - 0.07) * k, by * k)), b = place(geo.at((bx + 0.07) * k, by * k));
487
+ blush.setAttribute('d', `M${r1(a[0])},${r1(a[1])}L${r1(b[0])},${r1(b[1])}`); blush.removeAttribute('display');
488
+ blush.setAttribute('stroke-width', (0.17 * S * k * fade).toFixed(2)); blush.setAttribute('opacity', (0.75 * p.blush * p.sat).toFixed(2));
489
+ });
490
+
491
+ const rise = Math.max(0, -lift);
492
+ this.shadow.setAttribute('rx', Math.max(13 * morph, geo.foot * S * sx * (1 - Math.min(0.5, rise * 0.02))).toFixed(1));
493
+ this.shadow.setAttribute('opacity', ((this.dark ? 0.45 : 0.16) * (1 - Math.min(0.6, rise * 0.03))).toFixed(3));
494
+ this.effects(lift, morph);
495
+ }
496
+
497
+ // Things around the body: circling dots, dizzy stars, a glyph, a ring, sound bars, particles.
498
+ effects(lift, morph = 0) {
499
+ const hue = this.hue, t = this.t, aura = this.aura, cy = CY + lift;
500
+ const accent = `oklch(0.72 ${Math.min(0.16, this.tone.chroma + 0.02)} ${hue})`, bright = `oklch(0.86 0.14 ${hue + 50})`;
501
+ const circling = (key, count, make) => {
502
+ const nodes = (this[key + 'Nodes'] = this[key + 'Nodes'] || []);
503
+ if (aura[key] < 0.02) { for (const node of nodes) node.setAttribute('display', 'none'); return null; }
504
+ while (nodes.length < count) nodes.push(make());
505
+ return nodes;
506
+ };
507
+ circling('orbit', 3, () => el('circle', {}, this.back))?.forEach((node, i) => {
508
+ const a = this.phase + i * TAU / 3, z = Math.sin(a), layer = z < 0 ? this.front : this.back;
509
+ if (node.parentNode !== layer) layer.append(node);
510
+ node.removeAttribute('display'); node.setAttribute('fill', accent);
511
+ node.setAttribute('cx', r1(50 + 1.75 * UNIT * Math.cos(a))); node.setAttribute('cy', r1(cy + UNIT * (-0.1 + 0.45 * z)));
512
+ node.setAttribute('r', Math.max(0, (3.6 - 0.9 * z) * aura.orbit).toFixed(2));
513
+ });
514
+ circling('stars', 3, () => el('path', {d: STAR}, this.front))?.forEach((node, i) => {
515
+ const a = t * 4 + i * TAU / 3, z = Math.sin(a), layer = z < 0 ? this.front : this.back;
516
+ if (node.parentNode !== layer) layer.append(node);
517
+ node.removeAttribute('display'); node.setAttribute('fill', bright);
518
+ node.setAttribute('transform', `translate(${r1(50 + 0.95 * UNIT * Math.cos(a))} ${r1(cy + UNIT * (-1.45 + 0.2 * z))}) scale(${((3.2 - 0.6 * z) * aura.stars).toFixed(2)})`);
519
+ });
520
+ const mark = circling('mark', 1, () => { const group = el('g', {'stroke-linecap': 'round', 'stroke-linejoin': 'round'}, this.front); el('path', {}, group); el('circle', {stroke: 'none'}, group); return group; });
521
+ if (mark) {
522
+ const def = MARKS[this.markName] || MARKS.ask, [group] = mark, path = group.firstChild, dot = group.lastChild, paint = def.paint || accent;
523
+ if (group.botMark !== this.markName) {
524
+ group.botMark = this.markName; path.setAttribute('d', def.d); path.setAttribute('stroke-width', def.wide ? 4.2 : def.fill ? 1.4 : 3.2);
525
+ if (def.dot) { dot.setAttribute('cx', def.dot[0]); dot.setAttribute('cy', def.dot[1]); dot.setAttribute('r', def.dot[2]); dot.removeAttribute('display'); } else dot.setAttribute('display', 'none');
526
+ }
527
+ path.setAttribute('stroke', paint); path.setAttribute('fill', def.fill ? paint : 'none'); dot.setAttribute('fill', paint);
528
+ group.removeAttribute('display');
529
+ group.setAttribute('transform', `translate(${r1(50 + 1.35 * UNIT)} ${r1(cy - 1.25 * UNIT + 1.5 * Math.sin(t * 3))}) rotate(${def.dot && def.d ? 12 : 0}) scale(${((this.size <= 28 ? 1.7 : 1.35) * aura.mark).toFixed(2)})`);
530
+ }
531
+ if (aura.emph < 0.02) this.haloNode.setAttribute('display', 'none');
532
+ else {
533
+ const rx = 31 + 1.5 * Math.sin(t * 3);
534
+ this.haloNode.removeAttribute('display'); this.haloNode.setAttribute('rx', r1(rx)); this.haloNode.setAttribute('ry', r1(rx * 0.24));
535
+ this.haloNode.setAttribute('stroke', accent); this.haloNode.setAttribute('stroke-width', (2.4 * aura.emph).toFixed(2));
536
+ }
537
+ if (morph < 0.02) this.symbolNode.setAttribute('display', 'none');
538
+ else {
539
+ if (SYMBOLS[this.state]) this.symbolName = this.state;
540
+ const def = (SYMBOLS[this.symbolName] || SYMBOLS.loading)(t, this.progress), tone = this.tone, node = this.symbolNode, path = node.firstChild, dots = def.dots || [];
541
+ const paint = `oklch(${tone.base} ${tone.chroma} ${hue})`;
542
+ node.removeAttribute('display'); node.setAttribute('opacity', (def.fade ?? 1).toFixed(2));
543
+ node.setAttribute('transform', `translate(50 ${r1(cy)}) rotate(${r1((1 - morph) * -50)}) scale(${(morph * (def.scale ?? 1) * 1.15).toFixed(3)})`);
544
+ path.setAttribute('d', def.d || ''); path.setAttribute('stroke', paint); path.setAttribute('stroke-width', def.w || 0);
545
+ while (node.childNodes.length - 1 < dots.length) el('circle', {}, node);
546
+ for (let i = 1; i < node.childNodes.length; i++) {
547
+ const dot = dots[i - 1], c = node.childNodes[i];
548
+ if (!dot) { c.setAttribute('display', 'none'); continue; }
549
+ c.removeAttribute('display'); c.setAttribute('fill', paint); c.setAttribute('cx', r1(dot[0])); c.setAttribute('cy', r1(dot[1])); c.setAttribute('r', Math.max(0, dot[2]).toFixed(2));
550
+ }
551
+ }
552
+ if (aura.ring < 0.02) this.ringNode.setAttribute('display', 'none');
553
+ else {
554
+ const around = TAU * RING, steady = this.ringKind === 'progress', part = steady ? clamp(this.progress ?? (this.since * 0.22) % 1, 0, 1) : 0.22;
555
+ this.ringNode.removeAttribute('display'); this.ringNode.setAttribute('cy', r1(cy)); this.ringNode.setAttribute('stroke', accent);
556
+ this.ringNode.setAttribute('stroke-width', (4 * aura.ring).toFixed(2)); this.ringNode.setAttribute('stroke-dasharray', `${r1(Math.max(0.01, part) * around)} ${r1(around)}`);
557
+ this.ringNode.setAttribute('transform', `rotate(${r1(steady ? -90 : t * 320)} 50 ${r1(cy)})`);
558
+ }
559
+ if (aura.bars < 0.02) this.barsNode.setAttribute('display', 'none');
560
+ else {
561
+ let d = '';
562
+ for (let i = 0; i < 4; i++) { const x = r1(50 + 1.42 * UNIT + i * 4.6), tall = 1.5 + 8 * Math.abs(Math.sin(t * 7 + i * 1.3) * Math.cos(t * 2.3 + i)); d += `M${x},${r1(cy - tall)}L${x},${r1(cy + tall)}`; }
563
+ this.barsNode.removeAttribute('display'); this.barsNode.setAttribute('d', d); this.barsNode.setAttribute('stroke', accent); this.barsNode.setAttribute('stroke-width', (2.6 * aura.bars).toFixed(2));
564
+ }
565
+ for (const q of this.particles) {
566
+ const u = q.age / q.life, x = r1(50 + q.x * UNIT), y = r1(CY + q.y * UNIT), node = q.node;
567
+ if (q.type === 'ring') {
568
+ node.removeAttribute('transform'); node.setAttribute('rx', r1(8 + 30 * u)); node.setAttribute('ry', r1((8 + 30 * u) * 0.22));
569
+ node.setAttribute('stroke', accent); node.setAttribute('stroke-width', (1.8 * (1 - u)).toFixed(2)); node.setAttribute('opacity', (1 - u).toFixed(2));
570
+ } else if (q.stroked) {
571
+ node.setAttribute('stroke', accent); node.setAttribute('opacity', bump(u).toFixed(2));
572
+ node.setAttribute('transform', `translate(${x} ${y}) rotate(${q.turn}) scale(${(q.size * (1 - q.grow * 0.4 + q.grow * u)).toFixed(2)})`);
573
+ } else {
574
+ node.setAttribute('fill', q.paint || (q.bright ? bright : accent));
575
+ node.setAttribute('transform', `translate(${x} ${y}) rotate(${r1(q.turn + q.spin * q.age)}) scale(${(q.size * Math.sqrt(bump(u))).toFixed(2)})`);
576
+ }
577
+ }
578
+ }
579
+ }
@@ -0,0 +1,56 @@
1
+ // The face is two eyes, drawn as strokes on the surface of the solid.
2
+ //
3
+ // An expression is a function (side, style) -> {lines, w, fill, shut}. `side`
4
+ // is -1 for the left eye and 1 for the right. `lines` are polylines in eye
5
+ // units, centred on the eye, y down. `w` is the stroke width. `fill` closes and
6
+ // fills the shape. `shut` marks an expression that is already a closed eye, so
7
+ // blinking leaves it alone.
8
+
9
+ const TAU = Math.PI * 2;
10
+
11
+ /** The neutral eye a Bot is born with. `gap` is half the distance between eyes. */
12
+ export const EYE_STYLES = {
13
+ bar: {h: 0.2, w: 0.3, gap: 0.4},
14
+ dot: {h: 0.03, w: 0.42, gap: 0.42},
15
+ tall: {h: 0.27, w: 0.2, gap: 0.34},
16
+ };
17
+
18
+ const loop = (n, fn) => Array.from({length: n + 1}, (_, i) => fn(i / n * TAU));
19
+ const mirror = (side, pts) => pts.map(([x, y]) => [-side * x, y]);
20
+ const LID = [[-0.15, 0.06], [0.15, 0.06]];
21
+ const bar = (st, tall = 1, wide = 1) => ({lines: [[[0, -st.h * tall], [0, st.h * tall]]], w: st.w * wide});
22
+
23
+ export const EXPRESSIONS = {
24
+ neutral: (side, st) => bar(st),
25
+ wide: (side, st) => bar(st, st.h < 0.1 ? 1 : 1.35, 1.12),
26
+ happy: () => ({lines: [[[-0.17, 0.1], [0, -0.12], [0.17, 0.1]]], w: 0.2}),
27
+ closed: () => ({lines: [LID], w: 0.2, shut: true}),
28
+ sleep: () => ({lines: [[[-0.16, 0], [-0.06, 0.09], [0.06, 0.09], [0.16, 0]]], w: 0.17, shut: true}),
29
+ squint: side => ({lines: [mirror(side, [[-0.13, -0.14], [0.1, 0], [-0.13, 0.14]])], w: 0.18}),
30
+ sad: side => ({lines: [mirror(side, [[-0.1, 0.16], [0.08, -0.14]])], w: 0.26}),
31
+ focus: side => ({lines: [mirror(side, [[-0.11, -0.13], [0.09, 0.13]])], w: 0.28}),
32
+ angry: side => ({lines: [mirror(side, [[-0.14, -0.17], [0.11, -0.02]]), [[0, 0.05], [0, 0.19]]], w: 0.19}),
33
+ calm: () => ({lines: [[[-0.15, -0.02], [-0.07, 0.07], [0.07, 0.07], [0.15, -0.02]]], w: 0.18}),
34
+ sleepy: (side, st) => ({lines: [[[-0.15, -0.04], [0.15, -0.04]], [[0, 0.03], [0, 0.1 + st.h * 0.6]]], w: 0.16}),
35
+ shy: (side, st) => bar(st, st.h < 0.1 ? 1 : 0.55, 0.9),
36
+ inspecting: (side, st) => (side < 0 ? bar(st, 1.45, 1.15) : {lines: [[[-0.13, 0.03], [0.13, 0.03]]], w: 0.2}),
37
+ confused: (side, st) => (side < 0 ? bar(st, 1.2) : {lines: [loop(12, a => [0.09 * Math.cos(a), 0.09 * Math.sin(a)])], w: 0.11}),
38
+ wink: (side, st) => (side > 0 ? EXPRESSIONS.happy() : bar(st)),
39
+ skeptic: (side, st) => (side > 0 ? {lines: [[[-0.14, -0.02], [0.14, -0.08]]], w: 0.2} : bar(st)),
40
+ cross: () => ({lines: [[[-0.13, -0.13], [0.13, 0.13]], [[0.13, -0.13], [-0.13, 0.13]]], w: 0.15}),
41
+ surprised: () => ({lines: [loop(14, a => [0.15 * Math.cos(a), 0.17 * Math.sin(a)])], w: 0.12}),
42
+ dizzy: side => ({lines: [Array.from({length: 19}, (_, i) => { const a = i * 0.62 * side, r = 0.012 * i; return [r * Math.cos(a), r * Math.sin(a)]; })], w: 0.09}),
43
+ love: () => ({lines: [loop(18, a => [0.014 * 16 * Math.sin(a) ** 3, -0.014 * (13 * Math.cos(a) - 5 * Math.cos(2 * a) - 2 * Math.cos(3 * a) - Math.cos(4 * a)) - 0.02])], w: 0.06, fill: true}),
44
+ sparkle: () => ({lines: [loop(8, a => { const r = Math.round(a / TAU * 8) % 2 ? 0.07 : 0.26; return [r * Math.sin(a), -r * Math.cos(a)]; })], w: 0.05, fill: true}),
45
+ };
46
+
47
+ /**
48
+ * Points of one eye for an expression, with `open` (0..1) applied. Below a
49
+ * quarter open, any expression collapses to a closed lid.
50
+ */
51
+ export function eyeShape(name, side, style, open) {
52
+ const shape = (EXPRESSIONS[name] || EXPRESSIONS.neutral)(side, style);
53
+ if (shape.shut) return shape;
54
+ if (open < 0.25) return {lines: [LID], w: 0.2};
55
+ return {...shape, lines: shape.lines.map(line => line.map(([x, y]) => [x, y * Math.min(open, 1.4)]))};
56
+ }