Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(mascot): Fluffy avatars from Open Bot Avatar 0.4.0
aivsomkar93348be497b5
diff --git a/electron/places-together.d.mts b/electron/places-together.d.mtsindex 962e2e95d0..6f941bf31a 100644--- a/electron/places-together.d.mts+++ b/electron/places-together.d.mts@@ -16,6 +16,7 @@ export interface PlaceBotRow {mascotBody?: string;mascotFaceColor?: string;mascotBodyColor?: string;+ mascotMaterial?: string;chief?: true;waiting?: true;working?: true;diff --git a/electron/places-together.mjs b/electron/places-together.mjsindex b0c79ba8be..f6b9675b93 100644--- a/electron/places-together.mjs+++ b/electron/places-together.mjs@@ -54,9 +54,9 @@ export function botRow(bot, home) {if (!record(bot) || !ID.test(String(bot.id)) || !ID.test(String(bot.threadId)) || bot.hidden || bot.sidebarHidden || bot.movedTo) return null;const name = text(bot.name, 80);if (!name) return null;- const title = text(bot.title, 80), color = look(bot.color), body = look(bot.mascotBody), face = look(bot.mascotFaceColor), tint = look(bot.mascotBodyColor);+ const title = text(bot.title, 80), color = look(bot.color), body = look(bot.mascotBody), face = look(bot.mascotFaceColor), tint = look(bot.mascotBodyColor), fur = look(bot.mascotMaterial);return { home, id: bot.id, threadId: bot.threadId, name, ...(title ? { title } : {}), ...(color ? { color } : {}),- ...(body ? { mascotBody: body } : {}), ...(face ? { mascotFaceColor: face } : {}), ...(tint ? { mascotBodyColor: tint } : {}), ...(bot.chiefOfStaff === true ? { chief: true } : {}), ...rowState(bot) };+ ...(body ? { mascotBody: body } : {}), ...(face ? { mascotFaceColor: face } : {}), ...(tint ? { mascotBodyColor: tint } : {}), ...(fur ? { mascotMaterial: fur } : {}), ...(bot.chiefOfStaff === true ? { chief: true } : {}), ...rowState(bot) };}/** The AIs a place's `GET /api/instances` answer says are ready to use: installed and signed in, never one that onlydiff --git a/packages/phone-protocol/src/bot-avatar.ts b/packages/phone-protocol/src/bot-avatar.tsindex adcb38e400..72ad56f520 100644--- a/packages/phone-protocol/src/bot-avatar.ts+++ b/packages/phone-protocol/src/bot-avatar.ts@@ -4,6 +4,11 @@ export const MASCOT_FACE_COLORS = ["white", "black"] as const;export const mascotFaceColorSchema = z.enum(MASCOT_FACE_COLORS);export type MascotFaceColor = z.infer<typeof mascotFaceColorSchema>;+/** The finish of an engine-drawn avatar body (the shapes and Open Bot Avatar objects): Open Bot Avatar's fluffy fur; absent or null is flat. */+export const MASCOT_MATERIALS = ["fluffy"] as const;+export const mascotMaterialSchema = z.enum(MASCOT_MATERIALS);+export type MascotMaterial = z.infer<typeof mascotMaterialSchema>;+/** A custom avatar body tint, stored as lowercase `#rrggbb`. */export const mascotBodyColorSchema = z.string()diff --git a/packages/phone-protocol/src/open-bot-avatar/README.md b/packages/phone-protocol/src/open-bot-avatar/README.mdindex 146c3ba320..a78d053754 100644--- a/packages/phone-protocol/src/open-bot-avatar/README.md+++ b/packages/phone-protocol/src/open-bot-avatar/README.md@@ -1,8 +1,8 @@# open-bot-avatarVendored sources of [Open Bot Avatar](https://github.com/DominikScholz/open-bot-avatar)-(MIT, see `LICENSE`) at commit `5e64c081971eb296f562544641bad37d40fb36b6`, which npm publishes as-`open-bot-avatar` 0.3.0:+(MIT, see `LICENSE`) at commit `323ce6ab8bc6b0bc9603a418ee3d91442e4996fc`, which npm publishes as+`open-bot-avatar` 0.4.0:- `*.ts` ← `packages/core/src/*.ts`, the engine: validation, volume, motion and SVG rendering, with no DOM.Upstream's `index.ts` (a re-export barrel) and `seams.ts` (nothing imports it) are left out; import each@@ -12,11 +12,13 @@ Vendored sources of [Open Bot Avatar](https://github.com/DominikScholz/open-bot-## Our changes-`render.ts` carries our only code changes, each marked `MausBot:`:+`render.ts` and `dom/paint.ts` carry our only code changes, each marked `MausBot:`:- A smile under the eyes (`mouthMark`), drawn with the eyes in the canvas and SVG renderers. The CSS-3D`renderAvatarScene` path has no mouth; `mountAvatar` only falls back to it where canvas is missing(never in the desktop app).+- With the fluffy material the coat seats only the two eyes, so `dom/paint.ts` paints the mouth flat on top+ of it.- The ribbons of `working` and `done` take our six rainbow comet palettes (`COMET_COLORS`) instead ofshades of the body colour.diff --git a/packages/phone-protocol/src/open-bot-avatar/contour.ts b/packages/phone-protocol/src/open-bot-avatar/contour.tsindex 22582bf650..7af7881c70 100644--- a/packages/phone-protocol/src/open-bot-avatar/contour.ts+++ b/packages/phone-protocol/src/open-bot-avatar/contour.ts@@ -15,114 +15,265 @@ export interface Field {step: number;}-/** Closed loops where the field crosses `level` (inside = value ≥ level). */-export function contourLoops(field: Field, level: number): Point[][] {+/** Cells per run of a row that a caller of contourLoops can rule out at once (see `runsOf`). */+export const RUN = 8;++/** Runs in a row of cells of a field `nx` samples wide. */+export const runsOf = (nx: number) => Math.ceil((nx - 1) / RUN);++/**+ * Smallest and largest sample around each run of cells: over both rows of samples the run's cells+ * touch. A run whose values all lie on one side of a level has no crossing at that level.+ */+export function runRange(values: Float64Array, nx: number, ny: number): { min: Float64Array; max: Float64Array } {+ const runs = runsOf(nx);+ const lo = new Float64Array(runs * ny), hi = new Float64Array(runs * ny);+ for (let j = 0; j < ny; j++) {+ for (let r = 0; r < runs; r++) {+ let a = Infinity, b = -Infinity;+ for (let k = j * nx + r * RUN, end = j * nx + Math.min(nx - 1, (r + 1) * RUN); k <= end; k++) {+ const v = values[k];+ if (v < a) a = v;+ if (v > b) b = v;+ }+ lo[j * runs + r] = a; hi[j * runs + r] = b;+ }+ }+ const min = new Float64Array(runs * Math.max(0, ny - 1)), max = new Float64Array(min.length);+ for (let k = 0; k < min.length; k++) {+ min[k] = Math.min(lo[k], lo[k + runs]);+ max[k] = Math.max(hi[k], hi[k + runs]);+ }+ return { min, max };+}++// Scratch for tracing, kept between calls: per cell edge its two links (-1: none) and whether a+// loop has passed it. Every call leaves them as it found them.+let linkA = new Int32Array(0), linkB = new Int32Array(0);+let passed = new Uint8Array(0);+let order = new Int32Array(256);+// The traced loops' points, x and y in turn, one loop after another, and where each loop ends.+let traced = new Float64Array(1024);+let ends = new Int32Array(16);++/**+ * Traces the loops where the field crosses `level` into `traced` and `ends`; returns how many.+ * A loop here may have fewer than three points.+ */+function trace(field: Field, level: number, flat: Uint8Array | undefined): number {const { values, nx, ny, x0, y0, step } = field;- const at = (i: number, j: number) => values[j * nx + i] - level;// Edge keys: horizontal edge (i,j)-(i+1,j) = 2*(j*nx+i), vertical (i,j)-(i,j+1) = 2*(j*nx+i)+1.- const points = new Map<number, Point>();- const links = new Map<number, number[]>();- const point = (key: number): void => {- if (points.has(key)) return;- const idx = key >> 1, i = idx % nx, j = (idx - i) / nx;- const a = at(i, j);- if (key & 1) {- const b = at(i, j + 1), t = a / (a - b);- points.set(key, [x0 + i * step, y0 + (j + t) * step]);- } else {- const b = at(i + 1, j), t = a / (a - b);- points.set(key, [x0 + (i + t) * step, y0 + j * step]);- }- };- const link = (p: number, q: number) => {- point(p); point(q);- (links.get(p) ?? links.set(p, []).get(p)!).push(q);- (links.get(q) ?? links.set(q, []).get(q)!).push(p);+ if (linkA.length < 2 * nx * ny) {+ linkA = new Int32Array(2 * nx * ny).fill(-1);+ linkB = new Int32Array(2 * nx * ny).fill(-1);+ passed = new Uint8Array(2 * nx * ny);+ }+ const a = linkA, b = linkB;+ // Linked edges in the order they were first linked; each has at most two links, one per cell.+ let count = 0;+ const join = (p: number, q: number) => {+ if (a[p] < 0) {+ if (count === order.length) { const grown = new Int32Array(2 * count); grown.set(order); order = grown; }+ order[count++] = p;+ a[p] = q;+ } else b[p] = q;};+ const link = (p: number, q: number) => { join(p, q); join(q, p); };+ const runs = runsOf(nx);for (let j = 0; j < ny - 1; j++) {- for (let i = 0; i < nx - 1; i++) {- const tl = at(i, j) >= 0, tr = at(i + 1, j) >= 0, br = at(i + 1, j + 1) >= 0, bl = at(i, j + 1) >= 0;- const code = (tl ? 8 : 0) | (tr ? 4 : 0) | (br ? 2 : 0) | (bl ? 1 : 0);- if (code === 0 || code === 15) continue;- const top = 2 * (j * nx + i), bottom = 2 * ((j + 1) * nx + i);- const left = 2 * (j * nx + i) + 1, right = 2 * (j * nx + i + 1) + 1;- if (code === 10 || code === 5) {- const center = (at(i, j) + at(i + 1, j) + at(i + 1, j + 1) + at(i, j + 1)) / 4 >= 0;- // Diagonal corners: the center decides whether they connect through the cell.- if ((code === 10) === center) { link(top, right); link(bottom, left); }- else { link(left, top); link(right, bottom); }- continue;+ const row = j * nx;+ for (let r = 0; r < runs; r++) {+ if (flat && flat[j * runs + r]) continue;+ let i = r * RUN;+ const end = Math.min(nx - 1, i + RUN);+ let tl = values[row + i] - level >= 0, bl = values[row + nx + i] - level >= 0;+ for (; i < end; i++) {+ const tr = values[row + i + 1] - level >= 0, br = values[row + nx + i + 1] - level >= 0;+ if (tl !== tr || tr !== br || br !== bl) {+ const top = 2 * (row + i), bottom = 2 * (row + nx + i), left = top + 1, right = top + 3;+ if (tl === br && tr === bl) {+ const center = ((values[row + i] - level) + (values[row + i + 1] - level) + (values[row + nx + i + 1] - level) + (values[row + nx + i] - level)) / 4 >= 0;+ // Diagonal corners: the center decides whether they connect through the cell.+ if (tl === center) { link(top, right); link(bottom, left); }+ else { link(left, top); link(right, bottom); }+ } else if (tl !== tr) link(top, tr !== br ? right : br !== bl ? bottom : left);+ else if (tr !== br) link(right, br !== bl ? bottom : left);+ else link(bottom, left);+ }+ tl = tr; bl = br;}- const crossed: number[] = [];- if (tl !== tr) crossed.push(top);- if (tr !== br) crossed.push(right);- if (br !== bl) crossed.push(bottom);- if (bl !== tl) crossed.push(left);- link(crossed[0], crossed[1]);}}- const loops: Point[][] = [];- const seen = new Set<number>();- for (const start of links.keys()) {- if (seen.has(start)) continue;- const loop: Point[] = [];- let prev = -1, cur = start;- while (!seen.has(cur)) {- seen.add(cur);- loop.push(points.get(cur)!);- const next = links.get(cur)!.find((n) => n !== prev && !seen.has(n));- if (next === undefined) break;+ // Every linked edge is passed once, so its crossing is one point of one loop.+ if (traced.length < 2 * count) traced = new Float64Array(4 * count);+ const xy = traced;+ let n = 0, loops = 0;+ for (let k = 0; k < count; k++) {+ if (passed[order[k]]) continue;+ let prev = -1, cur = order[k];+ while (!passed[cur]) {+ passed[cur] = 1;+ const idx = cur >> 1, i = idx % nx, j = (idx - i) / nx;+ const v = values[idx] - level;+ if (cur & 1) {+ const t = v / (v - (values[idx + nx] - level));+ xy[n++] = x0 + i * step; xy[n++] = y0 + (j + t) * step;+ } else {+ const t = v / (v - (values[idx + 1] - level));+ xy[n++] = x0 + (i + t) * step; xy[n++] = y0 + j * step;+ }+ // The first link that does not lead back.+ let next = a[cur];+ if (next === prev || passed[next]) {+ next = b[cur];+ if (next < 0 || next === prev || passed[next]) break;+ }prev = cur; cur = next;}- if (loop.length >= 3) loops.push(loop);+ if (loops === ends.length) { const grown = new Int32Array(2 * loops); grown.set(ends); ends = grown; }+ ends[loops++] = n;}+ for (let k = 0; k < count; k++) { a[order[k]] = b[order[k]] = -1; passed[order[k]] = 0; }return loops;}-function perpendicular(p: Point, a: Point, b: Point): number {- const dx = b[0] - a[0], dy = b[1] - a[1];- const len = Math.hypot(dx, dy);- if (len === 0) return Math.hypot(p[0] - a[0], p[1] - a[1]);- return Math.abs(dx * (a[1] - p[1]) - dy * (a[0] - p[0])) / len;+/** Points of `xy` (x and y in turn) from `start` to `end` as a loop; with `keep`, only the marked ones. */+function pointsOf(xy: Float64Array, start: number, end: number, keep?: Uint8Array): Point[] {+ const loop: Point[] = [];+ for (let k = start; k < end; k += 2) if (!keep || keep[(k - start) >> 1]) loop.push([xy[k], xy[k + 1]]);+ return loop;}-/** Ramer-Douglas-Peucker on a closed loop. */-export function simplifyLoop(loop: Point[], tolerance: number): Point[] {- if (loop.length <= 8) return loop;- // Split at the point farthest from the first so the closed loop becomes two open chains.- let far = 0, best = -1;- for (let k = 1; k < loop.length; k++) {- const d = Math.hypot(loop[k][0] - loop[0][0], loop[k][1] - loop[0][1]);- if (d > best) { best = d; far = k; }+/**+ * Closed loops where the field crosses `level` (inside = value ≥ level). `flat` marks runs of+ * cells (RUN per row, row-major) that are known not to cross it; their samples are not read.+ */+export function contourLoops(field: Field, level: number, flat?: Uint8Array): Point[][] {+ const loops: Point[][] = [];+ for (let k = 0, n = trace(field, level, flat), start = 0; k < n; start = ends[k++]) {+ if (ends[k] - start >= 6) loops.push(pointsOf(traced, start, ends[k]));+ }+ return loops;+}++/** The loops of contourLoops, each simplified as by simplifyLoop, without those left with under three points. */+export function contourOutlines(field: Field, level: number, tolerance: number, flat?: Uint8Array): Point[][] {+ const loops: Point[][] = [];+ for (let k = 0, n = trace(field, level, flat), start = 0; k < n; start = ends[k++]) {+ const points = (ends[k] - start) >> 1;+ if (points < 3) continue;+ if (points <= 8) { loops.push(pointsOf(traced, start, ends[k])); continue; }+ const keep = simplify(traced, start, points, tolerance);+ let kept = 0;+ for (let q = 0; q < points; q++) kept += keep[q];+ if (kept >= 3) loops.push(pointsOf(traced, start, ends[k], keep));+ }+ return loops;+}++/**+ * A comparison that plain products decide by more than this, relative, comes out the same through+ * Math.hypot or Math.atan2: both are accurate to many orders below it. Closer calls are left to+ * the function itself, so the decision is always the one it would have made. (Math.hypot is slow+ * and allocates, and nearly every call to it and to Math.atan2 here only feeds a comparison.)+ */+const CLEAR = 1e-9;++// Scratch for simplify: which points stay, and the chains still to split.+let kept = new Uint8Array(256);+let chains = new Int32Array(64);++/**+ * Ramer-Douglas-Peucker on a closed loop of `n` points at xy[start] (x and y in turn). Returns+ * which points stay, as flags that are valid until the next call.+ */+function simplify(xy: Float64Array, start: number, n: number, tolerance: number): Uint8Array {+ if (kept.length < n) kept = new Uint8Array(2 * n);+ const keep = kept.fill(0, 0, n);+ // Split at the point farthest from the first so the closed loop becomes two open chains: the+ // first point with the largest Math.hypot. A single clear winner by squares is that point.+ const x0 = xy[start], y0 = xy[start + 1];+ let far = 0, top = -1, next = -1;+ for (let k = 1; k < n; k++) {+ const dx = xy[start + 2 * k] - x0, dy = xy[start + 2 * k + 1] - y0, d = dx * dx + dy * dy;+ if (d > top) { next = top; top = d; far = k; } else if (d > next) next = d;+ }+ if (next >= top * (1 - CLEAR)) {+ let best = -1;+ far = 0;+ for (let k = 1; k < n; k++) {+ const d = Math.hypot(xy[start + 2 * k] - x0, xy[start + 2 * k + 1] - y0);+ if (d > best) { best = d; far = k; }+ }}- const keep = new Uint8Array(loop.length);keep[0] = keep[far] = 1;- const stack: [number, number][] = [[0, far], [far, loop.length]];- while (stack.length) {- const [s, e] = stack.pop()!;- const end = loop[e % loop.length];- let idx = -1, max = tolerance;+ let open = 0;+ chains[open++] = 0; chains[open++] = far; chains[open++] = far; chains[open++] = n;+ while (open) {+ const e = chains[--open], s = chains[--open];+ // The first point between s and e that is farthest from the line through them (from s, if+ // they coincide), if that is over the tolerance. Each distance is a cross product over the+ // line's length (Math.hypot), so the largest product names the point, if it is clear of the+ // next largest and of the tolerance.+ const ax = xy[start + 2 * s], ay = xy[start + 2 * s + 1];+ const dx = xy[start + 2 * (e % n)] - ax, dy = xy[start + 2 * (e % n) + 1] - ay;+ let idx = -1, lead = -1, second = -1;for (let k = s + 1; k < e; k++) {- const d = perpendicular(loop[k], loop[s], end);- if (d > max) { max = d; idx = k; }+ const d = Math.abs(dx * (ay - xy[start + 2 * k + 1]) - dy * (ax - xy[start + 2 * k]));+ if (d > lead) { second = lead; lead = d; idx = k; } else if (d > second) second = d;+ }+ const bar = tolerance * Math.sqrt(dx * dx + dy * dy);+ if (lead <= bar * (1 - CLEAR) && bar > 0) idx = -1;+ else if (!(lead > bar * (1 + CLEAR) && second < lead * (1 - CLEAR))) {+ const len = Math.hypot(dx, dy);+ let max = tolerance;+ idx = -1;+ for (let k = s + 1; k < e; k++) {+ const px = xy[start + 2 * k], py = xy[start + 2 * k + 1];+ const d = len === 0 ? Math.hypot(px - ax, py - ay) : Math.abs(dx * (ay - py) - dy * (ax - px)) / len;+ if (d > max) { max = d; idx = k; }+ }+ }+ if (idx >= 0) {+ keep[idx] = 1;+ if (open + 4 > chains.length) { const grown = new Int32Array(2 * chains.length); grown.set(chains); chains = grown; }+ chains[open++] = s; chains[open++] = idx; chains[open++] = idx; chains[open++] = e;}- if (idx >= 0) { keep[idx] = 1; stack.push([s, idx], [idx, e]); }}+ return keep;+}++/** Ramer-Douglas-Peucker on a closed loop. */+export function simplifyLoop(loop: Point[], tolerance: number): Point[] {+ if (loop.length <= 8) return loop;+ const xy = new Float64Array(2 * loop.length);+ for (let k = 0; k < loop.length; k++) { xy[2 * k] = loop[k][0]; xy[2 * k + 1] = loop[k][1]; }+ const keep = simplify(xy, 0, loop.length, tolerance);return loop.filter((_, k) => keep[k]);}+/** simplifyLoop for a loop given as `n` points in `xy`, x and y in turn. */+export function simplifiedLoop(xy: Float64Array, n: number, tolerance: number): Point[] {+ return n <= 8 ? pointsOf(xy, 0, 2 * n) : pointsOf(xy, 0, 2 * n, simplify(xy, 0, n, tolerance));+}+/** Path numbers are hundredths; vertices snap to even ones so edge midpoints land exactly on the grid. */const UNIT = 100;/** A grid value as a path number, as short as SVG allows: no leading zero, no `-0`. */-const num = (k: number) => {+const write = (k: number) => {const a = Math.abs(k), whole = Math.floor(a / UNIT), frac = a % UNIT;const f = frac === 0 ? '' : frac % 10 === 0 ? `.${frac / 10}` : frac < 10 ? `.0${frac}` : `.${frac}`;return (k < 0 ? '-' : '') + (whole || !f ? whole : '') + f;};+/** Path numbers are mostly small steps: the written form of each whole value within NEAR of 0 is kept. */+const NEAR = 4096;+const written: (string | undefined)[] = new Array(2 * NEAR + 1);+const num = (k: number) => (Number.isInteger(k) && k >= -NEAR && k <= NEAR ? (written[k + NEAR] ??= write(k)) : write(k));+/** Turns sharper than this (radians) stay corners; gentler ones are drawn as curves. */const CORNER = 0.6;@@ -131,6 +282,11 @@ const CORNER = 0.6;* it stays sharp once its curve would leave the traced loop by more than this (viewBox units).*/const SAG = 0.1;+const TAN_CORNER = Math.tan(CORNER);++// Scratch for loopsToPath, kept between calls.+let snapped = new Float64Array(512);+let corners = new Uint8Array(256);/*** Compact closed path from loops (draw with fill-rule evenodd). Traced loops are polylines, so@@ -140,10 +296,11 @@ const SAG = 0.1;*/export function loopsToPath(loops: Point[][]): string {let d = '', cmd = '', last = '';- const emit = (c: string, ...ks: number[]) => {+ /** One command with a pair of numbers; a repeat of the last command goes without its letter. */+ const emit = (c: string, x: number, y: number) => {if (c !== cmd) { d += c; cmd = c; last = ''; }- for (const k of ks) {- const t = num(k);+ for (let k = 0; k < 2; k++) {+ const t = num(k ? y : x);// A separator is only needed where the next number could be read as part of the last one.if (last && t[0] !== '-' && !(t[0] === '.' && last.includes('.'))) d += ' ';d += t;@@ -152,36 +309,46 @@ export function loopsToPath(loops: Point[][]): string {};for (const loop of loops) {const n = loop.length;- const v = loop.map(([x, y]) => [2 * Math.round(x * UNIT / 2), 2 * Math.round(y * UNIT / 2)]);- const corner = loop.map((p, k) => {- const a = loop[(k + n - 1) % n], b = loop[(k + 1) % n];+ if (snapped.length < 2 * n) { snapped = new Float64Array(4 * n); corners = new Uint8Array(2 * n); }+ // Vertices on the path grid (x and y in turn), and which of them are corners.+ const v = snapped, corner = corners;+ for (let k = 0; k < n; k++) {+ const p = loop[k], a = loop[(k + n - 1) % n], b = loop[(k + 1) % n];+ v[2 * k] = 2 * Math.round(p[0] * UNIT / 2); v[2 * k + 1] = 2 * Math.round(p[1] * UNIT / 2);const cross = (p[0] - a[0]) * (b[1] - p[1]) - (p[1] - a[1]) * (b[0] - p[0]);+ const dot = (p[0] - a[0]) * (b[0] - p[0]) + (p[1] - a[1]) * (b[1] - p[1]);+ // Both tests below are decided from products where they are clear, and exactly as written otherwise.+ const turn = Math.abs(cross), steep = dot * TAN_CORNER;+ if (dot > 0 ? turn > steep * (1 + CLEAR) || (turn >= steep * (1 - CLEAR) && Math.abs(Math.atan2(cross, dot)) > CORNER) : Math.abs(Math.atan2(cross, dot)) > CORNER) {+ corner[k] = 1;+ continue;+ }// The curve passes a quarter of p's height over the chord a-b away from p.- return Math.abs(Math.atan2(cross, (p[0] - a[0]) * (b[0] - p[0]) + (p[1] - a[1]) * (b[1] - p[1]))) > CORNER- || Math.abs(cross) > 4 * SAG * Math.hypot(b[0] - a[0], b[1] - a[1]);- });- const mid = (k: number) => [(v[k % n][0] + v[(k + 1) % n][0]) / 2, (v[k % n][1] + v[(k + 1) % n][1]) / 2];- let [cx, cy] = mid(0);+ const chord = (4 * SAG) ** 2 * ((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2);+ corner[k] = turn * turn > chord * (1 + CLEAR) || (turn * turn >= chord * (1 - CLEAR) && turn > 4 * SAG * Math.hypot(b[0] - a[0], b[1] - a[1])) ? 1 : 0;+ }+ // The path runs between the midpoints of the edges: from vertex k to the next one, (v[k] + v[k + 1]) / 2.+ let cx = (v[0] + v[2 * (1 % n)]) / 2, cy = (v[1] + v[2 * (1 % n) + 1]) / 2;emit('M', cx, cy);let smooth = false;for (let k = 1; k <= n; k++) {- const [px, py] = v[k % n];+ const at = 2 * (k % n), after = 2 * ((k + 1) % n);+ const px = v[at], py = v[at + 1];+ const mx = (px + v[after]) / 2, my = (py + v[after + 1]) / 2;if (corner[k % n]) {// A midpoint between two corners lies on their straight edge, so it is only kept to start a curve.emit('l', px - cx, py - cy);cx = px; cy = py;if (k < n && !corner[(k + 1) % n]) {- const [mx, my] = mid(k);emit('l', mx - cx, my - cy);cx = mx; cy = my;}smooth = false;} else {- const [mx, my] = mid(k);// After a curve, the reflected control point is exactly this vertex (it mirrors the last one// across their shared midpoint), so t needs only the end point.if (smooth) emit('t', mx - cx, my - cy);- else emit('q', px - cx, py - cy, mx - cx, my - cy);+ else { emit('q', px - cx, py - cy); emit('q', mx - cx, my - cy); }cx = mx; cy = my;smooth = true;}diff --git a/packages/phone-protocol/src/open-bot-avatar/distance.ts b/packages/phone-protocol/src/open-bot-avatar/distance.tsnew file mode 100644index 0000000000..6ab06a4999--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/distance.ts@@ -0,0 +1,352 @@+/**+ * Distance from points to the nearest edge of a set of polygons.+ *+ * Every answer here is the smallest value of one expression (the squared distance to a segment,+ * `segDist2`) over all edges, then its square root. A minimum does not depend on the order or the+ * number of values it is taken over, as long as the smallest one is among them. So the index may+ * skip any edge it can prove is farther than the nearest, and still return the same bits a pass+ * over every edge would. All the proofs below keep a margin (SLACK) far wider than rounding error+ * and far narrower than anything it could cost.+ */+import type { Bounds, Point } from './path.ts';+import type { EdgeBands } from './path.ts';++/** Margin on every bound that lets an edge be skipped, viewBox units. */+const SLACK = 1e-6;+/** Side of a bucket of the coarse edge grid, viewBox units. */+const CELL = 4;+/** Side, in samples, of the tiles a sample grid is cut into before each is halved down to samples. */+const TILE = 16;++export function segDist2(px: number, py: number, ax: number, ay: number, bx: number, by: number): number {+ const dx = bx - ax, dy = by - ay;+ const len = dx * dx + dy * dy;+ let t = len > 0 ? ((px - ax) * dx + (py - ay) * dy) / len : 0;+ t = t < 0 ? 0 : t > 1 ? 1 : t;+ const ex = ax + t * dx - px, ey = ay + t * dy - py;+ return ex * ex + ey * ey;+}++// Scratch for walking a grid, shared by every index and kept between walks.+/** Per edge: the last `collect` that listed it, so an edge in several buckets is listed once. */+let stamp = new Int32Array(0);+let tags = 0;+/** Candidate lists of the tile in hand, one after another (see `narrow`). */+let lists = new Int32Array(0);+/** Per candidate of the last `survey`: squared distance from its point and the vector to the nearest point. */+let d2 = new Float64Array(0), vx = new Float64Array(0), vy = new Float64Array(0);++/** A regular grid of sample points: x0 + i * step, y0 + j * step. */+export interface SampleGrid { x0: number; y0: number; step: number; nx: number; ny: number }++/**+ * Edges bucketed on a coarse grid, for nearest-edge queries that only visit edges that can matter.+ * The grid is dense and CELL units to a bucket: made for outlines in the 0..100 viewBox.+ */+export class EdgeIndex {+ /** ax, ay, dx, dy, dx² + dy² per edge: the terms of segDist2 that do not depend on the point. */+ private readonly e: Float64Array;+ private readonly start: Int32Array;+ private readonly items: Int32Array;+ private readonly ox: number;+ private readonly oy: number;+ private readonly span: number;+ private readonly count: number;+ /** The last survey's vector to the nearest point of all. */+ private bx = 0;+ private by = 0;+ // The grid being walked.+ private x0 = 0;+ private y0 = 0;+ private step = 0;+ private nx = 0;++ constructor(polys: Point[][], b: Bounds) {+ let count = 0;+ for (const poly of polys) count += poly.length;+ this.count = count;+ const e = this.e = new Float64Array(5 * count);+ this.ox = b.minX - 4; this.oy = b.minY - 4;+ const span = this.span = Math.ceil((Math.max(b.maxX - b.minX, b.maxY - b.minY) + 8) / CELL) + 1;+ // Counting sort of the edges into every bucket they pass through: count, then place.+ const start = this.start = new Int32Array(span * span + 1);+ let items = this.items = new Int32Array(0), next = start;+ for (const place of [false, true]) {+ if (place) {+ for (let q = 0; q < span * span; q++) start[q + 1] += start[q];+ items = this.items = new Int32Array(start[span * span]);+ next = start.slice(0, span * span);+ }+ let k = 0;+ for (const poly of polys) {+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++, k += 5) {+ const ax = poly[j][0], ay = poly[j][1], bx = poly[i][0], by = poly[i][1];+ const dx = bx - ax, dy = by - ay;+ e[k] = ax; e[k + 1] = ay; e[k + 2] = dx; e[k + 3] = dy; e[k + 4] = dx * dx + dy * dy;+ const cy0 = this.cy(Math.min(ay, by)), cy1 = this.cy(Math.max(ay, by));+ for (let cy = cy0; cy <= cy1; cy++) {+ // The stretch of the edge inside this row of buckets, a little generously, so a long+ // slanted edge is not listed in every bucket of its box. The outermost rows also hold+ // whatever lies beyond them, so there the whole edge counts.+ let x0 = Math.min(ax, bx), x1 = Math.max(ax, bx);+ if (cy0 < cy1 && cy > 0 && cy < span - 1) {+ const t0 = Math.min(1, Math.max(0, (this.oy + cy * CELL - SLACK - ay) / dy));+ const t1 = Math.min(1, Math.max(0, (this.oy + (cy + 1) * CELL + SLACK - ay) / dy));+ x0 = Math.min(ax + t0 * dx, ax + t1 * dx) - SLACK;+ x1 = Math.max(ax + t0 * dx, ax + t1 * dx) + SLACK;+ }+ for (let cx = this.cx(x0), end = this.cx(x1); cx <= end; cx++) {+ if (place) items[next[cy * span + cx]++] = k;+ else start[cy * span + cx + 1]++;+ }+ }+ }+ }+ }+ }++ /** Makes the shared scratch large enough for a walk over this index's edges. */+ private ready(): void {+ if (stamp.length >= this.count) return;+ stamp = new Int32Array(2 * this.count);+ // A tile's own list, then one shorter list per halving on the way down to a sample.+ lists = new Int32Array((2 + Math.ceil(Math.log2(TILE))) * stamp.length);+ d2 = new Float64Array(stamp.length);+ vx = new Float64Array(stamp.length);+ vy = new Float64Array(stamp.length);+ }++ private cx(x: number) { return Math.max(0, Math.min(this.span - 1, Math.floor((x - this.ox) / CELL))); }+ private cy(y: number) { return Math.max(0, Math.min(this.span - 1, Math.floor((y - this.oy) / CELL))); }++ /** Distance to the nearest edge, searching rings of buckets outward until no closer edge can exist. */+ distance(x: number, y: number): number {+ const { e, items, start, span } = this;+ const bx = this.cx(x), by = this.cy(y);+ let best = Infinity;+ for (let r = 0; r < span; r++) {+ for (let cy = by - r; cy <= by + r; cy++) {+ if (cy < 0 || cy >= span) continue;+ const edgeRow = cy === by - r || cy === by + r;+ for (let cx = bx - r; cx <= bx + r; cx += edgeRow ? 1 : 2 * r || 1) {+ if (cx < 0 || cx >= span) continue;+ const b = cy * span + cx;+ for (let q = start[b], end = start[b + 1]; q < end; q++) {+ // segDist2, written out here and in `nearest` and `survey`: all three must stay the same.+ const k = items[q];+ const ax = e[k], ay = e[k + 1], dx = e[k + 2], dy = e[k + 3], len = e[k + 4];+ let t = len > 0 ? ((x - ax) * dx + (y - ay) * dy) / len : 0;+ t = t < 0 ? 0 : t > 1 ? 1 : t;+ const ex = ax + t * dx - x, ey = ay + t * dy - y;+ const d = ex * ex + ey * ey;+ if (d < best) best = d;+ }+ }+ }+ // Every edge not seen yet lies in a bucket more than r cells away (best is squared).+ const reach = r * CELL - SLACK;+ if (reach > 0 && best <= reach * reach) break;+ }+ return Math.sqrt(best);+ }++ /** Distance to the nearest edge at every sample of a grid, row-major. */+ distances(g: SampleGrid): Float64Array {+ const out = new Float64Array(g.nx * g.ny);+ this.ready();+ this.x0 = g.x0; this.y0 = g.y0; this.step = g.step; this.nx = g.nx;+ for (let j0 = 0; j0 < g.ny; j0 += TILE) {+ for (let i0 = 0; i0 < g.nx; i0 += TILE) {+ const i1 = Math.min(g.nx, i0 + TILE) - 1, j1 = Math.min(g.ny, j0 + TILE) - 1;+ const im = (i0 + i1) >> 1, jm = (j0 + j1) >> 1;+ const x = g.x0 + im * g.step, y = g.y0 + jm * g.step;+ this.fill(out, i0, i1, j0, j1, 0, this.collect(x, y, this.distance(x, y) + 2 * radiusOf(g.step, i0, i1, j0, j1) + SLACK));+ }+ }+ return out;+ }++ /**+ * The largest distance to the nearest edge over the grid's samples that are inside the fill+ * (`insideRow` of each sample's row), or 0 if none is. Same as the largest inside value of+ * `distances`, but most of the grid is ruled out without being measured.+ */+ widest(g: SampleGrid, rows: EdgeBands): number {+ this.ready();+ this.x0 = g.x0; this.y0 = g.y0; this.step = g.step; this.nx = g.nx;+ const tiles: number[] = [];+ for (let j0 = 0; j0 < g.ny; j0 += TILE) {+ for (let i0 = 0; i0 < g.nx; i0 += TILE) tiles.push(i0, Math.min(g.nx, i0 + TILE) - 1, j0, Math.min(g.ny, j0 + TILE) - 1);+ }+ // Start from the best middle sample of a tile, so most tiles are ruled out before they are opened.+ const middles = new Float64Array(tiles.length / 4);+ let best = 0;+ for (let k = 0; k < tiles.length; k += 4) {+ const x = g.x0 + ((tiles[k] + tiles[k + 1]) >> 1) * g.step, y = g.y0 + ((tiles[k + 2] + tiles[k + 3]) >> 1) * g.step;+ const d = middles[k / 4] = this.distance(x, y);+ if (d > best && rows.insideRowAt(x, y)) best = d;+ }+ for (let k = 0; k < tiles.length; k += 4) {+ const i0 = tiles[k], i1 = tiles[k + 1], j0 = tiles[k + 2], j1 = tiles[k + 3];+ const x = g.x0 + ((i0 + i1) >> 1) * g.step, y = g.y0 + ((j0 + j1) >> 1) * g.step;+ const d = middles[k / 4], radius = radiusOf(g.step, i0, i1, j0, j1);+ // No sample of the tile is farther from the outline than its middle plus its radius.+ if (d + radius + SLACK < best) continue;+ // If the outline does not reach into the tile, it is inside or outside as a whole.+ const whole = d > radius + SLACK;+ if (whole && !rows.insideRowAt(x, y)) continue;+ best = this.peak(rows, best, whole, i0, i1, j0, j1, 0, this.collect(x, y, d + 2 * radius + SLACK));+ }+ return best;+ }++ /** Lists every edge with a point in the square of `reach` around (x, y) at the start of `lists`. */+ private collect(x: number, y: number, reach: number): number {+ const { items, start, span } = this;+ // Stamps are 32-bit: start over long before the count of collections could wrap.+ if (tags >= 0x7fffff00) { stamp.fill(0); tags = 0; }+ const tag = ++tags;+ let n = 0;+ const cx1 = this.cx(x + reach), cy1 = this.cy(y + reach);+ for (let cy = this.cy(y - reach); cy <= cy1; cy++) {+ for (let cx = this.cx(x - reach); cx <= cx1; cx++) {+ const b = cy * span + cx;+ for (let q = start[b], end = start[b + 1]; q < end; q++) {+ const k = items[q];+ if (stamp[k / 5] === tag) continue;+ stamp[k / 5] = tag;+ lists[n++] = k;+ }+ }+ }+ return n;+ }++ /** Squared distance from (x, y) to the nearest of the edges `lists[lo..hi)`. */+ private nearest(lo: number, hi: number, x: number, y: number): number {+ const e = this.e;+ let best = Infinity;+ for (let q = lo; q < hi; q++) {+ const k = lists[q];+ const ax = e[k], ay = e[k + 1], dx = e[k + 2], dy = e[k + 3], len = e[k + 4];+ let t = len > 0 ? ((x - ax) * dx + (y - ay) * dy) / len : 0;+ t = t < 0 ? 0 : t > 1 ? 1 : t;+ const ex = ax + t * dx - x, ey = ay + t * dy - y;+ const d = ex * ex + ey * ey;+ if (d < best) best = d;+ }+ return best;+ }++ /** `nearest`, keeping for `narrow` each edge's squared distance and the vector to its nearest point. */+ private survey(lo: number, hi: number, x: number, y: number): number {+ const e = this.e;+ let best = Infinity;+ for (let q = lo; q < hi; q++) {+ const k = lists[q];+ const ax = e[k], ay = e[k + 1], dx = e[k + 2], dy = e[k + 3], len = e[k + 4];+ let t = len > 0 ? ((x - ax) * dx + (y - ay) * dy) / len : 0;+ t = t < 0 ? 0 : t > 1 ? 1 : t;+ const ex = ax + t * dx - x, ey = ay + t * dy - y;+ const d = ex * ex + ey * ey;+ d2[q - lo] = d; vx[q - lo] = ex; vy[q - lo] = ey;+ if (d < best) { best = d; this.bx = ex; this.by = ey; }+ }+ return best;+ }++ /**+ * After a survey of `lists[lo..hi)` from a point at distance `d` from the nearest edge: lists,+ * from `hi` on, the edges that can be nearest to some point within `radius` of it. Returns the+ * end of that list.+ *+ * An edge nearest to such a point p is no farther from p than the surveyed point's nearest point+ * n is. With u and w the unit directions from n and from the edge's nearest point to the+ * surveyed point m, and v = p - m, that gives D + w·v ≤ |p - n| ≤ d + u·v + |v|² / 2d. So the+ * edge's distance D from m exceeds d by at most |u - w| r + r² / 2d, and never by more than 2r.+ */+ private narrow(lo: number, hi: number, d: number, radius: number): number {+ const ball = d + 2 * radius + SLACK;+ const bend = d > 0 ? (radius * radius) / (2 * d) : Infinity;+ const ux = d > 0 ? this.bx / d : 0, uy = d > 0 ? this.by / d : 0;+ let end = hi;+ for (let q = lo; q < hi; q++) {+ const far2 = d2[q - lo];+ if (far2 > ball * ball) continue;+ if (bend < 2 * radius) {+ const far = Math.sqrt(far2);+ const wx = vx[q - lo] / far - ux, wy = vy[q - lo] / far - uy;+ if (far - d > Math.sqrt(wx * wx + wy * wy) * radius + bend + SLACK) continue;+ }+ lists[end++] = lists[q];+ }+ return end;+ }++ /**+ * Measures the samples i0..i1 × j0..j1 into `out`. `lists[lo..hi)` holds every edge that is+ * nearest to some point of the block. The block's middle sample is measured against all of+ * them; that rules most of them out for the rest of the block, and each quarter goes on with+ * the shorter list.+ */+ private fill(out: Float64Array, i0: number, i1: number, j0: number, j1: number, lo: number, hi: number): void {+ const { x0, y0, step, nx } = this;+ if ((i1 - i0 < 2 && j1 - j0 < 2) || hi - lo < 2) {+ for (let j = j0; j <= j1; j++) {+ for (let i = i0; i <= i1; i++) out[j * nx + i] = Math.sqrt(this.nearest(lo, hi, x0 + i * step, y0 + j * step));+ }+ return;+ }+ const im = (i0 + i1) >> 1, jm = (j0 + j1) >> 1;+ const d = out[jm * nx + im] = Math.sqrt(this.survey(lo, hi, x0 + im * step, y0 + jm * step));+ const end = this.narrow(lo, hi, d, radiusOf(step, i0, i1, j0, j1));+ this.fill(out, i0, im, j0, jm, hi, end);+ if (im < i1) this.fill(out, im + 1, i1, j0, jm, hi, end);+ if (jm < j1) {+ this.fill(out, i0, im, jm + 1, j1, hi, end);+ if (im < i1) this.fill(out, im + 1, i1, jm + 1, j1, hi, end);+ }+ }++ /**+ * `fill` for `widest`: returns the larger of `best` and the largest distance of an inside sample+ * of the block, skipping blocks that cannot hold one. `whole`: the block is known to be inside.+ */+ private peak(rows: EdgeBands, best: number, whole: boolean, i0: number, i1: number, j0: number, j1: number, lo: number, hi: number): number {+ const { x0, y0, step } = this;+ if ((i1 - i0 < 2 && j1 - j0 < 2) || hi - lo < 2) {+ for (let j = j0; j <= j1; j++) {+ for (let i = i0; i <= i1; i++) {+ const x = x0 + i * step, y = y0 + j * step;+ const d = Math.sqrt(this.nearest(lo, hi, x, y));+ if (d > best && (whole || rows.insideRowAt(x, y))) best = d;+ }+ }+ return best;+ }+ const im = (i0 + i1) >> 1, jm = (j0 + j1) >> 1;+ const x = x0 + im * step, y = y0 + jm * step;+ const d = Math.sqrt(this.survey(lo, hi, x, y)), radius = radiusOf(step, i0, i1, j0, j1);+ // The same two ways out as for a tile (see widest).+ if (d + radius + SLACK < best) return best;+ if (!whole && d > radius + SLACK) {+ if (!rows.insideRowAt(x, y)) return best;+ whole = true;+ }+ if (d > best && (whole || rows.insideRowAt(x, y))) best = d;+ const end = this.narrow(lo, hi, d, radius);+ best = this.peak(rows, best, whole, i0, im, j0, jm, hi, end);+ if (im < i1) best = this.peak(rows, best, whole, im + 1, i1, j0, jm, hi, end);+ if (jm < j1) {+ best = this.peak(rows, best, whole, i0, im, jm + 1, j1, hi, end);+ if (im < i1) best = this.peak(rows, best, whole, im + 1, i1, jm + 1, j1, hi, end);+ }+ return best;+ }+}++/** How far the samples i0..i1 × j0..j1 reach from the middle one, (i0 + i1) >> 1 and (j0 + j1) >> 1. */+function radiusOf(step: number, i0: number, i1: number, j0: number, j1: number): number {+ const im = (i0 + i1) >> 1, jm = (j0 + j1) >> 1;+ return step * Math.hypot(Math.max(im - i0, i1 - im), Math.max(jm - j0, j1 - jm));+}diff --git a/packages/phone-protocol/src/open-bot-avatar/dom/eye.ts b/packages/phone-protocol/src/open-bot-avatar/dom/eye.tsnew file mode 100644index 0000000000..c415029ad5--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/dom/eye.ts@@ -0,0 +1,38 @@+/** An eye mark on a 2D canvas: its bounds, and its paint. Shared by the flat painter and the fluffy sockets. */+import type { EyeMark, FramePath } from '../render.ts';++export function eyeBox(mark: EyeMark): FramePath['box'] {+ if (mark.shape === 'pill') return { x: mark.x, y: mark.y, w: mark.width, h: mark.height };+ // Quadratics lie within their points' hull; an arc's stroke reaches half its width past it.+ const reach = mark.shape === 'arc' ? mark.strokeWidth : 0;+ const n = (mark.d.match(/-?\d+(?:\.\d+)?/g) ?? []).map(Number);+ const xs = n.filter((_, i) => i % 2 === 0), ys = n.filter((_, i) => i % 2 === 1);+ const x = Math.min(...xs) - reach, y = Math.min(...ys) - reach;+ return { x, y, w: Math.max(...xs) + reach - x, h: Math.max(...ys) + reach - y };+}++/** Fill or stroke the mark in the context's current styles. */+export function paintEye(ctx: CanvasRenderingContext2D, mark: EyeMark) {+ if (mark.shape === 'path') {+ ctx.fill(new Path2D(mark.d));+ return;+ }+ if (mark.shape === 'arc') {+ ctx.lineWidth = mark.strokeWidth;+ ctx.stroke(new Path2D(mark.d));+ return;+ }+ const { x, y, width: w, height: h, radius: r } = mark;+ ctx.beginPath();+ if (typeof ctx.roundRect === 'function') ctx.roundRect(x, y, w, h, r);+ else {+ // Safari before 16 and Firefox before 112.+ ctx.moveTo(x + r, y);+ ctx.arcTo(x + w, y, x + w, y + h, r);+ ctx.arcTo(x + w, y + h, x, y + h, r);+ ctx.arcTo(x, y + h, x, y, r);+ ctx.arcTo(x, y, x + w, y, r);+ ctx.closePath();+ }+ ctx.fill();+}diff --git a/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/dye.ts b/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/dye.tsnew file mode 100644index 0000000000..53a37df215--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/dye.ts@@ -0,0 +1,62 @@+/**+ * How a fluffy coat takes its color: one row of colors per dye, from the darkest recess to the+ * brightest lit tip. The shader works out how much light a fiber catches and looks the color up+ * here, so every dye keeps its hue through the same range of shading.+ */+import { oklch, toOklch, type Rgb } from '../../color.ts';++/** Colors in a ramp. */+export const DYE_RAMP_SIZE = 96;+/** Exposure at the bright end of a ramp; 1 is the dye's own color. */+export const DYE_RAMP_RANGE = 2.4;++const ramps = new Map<number, Uint8Array<ArrayBuffer>>();++/** Keep regular lightness steps through the midtones, rolling off near black and white. */+function shoulder(distance: number, room: number): number {+ const knee = room / 2;+ return distance <= knee ? distance : room - knee * Math.exp((knee - distance) / knee);+}++function smoothstep(low: number, high: number, value: number): number {+ const t = Math.max(0, Math.min(1, (value - low) / (high - low)));+ return t * t * (3 - 2 * t);+}++/**+ * The ramp for a body color, as RGBA bytes. RGB is the color at each exposure. Alpha, the same+ * along the row, is how far the shader replaces it with its separate response for yellow fibers.+ */+export function dyeRamp(rgb: Rgb): Uint8Array<ArrayBuffer> {+ const key = (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];+ const cached = ramps.get(key);+ if (cached) return cached;+ const [lightness, chroma, hue] = toOklch(rgb);+ // Amber through lemon keep separate diffuse and glint colors, fading into the shared ramp for+ // neighboring hues, pale creams and dark olives.+ const yellow = (1 - smoothstep(22, 32, Math.abs(hue - 90))) * smoothstep(0.025, 0.085, chroma) * smoothstep(0.54, 0.75, lightness);+ // The dye bounds the brightest tip. Where a channel is already full, the other dyed channels+ // lift more than the weakest one.+ const value = Math.max(...rgb);+ const dye = rgb.map((channel) => (value ? channel / value : 1));+ const weakest = Math.min(...dye);+ const peak = dye.map((channel) => 255 * (channel + (1 - channel) * (0.16 + 0.84 * (channel - weakest)))) as Rgb;+ const [peakLightness] = toOklch(peak);+ // Even black, white and fully saturated primaries need some headroom.+ const mid = Math.max(0.16, Math.min(lightness, peakLightness - 0.025));+ const midChroma = chroma * Math.min(1, mid / Math.max(0.001, lightness));+ const headroom = peakLightness - mid;+ const row = new Uint8Array(DYE_RAMP_SIZE * 4);+ for (let i = 0; i < DYE_RAMP_SIZE; i++) {+ const exposure = ((i + 0.5) * DYE_RAMP_RANGE) / DYE_RAMP_SIZE;+ // At fixed chromaticity, Oklab lightness scales with the cube root of linear light: carry+ // the excursion of a reference dye over to this one.+ const delta = 0.82 * (Math.cbrt(exposure) - 1);+ const L = delta < 0 ? mid - shoulder(-delta, mid) : mid + shoulder(delta, headroom);+ const [r, g, b] = oklch(L, midChroma * Math.min(1, L / mid), hue);+ row.set([Math.round(r), Math.round(g), Math.round(b), Math.round(255 * yellow)], i * 4);+ }+ if (ramps.size >= 64) ramps.delete(ramps.keys().next().value!);+ ramps.set(key, row);+ return row;+}diff --git a/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/marks.ts b/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/marks.tsnew file mode 100644index 0000000000..77a6ee443a--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/marks.ts@@ -0,0 +1,54 @@+/**+ * The marks of `thinking` and `blocked` in fluffy: each dot or bar is a small pompom, rendered+ * once per shape, color and size and kept as a sprite, since the three dots and both parts of+ * the exclamation mark only ever move, squash and fade.+ */+import { viewBasis, type FramePath } from '../../render.ts';+import type { Capsule } from './mesh.ts';+import { renderFluffy } from './renderer.ts';++/** Radius of a mark's model, viewBox units: enough for the short pile to read on a small dot. */+const RADIUS = 12;+const FRONT = viewBasis(0, 0);+/** Sprites are rendered a little larger than they are drawn, for the top of a hop. */+const HEADROOM = 1.12;++const models = new Map<number, Capsule>();+const sprites = new Map<string, { canvas: HTMLCanvasElement; radius: number }>();++/**+ * Paint a mark face-on as a fluffy ball or capsule filling `box`, under the context's transform+ * (which animates it). `scale` is device pixels per viewBox unit. False where fluffy can't be+ * drawn: the caller fills the mark's path instead.+ */+export function paintFluffyMark(ctx: CanvasRenderingContext2D, box: FramePath['box'], scale: number, color: string): boolean {+ const aspect = Math.round((1000 * box.h) / box.w) / 1000;+ let model = models.get(aspect);+ if (!model) {+ const halfHeight = RADIUS * aspect;+ model = { radius: RADIUS, bounds: { minX: -RADIUS, maxX: RADIUS, minY: -halfHeight, maxY: halfHeight } };+ models.set(aspect, model);+ }+ /** Drawn units per model unit. */+ const unit = box.w / (2 * RADIUS);+ // Whole powers of two, so a mark that grows or shrinks keeps the same fibers.+ const density = Math.min(8, Math.max(0.5, 2 ** Math.ceil(Math.log2(HEADROOM * scale * unit))));+ const key = `${aspect}|${color}|${density}`;+ let sprite = sprites.get(key);+ if (!sprite) {+ const image = renderFluffy(model, FRONT, { color, ink: color, eyes: [] }, density);+ if (!image) return false;+ // The renderer's canvas is shared with the body: keep a copy.+ const canvas = document.createElement('canvas');+ canvas.width = canvas.height = image.size;+ const copy = canvas.getContext('2d');+ if (!copy) return false;+ copy.drawImage(image.canvas, image.x, image.y, image.size, image.size, 0, 0, image.size, image.size);+ sprite = { canvas, radius: image.radius };+ if (sprites.size >= 12) sprites.delete(sprites.keys().next().value!);+ sprites.set(key, sprite);+ }+ const radius = sprite.radius * unit;+ ctx.drawImage(sprite.canvas, -radius, -radius, 2 * radius, 2 * radius);+ return true;+}diff --git a/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/mesh.ts b/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/mesh.tsnew file mode 100644index 0000000000..fd2a1e5d03--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/mesh.ts@@ -0,0 +1,260 @@+/**+ * The fluffy body as a triangle mesh: surface nets over the union of the avatar's parts. One vertex+ * per boundary cell gives a closed surface, including the backs of ears and the walls of holes.+ * Hair roots are scattered over it by area, and the front around the eyes is refined so a socket+ * and its bead keep their shape in profile.+ *+ * Building a mesh takes tens of milliseconds, so the renderer keeps what it builds (see renderer.ts).+ */+import { EdgeIndex } from '../../distance.ts';+import { edgeBands, type Bounds } from '../../path.ts';+import { EYE_H, EYE_W, GAZE_X, GAZE_Y, HAPPY_ARC } from '../../validate.ts';+import type { Volume, VolumePart } from '../../volume.ts';+import { SOCKET_PAD } from './socket.ts';++export interface FluffyMesh {+ /** Position and outward normal per vertex (6 floats). */+ vertices: Float32Array;+ /** The triangles twice: as the grid gives them, then with those around the eyes refined. */+ indices: Uint32Array;+ /** Where each set sits in `indices`. A small avatar is drawn from the coarse one. */+ coarse: IndexRange;+ fine: IndexRange;+ /**+ * Hair roots, independent of the triangles: position, normal and two random numbers (8 floats).+ * Stored in ROOT_PASSES passes over the surface, so the first few passes are an even share of+ * the coat (see rootsIn).+ */+ roots: Float32Array;+}++export interface IndexRange {+ start: number;+ count: number;+}++/** A state mark: a vertical capsule centered at the origin. Equal width and height give a ball. */+export interface Capsule {+ bounds: Bounds;+ radius: number;+}++export type FluffyShape = Volume | Capsule;++const isCapsule = (shape: FluffyShape): shape is Capsule => 'radius' in shape;++/** Front-to-back half extent of a shape, viewBox units. */+export function halfDepth(shape: FluffyShape): number {+ return isCapsule(shape) ? shape.radius : Math.max(0.5, ...shape.parts.map((part) => part.depth / 2));+}++/** Grid spacing, viewBox units. */+const STEP = 1.05;+/** Empty margin around the shape, viewBox units. */+const PAD = 3 * STEP;+/**+ * The roots are stored in this many passes over the surface, each taking every ROOT_PASSES-th+ * root. Each pass runs along the surface, which draws faster than roots in random order.+ */+export const ROOT_PASSES = 8;++/** How many of `total` roots the first `passes` passes hold. */+export function rootsIn(total: number, passes: number): number {+ let count = 0;+ for (let pass = 0; pass < passes; pass++) count += Math.ceil((total - pass) / ROOT_PASSES);+ return count;+}++/** Hair roots per square unit of surface. */+const ROOT_DENSITY = 3.3;+/** Each level splits the triangles around the eyes in four. */+const SOCKET_LEVELS = 2;++/** Samples of a field that is positive inside the shape, on a regular grid. */+interface Grid {+ x0: number;+ y0: number;+ z0: number;+ nx: number;+ ny: number;+ nz: number;+ field: Float32Array;+}++function emptyGrid(shape: FluffyShape): Grid {+ const b = shape.bounds, half = halfDepth(shape);+ const nx = Math.ceil((b.maxX - b.minX + 2 * PAD) / STEP) + 1;+ const ny = Math.ceil((b.maxY - b.minY + 2 * PAD) / STEP) + 1;+ const nz = Math.ceil((2 * half + 2 * PAD) / STEP) + 1;+ return { x0: b.minX - PAD, y0: b.minY - PAD, z0: -half - PAD, nx, ny, nz, field: new Float32Array(nx * ny * nz).fill(-1000) };+}++function addCapsule(g: Grid, { bounds, radius }: Capsule) {+ const halfStem = bounds.maxY - radius;+ for (let j = 0; j < g.ny; j++) {+ const dy = Math.max(0, Math.abs(g.y0 + j * STEP) - halfStem);+ for (let i = 0; i < g.nx; i++) {+ const radial = (g.x0 + i * STEP) ** 2 + dy ** 2;+ for (let k = 0; k < g.nz; k++) g.field[i + j * g.nx + k * g.nx * g.ny] = radius - Math.sqrt(radial + (g.z0 + k * STEP) ** 2);+ }+ }+}++/** Union one part into the grid: its outline's distance, capped by its height or rounded by its fillet. */+function addPart(g: Grid, part: VolumePart) {+ const { field, nx } = g, plane = nx * g.ny;+ const rounded = part.kind === 'inflate' && part.rxy > 0 && part.rz > 0;+ const distances = new EdgeIndex(part.polys, part.bounds).distances({ x0: g.x0, y0: g.y0, step: STEP, nx, ny: g.ny });+ // By winding, as the volume's own height does: grid columns start at the body's bounds, where+ // many outlines have a straight edge, and a point on an edge must fall on the same side.+ const outline = edgeBands(part.polys);+ for (let j = 0; j < g.ny; j++) {+ const y = g.y0 + j * STEP;+ for (let i = 0; i < nx; i++) {+ const x = g.x0 + i * STEP;+ const inside = outline.winding(x, y) !== 0;+ const sd = inside ? distances[i + j * nx] : -distances[i + j * nx];+ // An inflated part is shaped by its fillet instead; outside the outline there is no height.+ const h = part.kind === 'inflate' || !inside ? 0 : part.height(x, y);+ for (let k = 0; k < g.nz; k++) {+ const z = Math.abs(g.z0 + k * STEP);+ let d;+ if (rounded) {+ const side = (part.rxy - sd) / part.rxy, top = (z - part.depth / 2 + part.rz) / part.rz;+ d = (1 - Math.hypot(Math.max(0, side), Math.max(0, top))) * Math.min(part.rxy, part.rz);+ } else d = Math.min(sd, Math.max(0.55, h) - z);+ const at = i + j * nx + k * plane;+ if (d > field[at]) field[at] = d;+ }+ }+ }+}++/** One vertex in every cell the surface crosses, at the mean of its edge crossings, and a quad across every crossed edge. */+function surfaceNets(g: Grid): { vertices: number[]; indices: number[] } {+ const { field, nx, ny, nz } = g, plane = nx * ny;+ const corners = [0, 1, nx, nx + 1, plane, plane + 1, plane + nx, plane + nx + 1];+ const strides = [1, nx, plane];+ const ids = new Int32Array(field.length).fill(-1);+ const vertices: number[] = [], indices: number[] = [];+ for (let k = 1; k < nz - 2; k++) for (let j = 1; j < ny - 2; j++) for (let i = 1; i < nx - 2; i++) {+ const cell = i + j * nx + k * plane, inside = field[cell] > 0;+ let crossed = false;+ for (let c = 1; c < 8 && !crossed; c++) crossed = (field[cell + corners[c]] > 0) !== inside;+ if (!crossed) continue;+ let sx = 0, sy = 0, sz = 0, count = 0, gx = 0, gy = 0, gz = 0;+ for (let c = 0; c < 8; c++) {+ const a = cell + corners[c];+ for (let axis = 0; axis < 3; axis++) {+ if (c & (1 << axis)) continue;+ const other = a + strides[axis];+ if ((field[a] > 0) === (field[other] > 0)) continue;+ const t = field[a] / (field[a] - field[other]);+ sx += (c & 1) + (axis === 0 ? t : 0);+ sy += ((c >> 1) & 1) + (axis === 1 ? t : 0);+ sz += ((c >> 2) & 1) + (axis === 2 ? t : 0);+ // The field's gradient at the crossing, from central differences at the edge's two ends.+ gx += (field[a - 1] - field[a + 1]) * (1 - t) + (field[other - 1] - field[other + 1]) * t;+ gy += (field[a - nx] - field[a + nx]) * (1 - t) + (field[other - nx] - field[other + nx]) * t;+ gz += (field[a - plane] - field[a + plane]) * (1 - t) + (field[other - plane] - field[other + plane]) * t;+ count++;+ }+ }+ const norm = Math.hypot(gx, gy, gz) || 1;+ const id = vertices.length / 6;+ ids[cell] = id;+ vertices.push(g.x0 + (i + sx / count) * STEP, g.y0 + (j + sy / count) * STEP, g.z0 + (k + sz / count) * STEP, gx / norm, gy / norm, gz / norm);+ for (let axis = 0; axis < 3; axis++) {+ if ((field[cell + strides[axis]] > 0) === inside) continue;+ const u = strides[(axis + 1) % 3], v = strides[(axis + 2) % 3];+ const p = ids[cell - u], q = ids[cell - u - v], r = ids[cell - v];+ if (Math.min(p, q, r) >= 0) indices.push(id, p, q, id, q, r);+ }+ }+ return { vertices, indices };+}++/** Seeded, so a shape always grows the same coat. */+function randomFrom(seed: number): () => number {+ return () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) / 4294967296;+}++/** Hair roots spread evenly by area, each with two random numbers for its strand. */+function scatterRoots(vertices: number[], indices: number[]): Float32Array {+ const random = randomFrom(51821);+ const roots: number[] = [];+ for (let i = 0; i < indices.length; i += 3) {+ const a = indices[i] * 6, b = indices[i + 1] * 6, c = indices[i + 2] * 6;+ const abx = vertices[b] - vertices[a], aby = vertices[b + 1] - vertices[a + 1], abz = vertices[b + 2] - vertices[a + 2];+ const acx = vertices[c] - vertices[a], acy = vertices[c + 1] - vertices[a + 1], acz = vertices[c + 2] - vertices[a + 2];+ const area = 0.5 * Math.hypot(aby * acz - abz * acy, abz * acx - abx * acz, abx * acy - aby * acx);+ const count = Math.floor(area * ROOT_DENSITY + random());+ for (let n = 0; n < count; n++) {+ const u = Math.sqrt(random()), v = u * random();+ for (let k = 0; k < 6; k++) roots.push((1 - u) * vertices[a + k] + (u - v) * vertices[b + k] + v * vertices[c + k]);+ roots.push(random(), random());+ }+ }+ const total = roots.length / 8;+ const passes = new Float32Array(roots.length);+ let at = 0;+ for (let pass = 0; pass < ROOT_PASSES; pass++) {+ for (let i = pass; i < total; i += ROOT_PASSES) for (let k = 0; k < 8; k++) passes[at++] = roots[8 * i + k];+ }+ return passes;+}++/**+ * The grid is too coarse to describe a bead in profile: split the front triangles within reach of+ * an eye (its largest mark, anywhere its gaze takes it). Adds the new vertices to `vertices`.+ */+function refineSockets(vertices: number[], indices: number[], vol: Volume): number[] {+ const pad = SOCKET_PAD + 2 * STEP;+ const reachX = vol.eyeScale * (EYE_W * (HAPPY_ARC.halfWidth + HAPPY_ARC.stroke / 2) + GAZE_X) + pad;+ const reachY = vol.eyeScale * (EYE_H / 2 + GAZE_Y) + pad;+ const refined: number[] = [];+ const midpoints = new Map<number, number>();+ const midpoint = (a: number, b: number) => {+ const key = Math.min(a, b) * 2 ** 26 + Math.max(a, b);+ let id = midpoints.get(key);+ if (id === undefined) {+ id = vertices.length / 6;+ for (let k = 0; k < 6; k++) vertices.push((vertices[6 * a + k] + vertices[6 * b + k]) / 2);+ midpoints.set(key, id);+ }+ return id;+ };+ const split = (a: number, b: number, c: number, level: number) => {+ if (level === 0) {+ refined.push(a, b, c);+ return;+ }+ const ab = midpoint(a, b), bc = midpoint(b, c), ca = midpoint(c, a);+ split(a, ab, ca, level - 1);+ split(ab, b, bc, level - 1);+ split(ca, bc, c, level - 1);+ split(ab, bc, ca, level - 1);+ };+ for (let i = 0; i < indices.length; i += 3) {+ const a = indices[i], x = vertices[6 * a], y = vertices[6 * a + 1], z = vertices[6 * a + 2];+ const near = z >= -2 * STEP && vol.eyePlanes.some((eye) => Math.abs(eye.x - x) <= reachX && Math.abs(eye.y - y) <= reachY);+ split(a, indices[i + 1], indices[i + 2], near ? SOCKET_LEVELS : 0);+ }+ return refined;+}++export function buildMesh(shape: FluffyShape): FluffyMesh {+ const grid = emptyGrid(shape);+ if (isCapsule(shape)) addCapsule(grid, shape);+ else for (const part of shape.parts) addPart(grid, part);+ const { vertices, indices } = surfaceNets(grid);+ // Roots first: refining would otherwise change which triangle each one falls on.+ const roots = scatterRoots(vertices, indices);+ const coarse = { start: 0, count: indices.length };+ if (isCapsule(shape)) return { vertices: new Float32Array(vertices), indices: new Uint32Array(indices), coarse, fine: coarse, roots };+ const refined = refineSockets(vertices, indices, shape);+ const all = new Uint32Array(indices.length + refined.length);+ all.set(indices);+ all.set(refined, indices.length);+ return { vertices: new Float32Array(vertices), indices: all, coarse, fine: { start: indices.length, count: refined.length }, roots };+}diff --git a/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/renderer.ts b/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/renderer.tsnew file mode 100644index 0000000000..f3fc9b5f07--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/renderer.ts@@ -0,0 +1,436 @@+/**+ * The fluffy renderer: draws a body as a lit coat of fur with the eyes seated in it. Every fluffy+ * avatar on the page shares one WebGL2 context (browsers allow only a handful), which renders one+ * avatar at a time into its own canvas; the 2D painter copies that image into the avatar's canvas+ * (see paint.ts), under the ribbons and marks it draws itself.+ *+ * A frame is three kinds of draw over the same mesh: the solid body, a few shells of pile lifted+ * off it, and the single strands (see shaders.ts). Meshes are built once per shape and kept on+ * the GPU while their avatars keep painting, so a page of avatars only pays for drawing, and a+ * small avatar draws less of each (see fluffyDetail).+ */+import type { EyeMark, SurfaceEye, ViewBasis } from '../../render.ts';+import { DYE_RAMP_SIZE, dyeRamp } from './dye.ts';+import { ROOT_PASSES, buildMesh, halfDepth, rootsIn, type IndexRange, type FluffyShape } from './mesh.ts';+import { PASS, fragmentShader, vertexShader } from './shaders.ts';+import { SOCKET_TILE, exposedHeight, socketKey, socketRegion, socketTile } from './socket.ts';++/** The colors of a coat and the eyes set into it (none for a state mark). */+export interface FluffyLook {+ /** Body color, any CSS color. */+ color: string;+ /** Eye color, any CSS color. */+ ink: string;+ /** Up to two eyes, left first. */+ eyes: SurfaceEye[];+}++/** A rendered coat. It lasts until the next render: draw or copy it at once. */+export interface FluffyImage {+ /** The renderer's canvas, which may be larger than the image. */+ canvas: HTMLCanvasElement;+ /** The image's square in the canvas, pixels: `size` to the right of and below (x, y). */+ x: number;+ y: number;+ size: number;+ /** The square the image covers, viewBox units: `radius` to each side of (cx, cy). */+ cx: number;+ cy: number;+ radius: number;+}++/** Shells of pile between the body and the strands, at full detail. */+const SHELLS = 5;+/**+ * Pixels per viewBox unit from which a coat is drawn in full: an avatar 128 CSS pixels wide on a+ * 2× display. Below it the pile is finer than the pixels that show it (see fluffyDetail).+ */+const FULL_DETAIL = 2.56;+/** Largest image, pixels a side. */+const MAX_PIXELS = 1024;+const MIN_PIXELS = 32;+/** Room around the body for the pile, viewBox units. */+const PILE_REACH = 4;+/** The eyes sit this far above their host's surface at most, viewBox units. */+const SOCKET_RISE = 0.8;+/** A view this close to the last one drawn, in pixels of surface movement, reuses its image. */+const SAME_VIEW = 0.1;+/** This many meshes always stay on the GPU; any more only while they were drawn within IDLE_MS. */+const KEPT_MESHES = 8;+const IDLE_MS = 2000;++/**+ * How much of a coat to draw at `scale` pixels per viewBox unit. A small avatar gets fewer shells,+ * the unrefined triangles around its eyes, and a share of its strands (`strandPasses` of the+ * mesh's ROOT_PASSES), each widened by as much as there are fewer, so they cover the same. The+ * image averages out to the same coat at half to two thirds of the cost.+ */+export function fluffyDetail(scale: number): { shells: number; strandPasses: number; fineSockets: boolean } {+ const detail = Math.min(1, scale / FULL_DETAIL);+ return {+ shells: Math.max(2, Math.ceil(SHELLS * detail)),+ // By the root, not in proportion: strands that get much wider show as wisps along the outline.+ strandPasses: Math.max(ROOT_PASSES / 4, Math.ceil(ROOT_PASSES * Math.sqrt(detail))),+ fineSockets: detail > 0.75,+ };+}++/** A mesh on the GPU, and where its shape sits. */+interface Geometry {+ surface: WebGLVertexArrayObject;+ strands: WebGLVertexArrayObject;+ buffers: WebGLBuffer[];+ coarse: IndexRange;+ fine: IndexRange;+ strandCount: number;+ cx: number;+ cy: number;+ /** Half extents of the shape, for bending normals across its flat faces. */+ extent: [number, number, number];+ radius: number;+ usedAt: number;+}++type Rgb = [number, number, number];++/** Seeded, so the pile is the same on every page load. */+function randomFrom(seed: number): () => number {+ return () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) / 4294967296;+}++/** A tileable texture of short curved fibers, for the compressed pile around the eye sockets. */+function fiberTile(): HTMLCanvasElement {+ const size = 128;+ const tile = document.createElement('canvas');+ tile.width = tile.height = size;+ const g = tile.getContext('2d')!;+ g.fillStyle = '#252525';+ g.fillRect(0, 0, size, size);+ g.lineCap = 'round';+ const random = randomFrom(9213);+ for (let i = 0; i < 1400; i++) {+ const x = random() * size, y = random() * size;+ const angle = 2.4 * Math.sin((y * Math.PI) / 32) + 1.4 * Math.cos((x * Math.PI) / 32) + (random() - 0.5) * 3.3;+ const dx = Math.cos(angle), dy = Math.sin(angle), length = 3 + random() * 8, curl = (random() - 0.5) * length;+ const grey = Math.round(55 + 200 * random());+ g.strokeStyle = `rgb(${grey} ${grey} ${grey})`;+ g.lineWidth = 0.8 + random() * 1.5;+ // Draw each fiber on every neighboring tile it reaches into, so the edges wrap.+ for (const ox of [-size, 0, size]) for (const oy of [-size, 0, size]) {+ if (x + ox < -12 || x + ox > size + 12 || y + oy < -12 || y + oy > size + 12) continue;+ g.beginPath();+ g.moveTo(x + ox, y + oy);+ g.quadraticCurveTo(x + ox + dx * length * 0.5 - dy * curl, y + oy + dy * length * 0.5 + dx * curl, x + ox + dx * length, y + oy + dy * length);+ g.stroke();+ }+ }+ return tile;+}++/** Random root density in a repeating cube: a volume has no UV seams or poles. */+function rootVolume(side: number): Uint8Array {+ const roots = new Uint8Array(side ** 3);+ let seed = 73021;+ for (let i = 0; i < roots.length; i++) {+ seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;+ roots[i] = seed >>> 24;+ }+ return roots;+}++function link(gl: WebGL2RenderingContext, vertex: string, fragment: string): WebGLProgram {+ const program = gl.createProgram()!;+ for (const [kind, source] of [[gl.VERTEX_SHADER, vertex], [gl.FRAGMENT_SHADER, fragment]] as const) {+ const shader = gl.createShader(kind)!;+ gl.shaderSource(shader, source);+ gl.compileShader(shader);+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(shader) ?? 'shader compilation failed');+ gl.attachShader(program, shader);+ gl.deleteShader(shader);+ }+ gl.linkProgram(program);+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(program) ?? 'shader linking failed');+ return program;+}++/** Reads any CSS color as RGB bytes. */+function colorReader(): (color: string) => Rgb {+ const canvas = document.createElement('canvas');+ canvas.width = canvas.height = 1;+ const ctx = canvas.getContext('2d', { willReadFrequently: true })!;+ const known = new Map<string, Rgb>();+ return (color) => {+ let rgb = known.get(color);+ if (!rgb) {+ ctx.clearRect(0, 0, 1, 1);+ ctx.fillStyle = '#000';+ ctx.fillStyle = color;+ ctx.fillRect(0, 0, 1, 1);+ const [r, g, b] = ctx.getImageData(0, 0, 1, 1).data;+ rgb = [r, g, b];+ if (known.size >= 64) known.clear();+ known.set(color, rgb);+ }+ return rgb;+ };+}++type Renderer = (shape: FluffyShape, view: ViewBasis, look: FluffyLook, scale: number) => FluffyImage | null;++/** Null without WebGL2. Throws if the shaders don't compile. */+function createRenderer(onContextRestored: () => void): Renderer | null {+ const canvas = document.createElement('canvas');+ // Square, and only ever grown (see below).+ canvas.width = canvas.height = MIN_PIXELS;+ const gl = canvas.getContext('webgl2', { alpha: true, antialias: true, premultipliedAlpha: true, preserveDrawingBuffer: true });+ if (!gl) return null;+ // A lost context returns no image until the browser restores it; the avatar draws flat meanwhile.+ canvas.addEventListener('webglcontextlost', (event) => event.preventDefault());+ canvas.addEventListener('webglcontextrestored', onContextRestored);++ const program = link(gl, vertexShader, fragmentShader);+ gl.useProgram(program);+ const uniform = (name: string) => gl.getUniformLocation(program, name);+ const u = {+ view: uniform('view'), pivot: uniform('pivot'), extent: uniform('extent'), radius: uniform('radius'),+ shell: uniform('shell'), strandWidth: uniform('strandWidth'), pass: uniform('pass'), color: uniform('color'), ink: uniform('ink'),+ eyeRegion: uniform('eyeRegion[0]'), eyeSize: uniform('eyeSize[0]'),+ };+ gl.enable(gl.DEPTH_TEST);+ gl.depthFunc(gl.LEQUAL);+ gl.enable(gl.SCISSOR_TEST);++ // Texture units: 0 fibers, 1 eye distance tiles, 2 root density, 3 dye ramp.+ const texture = (unit: number, sampler: string, target: number) => {+ gl.activeTexture(gl.TEXTURE0 + unit);+ gl.bindTexture(target, gl.createTexture());+ gl.uniform1i(uniform(sampler), unit);+ };+ const clampLinear = () => {+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ };+ texture(0, 'pile', gl.TEXTURE_2D);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, fiberTile());+ gl.generateMipmap(gl.TEXTURE_2D);+ texture(2, 'brushedPile', gl.TEXTURE_3D);+ const side = 64;+ gl.texImage3D(gl.TEXTURE_3D, 0, gl.R8, side, side, side, 0, gl.RED, gl.UNSIGNED_BYTE, rootVolume(side));+ gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);+ gl.generateMipmap(gl.TEXTURE_3D);+ texture(3, 'dyeRamp', gl.TEXTURE_2D);+ gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA8, DYE_RAMP_SIZE, 1);+ clampLinear();+ // Last, so its unit stays active: the eyes' tiles sit side by side, and change the most.+ texture(1, 'eyeField', gl.TEXTURE_2D);+ gl.texStorage2D(gl.TEXTURE_2D, 1, gl.R8, 2 * SOCKET_TILE, SOCKET_TILE);+ clampLinear();++ // --- Meshes -------------------------------------------------------------------------------------++ const geometries = new Map<FluffyShape, Geometry>();+ let sweepPending = false;++ const upload = (shape: FluffyShape): Geometry => {+ const mesh = buildMesh(shape);+ const buffer = (target: number, data: Float32Array | Uint32Array) => {+ const b = gl.createBuffer();+ gl.bindBuffer(target, b);+ gl.bufferData(target, data, gl.STATIC_DRAW);+ return b;+ };+ const attributes = (stride: number, sizes: number[], perInstance: boolean) => {+ let offset = 0;+ sizes.forEach((size, location) => {+ gl.enableVertexAttribArray(location);+ gl.vertexAttribPointer(location, size, gl.FLOAT, false, stride, offset);+ if (perInstance) gl.vertexAttribDivisor(location, 1);+ offset += 4 * size;+ });+ };+ // The body and its shells: position and normal per vertex.+ const surface = gl.createVertexArray();+ gl.bindVertexArray(surface);+ const vertices = buffer(gl.ARRAY_BUFFER, mesh.vertices);+ attributes(24, [3, 3], false);+ const indices = buffer(gl.ELEMENT_ARRAY_BUFFER, mesh.indices);+ // The strands: one instance per root (position, normal, two random numbers); the shader+ // shapes its eight vertices from gl_VertexID.+ const strands = gl.createVertexArray();+ gl.bindVertexArray(strands);+ const roots = buffer(gl.ARRAY_BUFFER, mesh.roots);+ attributes(32, [3, 3, 2], true);++ const b = shape.bounds, rx = (b.maxX - b.minX) / 2, ry = (b.maxY - b.minY) / 2, rz = halfDepth(shape);+ return {+ surface, strands, buffers: [vertices, indices, roots],+ coarse: mesh.coarse, fine: mesh.fine, strandCount: mesh.roots.length / 8,+ cx: b.minX + rx, cy: b.minY + ry, extent: [rx, ry, rz], radius: Math.ceil(Math.hypot(rx, ry, rz) + PILE_REACH), usedAt: 0,+ };+ };++ /** Free the meshes that have not been drawn for a while, beyond the few most recent. */+ const sweep = () => {+ const now = performance.now();+ for (const [shape, geometry] of geometries) {+ if (geometries.size <= KEPT_MESHES) return;+ if (now - geometry.usedAt < IDLE_MS) continue;+ gl.deleteVertexArray(geometry.surface);+ gl.deleteVertexArray(geometry.strands);+ geometry.buffers.forEach((b) => gl.deleteBuffer(b));+ geometries.delete(shape);+ }+ // Stills paint once: without another frame, nothing else would come back for theirs.+ if (!sweepPending) {+ sweepPending = true;+ setTimeout(() => {+ sweepPending = false;+ sweep();+ }, IDLE_MS);+ }+ };++ const geometryOf = (shape: FluffyShape): Geometry => {+ let geometry = geometries.get(shape);+ if (geometry) geometries.delete(shape);+ else geometry = upload(shape);+ // Most recently drawn last.+ geometries.set(shape, geometry);+ geometry.usedAt = performance.now();+ if (geometries.size > KEPT_MESHES) sweep();+ return geometry;+ };++ // --- Eyes ---------------------------------------------------------------------------------------++ const regions = new Float32Array(8), sizes = new Float32Array(4);+ const scratch = document.createElement('canvas');+ scratch.width = scratch.height = SOCKET_TILE;+ const scratchCtx = scratch.getContext('2d', { willReadFrequently: true })!;+ /** Distance tiles by contour: both eyes usually share one, and an avatar returns to the same few. */+ const tiles = new Map<string, Uint8Array<ArrayBuffer>>();+ const tileOf = (mark: EyeMark, key: string) => {+ let tile = tiles.get(key);+ if (!tile) {+ tile = socketTile(scratchCtx, mark);+ if (tiles.size >= 48) tiles.delete(tiles.keys().next().value!);+ tiles.set(key, tile);+ }+ return tile;+ };++ // --- What the canvas shows, and what is on the GPU ----------------------------------------------++ const readColor = colorReader();+ const shown = {+ geometry: null as Geometry | null, view: null as ViewBasis | null, pixels: 0, color: '', ink: '',+ regions: new Float32Array(8), contours: ['', ''],+ };+ let dye = '';++ return (shape, view, look, scale) => {+ if (gl.isContextLost()) return null;+ const geometry = geometryOf(shape);+ const { cx, cy, radius } = geometry;+ const pixels = Math.min(MAX_PIXELS, Math.max(MIN_PIXELS, Math.ceil(2 * radius * scale)));+ // Avatars of different sizes take turns in the canvas: it only grows, since resizing it+ // allocates its buffers anew. Each image sits in the corner WebGL counts from, the lower left.+ if (canvas.width < pixels) canvas.width = canvas.height = pixels;+ const image = { canvas, x: 0, y: canvas.height - pixels, size: pixels, cx, cy, radius };++ // The sockets: where each eye is, and its contour's distance tile.+ const eyeZ = 'eyeZ' in shape ? shape.eyeZ : [];+ regions.fill(0);+ const contours = ['', ''];+ look.eyes.forEach(({ mark, dx, dy }, slot) => {+ const region = socketRegion(mark);+ regions.set([region.cx + dx, region.cy + dy, region.span, eyeZ[slot] + SOCKET_RISE], 4 * slot);+ sizes.set([region.w, region.h * exposedHeight(region.w, region.h)], 2 * slot);+ contours[slot] = socketKey(mark);+ });++ // Root motion is composited by the painter, so only a turn of the surface or a change of+ // look needs a new image.+ const turn = shown.view+ ? Math.abs(view.cY - shown.view.cY) + Math.abs(view.sY - shown.view.sY) + Math.abs(view.sP - shown.view.sP) + Math.abs(view.cP - shown.view.cP)+ : Infinity;+ if (+ shown.geometry === geometry && shown.pixels === pixels && shown.color === look.color && shown.ink === look.ink &&+ contours.every((key, slot) => key === shown.contours[slot]) && regions.every((value, i) => value === shown.regions[i]) &&+ turn < SAME_VIEW / (radius * scale)+ ) {+ return image;+ }+ shown.geometry = geometry;+ shown.view = view;+ shown.pixels = pixels;+ shown.color = look.color;+ shown.ink = look.ink;+ shown.regions.set(regions);++ look.eyes.forEach(({ mark }, slot) => {+ if (contours[slot] === shown.contours[slot]) return;+ gl.texSubImage2D(gl.TEXTURE_2D, 0, slot * SOCKET_TILE, 0, SOCKET_TILE, SOCKET_TILE, gl.RED, gl.UNSIGNED_BYTE, tileOf(mark, contours[slot]));+ });+ shown.contours = contours;+ gl.uniform4fv(u.eyeRegion, regions);+ gl.uniform2fv(u.eyeSize, sizes);++ const [r, g, b] = readColor(look.color);+ gl.uniform3f(u.color, r / 255, g / 255, b / 255);+ if (dye !== look.color) {+ gl.activeTexture(gl.TEXTURE3);+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, DYE_RAMP_SIZE, 1, gl.RGBA, gl.UNSIGNED_BYTE, dyeRamp([r, g, b]));+ gl.activeTexture(gl.TEXTURE1);+ dye = look.color;+ }+ const [inkR, inkG, inkB] = readColor(look.ink);+ gl.uniform3f(u.ink, inkR / 255, inkG / 255, inkB / 255);++ gl.uniform3f(u.pivot, cx, cy, 0);+ gl.uniform3fv(u.extent, geometry.extent);+ gl.uniform1f(u.radius, radius);+ // Rotation by yaw, then pitch, as columns.+ gl.uniformMatrix3fv(u.view, false, [view.cY, view.sY * view.sP, -view.sY * view.cP, 0, view.cP, view.sP, view.sY, -view.cY * view.sP, view.facing]);++ gl.viewport(0, 0, pixels, pixels);+ gl.scissor(0, 0, pixels, pixels);+ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);+ const { shells, strandPasses, fineSockets } = fluffyDetail(scale);+ const triangles = fineSockets ? geometry.fine : geometry.coarse;+ gl.bindVertexArray(geometry.surface);+ gl.uniform1i(u.pass, PASS.body);+ gl.drawElements(gl.TRIANGLES, triangles.count, gl.UNSIGNED_INT, 4 * triangles.start);+ gl.uniform1i(u.pass, PASS.shell);+ for (let layer = 1; layer <= shells; layer++) {+ gl.uniform1f(u.shell, layer / shells);+ gl.drawElements(gl.TRIANGLES, triangles.count, gl.UNSIGNED_INT, 4 * triangles.start);+ }+ gl.bindVertexArray(geometry.strands);+ gl.uniform1i(u.pass, PASS.strand);+ gl.uniform1f(u.strandWidth, ROOT_PASSES / strandPasses);+ gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 8, rootsIn(geometry.strandCount, strandPasses));+ return image;+ };+}++let renderer: Renderer | null | undefined;++/**+ * Render `shape` under `view` at `scale` pixels per viewBox unit. Null where fluffy can't be+ * drawn (no WebGL2, or its context is lost): the caller paints flat instead.+ */+export function renderFluffy(shape: FluffyShape, view: ViewBasis, look: FluffyLook, scale: number): FluffyImage | null {+ if (renderer === undefined) {+ renderer = null;+ try {+ // After a restore everything on the GPU is gone: start over on the next frame.+ renderer = createRenderer(() => (renderer = undefined));+ } catch (error) {+ console.warn('open-bot-avatar: fluffy is unavailable, drawing flat', error);+ }+ }+ return renderer?.(shape, view, look, scale) ?? null;+}diff --git a/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/shaders.ts b/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/shaders.tsnew file mode 100644index 0000000000..56eb0d94d1--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/shaders.ts@@ -0,0 +1,284 @@+/**+ * The fluffy shaders. One program draws three kinds of geometry, chosen by `pass`: the body's+ * solid surface with the eyes seated in it, shells of pile lifted off that surface, and single+ * strands on top. All three sample the same model-space pile, so the coat holds together as the+ * avatar turns.+ */+import { DYE_RAMP_RANGE } from './dye.ts';+import { SOCKET_PAD } from './socket.ts';++/** The values of the `pass` uniform. */+export const PASS = { body: 0, shell: 1, strand: 2 } as const;++/** A number as a GLSL float literal. */+const float = (n: number) => (Number.isInteger(n) ? `${n}.` : `${n}`);++const passes = `const int BODY = ${PASS.body}, SHELL = ${PASS.shell}, STRAND = ${PASS.strand};`;++// Distance to the nearer eye's contour, viewBox units, from the eyes' distance tiles (see+// socket.ts). Coordinates stay on the avatar's front surface, so a socket turns with the head.+const socketField = `+uniform highp sampler2D eyeField;+uniform vec4 eyeRegion[2]; // face-plane center, square span, maximum host depth+uniform vec2 eyeSize[2];+const float FAR = ${float(SOCKET_PAD)};++float socketDistance(vec3 p, vec3 normal, out vec2 uv, out vec3 local) {+ uv = vec2(0.);+ local = vec3(0.);+ if (normal.z < .03 || p.z < -.05) return FAR;+ for (int i = 0; i < 2; i++) {+ vec4 e = eyeRegion[i];+ vec2 delta = p.xy - e.xy;+ if (e.z > 0. && p.z <= e.w && max(abs(delta.x), abs(delta.y)) < e.z * .49) {+ vec2 coords = delta / e.z;+ vec2 sampleUV = (coords + .5 + vec2(float(i), 0.)) * vec2(.5, 1.);+ float d = (textureLod(eyeField, sampleUV, 0.).r - .5) * ${float(2 * SOCKET_PAD)};+ if (d >= 3.77) continue;+ uv = sampleUV;+ local.xy = 2. * delta / max(eyeSize[i], vec2(.01));+ // As lids close, the pressed lip narrows with the expression.+ local.z = smoothstep(.35, 1.5, eyeSize[i].y / max(.01, eyeSize[i].x));+ return d * mix(1.5, 1., local.z);+ }+ }+ return FAR;+}`;++export const vertexShader = `#version 300 es+precision highp float;+precision highp int;+layout(location = 0) in vec3 position;+layout(location = 1) in vec3 normal;+layout(location = 2) in vec2 seed;+uniform mat3 view;+uniform vec3 pivot, extent;+uniform float radius, shell;+uniform float strandWidth; // 1 at full detail; wider where fewer strands are drawn+uniform int pass;+out vec3 P, N, V, pilePosition, lean;+out float tip, variation, across, pocketDepth;+${passes}+${socketField}++void main() {+ vec3 n = normalize(normal), p = position;+ vec3 rounded = (position - pivot) / extent;+ // Broadly bend the lighting normals across flat front faces of inflated paths.+ vec3 shadingNormal = normalize(n + .78 * rounded);+ pilePosition = position;+ // Sweep across the visible surface. A downwards bias keeps the front from parting at a point.+ // Project without normalizing, so foreshortened locks get shorter continuously at a grazing angle.+ float wave = .21 * sin(dot(position, vec3(.11, .045, .08))) + .14 * sin(.13 * position.y - .07 * position.z);+ float angle = .22 + .94 * (view * shadingNormal).x + wave;+ vec3 sweep = transpose(view) * vec3(sin(angle), cos(angle), .18);+ lean = sweep - n * dot(n, sweep);++ vec2 uv;+ vec3 local;+ float d = socketDistance(position, n, uv, local);+ float seat = min(1.55, max(0., position.z) * .40);+ // The rounded cap sits below the packed pile at the mouth of the socket. At grazing angles the+ // near lip progressively hides the bead.+ float dome = sqrt(max(0., 1. - dot(local.xy, local.xy)));+ float cap = mix(smoothstep(0., 1.3, -d), dome, local.z) * smoothstep(-.15, .38, -d);+ float floorDepth = 1. - smoothstep(-.15, 1.65, d);+ p.z += seat * (.56 * cap - .98 * floorDepth);+ // Compressed fibers lie along the lip. The packed undercoat fills most of their height here, so+ // the opening has a continuous, softly fuzzy edge.+ float loft = mix(.07, 1., smoothstep(.75, 3.7, d));+ float lip = smoothstep(-.10, 1., d) * (1. - smoothstep(1., 2.85, d));+ if (pass == BODY) p.z += seat * .15 * lip;+ pilePosition.z = p.z;++ tip = 0.;+ variation = .5;+ across = 0.;+ if (pass == SHELL) {+ p += n * shell * 1.10 * loft;+ p += lean * (1.05 * shell * loft);+ }+ if (pass == STRAND) {+ // Four cross-sections make a bent, tapered strand. Roots are fixed in model space.+ tip = float(gl_VertexID / 2) / 3.;+ across = float(gl_VertexID % 2) * 2. - 1.;+ vec3 tangent = normalize(cross(n, abs(n.y) < .93 ? vec3(0, 1, 0) : vec3(1, 0, 0)));+ vec3 bitangent = cross(n, tangent);+ float flow = 2.3 * sin(.24 * p.x + .13 * p.z + sin(.22 * p.y)) + 1.3 * sin(.32 * p.y - .15 * p.x);+ float angle = flow + (seed.x - .5) * 2.6;+ vec3 comb = lean + .24 * (tangent * cos(angle) + bitangent * sin(angle));+ if (d < 3.5) {+ // Around a socket the strands lie along its edge.+ vec2 radial = normalize(local.xy * vec2(1.7, 1.) + vec2(.001));+ vec2 alongEdge = vec2(-radial.y, radial.x);+ comb.xy = mix(comb.xy, alongEdge * (dot(comb.xy, alongEdge) < 0. ? -1. : 1.), .88 * (1. - smoothstep(.4, 3.5, d)));+ }+ vec3 bend = cross(n, comb);+ float len = mix(1.6, 3.8, seed.y) * loft;+ vec3 direction = n * (.30 + .18 * tip) + comb * (.93 - .12 * tip) + bend * (seed.x - .5) * .45 * tip;+ pilePosition += comb * (.7 * len * tip);+ p += n * .52 * loft;+ float width = (.073 + .11 * seed.y) * strandWidth;+ p += .065 * n + len * tip * direction;+ vec3 screenDir = view * (direction + .06 * comb);+ vec2 widthDir = normalize(vec2(-screenDir.y, screenDir.x) + vec2(.0001, 0));+ p += transpose(view) * vec3(widthDir * across * width * (1. - .94 * tip), 0);+ shadingNormal = normalize(shadingNormal + .19 * comb);+ variation = seed.x;+ }++ vec3 projected = view * (p - pivot);+ pocketDepth = dot(position - p, n) / max(.01, seat);+ // Test displaced shells and strand tips in the socket's model-space footprint. Their visibility+ // against the bead follows actual depth.+ P = vec3(p.xy, position.z);+ N = view * shadingNormal;+ V = normal;+ gl_Position = vec4(projected.x, -projected.y, -projected.z, radius) / radius;+}`;++export const fragmentShader = `#version 300 es+precision highp float;+precision highp int;+uniform sampler2D pile;+uniform sampler2D dyeRamp;+uniform highp sampler3D brushedPile;+uniform vec3 color, ink;+uniform mat3 view;+uniform int pass;+uniform float shell;+in vec3 P, N, V, pilePosition, lean;+in float tip, variation, across, pocketDepth;+out vec4 result;+${passes}+${socketField}++float fiberMap(vec3 p, vec3 n) {+ vec3 w = pow(abs(n), vec3(5.));+ w /= max(.001, w.x + w.y + w.z);+ return dot(w, vec3(texture(pile, p.zy / 16.).r, texture(pile, p.xz / 16.).r, texture(pile, p.xy / 16.).r));+}++// Sample the same model-space roots at every view: only the direction of the short filter+// changes. The solid coat, the shells and the strands all use this one field.+float brushedHeight() {+ vec3 uvw = pilePosition / 15.;+ vec3 stepUV = lean * .019;+ float locks = 4. * texture(brushedPile, uvw).r;+ for (int i = 1; i <= 3; i++) {+ vec3 delta = float(i) * stepUV;+ locks += (4. - float(i)) * (texture(brushedPile, uvw + delta).r + texture(brushedPile, uvw - delta).r);+ }+ float tuft = texture(brushedPile, uvw * .42).r;+ return clamp(.5 + 1.65 * (locks / 16. - .5) + .16 * (tuft - .5), 0., 1.);+}++void main() {+ vec3 n = normalize(N);+ vec3 light = normalize(vec3(-.52, -.83, .62));+ float diffuse = dot(n, light);+ float wrap = clamp((diffuse + .65) / 1.65, 0., 1.);+ float facingLight = clamp(.66 + .34 * diffuse, 0., 1.);+ float diffuseLevel = .87 + .13 * wrap;+ float sheen = .014 * wrap * wrap;+ float rimExposure = 1.;++ // Pile gives way to the eye.+ vec2 uv;+ vec3 local;+ float d = socketDistance(P, normalize(V), uv, local);+ if (pass == SHELL && d < .1) discard;+ if (pass == STRAND && d < .10 - .08 * variation) discard;++ float height = brushedHeight();+ // Density variation survives rim lighting even when the strongest dye channel is saturated.+ float pileFill = .925 + .075 * smoothstep(.22, .81, height);+ if (pass == STRAND) {+ // MSAA can evaluate a subpixel ribbon outside its edges at the pixel center.+ float edge = min(1., abs(across));+ float glint = smoothstep(.08, .82, tip) * (1. - .32 * edge * edge);+ diffuseLevel *= .935 + .11 * variation + .035 * clamp(tip, 0., 1.);+ sheen += (.012 + .20 * glint) * (.44 + .56 * variation) * facingLight;+ } else {+ float layer = pass == SHELL ? shell : 0.;+ // A shell keeps only the locks that reach its height.+ if (pass == SHELL && height < .21 + .59 * layer) discard;+ // The solid backing is dyed as brightly as the roots. Relief is mostly from the softly lit+ // crests of neighboring locks.+ diffuseLevel *= .895 + .16 * height + .035 * layer;+ sheen += (.012 + .13 * smoothstep(.41, .86, height) + .022 * layer) * facingLight;+ rimExposure = .80 + .34 * layer;+ }++ // A soft light behind the right shoulder grazes the pile. Weighting by view angle confines it+ // to the silhouette as the avatar turns.+ float grazing = 1. - smoothstep(.09, .83, abs(n.z));+ float backlit = smoothstep(-.20, .79, dot(n.xy, vec2(.66, -.75)));++ // Around a socket: a crease where the pile is pressed down, and light on its rolled lip.+ float upper = 0., crease = 0., pileRelief = 0., contact = 0., lipLight = 0.;+ if (d < 3.7) {+ vec2 texel = 1. / vec2(textureSize(eyeField, 0));+ vec2 g = vec2(texture(eyeField, uv + vec2(texel.x, 0)).r - texture(eyeField, uv - vec2(texel.x, 0)).r,+ texture(eyeField, uv + vec2(0, texel.y)).r - texture(eyeField, uv - vec2(0, texel.y)).r);+ vec2 outward = g / max(length(g), .001);+ upper = dot(outward, normalize(vec2(.96, -.28)));+ float fibers = fiberMap(P, normalize(V));+ // Only material below the mouth picks up the deep socket color. Tips which cover the eye in+ // profile keep the dye of the exposed coat.+ float buried = smoothstep(-.12, .82, pocketDepth);+ crease = (1. - smoothstep(-.12, 1.65 + 1.30 * upper + .6 * (fibers - .5), d)) * mix(.24, 1., buried);+ if (pass == STRAND) {+ // The rolled lip reveals brighter tips above a darker, compressed undercoat.+ pileRelief = ((tip - .46) * .16 + (fibers - .48) * .11) * (1. - smoothstep(1.5, 3.65, d));+ }+ contact = (1. - smoothstep(-.04, .38, d)) * mix(.35, 1., buried);+ float lip = smoothstep(.03, .49, d) * (1. - smoothstep(1.10, 3.65, d));+ float gathered = clamp(.22 - .52 * outward.x + 1.14 * outward.y, 0., 1.22);+ float tipLight = .14 + .22 * fibers;+ lipLight = tipLight * gathered * lip * mix(.40, 1., local.z);+ }+ float occlusion = crease * (.76 + .18 * upper);+ float fiberLight = (sheen + .46 * grazing * backlit * rimExposure) * (1. - crease) + lipLight;+ diffuseLevel = (diffuseLevel * (1. - .48 * occlusion) + pileRelief) * (1. - (.36 + .04 * upper) * contact);++ // Light falling on the body reveals its curvature. Light caught by raised fibers can carry on+ // above the nominal exposure of the dye.+ float backing = diffuseLevel * pileFill;+ float exposure = backing * backing * (.72 + .39 * wrap) + 1.45 * fiberLight * pileFill;+ vec4 ramp = texture(dyeRamp, vec2(exposure / ${float(DYE_RAMP_RANGE)}, .5));+ vec3 base = ramp.rgb;+ if (ramp.a > 0.) {+ // On yellow, the dyed roots and the light scattered by the tips can have the same lightness+ // and still differ in color.+ float value = max(color.r, max(color.g, color.b));+ vec3 dye = color / max(value, .001);+ float weakest = min(dye.r, min(dye.g, dye.b));+ vec3 scatter = (1. - dye) * (.09 + .91 * (dye - weakest)) * clamp(1.85 * fiberLight, 0., 1.);+ float brightness = clamp(value * diffuseLevel + (.35 + .65 * value) * fiberLight, 0., 1.);+ base = mix(base, (dye + scatter) * brightness * pileFill, ramp.a);+ }++ if (pass == BODY && d < 3.7) {+ // The eye: a glossy bead in the socket.+ vec2 curve = local.xy * .94;+ vec3 dome = normalize(vec3(curve, sqrt(max(.02, 1. - dot(curve, curve)))));+ vec3 beadNormal = normalize(view * dome);+ // The high strip reflects mostly the light source. The softer side fill picks up more of the+ // nearby coat as the bead turns.+ vec2 key = beadNormal.xy - vec2(.59, -.865);+ key = vec2(key.x - .76 * key.y, key.y) / vec2(.55, .70);+ vec2 fill = beadNormal.xy - vec2(.61, -.195);+ fill = vec2(fill.x - .37 * fill.y, fill.y) / vec2(.47, 1.01);+ float stripLight = .38 * exp(-dot(key, key));+ float sideLight = .13 * exp(-dot(fill, fill));+ float coatBounce = .003 + .018 * pow(1. - clamp(beadNormal.z, 0., 1.), 1.6);+ float inkValue = max(ink.r, max(ink.g, ink.b));+ vec3 bead = ink * sqrt(inkValue) * (.40 + .24 * beadNormal.z + .24 * inkValue) + color * coatBounce;+ vec3 reflection = mix(vec3(1.), color, .28) * stripLight + mix(vec3(1.), color, .72) * sideLight;+ bead += reflection * smoothstep(-.12, .55, -d);+ float aa = max(.15, fwidth(d));+ base = mix(bead, base, smoothstep(-aa * .5, aa * .5, d));+ }+ result = vec4(base, 1.);+}`;diff --git a/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/socket.ts b/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/socket.tsnew file mode 100644index 0000000000..b97cbf66fd--- /dev/null+++ b/packages/phone-protocol/src/open-bot-avatar/dom/fluffy/socket.ts@@ -0,0 +1,126 @@+/**+ * Fluffy eyes are beads seated in sockets pressed into the coat. A socket follows its eye's+ * contour through every shape the eye takes, so the shader reads the contour as a small+ * distance field: one square tile per eye, re-made only when the contour changes.+ */+import type { EyeMark } from '../../render.ts';+import { eyeBox, paintEye } from '../eye.ts';++/** Width and height of a tile, pixels. */+export const SOCKET_TILE = 96;+/** How far around an eye the coat is pressed down, viewBox units. Also the range of the distance field. */+export const SOCKET_PAD = 3.8;++/** The share of a bead's height that shows: an open bead is partly buried, a shallower expression keeps its arc. */+export function exposedHeight(w: number, h: number): number {+ const openness = Math.max(0, Math.min(1, h / w - 1));+ return 0.8 - 0.175 * openness;+}++/** Where a socket sits around its eye: the eye's center and size, and the width of the square its tile covers. */+export interface SocketRegion {+ cx: number;+ cy: number;+ w: number;+ h: number;+ span: number;+}++function regionOf(mark: EyeMark): SocketRegion {+ const { x, y, w, h } = eyeBox(mark);+ return { cx: x + w / 2, cy: y + h / 2, w, h, span: Math.max(w, h) + 2 * SOCKET_PAD };+}++// An outline's box is parsed from its path, and an eye holds one outline for many frames.+const outlineRegions = new Map<string, SocketRegion>();++export function socketRegion(mark: EyeMark): SocketRegion {+ if (mark.shape === 'pill') return regionOf(mark);+ const key = socketKey(mark);+ let region = outlineRegions.get(key);+ if (!region) {+ region = regionOf(mark);+ if (outlineRegions.size >= 16) outlineRegions.clear();+ outlineRegions.set(key, region);+ }+ return region;+}++/**+ * What a tile depends on: the eye's contour, wherever it is. A pill is the same contour at both+ * eyes; other marks are outlines in face coordinates, one per eye.+ */+export function socketKey(mark: EyeMark): string {+ if (mark.shape === 'pill') return `${mark.width}|${mark.height}|${mark.radius}`;+ return mark.shape === 'arc' ? `${mark.strokeWidth}|${mark.d}` : mark.d;+}++/**+ * Signed distance to the eye's seated contour, in units of 2 × SOCKET_PAD around 0.5 (inside is+ * below), one byte per pixel. `ctx` is a scratch canvas of SOCKET_TILE pixels.+ */+export function socketTile(ctx: CanvasRenderingContext2D, mark: EyeMark): Uint8Array<ArrayBuffer> {+ const size = SOCKET_TILE;+ const { cx, cy, span, w, h } = socketRegion(mark);+ const scale = size / span;+ const exposure = exposedHeight(w, h);+ ctx.resetTransform();+ ctx.clearRect(0, 0, size, size);+ ctx.setTransform(scale, 0, 0, scale, size / 2 - cx * scale, size / 2 - cy * scale);+ ctx.lineCap = 'round';+ ctx.fillStyle = ctx.strokeStyle = '#fff';+ // The surrounding nap hides a little of the top and bottom of the bead.+ ctx.translate(cx, cy);+ ctx.scale(1, exposure);+ ctx.translate(-cx, -cy);+ paintEye(ctx, mark);+ const rgba = ctx.getImageData(0, 0, size, size).data;++ // Round out the straight sides of the stadium into a soft bead profile, and apply the same+ // continuous warp to the contours between expressions.+ const coverage = new Uint8Array(size * size);+ const cap = Math.min(1, w / h);+ for (let y = 0; y < size; y++) {+ const v = Math.min(0.9999, Math.abs((y + 0.5 - size / 2) / ((scale * h * exposure) / 2)));+ const capY = Math.max(0, (v - 1 + cap) / cap);+ const stadium = Math.sqrt(1 - capY * capY);+ const oval = Math.pow(1 - Math.pow(v, 2.2), 1 / 2.2);+ const taper = h > w ? Math.min(1, oval / stadium) : 1;+ // A slight cant in the seated oval is most visible on an open eye.+ const cant = 0.04 * Math.max(0, 1 - cap) * (y + 0.5 - size / 2);+ for (let x = 0; x < size; x++) {+ const source = (x + 0.5 - size / 2 - cant) / taper + size / 2 - 0.5;+ const i = Math.floor(source);+ if (i < 0 || i + 1 >= size) continue;+ const offset = 4 * (y * size + i) + 3;+ coverage[y * size + x] = Math.round(rgba[offset] + (rgba[offset + 4] - rgba[offset]) * (source - i));+ }+ }++ // Start on each side of the antialiased boundary, then sweep the distance out both ways.+ const distance = new Float32Array(size * size).fill(size);+ for (let i = size + 1; i < distance.length - size - 1; i++) {+ const a = coverage[i] / 255;+ const inside = a >= 0.5;+ if (+ (a > 0 && a < 1) ||+ (coverage[i - 1] >= 128) !== inside || (coverage[i + 1] >= 128) !== inside ||+ (coverage[i - size] >= 128) !== inside || (coverage[i + size] >= 128) !== inside+ ) {+ distance[i] = Math.abs(a - 0.5);+ }+ }+ for (const step of [1, -1]) {+ for (let j = 1; j < size - 1; j++) for (let k = 1; k < size - 1; k++) {+ const i = step === 1 ? j * size + k : (size - 1 - j) * size + size - 1 - k;+ const prev = i - size * step;+ distance[i] = Math.min(distance[i], distance[i - step] + 1, distance[prev] + 1, distance[prev - 1] + Math.SQRT2, distance[prev + 1] + Math.SQRT2);+ }+ }+ const tile = new Uint8Array(distance.length);+ for (let i = 0; i < tile.length; i++) {+ const signed = ((coverage[i] >= 128 ? -1 : 1) * distance[i]) / scale;+ tile[i] = Math.round(255 * Math.max(0, Math.min(1, 0.5 + signed / (2 * SOCKET_PAD))));+ }+ return tile;+}diff --git a/packages/phone-protocol/src/open-bot-avatar/dom/mount.ts b/packages/phone-protocol/src/open-bot-avatar/dom/mount.tsindex e5445da619..e1700b78e0 100644--- a/packages/phone-protocol/src/open-bot-avatar/dom/mount.ts+++ b/packages/phone-protocol/src/open-bot-avatar/dom/mount.ts@@ -9,15 +9,15 @@* layer and a small bitmap per avatar. `renderer: 'scene'` mounts a CSS 3D scene* instead, where every cross-section is its own small SVG and each frame only* writes a few CSS transforms; it costs a compositor layer per visible slice,- * and is also the fallback where canvas is unavailable. `still` avatars are a- * single static SVG and never animate. Every avatar on the page shares one+ * and is also the fallback where canvas is unavailable. `still` avatars are+ * static images and never animate. Every avatar on the page shares one* animation loop.*/import { createAnimator } from '../animator.ts';import { pointerGaze } from '../follow.ts';import { resolveLook } from '../motion.ts';import { DEFAULT_COLOR, DEFAULT_EYE_COLOR, liveFrame, renderAvatarScene, renderAvatarSvg, sceneFrame, type SceneFrame } from '../render.ts';-import type { AvatarDefinition, AvatarMood, AvatarState, RenderOptions } from '../types.ts';+import type { AvatarDefinition, AvatarMaterial, AvatarMood, AvatarState, RenderOptions } from '../types.ts';import { requestFrame, subscribeFrames } from './clock.ts';import { canvasSupported, mountCanvas, paintCanvas, type CanvasSurface } from './paint.ts';import { trackPointer } from './pointer.ts';@@ -29,6 +29,11 @@ export interface AvatarOptions {color?: string;/** Eye color: #rgb or #rrggbb, or any CSS color. Defaults to a near-black ink. */eyeColor?: string;+ /**+ * The body's finish: 'flat' (default), or 'fluffy' for a coat of fur with the eyes set into it.+ * Fluffy needs the canvas renderer and WebGL2; without them the avatar draws flat.+ */+ material?: AvatarMaterial;/** Volume amount 0..14 (6 = natural depth, 0 = flat). */depth?: number;/** What the bot is doing (default `idle`). Changes ease from what is on screen. */@@ -48,7 +53,7 @@ export interface AvatarOptions {view?: { yaw: number; pitch: number };/** true or false to force; 'system' (default) follows prefers-reduced-motion. */reducedMotion?: boolean | 'system';- /** Render one static SVG and never animate (thumbnails, lists). */+ /** Render one fixed pose and never animate (thumbnails, lists): a static SVG, or for fluffy one painted canvas. */still?: boolean;/*** How a live avatar draws. 'canvas' (default) paints each frame to one canvas: one compositor layer@@ -166,6 +171,12 @@ const VIEW_MARGIN = 100;/** Slack so a 60 Hz display reliably draws every other frame rather than drifting between 1 and 3. */const FRAME_SLACK = 0.004;+/**+ * The frame that last painted a fluffy still. They take turns, one a frame: the first paint of a+ * shape builds its mesh, and a gallery that changes finish asks for all of its stills at once.+ */+let fluffyStillAt = -1;+export function mountAvatar(host: HTMLElement, initial: AvatarOptions): MountedAvatar {let opts: AvatarOptions = { ...initial };const animator = createAnimator();@@ -183,6 +194,7 @@ export function mountAvatar(host: HTMLElement, initial: AvatarOptions): MountedAconst next = entry.contentRect.width;if (next === size) return;size = next;+ dirty = true;requestFrame();});resize?.observe(host);@@ -232,6 +244,22 @@ export function mountAvatar(host: HTMLElement, initial: AvatarOptions): MountedAlastStill = '';};+ /** Whether the avatar is painted in fluffy: on a canvas, live or still. */+ const fluffy = () => opts.material === 'fluffy' && opts.renderer !== 'scene' && canvasSupported();++ const paint = (p: AvatarOptions, options: RenderOptions) => {+ if (scene || lastStill) clear();+ const flat = liveFrame(p.definition, { ...options, color: p.color, eyeColor: p.eyeColor });+ const key = `${geometryKey(p.definition)}|${p.depth}`;+ if (!surface || surface.key !== key || !host.contains(surface.canvas)) surface = mountCanvas(host, key, p.definition, p.depth);+ // Any CSS color works, as in the scene: one that is not hex is read back every frame from the+ // host's computed `color` and --avatar-ink (which syncHost sets), so themes apply live.+ const css = isHex(p.color) && isHex(p.eyeColor) ? null : getComputedStyle(host);+ const fill = css && !isHex(p.color) ? css.color || flat.color : flat.color;+ const ink = css && !isHex(p.eyeColor) ? css.getPropertyValue('--avatar-ink').trim() || flat.ink : flat.ink;+ paintCanvas(surface, flat, size, fill, ink, p.material);+ };+const draw = (time: number, pointer: { x: number; y: number } | null): boolean => {const p = opts;const reducedMotion = p.reducedMotion === 'system' || p.reducedMotion === undefined ? prefersReducedMotion() : p.reducedMotion;@@ -240,8 +268,7 @@ export function mountAvatar(host: HTMLElement, initial: AvatarOptions): MountedAconst look = resolveLook({ state: p.state, mood: p.mood, motion: p.mood });try {if (p.still) {- if (scene || surface) clear();- const svg = renderAvatarSvg(p.definition, {+ const options: RenderOptions = {color: p.color,eyeColor: p.eyeColor,depth: p.depth,@@ -250,7 +277,15 @@ export function mountAvatar(host: HTMLElement, initial: AvatarOptions): MountedAview: p.view,gaze: p.lookAt ?? undefined,reducedMotion: true,- });+ };+ if (fluffy()) {+ // Nothing to paint until the host has a size; the resize that gives it one redraws.+ if (size > 0) paint(p, { ...options, size });+ failed = false;+ return false;+ }+ if (scene || surface) clear();+ const svg = renderAvatarSvg(p.definition, options);// The engine derives SVG ids from geometry, so repeated avatars can share them safely.if (svg !== lastStill) {host.innerHTML = svg;@@ -280,16 +315,7 @@ export function mountAvatar(host: HTMLElement, initial: AvatarOptions): MountedAreducedMotion,};if (p.renderer !== 'scene' && canvasSupported()) {- if (scene) clear();- const flat = liveFrame(p.definition, { ...options, color: p.color, eyeColor: p.eyeColor });- const key = `${geometryKey(p.definition)}|${p.depth}`;- if (!surface || surface.key !== key || !host.contains(surface.canvas)) surface = mountCanvas(host, key, p.definition, p.depth);- // Any CSS color works, as in the scene: one that is not hex is read back every frame from the- // host's computed `color` and --avatar-ink (which syncHost sets), so themes apply live.- const css = isHex(p.color) && isHex(p.eyeColor) ? null : getComputedStyle(host);- const fill = css && !isHex(p.color) ? css.color || flat.color : flat.color;- const ink = css && !isHex(p.eyeColor) ? css.getPropertyValue('--avatar-ink').trim() || flat.ink : flat.ink;- paintCanvas(surface, flat, size, fill, ink);+ paint(p, options);failed = false;return !reducedMotion || step.moving;}@@ -320,6 +346,10 @@ export function mountAvatar(host: HTMLElement, initial: AvatarOptions): MountedA// Stills, and live avatars out of view, only redraw after a change; live avatars in view every// frame they ask for. A change still draws offscreen, so the content is current when printed.if ((opts.still || !visible) && !dirty) return false;+ if (opts.still && size > 0 && fluffy()) {+ if (fluffyStillAt === time) return true;+ fluffyStillAt = time;+ }dirty = false;const more = draw(time, pointer);if (!visible) return false;diff --git a/packages/phone-protocol/src/open-bot-avatar/dom/paint.ts b/packages/phone-protocol/src/open-bot-avatar/dom/paint.tsindex fea4f035bc..2c6c78f1bf 100644--- a/packages/phone-protocol/src/open-bot-avatar/dom/paint.ts+++ b/packages/phone-protocol/src/open-bot-avatar/dom/paint.ts@@ -11,10 +11,17 @@** The canvas sits in a wrapper at the host's content box, as the scene does,* overhangs it by the avatar's reach and ignores the pointer.+ *+ * A fluffy avatar is painted the same way, except that its body and eyes come as one image from+ * the fluffy renderer (see fluffy/renderer.ts) in place of the slices and eye marks.*/-import { avatarExtent } from '../render.ts';-import type { AvatarFrame, EyeMark, FramePath, Matrix } from '../render.ts';-import type { AvatarDefinition } from '../types.ts';+import { avatarExtent, preparedVolume } from '../render.ts';+import type { AvatarFrame, FramePath, FrameShape, Matrix } from '../render.ts';+import type { AvatarDefinition, AvatarMaterial } from '../types.ts';+import type { Volume } from '../volume.ts';+import { eyeBox, paintEye } from './eye.ts';+import { paintFluffyMark } from './fluffy/marks.ts';+import { renderFluffy } from './fluffy/renderer.ts';/** A square in viewBox units. */export interface Square {@@ -35,6 +42,8 @@ export interface Bounds {export const FIT_SLACK = 8;/** Margin a frame keeps from the bitmap's edge for antialiasing, viewBox units. */export const FIT_PAD = 1;+/** How far a fluffy coat's pile reaches past the frame's flat bounds, viewBox units. */+const PILE_MARGIN = 3;/*** The square to lay the bitmap out over: `prev` while it still holds `b`, else `prev` grown to@@ -65,6 +74,7 @@ export function fitSquare(prev: Square | null, b: Bounds, cap: Square): Square {}interface Section {+ box: FramePath['box'];path: Path2D;rule: CanvasFillRule;}@@ -112,46 +122,13 @@ export function framePlacement(frame: AvatarFrame): { matrices: Matrix[]; boundsreturn { matrices, bounds };}-function eyeBox(mark: EyeMark): FramePath['box'] {- if (mark.shape === 'pill') return { x: mark.x, y: mark.y, w: mark.width, h: mark.height };- // Quadratics lie within their points' hull; an arc's stroke reaches half its width past it.- const reach = mark.shape === 'arc' ? mark.strokeWidth : 0;- const n = (mark.d.match(/-?\d+(?:\.\d+)?/g) ?? []).map(Number);- const xs = n.filter((_, i) => i % 2 === 0), ys = n.filter((_, i) => i % 2 === 1);- const x = Math.min(...xs) - reach, y = Math.min(...ys) - reach;- return { x, y, w: Math.max(...xs) + reach - x, h: Math.max(...ys) + reach - y };-}--function eye(ctx: CanvasRenderingContext2D, mark: EyeMark) {- if (mark.shape === 'path') {- ctx.fill(new Path2D(mark.d));- return;- }- if (mark.shape === 'arc') {- ctx.lineWidth = mark.strokeWidth;- ctx.stroke(new Path2D(mark.d));- return;- }- const { x, y, width: w, height: h, radius: r } = mark;- ctx.beginPath();- if (typeof ctx.roundRect === 'function') ctx.roundRect(x, y, w, h, r);- else {- // Safari before 16 and Firefox before 112.- ctx.moveTo(x + r, y);- ctx.arcTo(x + w, y, x + w, y + h, r);- ctx.arcTo(x + w, y + h, x, y + h, r);- ctx.arcTo(x, y + h, x, y, r);- ctx.arcTo(x, y, x + w, y, r);- ctx.closePath();- }- ctx.fill();-}-/** A mounted canvas and the square and size its bitmap was last laid out at. */export interface CanvasSurface {key: string;canvas: HTMLCanvasElement;ctx: CanvasRenderingContext2D | null;+ /** The avatar's volume, for a fluffy coat: built when first asked for. Null at depth 0, which has no surface to coat. */+ volume: (() => Volume) | null;cap: Square;fit: Square | null;layout: string;@@ -169,21 +146,39 @@ export function mountCanvas(el: HTMLElement, key: string, definition: AvatarDeficanvas.style.cssText = 'position:absolute';wrap.append(canvas);el.replaceChildren(wrap);- return { key, canvas, ctx: canvas.getContext('2d'), cap, fit: null, layout: '', left: 0, top: 0 };+ let volume: Volume | undefined;+ return {+ key, canvas, ctx: canvas.getContext('2d'), cap, fit: null, layout: '', left: 0, top: 0,+ volume: depth === 0 ? null : () => (volume ??= preparedVolume(definition, depth).vol),+ };}-/** Paint one frame `size` CSS pixels wide. `fill` and `ink` override the frame's colors with any canvas color. */-export function paintCanvas(surface: CanvasSurface, frame: AvatarFrame, size: number, fill = frame.color, ink = frame.ink) {+/** The marks of `thinking` and `blocked`, which a frame lists as slices in place of the body. */+const isMark = (shape: FrameShape) => shape.key.startsWith('mark-');++/**+ * Paint one frame `size` CSS pixels wide. `fill` and `ink` override the frame's colors with any+ * canvas color. A `fluffy` body falls back to flat where fluffy can't be drawn.+ */+export function paintCanvas(surface: CanvasSurface, frame: AvatarFrame, size: number, fill = frame.color, ink = frame.ink, material: AvatarMaterial = 'flat') {const { canvas, ctx } = surface;if (!ctx || size <= 0) return;const dpr = window.devicePixelRatio || 1;const scale = (size / 100) * dpr;const layout = `${size}|${dpr}`;if (sections.size > MAX_SECTIONS) sections.clear();- for (const { id, d, evenOdd } of frame.paths) {- if (!sections.has(id)) sections.set(id, { path: new Path2D(d), rule: evenOdd ? 'evenodd' : 'nonzero' });+ for (const { id, d, evenOdd, box } of frame.paths) {+ if (!sections.has(id)) sections.set(id, { box, path: new Path2D(d), rule: evenOdd ? 'evenodd' : 'nonzero' });}const { matrices, bounds } = framePlacement(frame);+ const volume = material === 'fluffy' ? surface.volume : null;+ const fluffy = volume !== null;+ if (fluffy) {+ bounds.x0 -= PILE_MARGIN;+ bounds.y0 -= PILE_MARGIN;+ bounds.x1 += PILE_MARGIN;+ bounds.y1 += PILE_MARGIN;+ }const fit = fitSquare(surface.layout === layout ? surface.fit : null, bounds, surface.cap);if (surface.layout === layout && fit === surface.fit) {ctx.setTransform(1, 0, 0, 1, 0, 0);@@ -201,6 +196,10 @@ export function paintCanvas(surface: CanvasSurface, frame: AvatarFrame, size: nucanvas.style.width = canvas.style.height = `${bitmap / dpr}px`;}+ // The whole body and its eyes as one image, unless it has shrunk away into a mark.+ const { view, scale: bodyScale, eyes } = frame.surface;+ const coat = volume && bodyScale > 0.001 ? renderFluffy(volume(), view, { color: fill, ink, eyes }, scale) : null;+ let coatPainted = false;ctx.lineCap = 'round';ctx.strokeStyle = ink;ctx.fillStyle = fill;@@ -210,10 +209,23 @@ export function paintCanvas(surface: CanvasSurface, frame: AvatarFrame, size: nuctx.setTransform(scale * m[0], scale * m[1], scale * m[2], scale * m[3], scale * m[4] - surface.left, scale * m[5] - surface.top);if (shape.kind === 'slice') {const section = sections.get(shape.path) as Section;- ctx.fill(section.path, section.rule);+ if (isMark(shape)) {+ if (!fluffy || !paintFluffyMark(ctx, section.box, scale, fill)) ctx.fill(section.path, section.rule);+ } else if (!coat) {+ ctx.fill(section.path, section.rule);+ } else if (!coatPainted) {+ // The body's slices follow one another: the coat takes the place of the first, under the root's motion.+ coatPainted = true;+ const [a, b, c, d, e, f] = frame.root;+ ctx.setTransform(scale * a, scale * b, scale * c, scale * d, scale * e - surface.left, scale * f - surface.top);+ const radius = coat.radius * bodyScale;+ ctx.drawImage(coat.canvas, coat.x, coat.y, coat.size, coat.size, coat.cx - radius, coat.cy - radius, 2 * radius, 2 * radius);+ }} else if (shape.kind === 'eye') {+ // MausBot: the coat seats only the two eyes; our mouth stays a flat mark on top of it.+ if (coat && shape.key !== 'mouth') continue;ctx.fillStyle = ink;- eye(ctx, shape.mark);+ paintEye(ctx, shape.mark);ctx.fillStyle = fill;} else {const g = shape.gradient;diff --git a/packages/phone-protocol/src/open-bot-avatar/effects.ts b/packages/phone-protocol/src/open-bot-avatar/effects.tsindex 62005cb68d..187d48e3a4 100644--- a/packages/phone-protocol/src/open-bot-avatar/effects.ts+++ b/packages/phone-protocol/src/open-bot-avatar/effects.ts@@ -76,21 +76,66 @@ const RING = 38.8 * (116 / 114.2705);*/const RIM_STEPS = 180;-/** How far `outlines` reach from (cx, cy) along a direction (radians), either way, exactly. */-function reachAlong(outlines: Point[][][], cx: number, cy: number, a: number): number {- const ux = Math.cos(a), uy = Math.sin(a);- let far = 0;- for (const poly of outlines.flat()) {- for (let i = 0; i < poly.length; i++) {- const [x1, y1] = poly[i], [x2, y2] = poly[(i + 1) % poly.length];- const ex = x2 - x1, ey = y2 - y1, den = ux * ey - uy * ex;+/** Directions a half turn is cut into for finding the edges a line through the centre can cross. */+const RIM_FANS = 180;++/**+ * How far `outlines` reach from (cx, cy) along a direction (radians), either way, exactly.+ *+ * A line through the centre only crosses the edges that span its direction as seen from there, so+ * the edges are listed by the directions they span, with a fan to spare on either side, and a+ * line is tested against the edges of its own fan. An edge left out lies a whole fan off the+ * line, far more than the test's rounding, so it would not have counted: the answer is the same+ * as from testing every edge.+ */+function reachFinder(outlines: Point[][][], cx: number, cy: number): (a: number) => number {+ let count = 0;+ for (const outline of outlines) for (const poly of outline) count += poly.length;+ // x1, y1 and the edge vector, per edge.+ const e = new Float64Array(4 * count);+ // The fans each edge spans: first and how many more. Edges at the centre span them all.+ const first = new Int32Array(count), more = new Int32Array(count);+ const start = new Int32Array(RIM_FANS + 1);+ let k = 0;+ for (const outline of outlines) {+ for (const poly of outline) {+ for (let i = 0; i < poly.length; i++, k++) {+ const p = poly[i], q = poly[(i + 1) % poly.length];+ e[4 * k] = p[0]; e[4 * k + 1] = p[1]; e[4 * k + 2] = q[0] - p[0]; e[4 * k + 3] = q[1] - p[1];+ const px = p[0] - cx, py = p[1] - cy, qx = q[0] - cx, qy = q[1] - cy;+ // The turn from p to q about the centre, the short way round.+ const from = Math.atan2(py, px), turn = Math.atan2(px * qy - py * qx, px * qx + py * qy);+ const near = px * px + py * py < 1e-6 || qx * qx + qy * qy < 1e-6 || Math.abs(turn) > Math.PI - 0.1;+ const lo = Math.floor((Math.min(from, from + turn) / Math.PI) * RIM_FANS) - 1;+ const hi = Math.floor((Math.max(from, from + turn) / Math.PI) * RIM_FANS) + 1;+ first[k] = near ? 0 : ((lo % RIM_FANS) + RIM_FANS) % RIM_FANS;+ more[k] = near || !(hi - lo < RIM_FANS) ? RIM_FANS - 1 : hi - lo;+ for (let f = 0; f <= more[k]; f++) start[((first[k] + f) % RIM_FANS) + 1]++;+ }+ }+ }+ for (let f = 0; f < RIM_FANS; f++) start[f + 1] += start[f];+ const items = new Int32Array(start[RIM_FANS]), next = start.slice(0, RIM_FANS);+ for (k = 0; k < count; k++) for (let f = 0; f <= more[k]; f++) items[next[(first[k] + f) % RIM_FANS]++] = 4 * k;++ return (a) => {+ const ux = Math.cos(a), uy = Math.sin(a);+ // The fan of the direction itself, so an angle of any size lands in the right one.+ const turns = Math.atan2(uy, ux) / Math.PI;+ const fan = Math.floor((turns - Math.floor(turns)) * RIM_FANS);+ // A direction that is in no fan (not a number) is tested against every edge.+ const known = fan >= 0 && fan < RIM_FANS;+ let far = 0;+ for (let n = known ? start[fan] : 0, end = known ? start[fan + 1] : count; n < end; n++) {+ const at = known ? items[n] : 4 * n;+ const x1 = e[at], y1 = e[at + 1], ex = e[at + 2], ey = e[at + 3], den = ux * ey - uy * ex;if (Math.abs(den) < 1e-12) continue;// Where the line through the centre crosses this edge: t along the line, s along the edge.const t = ((x1 - cx) * ey - (y1 - cy) * ex) / den, s = ((x1 - cx) * uy - (y1 - cy) * ux) / den;if (s >= 0 && s <= 1) far = Math.max(far, Math.abs(t));}- }- return far;+ return far;+ };}/** How each hoop is rolled in the picture, for an avatar's seed: hoop 0 is a working turn's. */@@ -106,7 +151,7 @@ export interface Rim {max: number;}export function rimOf(outlines: Point[][][], cx: number, cy: number): Rim {- const at = (angle: number) => reachAlong(outlines, cx, cy, angle);+ const at = reachFinder(outlines, cx, cy);const steps = Array.from({ length: RIM_STEPS }, (_, k) => at((k * Math.PI) / RIM_STEPS));// A spike between two samples can reach a little further than either: allow for a degree's sweep.return { cx, cy, at, max: Math.max(...steps) * 1.02 };diff --git a/packages/phone-protocol/src/open-bot-avatar/path.ts b/packages/phone-protocol/src/open-bot-avatar/path.tsindex 97f7070121..9e048369d6 100644--- a/packages/phone-protocol/src/open-bot-avatar/path.ts+++ b/packages/phone-protocol/src/open-bot-avatar/path.ts@@ -293,11 +293,143 @@ export function insideRow(polys: Point[][], y: number, xs: number[], out: Uint8A}}+/**+ * The edges of a set of polygons, listed by the horizontal bands they cross, for many point and+ * row tests against one outline. A query runs the arithmetic of `winding` or `insideRow` on the+ * edges of its band only. An edge outside the band cannot straddle the query's y, so it adds+ * nothing in the full pass either: the answers are the same, bit for bit.+ */+export class EdgeBands {+ /** xj, yj, xi, yi per edge, in the order `winding` visits them. */+ private readonly e: Float64Array;+ private readonly start: Int32Array;+ private readonly items: Int32Array;+ private readonly y0: number;+ private readonly inv: number;+ private readonly n: number;+ private hitX = new Float64Array(16);+ private hitDir = new Int8Array(16);++ constructor(polys: Point[][]) {+ let count = 0;+ for (const poly of polys) count += poly.length;+ const e = this.e = new Float64Array(4 * count);+ let k = 0, lo = Infinity, hi = -Infinity, climb = 0;+ for (const poly of polys) {+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {+ const yj = poly[j][1], yi = poly[i][1];+ e[k] = poly[j][0]; e[k + 1] = yj; e[k + 2] = poly[i][0]; e[k + 3] = yi;+ k += 4;+ if (yj < lo) lo = yj;+ if (yj > hi) hi = yj;+ climb += Math.abs(yi - yj);+ }+ }+ // About four edges to a band, but fewer bands where the edges are tall: an edge is listed in+ // every band it crosses, and the lists should not outgrow the outline (a few entries an edge).+ const tall = climb > 0 ? Math.floor((3 * count * (hi - lo)) / climb) : Infinity;+ const n = this.n = Math.max(1, Math.min(512, Math.ceil(count / 4), tall));+ this.y0 = count ? lo : 0;+ this.inv = hi > lo ? n / (hi - lo) : 0;+ // Counting sort of the edges into every band their y range touches.+ const start = this.start = new Int32Array(n + 1);+ for (k = 0; k < e.length; k += 4) {+ const a = this.band(Math.min(e[k + 1], e[k + 3])), b = this.band(Math.max(e[k + 1], e[k + 3]));+ for (let q = a; q <= b; q++) start[q + 1]++;+ }+ for (let q = 0; q < n; q++) start[q + 1] += start[q];+ const items = this.items = new Int32Array(start[n]);+ const next = start.slice(0, n);+ for (k = 0; k < e.length; k += 4) {+ const a = this.band(Math.min(e[k + 1], e[k + 3])), b = this.band(Math.max(e[k + 1], e[k + 3]));+ for (let q = a; q <= b; q++) items[next[q]++] = k;+ }+ }++ /** Monotonic in y, so an edge is listed in the band of every y between its ends. */+ private band(y: number): number {+ const q = Math.floor((y - this.y0) * this.inv);+ return q >= this.n ? this.n - 1 : q > 0 ? q : 0;+ }++ /** Same as `winding(polys, x, y)`. */+ winding(x: number, y: number): number {+ const { e, items } = this;+ const b = this.band(y);+ let w = 0;+ for (let q = this.start[b], end = this.start[b + 1]; q < end; q++) {+ const k = items[q];+ const xj = e[k], yj = e[k + 1], xi = e[k + 2], yi = e[k + 3];+ if (yj <= y) {+ if (yi > y && (xi - xj) * (y - yj) - (x - xj) * (yi - yj) > 0) w++;+ } else if (yi <= y && (xi - xj) * (y - yj) - (x - xj) * (yi - yj) < 0) w--;+ }+ return w;+ }++ /** The row's crossings, sorted by x, left in hitX and hitDir. Returns how many. */+ private crossings(y: number): number {+ const { e, items } = this;+ const b = this.band(y);+ const end = this.start[b + 1];+ if (end - this.start[b] > this.hitX.length) {+ this.hitX = new Float64Array(2 * (end - this.start[b]));+ this.hitDir = new Int8Array(this.hitX.length);+ }+ const hx = this.hitX, hd = this.hitDir;+ let n = 0;+ for (let q = this.start[b]; q < end; q++) {+ const k = items[q];+ const xj = e[k], yj = e[k + 1], xi = e[k + 2], yi = e[k + 3];+ let dir = 0;+ if (yj <= y && yi > y) dir = 1;+ else if (yi <= y && yj > y) dir = -1;+ else continue;+ const x = xj + ((y - yj) * (xi - xj)) / (yi - yj);+ // Insertion sort: a row has a handful of crossings. Ties may land in any order, since+ // crossings at one x are always counted together.+ let m = n++;+ for (; m > 0 && hx[m - 1] > x; m--) { hx[m] = hx[m - 1]; hd[m] = hd[m - 1]; }+ hx[m] = x; hd[m] = dir;+ }+ return n;+ }++ /** Same as `insideRow(polys, y, xs, out)`. */+ insideRow(y: number, xs: ArrayLike<number>, out: Uint8Array): void {+ const n = this.crossings(y);+ const hx = this.hitX, hd = this.hitDir;+ let w = 0, h = 0;+ for (let k = 0; k < xs.length; k++) {+ while (h < n && hx[h] < xs[k]) w += hd[h++];+ out[k] = w !== 0 ? 1 : 0;+ }+ }++ /** One flag of `insideRow`: what it reports for a row at `y` with `x` among its points. */+ insideRowAt(x: number, y: number): boolean {+ const n = this.crossings(y);+ let w = 0;+ for (let h = 0; h < n && this.hitX[h] < x; h++) w += this.hitDir[h];+ return w !== 0;+ }+}++const bands = new WeakMap<Point[][], EdgeBands>();++/** The band index of these polygons, built once per array. They must not change afterwards. */+export function edgeBands(polys: Point[][]): EdgeBands {+ let index = bands.get(polys);+ if (!index) bands.set(polys, index = new EdgeBands(polys));+ return index;+}+export interface Bounds { minX: number; minY: number; maxX: number; maxY: number }export function bounds(polys: Point[][]): Bounds {const b = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };- for (const p of polys) for (const [x, y] of p) {+ for (const p of polys) for (let k = 0; k < p.length; k++) {+ const x = p[k][0], y = p[k][1];if (x < b.minX) b.minX = x;if (y < b.minY) b.minY = y;if (x > b.maxX) b.maxX = x;@@ -312,8 +444,9 @@ export function filledArea(polys: Point[][], b: Bounds = bounds(polys)): numberconst xs: number[] = [];for (let x = Math.floor(b.minX) + 0.5; x < b.maxX; x += 1) xs.push(x);const row = new Uint8Array(xs.length);+ const index = edgeBands(polys);for (let y = Math.floor(b.minY) + 0.5; y < b.maxY; y += 1) {- insideRow(polys, y, xs, row);+ index.insideRow(y, xs, row);for (const v of row) n += v;}return n;diff --git a/packages/phone-protocol/src/open-bot-avatar/render.ts b/packages/phone-protocol/src/open-bot-avatar/render.tsindex df09066be7..bf2aa849e2 100644--- a/packages/phone-protocol/src/open-bot-avatar/render.ts+++ b/packages/phone-protocol/src/open-bot-avatar/render.ts@@ -32,7 +32,7 @@ import type { Bounds, Point } from './path.ts';import { EYE_H, EYE_W, GAZE_X, GAZE_Y, HAPPY_ARC, analyzeBody, eyeCenters, gazeRange, validateAvatar } from './validate.ts';import type { GazeRange } from './validate.ts';import { buildVolume } from './volume.ts';-import type { Volume, VolumeSlice } from './volume.ts';+import type { EyePlane, Vec3, Volume, VolumeSlice } from './volume.ts';import type { AvatarDefinition, RenderOptions } from './types.ts';export const DEFAULT_COLOR = '#ff6a1a';@@ -41,12 +41,12 @@ export const DEFAULT_EYE_COLOR = '#151515';export const DEFAULT_DEPTH = 6;const MAX_DEPTH = 14;/**- * Eyes sit this far above the surface so they never touch the body planes. iOS WebKit treats planes+ * CSS eyes sit this far above the surface so they never touch the body planes. iOS WebKit treats planes* closer than about a pixel as one and may draw the body over an eye (0.3 did: a band of the* barbell's bar through one eye), so the gap is a few pixels at the stage's size. Turned, an eye* drifts lift × sin(angle) from its spot: under half a unit at rest, about one at 45°.*/-const EYE_LIFT = 1.5;+const CSS_EYE_LIFT = 1.5;interface Prepared {def: AvatarDefinition;@@ -201,17 +201,23 @@ export function viewBasis(yaw: number, pitch: number): ViewBasis {return { cY, sY: Math.sin(yaw), cP, sP: Math.sin(pitch), facing: cY * cP };}-/** Minimum facing (toward-viewer component of the surface normal) for an eye to be drawn. */-const EYE_FACING = 0.22;-/** Toward-viewer component of a model-space direction under this view (1 = straight at the viewer). */-export function facingOf(v: ViewBasis, [x, y, z]: [number, number, number]): number {+export function facingOf(v: ViewBasis, [x, y, z]: Vec3): number {return v.sP * y + v.cP * (-v.sY * x + v.cY * z);}-/** Whether eye `i` is drawn: every surface normal under it must face the viewer. */-function eyeVisible(vol: Volume, v: ViewBasis, i: number): boolean {- return vol.eyeNormals[i].every((n) => facingOf(v, n) > EYE_FACING);+/** The signed projected area of a unit of eye plane goes to zero at the limb. */+function eyeVisible(v: ViewBasis, plane: EyePlane): boolean {+ return facingOf(v, [-plane.dzdx, -plane.dzdy, 1]) > 1e-6;+}++function eyeMatrix(v: ViewBasis, { x, y, z, dzdx, dzdy }: EyePlane, pivot: Point): M {+ const m = planeMatrix(v, z - x * dzdx - y * dzdy, pivot);+ m[0] += v.sY * dzdx;+ m[1] -= v.cY * v.sP * dzdx;+ m[2] += v.sY * dzdy;+ m[3] -= v.cY * v.sP * dzdy;+ return m;}/** Which slice stack faces the viewer more: front-facing z-planes or side-facing x-planes. */@@ -239,7 +245,7 @@ export function sidePlaneMatrix(v: ViewBasis, x0: number, pivot: Point): M {}/** Project a 3D point: screen x, screen y and depth toward the viewer. */-export function projectPoint(v: ViewBasis, [x, y, z]: [number, number, number], pivot: Point): [number, number, number] {+export function projectPoint(v: ViewBasis, [x, y, z]: Vec3, pivot: Point): Vec3 {const m = planeMatrix(v, z, pivot);const X = x - pivot[0], Y = y - pivot[1];return [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5], v.sP * Y + v.cP * (-v.sY * X + v.cY * z)];@@ -267,7 +273,7 @@ export function avatarExtent(definition: AvatarDefinition, depth?: number): { x:const { vol } = p;const b = vol.bounds;const [cx, cy] = pivotOf(b);- const radius = Math.hypot(b.maxX - b.minX, b.maxY - b.minY, Math.max(...vol.parts.map((part) => part.depth)) + 2 * EYE_LIFT) / 2;+ const radius = Math.hypot(b.maxX - b.minX, b.maxY - b.minY, Math.max(...vol.parts.map((part) => part.depth)) + 2 * CSS_EYE_LIFT) / 2;// Ribbons reach their hoop plus their band from the middle of the body's box, and keep the// canvas's antialiasing margin (FIT_PAD) inside.const { work, cage } = p.rims();@@ -365,8 +371,7 @@ function eyeMark(e: EyeState): EyeMark {* MausBot: a smile under the eyes, stroked like the happy arc. It follows the gaze with the eyes,* deepens as the eyes turn happy and flattens as they turn to a waiting slit.*/-function mouthMark(eyes: [EyeState, EyeState]): EyeMark {- const [a, b] = eyes;+function mouthMark([a, b]: [EyeState, EyeState]): EyeMark {const x = (a.x + b.x) / 2 + a.dx, y = a.y + a.h * 0.62 + a.dy;const hw = Math.max((b.x - a.x) * 0.3, a.w * 0.7);const happy = clamp(a.look.arc, 0, 1), flat = clamp(a.look.slit, 0, 1);@@ -458,6 +463,22 @@ export interface AvatarFrame {root: Matrix;/** Back to front. */shapes: FrameShape[];+ /**+ * The body as one surface, for a renderer that draws it in 3D instead of as slices (the fluffy+ * material): the view's rotation, the body's scale as it gives way to a mark, and both eyes,+ * including an eye `shapes` leaves out because its spot faces away.+ */+ surface: { view: ViewBasis; scale: number; eyes: SurfaceEye[] };+}++/**+ * An eye on the body's surface, in face coordinates: its mark where it rests, and how far its+ * gaze has moved it from there. Apart, so a renderer can tell a moving eye from a changing one.+ */+export interface SurfaceEye {+ mark: EyeMark;+ dx: number;+ dy: number;}/** Compute one flat frame of a definition. Throws if the definition is invalid. */@@ -506,7 +527,8 @@ function effectsOf(p: Prepared, pose: Pose, options: RenderOptions): Effects {const [cx, cy] = pivotOf(b);return {body: bodyScale(pose.bang, pose.dots),- 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) => {+ // No ribbons are out below a presence of 0.01 (see ribbonPieces), so their rims are not measured for it.+ ribbons: still || pose.ribbons <= 0.01 ? [] : 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) => {const hue = cometPalette(p.seed)[r.ribbon % 9];// The piece's stretch of its ribbon's colour run, front and back alike.const [s0, s1] = r.along;@@ -539,7 +561,7 @@ function flatFrame(definition: AvatarDefinition, options: RenderOptions, size: nconst pivot = pivotOf(b);const v = viewBasis(pose.yaw, pose.pitch);const stack = activeStack(v);- const eyesMid: Point = [p.def.eyes.x, p.def.eyes.y];+ const eyes: SurfaceEye[] = [];const fx = effectsOf(p, pose, options);const root = rootMatrix(pose, b);// The body shrinks toward its center as it gives way to a mark.@@ -555,29 +577,37 @@ function flatFrame(definition: AvatarDefinition, options: RenderOptions, size: npath = { id: p.ids.get(s.d) as string, d: s.d, evenOdd: s.evenOdd, box: { ...s.box } };paths.set(s.d, path);}- // Depth keys are taken under the eyes for the eye part, so only depth decides eye-vs-body order there.- const [rx, ry] = i === vol.eyePart ? eyesMid : vol.parts[i].center;- const depth = stack === 'z' ? projectPoint(v, [rx, ry, s.at], pivot)[2] : projectPoint(v, [s.at, ry, 0], pivot)[2];+ // Parallel slices have the same order along every viewing ray.+ const depth = stack === 'z' ? v.facing * s.at : -v.sY * v.cP * s.at;items.push({ depth, shape: { kind: 'slice', key: `${i}${stack}${j}`, path: path.id, matrix: shrink(m) } });});// Painted on the surface; each eye goes once the surface under it turns away.- const eyes = eyeStates(p, pose);- if (eyeVisible(vol, v, 0) && eyeVisible(vol, v, 1)) {- const z = (vol.eyeZ[0] + vol.eyeZ[1]) / 2 + EYE_LIFT;+ const states = eyeStates(p, pose);+ states.forEach((e, idx) => {+ const plane = vol.eyePlanes[idx];+ eyes.push({ mark: eyeMark({ ...e, dx: 0, dy: 0 }), dx: e.dx, dy: e.dy });+ if (!eyeVisible(v, plane)) return;+ // A slice through the middle of a mark must paint before the entire mark: sort at the near+ // edge of its footprint on the active stack.+ const halfW = e.w * (e.plain === 'pill' ? 0.5 : HAPPY_ARC.halfWidth + 0.5 * HAPPY_ARC.stroke);+ const xDepth = -v.sY * v.cP;+ const z = plane.z + e.dx * plane.dzdx + e.dy * plane.dzdy;+ const depth = stack === 'z'+ ? v.facing * z + Math.abs(v.facing) * (Math.abs(plane.dzdx) * halfW + (Math.abs(plane.dzdy) * e.h) / 2)+ : xDepth * (e.x + e.dx) + Math.abs(xDepth) * halfW;items.push({- depth: projectPoint(v, [eyesMid[0], eyesMid[1], z], pivot)[2] + 1e-6,- shape: { kind: 'eye', key: 'mouth', matrix: shrink(planeMatrix(v, z, pivot)), mark: mouthMark(eyes) },+ depth: depth + 1e-6,+ shape: { kind: 'eye', key: idx === 0 ? 'eye-0' : 'eye-1', matrix: shrink(eyeMatrix(v, plane, pivot)), mark: eyeMark(e) },});- }- eyes.forEach((e, idx) => {- if (eyeVisible(vol, v, idx)) {- const z = vol.eyeZ[idx] + EYE_LIFT;- items.push({- depth: projectPoint(v, [eyesMid[0], eyesMid[1], z], pivot)[2] + 1e-6,- shape: { kind: 'eye', key: idx === 0 ? 'eye-0' : 'eye-1', matrix: shrink(planeMatrix(v, z, pivot)), mark: eyeMark(e) },- });- }});+ // MausBot: the mouth sits on the plane midway between the eye planes and shows while both eyes+ // do. It paints over every slice, as on a fluffy coat: below the eyes the face can stand+ // proud of the eyes' plane, and its slices would cut through the mouth.+ const [pa, pb] = vol.eyePlanes;+ if (eyeVisible(v, pa) && eyeVisible(v, pb)) {+ const plane = { x: (pa.x + pb.x) / 2, y: (pa.y + pb.y) / 2, z: (pa.z + pb.z) / 2, dzdx: (pa.dzdx + pb.dzdx) / 2, dzdy: (pa.dzdy + pb.dzdy) / 2 };+ items.push({ depth: Infinity, shape: { kind: 'eye', key: 'mouth', matrix: shrink(eyeMatrix(v, plane, pivot)), mark: mouthMark(states) } });+ }items.sort((a, c) => a.depth - c.depth);}@@ -594,6 +624,7 @@ function flatFrame(definition: AvatarDefinition, options: RenderOptions, size: nreturn {name: p.def.name, color, ink, paths: [...paths.values()], root,shapes: [...ribbon(false), ...items.map((it) => it.shape), ...ribbon(true), ...marks],+ surface: { view: v, scale: fx.body, eyes },};}@@ -653,6 +684,8 @@ export function renderAvatarSvg(definition: AvatarDefinition, options: RenderOpt/** 1 viewBox unit = 1% of the scene's (square) container width. */const u = (n: number) => `${f(n)}cqw`;+const eyePlaneCss = ({ z, dzdx, dzdy }: EyePlane) =>+ `translateZ(${u(z + CSS_EYE_LIFT)}) matrix3d(1,0,${r4(dzdx)},0,0,1,${r4(dzdy)},0,0,0,1,0,0,0,0,1)`;const FILL = 'position:absolute;left:0;top:0;width:100%;height:100%;';function sliceMarkup(s: VolumeSlice): string {@@ -690,7 +723,7 @@ export function renderAvatarScene(definition: AvatarDefinition, options: Pick<Reconst eyes = eyeStates(p, poseOf(p, { reducedMotion: true })).map((e, i) => {const box = `left:${u(e.x - e.w / 2)};top:${u(e.y - e.h / 2)};width:${u(e.w)};height:${u(e.h)}`;return (- `<div data-eye="${i}" style="position:absolute;${box};backface-visibility:hidden;transform:translateZ(${u(vol.eyeZ[i] + EYE_LIFT)})">` ++ `<div data-eye="${i}" style="position:absolute;${box};backface-visibility:hidden;transform:${eyePlaneCss(vol.eyePlanes[i])}">` +`<i style="position:absolute;inset:0;border-radius:999px;background:${ink}"></i>` +`<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">` +`<path d="${happyArc(e)}" fill="none" stroke="${ink}" stroke-width="${f(e.w * HAPPY_ARC.stroke)}" stroke-linecap="round"/></svg>` +@@ -786,9 +819,9 @@ export function sceneFrame(definition: AvatarDefinition, options: RenderOptionsstack,slices: p.vol.parts.flatMap((part) => (stack === 'z' ? part.zSlices : part.xSlices).map((s) => kept[k++] && drawn(s))),eyes: states.map((e, i) => ({- visible: eyeVisible(p.vol, v, i),+ visible: eyeVisible(v, p.vol.eyePlanes[i]),happy: e.plain === 'arc',- transform: `translateZ(${u(p.vol.eyeZ[i] + EYE_LIFT)}) translate(${u(e.dx)},${u(e.dy)})`,+ transform: `${eyePlaneCss(p.vol.eyePlanes[i])} translate(${u(e.dx)},${u(e.dy)})`,pill: `translateY(${u(e.shift)}) scaleY(${r4(e.open / e.h)})`,d: e.plain === null ? eyePath(e.look, eyeSpot(e, false)) : '',})),diff --git a/packages/phone-protocol/src/open-bot-avatar/types.ts b/packages/phone-protocol/src/open-bot-avatar/types.tsindex 840aed1dd2..1047ee9316 100644--- a/packages/phone-protocol/src/open-bot-avatar/types.ts+++ b/packages/phone-protocol/src/open-bot-avatar/types.ts@@ -64,6 +64,9 @@ export interface AvatarMotionBlend {t: number;}+/** A body's finish: a flat fill, or a coat of fluffy fur (live avatars on a canvas, see AvatarOptions). */+export type AvatarMaterial = 'flat' | 'fluffy';+export interface RenderOptions {/** Body color as #rgb or #rrggbb. Invalid values fall back to the default. */color?: string;diff --git a/packages/phone-protocol/src/open-bot-avatar/validate.ts b/packages/phone-protocol/src/open-bot-avatar/validate.tsindex fa79574e06..371bb0d223 100644--- a/packages/phone-protocol/src/open-bot-avatar/validate.ts+++ b/packages/phone-protocol/src/open-bot-avatar/validate.ts@@ -1,4 +1,4 @@-import { bounds, filledArea, flattenPath, insideRow, isInside, parsePath, PathError, serializePath, splitSubpaths } from './path.ts';+import { bounds, edgeBands, filledArea, flattenPath, parsePath, PathError, serializePath, splitSubpaths } from './path.ts';import type { Bounds, Point } from './path.ts';import type { AvatarEyes, ValidationResult } from './types.ts';@@ -110,9 +110,10 @@ export function eyeCenters(eyes: AvatarEyes): [Point, Point] {}export function eyesFit(polys: Point[][], eyes: AvatarEyes, dx: number, dy: number, margin: number): Point | null {+ const index = edgeBands(polys);for (const [cx, cy] of eyeCenters(eyes)) {for (const [x, y] of eyeOutline(cx + dx, cy + dy, eyes.scale, margin)) {- if (!isInside(polys, x, y)) return [x, y];+ if (index.winding(x, y) === 0) return [x, y];}}return null;@@ -120,9 +121,10 @@ export function eyesFit(polys: Point[][], eyes: AvatarEyes, dx: number, dy: numb/** Like eyesFit, but for everything the renderer draws: the pill and the wider happy arc. */export function drawnEyesFit(polys: Point[][], eyes: AvatarEyes, dx: number, dy: number, margin: number): Point | null {+ const index = edgeBands(polys);for (const [cx, cy] of eyeCenters(eyes)) {for (const [x, y] of drawnEyeOutline(cx + dx, cy + dy, eyes.scale, margin)) {- if (!isInside(polys, x, y)) return [x, y];+ if (index.winding(x, y) === 0) return [x, y];}}return null;@@ -158,6 +160,7 @@ export function analyzeBody(path: string): BodyAnalysis {const segs = parsePath(path);const polys = flattenPath(segs);const b = bounds(polys);+ const whole = edgeBands(polys);const holes: BodyHole[] = [];const subpaths: BodySubpath[] = [];for (const sub of splitSubpaths(segs)) {@@ -172,9 +175,10 @@ export function analyzeBody(path: string): BodyAnalysis {const xs: number[] = [];for (let x = Math.floor(ob.minX) + step / 2; x < ob.maxX; x += step) xs.push(x);const mine = new Uint8Array(xs.length), all = new Uint8Array(xs.length);+ const self = edgeBands(own);for (let y = Math.floor(ob.minY) + step / 2; y < ob.maxY; y += step) {- insideRow(own, y, xs, mine);- if (!alone) insideRow(polys, y, xs, all);+ self.insideRow(y, xs, mine);+ if (!alone) whole.insideRow(y, xs, all);for (let k = 0; k < xs.length; k++) {if (!mine[k]) continue;inside++;diff --git a/packages/phone-protocol/src/open-bot-avatar/volume.ts b/packages/phone-protocol/src/open-bot-avatar/volume.tsindex 6784e19729..6f14f1c484 100644--- a/packages/phone-protocol/src/open-bot-avatar/volume.ts+++ b/packages/phone-protocol/src/open-bot-avatar/volume.ts@@ -18,8 +18,9 @@* the renderer shows whichever stack faces the viewer more, so no plane is* ever seen edge-on. Everything here is pure and cached by the renderer.*/-import { contourLoops, loopsToPath, simplifyLoop } from './contour.ts';-import { bounds, insideRow, isInside } from './path.ts';+import { RUN, contourOutlines, loopsToPath, runRange, runsOf, simplifiedLoop } from './contour.ts';+import { EdgeIndex, segDist2 } from './distance.ts';+import { bounds, edgeBands, isInside } from './path.ts';import type { Bounds, Point } from './path.ts';import { EYE_H, EYE_W, GAZE_X, GAZE_Y, analyzeBody, drawnEyesFit, eyeCenters, eyeClearance, gazeRange } from './validate.ts';import type { BodyAnalysis, GazeRange } from './validate.ts';@@ -69,18 +70,16 @@ export interface Volume {bounds: Bounds;/** Index of the part carrying the eyes. */eyePart: number;- /** Depth of each eye's plane: the highest surface under the eye and its gaze travel. */+ /** Highest host surface under each eye and its gaze travel, for socket mapping. */eyeZ: [number, number];/** Drawn eye scale: the definition's scale enlarged as far as the body allows (see EYE_BOOST). */eyeScale: number;- /**- * Host surface normals under each eye (left edge, center, right edge). On a- * curved host an eye is hidden once any of them turns away, so a flat eye- * never hangs past the curved silhouette.- */- eyeNormals: [Vec3[], Vec3[]];+ /** Tangent plane at each eye center for the flat, projected marks. */+ eyePlanes: [EyePlane, EyePlane];}+export interface EyePlane { x: number; y: number; z: number; dzdx: number; dzdy: number }+export type Vec3 = [number, number, number];/** Largest depth an inflated part may take, viewBox units. */@@ -113,15 +112,6 @@ const THIN_MARGIN = 2;/** Depth spacing of refinement slices, units. */const FINE_Z = 0.6;-function segDist2(px: number, py: number, ax: number, ay: number, bx: number, by: number): number {- const dx = bx - ax, dy = by - ay;- const len = dx * dx + dy * dy;- let t = len > 0 ? ((px - ax) * dx + (py - ay) * dy) / len : 0;- t = t < 0 ? 0 : t > 1 ? 1 : t;- const ex = ax + t * dx - px, ey = ay + t * dy - py;- return ex * ex + ey * ey;-}-function segDist(px: number, py: number, ax: number, ay: number, bx: number, by: number): number {return Math.sqrt(segDist2(px, py, ax, ay, bx, by));}@@ -225,6 +215,30 @@ function radiusAt(p: Profile, s: number): number {return p.r[k] + (p.r[k + 1] - p.r[k]) * (t - k);}+/**+ * What gives a part its depth, as plain data: an inflated part's edge fillet, or a revolved+ * part's radius profile about its axis. One function reads it for every part (surfaceHeight), so+ * the loops that call it per sample are compiled once instead of once per part's own closure.+ */+interface Surface {+ kind: PartKind;+ /** Inflated parts: depth and fillet radii, as surfaceZ and insetAt take them. */+ fillet: { depth: number; rxy: number; rz: number };+ /** Revolved parts: radius along the axis, the axis itself and the volume scale. */+ profile: Profile | null;+ axis: number;+ v: number;+}++/** Front surface height at a point inside the part, `sd` from its outline (used by inflated parts only). */+function surfaceHeight(s: Surface, x: number, y: number, sd: number): number {+ if (s.kind === 'inflate') return surfaceZ(s.fillet, sd);+ const p = s.profile as Profile;+ return s.kind === 'revolve-x'+ ? s.v * Math.sqrt(Math.max(0, radiusAt(p, x) ** 2 - (y - s.axis) ** 2))+ : s.v * Math.sqrt(Math.max(0, radiusAt(p, y) ** 2 - (x - s.axis) ** 2));+}+/*** Horizontal axis of revolution, if the body looks like a turned object seen* from the side: at least two parts, wider than tall, mirror-symmetric about@@ -243,9 +257,10 @@ export function revolveAxis(body: BodyAnalysis): number | null {const xs: number[] = [];for (let x = b.minX + 0.5; x < b.maxX; x += 1) xs.push(x);const top = new Uint8Array(xs.length), bottom = new Uint8Array(xs.length);+ const index = edgeBands(body.polys);for (let y = b.minY + 0.5; y < axis; y += 1) {- insideRow(body.polys, y, xs, top);- insideRow(body.polys, 2 * axis - y, xs, bottom);+ index.insideRow(y, xs, top);+ index.insideRow(2 * axis - y, xs, bottom);for (let k = 0; k < xs.length; k++) {if (top[k] || bottom[k]) filled++;if (top[k] !== bottom[k]) off++;@@ -255,84 +270,43 @@ export function revolveAxis(body: BodyAnalysis): number | null {}/** Sampled signed distance (positive inside) and height over a part's bounds. */-interface Grid { x0: number; y0: number; step: number; nx: number; ny: number; sd: Float64Array; h: Float64Array }--/** Edges bucketed on a coarse grid, for nearest-edge queries that only visit nearby buckets. */-class EdgeIndex {- private readonly cell = 6;- private readonly buckets = new Map<number, number[]>();- private readonly e: number[] = [];- private readonly ox: number;- private readonly oy: number;- private readonly span: number;-- constructor(polys: Point[][], b: Bounds) {- this.ox = b.minX - 4; this.oy = b.minY - 4;- this.span = Math.ceil((Math.max(b.maxX - b.minX, b.maxY - b.minY) + 8) / this.cell) + 1;- for (const poly of polys) {- for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {- const k = this.e.length;- this.e.push(poly[j][0], poly[j][1], poly[i][0], poly[i][1]);- const [x0, x1] = [Math.min(poly[j][0], poly[i][0]), Math.max(poly[j][0], poly[i][0])];- const [y0, y1] = [Math.min(poly[j][1], poly[i][1]), Math.max(poly[j][1], poly[i][1])];- for (let cy = this.cy(y0); cy <= this.cy(y1); cy++) {- for (let cx = this.cx(x0); cx <= this.cx(x1); cx++) {- const key = cy * this.span + cx;- (this.buckets.get(key) ?? this.buckets.set(key, []).get(key)!).push(k);- }- }- }- }- }+interface Grid { x0: number; y0: number; step: number; nx: number; ny: number; sd: Float64Array; h: Float64Array; inside: Uint8Array }- private cx(x: number) { return Math.max(0, Math.min(this.span - 1, Math.floor((x - this.ox) / this.cell))); }- private cy(y: number) { return Math.max(0, Math.min(this.span - 1, Math.floor((y - this.oy) / this.cell))); }-- /** Distance to the nearest edge, searching rings of buckets outward until no closer edge can exist. */- distance(x: number, y: number): number {- const bx = this.cx(x), by = this.cy(y);- let best = Infinity;- const e = this.e;- for (let r = 0; r < this.span; r++) {- for (let cy = by - r; cy <= by + r; cy++) {- if (cy < 0 || cy >= this.span) continue;- const edgeRow = cy === by - r || cy === by + r;- for (let cx = bx - r; cx <= bx + r; cx += edgeRow ? 1 : 2 * r || 1) {- if (cx < 0 || cx >= this.span) continue;- const list = this.buckets.get(cy * this.span + cx);- if (!list) continue;- for (const k of list) {- const d = segDist2(x, y, e[k], e[k + 1], e[k + 2], e[k + 3]);- if (d < best) best = d;- }- }- }- // Every bucket outside ring r is at least r cells away (best is squared).- if (best <= (r * this.cell) ** 2) break;- }- return Math.sqrt(best);- }-}--function sampleGrid(polys: Point[][], b: Bounds, step: number, height: (x: number, y: number, sd: number) => number): Grid {+/** A part's sample grid with its signed distances, before any height is known. */+function sampleGrid(polys: Point[][], b: Bounds, step: number, index: EdgeIndex): Grid {const pad = 1;const x0 = b.minX - pad, y0 = b.minY - pad;const nx = Math.ceil((b.maxX - b.minX + 2 * pad) / step) + 1;const ny = Math.ceil((b.maxY - b.minY + 2 * pad) / step) + 1;- const sd = new Float64Array(nx * ny), h = new Float64Array(nx * ny);- const index = new EdgeIndex(polys, b);+ const sd = index.distances({ x0, y0, step, nx, ny }), inside = new Uint8Array(nx * ny);const xs = Array.from({ length: nx }, (_, i) => x0 + i * step);- const inside = new Uint8Array(nx);+ const row = new Uint8Array(nx);+ const rows = edgeBands(polys);for (let j = 0; j < ny; j++) {- const y = y0 + j * step;- insideRow(polys, y, xs, inside);- for (let i = 0; i < nx; i++) {- const d = index.distance(xs[i], y);- sd[j * nx + i] = inside[i] ? d : -d;- h[j * nx + i] = inside[i] ? height(xs[i], y, d) : 0;+ rows.insideRow(y0 + j * step, xs, row);+ inside.set(row, j * nx);+ for (let i = 0; i < nx; i++) if (!row[i]) sd[j * nx + i] = -sd[j * nx + i];+ }+ return { x0, y0, step, nx, ny, sd, h: new Float64Array(nx * ny), inside };+}++/** Twice the largest inward distance over the samples of a grid like sampleGrid's, at `step`. */+function gridThickness(polys: Point[][], b: Bounds, step: number, index: EdgeIndex): number {+ const pad = 1;+ const nx = Math.ceil((b.maxX - b.minX + 2 * pad) / step) + 1;+ const ny = Math.ceil((b.maxY - b.minY + 2 * pad) / step) + 1;+ return 2 * index.widest({ x0: b.minX - pad, y0: b.minY - pad, step, nx, ny }, edgeBands(polys));+}++/** Fill in the grid's heights: the surface at every sample inside the outline, 0 outside. */+function sampleHeights(g: Grid, surface: Surface): void {+ for (let j = 0; j < g.ny; j++) {+ const y = g.y0 + j * g.step;+ for (let i = 0; i < g.nx; i++) {+ const k = j * g.nx + i;+ if (g.inside[k]) g.h[k] = surfaceHeight(surface, g.x0 + i * g.step, y, g.sd[k]);}}- return { x0, y0, step, nx, ny, sd, h };}function loopBox(loops: Point[][]): VolumeSlice['box'] {@@ -347,33 +321,88 @@ interface CellBox { i0: number; i1: number; j0: number; j1: number }interface ThinBox extends CellBox { top: number }/**- * A part's cross-section at `level` as a field that is positive inside it, zero on its edge and- * roughly a distance in viewBox units: smooth across the rim, so contours interpolated between grid- * samples follow the real edge instead of the grid. (Height itself is steep at the rim and zero- * outside, and contouring it left the outline faceted and stair-stepped.)+ * A part's cross-section at a level, clipped to the outline (and to a box, if given), as loops.+ *+ * It is the zero contour of a field that is positive inside the cross-section, zero on its edge+ * and roughly a distance in viewBox units: smooth across the rim, so contours interpolated between+ * grid samples follow the real edge instead of the grid. (Height itself is steep at the rim and+ * zero outside, and contouring it left the outline faceted and stair-stepped.) The field is capped+ * by the signed distance to the outline; both are continuous across it, so the smaller is too.*/-type LevelField = (x: number, y: number, sd: number, level: number) => number;--/** Cross-section at `level` clipped to the outline (and to `box`, if given), as loops. */-function levelLoops(g: Grid, level: number, field: LevelField, box?: CellBox): Point[][] {- // A box is contoured on its own samples plus one ring outside it, where the clip is negative.- const i0 = box ? Math.max(0, box.i0 - 1) : 0, i1 = box ? Math.min(g.nx - 1, box.i1 + 1) : g.nx - 1;- const j0 = box ? Math.max(0, box.j0 - 1) : 0, j1 = box ? Math.min(g.ny - 1, box.j1 + 1) : g.ny - 1;- const nx = i1 - i0 + 1, ny = j1 - j0 + 1;- const values = new Float64Array(nx * ny);+type LevelCut = (level: number, box?: CellBox) => Point[][];++/**+ * Cross-sections of an inflated part. Height grows with distance from the outline, so a level is+ * reached at a fixed inset: the field is the signed distance less that inset, which is the+ * distance grid itself contoured at the inset.+ */+function insetCuts(g: Grid, fillet: Surface['fillet']): LevelCut {+ const whole = { values: g.sd, nx: g.nx, ny: g.ny, x0: g.x0, y0: g.y0, step: g.step };+ const range = runRange(g.sd, g.nx, g.ny);+ const flat = new Uint8Array(range.min.length);+ return (level, box) => {+ const drop = insetAt(fillet, level);+ if (!box) {+ // Subtracting keeps order, so a run whose extremes are on one side of the inset is all on it.+ for (let k = 0; k < flat.length; k++) flat[k] = range.min[k] - drop >= 0 || range.max[k] - drop < 0 ? 1 : 0;+ return contourOutlines(whole, drop, 0.04, flat);+ }+ // A box is contoured on its own samples plus one ring outside it, where the clip is negative.+ const i0 = Math.max(0, box.i0 - 1), i1 = Math.min(g.nx - 1, box.i1 + 1);+ const j0 = Math.max(0, box.j0 - 1), j1 = Math.min(g.ny - 1, box.j1 + 1);+ const nx = i1 - i0 + 1, ny = j1 - j0 + 1;+ const values = new Float64Array(nx * ny);+ for (let j = 0; j < ny; j++) {+ for (let i = 0; i < nx; i++) {+ const sd = g.sd[(j + j0) * g.nx + i + i0];+ const v = Math.min(sd - drop, sd);+ values[j * nx + i] = Math.min(v, g.step * Math.min(i + i0 - box.i0, box.i1 - i - i0, j + j0 - box.j0, box.j1 - j - j0));+ }+ }+ return contourOutlines({ values, nx, ny, x0: g.x0 + i0 * g.step, y0: g.y0 + j0 * g.step, step: g.step }, 0, 0.04);+ };+}++/**+ * Cross-sections of a revolved part. With r the radius at a sample and t its offset from the+ * axis, height ≥ level where t² ≤ r² - (level / v)²: that difference over twice the radius is+ * about a distance, and it is the field.+ */+function revolveCuts(g: Grid, surface: Surface): LevelCut {+ const { nx, ny } = g;+ const { v, axis } = surface, p = surface.profile as Profile, alongX = surface.kind === 'revolve-x';+ // The field is (base - (level / v)²) / over: only the middle term changes with the level.+ const base = new Float64Array(nx * ny), over = new Float64Array(nx * ny);for (let j = 0; j < ny; j++) {+ const y = g.y0 + j * g.step;for (let i = 0; i < nx; i++) {- const k = (j + j0) * g.nx + i + i0;- const sd = g.sd[k];- // Both terms are continuous across the outline, so the min is too.- let v = Math.min(field(g.x0 + (i + i0) * g.step, g.y0 + (j + j0) * g.step, sd, level), sd);- if (box) v = Math.min(v, g.step * Math.min(i + i0 - box.i0, box.i1 - i - i0, j + j0 - box.j0, box.j1 - j - j0));- values[j * nx + i] = v;+ const x = g.x0 + i * g.step;+ const r = radiusAt(p, alongX ? x : y), t = alongX ? y - axis : x - axis;+ base[j * nx + i] = r * r - t * t;+ over[j * nx + i] = 2 * Math.max(r, 0.5);}}- return contourLoops({ values, nx, ny, x0: g.x0 + i0 * g.step, y0: g.y0 + j0 * g.step, step: g.step }, 0)- .map((l) => simplifyLoop(l, 0.04))- .filter((l) => l.length >= 3);+ const values = new Float64Array(nx * ny);+ const field = { values, nx, ny, x0: g.x0, y0: g.y0, step: g.step };+ const rise = runRange(base, nx, ny), edge = runRange(g.sd, nx, ny);+ const runs = runsOf(nx);+ const flat = new Uint8Array(rise.min.length);+ return (level) => {+ const drop = (level / Math.max(v, 1e-6)) ** 2;+ for (let k = 0; k < flat.length; k++) {+ // Subtracting keeps order and `over` is positive, so the extremes of a run tell its sign.+ const out = rise.max[k] - drop < 0 || edge.max[k] < 0, within = rise.min[k] - drop >= 0 && edge.min[k] >= 0;+ flat[k] = out || within ? 1 : 0;+ if (flat[k]) continue;+ // Only runs the contour may cross are read, so only they are filled in.+ const r = k % runs, j = (k - r) / runs;+ for (let q = j * nx + r * RUN, end = j * nx + Math.min(nx - 1, (r + 1) * RUN); q <= end; q++) {+ values[q] = Math.min((base[q] - drop) / over[q], g.sd[q]);+ values[q + nx] = Math.min((base[q + nx] - drop) / over[q + nx], g.sd[q + nx]);+ }+ }+ return contourOutlines(field, 0, 0.04, flat);+ };}/**@@ -385,23 +414,19 @@ function levelLoops(g: Grid, level: number, field: LevelField, box?: CellBox): Pfunction thinBoxes(g: Grid): ThinBox[] {const { nx, ny } = g;const reach = Math.ceil(THIN_REACH / g.step);- // Largest inward distance within `reach` samples (a square window, rows then columns).- const rows = new Float64Array(nx * ny), widest = new Float64Array(nx * ny);+ // Whether a sample THIN or more inside the outline lies within `reach` samples (a square+ // window, rows then columns): the largest inward distance there is THIN or more exactly then.+ const wide = new Uint8Array(nx * ny), near = new Uint8Array(nx * ny);+ const count = new Int32Array(Math.max(nx, ny) + 1);for (let j = 0; j < ny; j++) {- for (let i = 0; i < nx; i++) {- let m = 0;- for (let k = Math.max(0, i - reach), e = Math.min(nx - 1, i + reach); k <= e; k++) m = Math.max(m, g.sd[j * nx + k]);- rows[j * nx + i] = m;- }+ for (let i = 0; i < nx; i++) count[i + 1] = count[i] + (g.sd[j * nx + i] >= THIN ? 1 : 0);+ for (let i = 0; i < nx; i++) wide[j * nx + i] = count[Math.min(nx, i + reach + 1)] > count[Math.max(0, i - reach)] ? 1 : 0;}for (let i = 0; i < nx; i++) {- for (let j = 0; j < ny; j++) {- let m = 0;- for (let k = Math.max(0, j - reach), e = Math.min(ny - 1, j + reach); k <= e; k++) m = Math.max(m, rows[k * nx + i]);- widest[j * nx + i] = m;- }+ for (let j = 0; j < ny; j++) count[j + 1] = count[j] + wide[j * nx + i];+ for (let j = 0; j < ny; j++) near[j * nx + i] = count[Math.min(ny, j + reach + 1)] > count[Math.max(0, j - reach)] ? 1 : 0;}- const thin = (k: number) => g.sd[k] > 0 && widest[k] < THIN;+ const thin = (k: number) => g.sd[k] > 0 && !near[k];const seen = new Uint8Array(nx * ny);const grow = Math.ceil(THIN_MARGIN / g.step);const boxes: ThinBox[] = [];@@ -448,10 +473,10 @@ function thinBoxes(g: Grid): ThinBox[] {* height across the slab, so a stack of these seen side-on adds up to the* solid's side silhouette instead of one tooth per column where the outline* slopes. Where a row run meets the outline the profile ends at the surface- * height right there (`edgeHeight`: the wall of an inflated part, the rim of a- * revolved one), not at the last sample's.+ * height right there (the wall of an inflated part, the rim of a revolved+ * one), not at the last sample's.*/-function columnLoops(g: Grid, c0: number, c1: number, edgeHeight: (x: number, y: number) => number): Point[][] {+function columnLoops(g: Grid, c0: number, c1: number, surface: Surface): Point[][] {const loops: Point[][] = [];const sd = new Float64Array(g.ny).fill(-Infinity), h = new Float64Array(g.ny);for (let j = 0; j < g.ny; j++) {@@ -461,32 +486,43 @@ function columnLoops(g: Grid, c0: number, c1: number, edgeHeight: (x: number, y:if (g.sd[k] > 0 && g.h[k] > h[j]) h[j] = g.h[k];}}- const yAt = (jj: number) => g.y0 + jj * g.step;- // Where the outline crosses between an inside and an outside sample, and the surface height there.- const edge = (inside: number, outside: number) => yAt(inside) + ((yAt(outside) - yAt(inside)) * sd[inside]) / (sd[inside] - sd[outside]);- const rim = (y: number, j: number) => {- let top = 0;- for (let c = c0; c <= c1; c++) top = Math.max(top, edgeHeight(g.x0 + c * g.step, y));- return Math.min(h[j], top);- };+ // One run of rows at a time: its right side (u, y in turn) from top to bottom, then the mirror image back up.+ const xy = new Float64Array(4 * (g.ny + 2));let j = 0;while (j < g.ny) {if (sd[j] <= 0) { j++; continue; }const j0 = j;while (j < g.ny && sd[j] > 0) j++;const j1 = j - 1;- const yTop = j0 > 0 ? edge(j0, j0 - 1) : yAt(j0);- const yBot = j1 < g.ny - 1 ? edge(j1, j1 + 1) : yAt(j1);- const right: Point[] = [[j0 > 0 ? rim(yTop, j0) : h[j0], yTop]];- for (let k = j0; k <= j1; k++) right.push([h[k], yAt(k)]);- right.push([j1 < g.ny - 1 ? rim(yBot, j1) : h[j1], yBot]);- if (Math.max(...right.map((p) => p[0])) < 0.05) continue;- const left = right.map(([u, y]) => [-u, y] as Point).reverse();- loops.push(simplifyLoop([...right, ...left], 0.04));+ let n = 0;+ if (j0 > 0) n = rimPoint(g, c0, c1, surface, sd, h, j0, j0 - 1, xy, n);+ else { xy[n++] = h[j0]; xy[n++] = g.y0 + j0 * g.step; }+ for (let k = j0; k <= j1; k++) { xy[n++] = h[k]; xy[n++] = g.y0 + k * g.step; }+ if (j1 < g.ny - 1) n = rimPoint(g, c0, c1, surface, sd, h, j1, j1 + 1, xy, n);+ else { xy[n++] = h[j1]; xy[n++] = g.y0 + j1 * g.step; }+ let top = -Infinity;+ for (let k = 0; k < n; k += 2) top = Math.max(top, xy[k]);+ if (top < 0.05) continue;+ for (let k = n - 2, m = n; k >= 0; k -= 2) { xy[m++] = -xy[k]; xy[m++] = xy[k + 1]; }+ loops.push(simplifiedLoop(xy, n, 0.04));}return loops;}+/**+ * The end of a row run of columnLoops, written to xy[n]: where the outline crosses between the+ * run's last sample `inside` and its neighbor `outside`, and the surface height there, capped by+ * the sample's. Returns the next free slot.+ */+function rimPoint(g: Grid, c0: number, c1: number, surface: Surface, sd: Float64Array, h: Float64Array, inside: number, outside: number, xy: Float64Array, n: number): number {+ const yIn = g.y0 + inside * g.step;+ const y = yIn + ((g.y0 + outside * g.step - yIn) * sd[inside]) / (sd[inside] - sd[outside]);+ let top = 0;+ for (let c = c0; c <= c1; c++) top = Math.max(top, surfaceHeight(surface, g.x0 + c * g.step, y, 0));+ xy[n] = Math.min(h[inside], top); xy[n + 1] = y;+ return n + 2;+}+/** Depth levels in (flat, flat + round): even in angle over the rounded part of the profile. */function levels(flat: number, round: number, steps: number): number[] {const out: number[] = [];@@ -520,36 +556,23 @@ export function buildVolume(def: AvatarDefinition, volume = 1, body: BodyAnalysiif (profile) kind = 'revolve-y';}- let thickness: number, depth: number, rxy = 0, rz = 0;- let heightOf: (x: number, y: number, sd: number) => number;- let levelField: LevelField;+ const index = new EdgeIndex(polys, b);+ let thickness: number, depth: number, rxy = 0, rz = 0, axis = 0;if (kind === 'inflate' || !profile) {- const coarse = sampleGrid(polys, b, Math.max(step, 0.6), () => 0);- thickness = 2 * coarse.sd.reduce((m, d) => Math.max(m, d), 0);+ thickness = gridThickness(polys, b, Math.max(step, 0.6), index);depth = partDepth(thickness, b, v);rxy = Math.min(thickness / 2, depth / 2) * 0.9;rz = (depth / 2) * 0.85;- const shape = { depth, rxy, rz };- heightOf = (_x, _y, sd) => surfaceZ(shape, sd);- // Height grows with distance from the outline, so a level is reached at a fixed inset.- levelField = (_x, _y, sd, level) => sd - insetAt(shape, level);} else {- const p = profile;- const axis = kind === 'revolve-x' ? (xAxis as number) : center[0];- const radius = Math.max(...p.r);+ axis = kind === 'revolve-x' ? (xAxis as number) : center[0];+ const radius = Math.max(...profile.r);thickness = 2 * radius;depth = 2 * radius * v;- heightOf = kind === 'revolve-x'- ? (x, y) => v * Math.sqrt(Math.max(0, radiusAt(p, x) ** 2 - (y - axis) ** 2))- : (x, y) => v * Math.sqrt(Math.max(0, radiusAt(p, y) ** 2 - (x - axis) ** 2));- // Height ≥ level where t² ≤ R² - (level / v)²: that difference over 2R is about a distance.- levelField = (x, y, _sd, level) => {- const r = radiusAt(p, kind === 'revolve-x' ? x : y), t = kind === 'revolve-x' ? y - axis : x - axis;- return (r * r - t * t - (level / Math.max(v, 1e-6)) ** 2) / (2 * Math.max(r, 0.5));- };}+ const surface: Surface = { kind, fillet: { depth, rxy, rz }, profile, axis, v };+ const filled = edgeBands(polys);const height = (x: number, y: number) =>- isInside(polys, x, y) ? heightOf(x, y, kind === 'inflate' ? edgeDistance(polys, x, y) : 0) : 0;+ filled.winding(x, y) !== 0 ? surfaceHeight(surface, x, y, kind === 'inflate' ? index.distance(x, y) : 0) : 0;const core: VolumeSlice = {axis: 'z', at: 0, d: o.d + cuts.map((h) => h.d).join(''), loops: polys, evenOdd: false,@@ -559,17 +582,20 @@ export function buildVolume(def: AvatarDefinition, volume = 1, body: BodyAnalysiconst xSlices: VolumeSlice[] = [];const half = depth / 2;if (half > 0.05) {- const g = sampleGrid(polys, b, step, heightOf);+ const g = sampleGrid(polys, b, step, index);+ sampleHeights(g, surface);const steps = kind === 'inflate'? Math.max(4, Math.min(14, Math.round(rz / 0.8))): Math.max(5, Math.min(18, Math.round(half / 1.1)));// Inflated parts keep a straight wall up to half - rz; one slice at its end carries it.const ls = kind === 'inflate' ? [half - rz, ...levels(half - rz, rz, steps)] : levels(0, half, steps);+ const cut = kind === 'inflate' ? insetCuts(g, surface.fillet) : revolveCuts(g, surface);const addLevel = (level: number, box?: CellBox) => {- const loops = levelLoops(g, level, levelField, box);+ const loops = cut(level, box);if (!loops.length) return false;- const sample = loops.flat().filter((_, k) => k % 3 === 0);- const inset = Math.min(...sample.map(([x, y]) => edgeDistance(polys, x, y)));+ // Every third point of the loops, counted across them.+ let inset = Infinity, k = 0;+ for (const loop of loops) for (const p of loop) if (k++ % 3 === 0) inset = Math.min(inset, index.distance(p[0], p[1]));const slice = { axis: 'z' as const, d: loopsToPath(loops), loops, evenOdd: true, box: loopBox(loops), inset };zSlices.push({ ...slice, at: level }, { ...slice, at: -level });return true;@@ -589,11 +615,10 @@ export function buildVolume(def: AvatarDefinition, volume = 1, body: BodyAnalysiconst width = b.maxX - b.minX;const every = Math.max(1, Math.round(Math.max(1.1, width / MAX_X_SLICES) / g.step));- const edgeHeight = (x: number, y: number) => heightOf(x, y, 0);// One plane per `every` grid columns, standing for the whole slab around it.const before = Math.floor((every - 1) / 2);for (let i = 1; i < g.nx - 1; i += every) {- const loops = columnLoops(g, Math.max(0, i - before), Math.min(g.nx - 1, i - before + every - 1), edgeHeight);+ const loops = columnLoops(g, Math.max(0, i - before), Math.min(g.nx - 1, i - before + every - 1), surface);if (loops.length) xSlices.push({ axis: 'x', at: g.x0 + i * g.step, d: loopsToPath(loops), loops, evenOdd: true, box: loopBox(loops), inset: 0 });}}@@ -616,7 +641,7 @@ export function buildVolume(def: AvatarDefinition, volume = 1, body: BodyAnalysiif (z > bestZ) { bestZ = z; eyePart = i; }});const host = parts[eyePart];- // Flat eye planes sit at the highest surface under the eye and its gaze travel, so the body never cuts them.+ // Limit the socket to its host even when a taller part overlaps the face.const w = (EYE_W * eyeScale) / 2 + GAZE_X * eyeScale, hh = (EYE_H * eyeScale) / 2 + GAZE_Y * eyeScale;const eyeZ = centers.map(([x, y]) => {let top = 0;@@ -624,18 +649,15 @@ export function buildVolume(def: AvatarDefinition, volume = 1, body: BodyAnalysireturn top;}) as [number, number];- const normal = (x: number, y: number): Vec3 => {- if (!host) return [0, 0, 1];- const e = 0.75;- const gx = (host.height(x + e, y) - host.height(x - e, y)) / (2 * e);- const gy = (host.height(x, y + e) - host.height(x, y - e)) / (2 * e);- const n = Math.hypot(gx, gy, 1);- return [-gx / n, -gy / n, 1 / n];- };- const half = (EYE_W * eyeScale) / 2;- const eyeNormals = centers.map(([x, y]) => [normal(x - half, y), normal(x, y), normal(x + half, y)]) as [Vec3[], Vec3[]];+ const eyePlanes = centers.map(([x, y]) => {+ if (!host) return { x, y, z: 0, dzdx: 0, dzdy: 0 };+ const e = .75;+ const dzdx = (host.height(x + e, y) - host.height(x - e, y)) / (2 * e);+ const dzdy = (host.height(x, y + e) - host.height(x, y - e)) / (2 * e);+ return { x, y, z: host.height(x, y), dzdx, dzdy };+ }) as [EyePlane, EyePlane];- return { parts, bounds: body.bounds, eyePart, eyeZ, eyeScale, eyeNormals };+ return { parts, bounds: body.bounds, eyePart, eyeZ, eyeScale, eyePlanes };}/** Largest eye scale up to EYE_BOOST × the definition's whose drawn eyes keep EYE_BOOST_PAD from the outline. */diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.tsindex 71239c48a7..62a9095bec 100644--- a/packages/phone-protocol/src/wire.ts+++ b/packages/phone-protocol/src/wire.ts@@ -7,7 +7,7 @@ import type { ApprovalMode } from "./approval-mode.ts";import type { ToolScope } from "./tool-scope.ts"; import type { ToolGroup } from "./tool-groups.ts";import type { CommandAllowlistCandidate } from "./command-allowlist.ts";import type { TurnDigest } from "./digest.ts";-import type { BotAvatarCrop, MascotFaceColor } from "./bot-avatar.ts";+import type { BotAvatarCrop, MascotFaceColor, MascotMaterial } from "./bot-avatar.ts";import type { BotBodyId } from "./bot-body.ts";import type { ReplyStyle } from "./reply-style.ts";import type { CredentialTargetId, CUSTOM_SECRET_TARGET, SecretDelivery } from "./credential-request.ts"; import type { EmailOutgoingFields } from "./email.ts";@@ -285,7 +285,7 @@ export interface WireBot extends DefaultBotFields, BotAccessFields {mascotExpression?: MausExpression | null;mascotBody?: BotBodyId | null;/** Overrides both eyes and mouth. Absent or null preserves the body's default inks. */- mascotFaceColor?: MascotFaceColor | null; /** Lowercase `#rrggbb` tint for the avatar body only. Absent or null uses `color`. */ mascotBodyColor?: string | null;+ mascotFaceColor?: MascotFaceColor | null; /** Lowercase `#rrggbb` tint for the avatar body only. Absent or null uses `color`. */ mascotBodyColor?: string | null; mascotMaterial?: MascotMaterial | null;/** App-owned attachment served as this bot's custom profile image;* always present on the wire, null when the bot has none. */avatarUrl: string | null;diff --git a/server/bot-link/link.ts b/server/bot-link/link.tsindex 58db47a879..fab19416dd 100644--- a/server/bot-link/link.ts+++ b/server/bot-link/link.ts@@ -104,7 +104,7 @@ const endedSchema = z.array(z.object({ origin: z.string(), token: z.string(), atexport type EndedLink = z.infer<typeof endedSchema>[number];interface LocalBot { id: string; name: string; color?: string; hidden?: boolean; title?: string; description?: string; movedTo?: unknown;- mascotBody?: string | null; mascotFaceColor?: string | null; mascotBodyColor?: string | null; chiefOfStaff?: boolean; threadId?: string }+ mascotBody?: string | null; mascotFaceColor?: string | null; mascotBodyColor?: string | null; mascotMaterial?: string | null; chiefOfStaff?: boolean; threadId?: string }export interface BotLinkDeps {dataDir: string;@@ -209,7 +209,7 @@ export function createBotLink(deps: BotLinkDeps) {id: bot.id, name: bot.name, ...(bot.title ? { title: bot.title.slice(0, 200) } : {}), ...(bot.description ? { description: bot.description.slice(0, 400) } : {}),...(deps.model?.(bot) ? { model: deps.model(bot)!.slice(0, 200) } : {}), level: deps.level(bot),...(bot.color ? { color: bot.color.slice(0, 64) } : {}), ...(bot.mascotBody ? { mascotBody: bot.mascotBody.slice(0, 64) } : {}), ...(bot.mascotFaceColor ? { mascotFaceColor: bot.mascotFaceColor.slice(0, 64) } : {}),- ...(bot.mascotBodyColor ? { mascotBodyColor: bot.mascotBodyColor.slice(0, 64) } : {}),+ ...(bot.mascotBodyColor ? { mascotBodyColor: bot.mascotBodyColor.slice(0, 64) } : {}), ...(bot.mascotMaterial ? { mascotMaterial: bot.mascotMaterial.slice(0, 64) } : {}),...(bot.chiefOfStaff ? { chief: true } : {}), ...(bot.threadId ? { threadId: bot.threadId } : {}),})).slice(0, 500);diff --git a/server/bot-link/protocol.ts b/server/bot-link/protocol.tsindex cc28cdc54f..e03cd24723 100644--- a/server/bot-link/protocol.ts+++ b/server/bot-link/protocol.ts@@ -55,7 +55,7 @@ const level = z.enum(["ask", "edits", "auto", "full", "custom"]);export const linkedBotSchema = z.object({id: botId, name, title: z.string().max(200).optional(), description: z.string().max(400).optional(), model: z.string().max(200).optional(), level: level.optional(),/** How it looks and where its own chat is, so the other place can draw it as it is drawn at home. */- color: z.string().max(64).optional(), mascotBody: z.string().max(64).optional(), mascotFaceColor: z.string().max(64).optional(), mascotBodyColor: z.string().max(64).optional(), chief: z.boolean().optional(), threadId: botId.optional(),+ color: z.string().max(64).optional(), mascotBody: z.string().max(64).optional(), mascotFaceColor: z.string().max(64).optional(), mascotBodyColor: z.string().max(64).optional(), mascotMaterial: z.string().max(64).optional(), chief: z.boolean().optional(), threadId: botId.optional(),});export type LinkedBot = z.infer<typeof linkedBotSchema>;diff --git a/server/bot-profile.test.ts b/server/bot-profile.test.tsindex 2734c58fb2..f82009c80a 100644--- a/server/bot-profile.test.ts+++ b/server/bot-profile.test.ts@@ -154,6 +154,20 @@ describe("mascotBodyColor", () => {});});+describe("mascotMaterial", () => {+ it.each(["fluffy", null] as const)("accepts %s at both profile boundaries", (mascotMaterial) => {+ for (const strict of [true, false]) {+ expect(parseBotProfilePatch({ mascotMaterial }, strict)).toEqual({ ok: true, patch: { mascotMaterial } });+ }+ });++ it.each(["Fluffy", "fuzzy", "velvet", "", 1, {}])("rejects %j", (mascotMaterial) => {+ expect(parseBotProfilePatch({ mascotMaterial } as never, true)).toEqual({+ ok: false, error: "mascotMaterial must be fluffy, or null",+ });+ });+});+describe("soul (standing instructions)", () => {it("accepts soul on both the strict and broad boundaries", () => {expect(parseBotProfilePatch({ soul: "Be brief." }, true)).toEqual({ ok: true, patch: { soul: "Be brief." } });diff --git a/server/bot-profile.ts b/server/bot-profile.tsindex c1c2e8a65c..2d2aa00e50 100644--- a/server/bot-profile.ts+++ b/server/bot-profile.ts@@ -8,6 +8,8 @@ import {botAvatarUrlSchema,mascotBodyColorSchema,mascotFaceColorSchema,+ mascotMaterialSchema,+ MASCOT_MATERIALS,} from "../shared/bot-avatar.ts";import { BOT_PROFILE_LIMITS, fitsOnOneLine } from "../shared/bot-profile.ts";import { REPLY_STYLES } from "../shared/reply-style.ts";@@ -31,6 +33,7 @@ export const BOT_PROFILE_PATCH_FIELDS = ["mascotBody","mascotFaceColor","mascotBodyColor",+ "mascotMaterial","voice","speakReplies","replyStyle",@@ -71,6 +74,7 @@ export const profilePatchSchema = z.object({mascotBody: botBodySchema.optional(),mascotFaceColor: mascotFaceColorSchema.nullable().optional(),mascotBodyColor: mascotBodyColorSchema.nullable().optional(),+ mascotMaterial: mascotMaterialSchema.nullable().optional(),voice: z.string({ error: "voice must be a string" }).max(BOT_PROFILE_LIMITS.voice, { error: "voice must be at most 200 characters" })@@ -97,6 +101,7 @@ export type BotProfilePatch = Partial<| "mascotBody"| "mascotFaceColor"| "mascotBodyColor"+ | "mascotMaterial"| "voice"| "speakReplies"| "replyStyle"@@ -131,6 +136,9 @@ export function parseBotProfilePatch(input: BotProfilePatchInput, strict = falseif (issue?.path[0] === "mascotBodyColor") {return { ok: false, error: "mascotBodyColor must be a #rrggbb hex colour or null" };}+ if (issue?.path[0] === "mascotMaterial") {+ return { ok: false, error: `mascotMaterial must be ${MASCOT_MATERIALS.join(", ")}, or null` };+ }return { ok: false, error: issue?.message ?? "invalid profile patch" };}diff --git a/server/host/bot-link-host.ts b/server/host/bot-link-host.tsindex 2ef92e5fe3..9437ce4048 100644--- a/server/host/bot-link-host.ts+++ b/server/host/bot-link-host.ts@@ -2,7 +2,7 @@// server's store and coordinator, the computer's end that asks the Cloud, and the routes. With the link off (no// bot-link.json in the data folder) `start` asks nobody and every hook here answers as if the link did not exist.import { dirname } from "node:path";-import { mascotBodyColorSchema } from "../../shared/bot-avatar.ts";+import { mascotBodyColorSchema, mascotMaterialSchema } from "../../shared/bot-avatar.ts";import { createDialer } from "../bot-link/dial.ts";import { createBotLink } from "../bot-link/link.ts";@@ -47,11 +47,15 @@ export interface BotLinkHostDeps {log(line: string): void;}-/** Another place's body tint lands here only as a valid hex, since the avatar paints it. */+/** Another place's body tint and fur land here only as valid values, since the avatar paints them. */const bodyColor = (value: string | undefined) => {const color = mascotBodyColorSchema.safeParse(value).data;return color ? { mascotBodyColor: color } : {};};+const fur = (value: string | undefined) => {+ const style = mascotMaterialSchema.safeParse(value).data;+ return style ? { mascotMaterial: style } : {};+};export function createBotLinkHost(deps: BotLinkHostDeps) {const { store } = deps;@@ -63,14 +67,14 @@ export function createBotLinkHost(deps: BotLinkHostDeps) {next.set(id, { id, name: bot.name, color: bot.color ?? "blue", threadId: "", tasks: [], resumeCursors: {}, modelSelection: { instanceId: "", model: bot.model ?? "" },home: { place: peer, placeName: place.name, botId: bot.id, kind }, ...(bot.title ? { title: bot.title } : {}), ...(bot.description ? { description: bot.description } : {}),...(bot.mascotBody ? { mascotBody: bot.mascotBody } : {}), ...(bot.mascotFaceColor ? { mascotFaceColor: bot.mascotFaceColor } : {}),- ...bodyColor(bot.mascotBodyColor) } as unknown as BotRecord);+ ...bodyColor(bot.mascotBodyColor), ...fur(bot.mascotMaterial) } as unknown as BotRecord);}// A far member of a room here that cannot be reached now (the link is off, its place is unlinked, or its place no// longer has it) stays a member: it is found by its address, named as it was last known, and takes no turn.rooms.sync();- for (const { id, gone, name, color, place, placeName, botId, kind, title, mascotBody, mascotFaceColor, mascotBodyColor } of rooms.absent()) {+ for (const { id, gone, name, color, place, placeName, botId, kind, title, mascotBody, mascotFaceColor, mascotBodyColor, mascotMaterial } of rooms.absent()) {next.set(id, { id, name, color: color ?? "blue", threadId: "", tasks: [], resumeCursors: {}, modelSelection: { instanceId: "", model: "" },- home: { place, placeName, botId, ...(kind ? { kind } : {}), gone }, ...(title ? { title } : {}), ...(mascotBody ? { mascotBody } : {}), ...(mascotFaceColor ? { mascotFaceColor } : {}), ...bodyColor(mascotBodyColor) } as unknown as BotRecord);+ home: { place, placeName, botId, ...(kind ? { kind } : {}), gone }, ...(title ? { title } : {}), ...(mascotBody ? { mascotBody } : {}), ...(mascotFaceColor ? { mascotFaceColor } : {}), ...bodyColor(mascotBodyColor), ...fur(mascotMaterial) } as unknown as BotRecord);}store.standIns.clear();for (const [id, record] of next) if (isLinkedId(id)) store.standIns.set(id, record);diff --git a/server/host/bot-link-rooms.ts b/server/host/bot-link-rooms.tsindex c402162568..d0c2506951 100644--- a/server/host/bot-link-rooms.ts+++ b/server/host/bot-link-rooms.ts@@ -47,7 +47,7 @@ const FILE = "bot-link-rooms.json";const RECORDS_MAX = 2_000;/** What a far member was last known as, kept so that it can be named while its place cannot be asked. */-interface Known { name: string; color?: string; place: string; placeName: string; botId: string; kind?: "computer" | "cloud"; title?: string; mascotBody?: string; mascotFaceColor?: string; mascotBodyColor?: string }+interface Known { name: string; color?: string; place: string; placeName: string; botId: string; kind?: "computer" | "cloud"; title?: string; mascotBody?: string; mascotFaceColor?: string; mascotBodyColor?: string; mascotMaterial?: string }/** One turn handed over: where its words started and ended, so that the same turn sent again says the same and more, never* less; and how many members' answers led to it. */interface Turn { seat: string; hop: number; at: number; composed?: boolean; after?: string; through?: string }@@ -72,7 +72,7 @@ export interface LinkedRoomsDeps {linked(peer: string): boolean;online(peer: string): boolean;/** The bots the linked places have now, by their address here. */- linkedBots(): ReadonlyArray<{ id: string; peer: string; place: { name: string }; kind?: "computer" | "cloud"; bot: { id: string; name: string; color?: string; title?: string; mascotBody?: string; mascotFaceColor?: string; mascotBodyColor?: string } }>;+ linkedBots(): ReadonlyArray<{ id: string; peer: string; place: { name: string }; kind?: "computer" | "cloud"; bot: { id: string; name: string; color?: string; title?: string; mascotBody?: string; mascotFaceColor?: string; mascotBodyColor?: string; mascotMaterial?: string } }>;selfName(): string;/** There is work for a place that is not connected: a computer asks its Cloud for it now, as for any hand-off. */wanted(): void;@@ -180,7 +180,7 @@ export function createLinkedRooms(deps: LinkedRoomsDeps) {const one = live.get(id);if (one) kept.members[id] = { name: one.bot.name, place: one.peer, placeName: one.place.name, botId: one.bot.id, ...(one.kind ? { kind: one.kind } : {}), ...(one.bot.color ? { color: one.bot.color } : {}),...(one.bot.title ? { title: one.bot.title } : {}), ...(one.bot.mascotBody ? { mascotBody: one.bot.mascotBody } : {}), ...(one.bot.mascotFaceColor ? { mascotFaceColor: one.bot.mascotFaceColor } : {}),- ...(one.bot.mascotBodyColor ? { mascotBodyColor: one.bot.mascotBodyColor } : {}) };+ ...(one.bot.mascotBodyColor ? { mascotBodyColor: one.bot.mascotBodyColor } : {}), ...(one.bot.mascotMaterial ? { mascotMaterial: one.bot.mascotMaterial } : {}) };}for (const id of Object.keys(kept.members)) if (!ids.has(id)) delete kept.members[id];if (JSON.stringify([kept.members, Object.keys(kept.seats)]) !== before) save();diff --git a/server/mascot-face-color.e2e.test.ts b/server/mascot-face-color.e2e.test.tsindex 2bc4d88fd5..7194031447 100644--- a/server/mascot-face-color.e2e.test.ts+++ b/server/mascot-face-color.e2e.test.ts@@ -64,3 +64,33 @@ it("saves, reads and clears a custom body color through the isolated HTTP routesawait fixture.close();}}, 60_000);++it("saves, reads and clears the fluffy finish through the isolated HTTP routes", async () => {+ const fixture = await launchVerificationServer();+ const api = async (method: string, path: string, body?: unknown, status = 200) => {+ const response = await fetch(`${fixture.info.url}${path}`, {+ method, headers: { "content-type": "application/json", origin: fixture.info.url },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ });+ const data = await response.json() as { bot: WireBot; bots: WireBot[]; error?: string };+ expect(response.status, JSON.stringify(data)).toBe(status);+ return data;+ };+ try {+ const { bot } = await api("POST", "/api/bots", {+ name: "Fluffy fixture", useDefaults: false, settings: { color: "yellow", mascotBody: "blob", mascotMaterial: "fluffy" },+ }, 201);+ expect(bot.mascotMaterial).toBe("fluffy");+ const path = `/api/bots/${bot.id}`;+ for (const mascotMaterial of ["fluffy", null]) {+ expect((await api("PATCH", path, { mascotMaterial })).bot.mascotMaterial).toBe(mascotMaterial);+ const saved = JSON.parse(readFileSync(join(fixture.info.dataDir, "bots.json"), "utf8"));+ expect(saved.find((value: { id: string }) => value.id === bot.id).mascotMaterial).toBe(mascotMaterial);+ }+ expect((await api("PATCH", path, { mascotMaterial: "shaggy" }, 400)).error).toBe("mascotMaterial must be fluffy, or null");+ const after = (await api("GET", "/api/bots")).bots.find((value: { id: string }) => value.id === bot.id);+ expect(after).toMatchObject({ color: "yellow", mascotBody: "blob", mascotMaterial: null });+ } finally {+ await fixture.close();+ }+}, 60_000);diff --git a/server/request-auth.ts b/server/request-auth.tsindex 3e37a0bda7..2f00b544b4 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -532,12 +532,12 @@ export function requiredScope(method: string, path: string, features: { sharedCo/** A client may change how a bot looks, never what it may do. */const CLIENT_BOT_PATCH_FIELDS = new Set([- "unread", "pinned", "pinnedMessageId", "color", "mascotExpression", "mascotBody", "mascotFaceColor", "mascotBodyColor",+ "unread", "pinned", "pinnedMessageId", "color", "mascotExpression", "mascotBody", "mascotFaceColor", "mascotBodyColor", "mascotMaterial","avatarUrl", "avatarCrop", "avatarZoom", "avatarFocusX", "avatarFocusY", "sidebarHidden", "welcomed",]);/** How a bot looks to everyone who sees it. */const SHARED_LOOK_FIELDS = new Set([- "color", "mascotExpression", "mascotBody", "mascotFaceColor", "mascotBodyColor", "avatarUrl", "avatarCrop", "avatarZoom", "avatarFocusX", "avatarFocusY",+ "color", "mascotExpression", "mascotBody", "mascotFaceColor", "mascotBodyColor", "mascotMaterial", "avatarUrl", "avatarCrop", "avatarZoom", "avatarFocusX", "avatarFocusY",]);/** `ownMausBot`: the session's own MausBot on a Team Cloud, which its member may also rename. `teamMember`: a Team Cloud* member's session, which changes no other bot's look. */diff --git a/server/routes/bot-link.ts b/server/routes/bot-link.tsindex 4bf6994b50..8416e751bf 100644--- a/server/routes/bot-link.ts+++ b/server/routes/bot-link.ts@@ -103,7 +103,7 @@ export function createBotLinkRoutes(deps: BotLinkRouteDeps): RouteHandler {// Names and looks only, as each place told this one: no message, address or sign-in.return json(res, 200, { bots: link.linked().map(({ id, peer, place, kind, online, bot }) => ({ id, home: { id: place.id, key: peer, kind, name: place.name, online }, botId: bot.id, name: bot.name,...(bot.title ? { title: bot.title } : {}), ...(bot.color ? { color: bot.color } : {}), ...(bot.mascotBody ? { mascotBody: bot.mascotBody } : {}),- ...(bot.mascotFaceColor ? { mascotFaceColor: bot.mascotFaceColor } : {}), ...(bot.mascotBodyColor ? { mascotBodyColor: bot.mascotBodyColor } : {}),+ ...(bot.mascotFaceColor ? { mascotFaceColor: bot.mascotFaceColor } : {}), ...(bot.mascotBodyColor ? { mascotBodyColor: bot.mascotBodyColor } : {}), ...(bot.mascotMaterial ? { mascotMaterial: bot.mascotMaterial } : {}),...(bot.chief ? { chiefOfStaff: true } : {}), ...(bot.threadId ? { threadId: bot.threadId } : {}) })) });}diff --git a/server/store.ts b/server/store.tsindex 7057a0f287..9525381bb0 100644--- a/server/store.ts+++ b/server/store.ts@@ -1263,7 +1263,7 @@ export class Store {profile: Partial<Pick<BotRecord,- "name" | "title" | "description" | "soul" | "color" | "mascotExpression" | "mascotBody" | "mascotFaceColor" | "mascotBodyColor" | "modelSelection" | "section" | "cwd" | "visibility" | "toolScope" | "createdBy" | "reportsTo"+ "name" | "title" | "description" | "soul" | "color" | "mascotExpression" | "mascotBody" | "mascotFaceColor" | "mascotBodyColor" | "mascotMaterial" | "modelSelection" | "section" | "cwd" | "visibility" | "toolScope" | "createdBy" | "reportsTo">> = {},opts: {@@ -1285,7 +1285,7 @@ export class Store {soul: profile.soul ?? "",soulHash: soulHash(profile.soul ?? ""),notifications: true,- color: profile.color ?? rotationColor(this.bots.length), mascotFaceColor: profile.mascotFaceColor ?? undefined, mascotBodyColor: profile.mascotBodyColor ?? undefined,+ color: profile.color ?? rotationColor(this.bots.length), mascotFaceColor: profile.mascotFaceColor ?? undefined, mascotBodyColor: profile.mascotBodyColor ?? undefined, mascotMaterial: profile.mascotMaterial ?? undefined,...(profile.mascotExpression ? { mascotExpression: profile.mascotExpression } : {}),...(profile.mascotBody ? { mascotBody: profile.mascotBody } : {}),...this.newBotSharing(profile.visibility, newBotOwner(profile)),diff --git a/server/team-backup.test.ts b/server/team-backup.test.tsindex d5d35decfc..ad145c3c88 100644--- a/server/team-backup.test.ts+++ b/server/team-backup.test.ts@@ -24,7 +24,7 @@ function fixture() {});const chief = store.createBot({ name: "Mira", section: "Engineering", description: "Full instructions\n".repeat(400) }, { seedMessages: false });store.setSoul(chief.id, " Cite sources.\nRespect the user's current request. 🐭\n");- const scout = store.createBot({ name: "Scout", section: "Engineering", mascotBody: "circle", mascotFaceColor: "black", mascotBodyColor: "#12ab9f" }, { seedMessages: false });+ const scout = store.createBot({ name: "Scout", section: "Engineering", mascotBody: "circle", mascotFaceColor: "black", mascotBodyColor: "#12ab9f", mascotMaterial: "fluffy" }, { seedMessages: false });const otherChief = store.createBot({ name: "Ava", section: "Operations" }, { seedMessages: false });const archived = store.createBot({ name: "Archived" }, { seedMessages: false });store.patchBot(archived.id, { hidden: true });@@ -211,6 +211,7 @@ describe("additive portable team backups", () => {expect(importedScout.mascotBody).toBe(scout.mascotBody);expect(importedScout.mascotFaceColor).toBe("black");expect(importedScout.mascotBodyColor).toBe("#12ab9f");+ expect(importedScout.mascotMaterial).toBe("fluffy");expect(result.groups[0]).toMatchObject({ name: "Project room 2", section: "Engineering 2", memberIds: [importedChief.id, importedScout.id], defaultResponder: { kind: "member", botId: importedChief.id } });expect(result.groups[0].tasks?.map((task) => [task.title, task.createdAt])).toEqual(group.tasks?.map((task) => [task.title, task.createdAt]));const roomMessage = store.messagesFor(result.groups[0].threadId)[0];diff --git a/server/team-backup.ts b/server/team-backup.tsindex 7af4c724de..f0b4bcebac 100644--- a/server/team-backup.ts+++ b/server/team-backup.ts@@ -115,7 +115,7 @@ export function createTeamBackup(store: Store, routines: Routine[], name: stringkey: bot.id, name: bot.name, title: bot.title, description: bot.description, soul: bot.soul,section: bot.section, color: bot.color,mascotExpression: bot.mascotExpression ?? undefined, mascotBody: bot.mascotBody ?? undefined,- mascotFaceColor: bot.mascotFaceColor ?? undefined, mascotBodyColor: bot.mascotBodyColor ?? undefined,+ mascotFaceColor: bot.mascotFaceColor ?? undefined, mascotBodyColor: bot.mascotBodyColor ?? undefined, mascotMaterial: bot.mascotMaterial ?? undefined,chiefOfStaff: Boolean(bot.chiefOfStaff), hidden: Boolean(bot.hidden), playbooks: bot.playbooks ?? [],// Grants travel so the team's shape survives, but the import still lands every bot grant-less....(bot.connectorTools ? { connectorTools: structuredClone(bot.connectorTools) } : {}),@@ -185,7 +185,7 @@ export function importTeamBackup(store: Store, routines: RoutineManager, input:name: takeImportName(source.name, takenNames), title: source.title, description: source.description, soul: source.soul,color: source.color, mascotExpression: source.mascotExpression,mascotBody: botBodyId(source.mascotBody),- mascotFaceColor: source.mascotFaceColor, mascotBodyColor: source.mascotBodyColor,+ mascotFaceColor: source.mascotFaceColor, mascotBodyColor: source.mascotBodyColor, mascotMaterial: source.mascotMaterial,modelSelection: selection, section: sectionFor(source.section),// who may see the imported team is the importing admin's choice...(options.visibility ? { visibility: options.visibility } : {}),diff --git a/shared/new-bot-defaults.ts b/shared/new-bot-defaults.tsindex 5ae1f616ce..93be6e391b 100644--- a/shared/new-bot-defaults.ts+++ b/shared/new-bot-defaults.ts@@ -5,7 +5,7 @@ import type { ToolScope } from "./tool-scope";/** Data shared by the default template and an individual creation draft. */export type BotDefaultsProfile = Partial<Pick<WireBot,"name" | "title" | "description" | "soul" | "notifications" | "avatarUrl" | "avatarCrop" |- "mascotBody" | "mascotFaceColor" | "mascotBodyColor" | "color" | "voice" | "speakReplies" | "section" | "modelSelection" |+ "mascotBody" | "mascotFaceColor" | "mascotBodyColor" | "mascotMaterial" | "color" | "voice" | "speakReplies" | "section" | "modelSelection" |"cloudBackend" | "autoStartVps" | "approvalMode" | "alwaysAllow" | "chiefOfStaff" |"managedSections" | "composio" | "browser" | "voiceNotes">> & {diff --git a/shared/team-backup.ts b/shared/team-backup.tsindex 332d28e3fa..ddb1ceac1b 100644--- a/shared/team-backup.ts+++ b/shared/team-backup.ts@@ -1,5 +1,5 @@import { z } from "zod";-import { mascotBodyColorSchema, mascotFaceColorSchema } from "./bot-avatar.ts";+import { mascotBodyColorSchema, mascotFaceColorSchema, mascotMaterialSchema } from "./bot-avatar.ts";import { CONNECTOR_SLUG_PATTERN, CONNECTOR_TOOL_NAME_PATTERN, MAUS_COLOR_NAMES } from "./wire.ts";import { parseToolScope, type ToolScope } from "./tool-scope.ts";@@ -123,6 +123,7 @@ const backupSchema = z.object({mascotBody: z.string().max(40).optional(),mascotFaceColor: mascotFaceColorSchema.optional(),mascotBodyColor: mascotBodyColorSchema.optional(),+ mascotMaterial: mascotMaterialSchema.optional(),chiefOfStaff: z.boolean(),hidden: z.boolean(),playbooks: z.array(playbook).max(200),diff --git a/src/components/AskCard.tsx b/src/components/AskCard.tsxindex 84bf48d3e8..5e8d7bed61 100644--- a/src/components/AskCard.tsx+++ b/src/components/AskCard.tsx@@ -10,7 +10,7 @@ import { BotAvatar } from "./Avatar";import { ELEVATED_CARD, ELEVATED_FLOAT } from "./elevated";/** The bot a card asks for: its face and name lead the card. */-export type Asker = Pick<Bot, "name" | "color"> & Partial<Pick<Bot, "avatarUrl" | "avatarCrop" | "avatarZoom" | "avatarFocusX" | "avatarFocusY" | "mascotBody" | "mascotFaceColor" | "mascotBodyColor">>;+export type Asker = Pick<Bot, "name" | "color"> & Partial<Pick<Bot, "avatarUrl" | "avatarCrop" | "avatarZoom" | "avatarFocusX" | "avatarFocusY" | "mascotBody" | "mascotFaceColor" | "mascotBodyColor" | "mascotMaterial">>;export function AskHeader({ asker, line, origin }: { asker: Asker; line: string; origin?: { label: string; hint: string; open(): void } }) {return (diff --git a/src/components/Avatar.tsx b/src/components/Avatar.tsxindex 51d6db6864..9c5aa31dbf 100644--- a/src/components/Avatar.tsx+++ b/src/components/Avatar.tsx@@ -13,7 +13,7 @@ import { CHROME_EYES, CHROME_GRADIENT, MAUS_COLORS, type MausColor, type MausMotimport { CursorAvatar, type CursorAvatarHandle } from "./CursorAvatar";import { ACTIVE_STATES } from "./mascot-motion";import { MOTION_BEAT_MS } from "./mascot-beat";-import { avatarCropRadius, botAvatarProfile, clampAvatarFocus, clampAvatarZoom, mascotBodyColorSchema, mascotFaceInk, type BotAvatarCrop, type MascotFaceColor } from "../../shared/bot-avatar";+import { avatarCropRadius, botAvatarProfile, clampAvatarFocus, clampAvatarZoom, mascotBodyColorSchema, mascotFaceInk, mascotMaterialSchema, type BotAvatarCrop, type MascotFaceColor, type MascotMaterial } from "../../shared/bot-avatar";import { MASCOT_BODIES, botMascotBody } from "../../shared/mascot-bodies";import { isCarvedBody, type BotBodyId } from "../../shared/bot-body";import { engineBody } from "../../shared/object-bodies";@@ -108,6 +108,8 @@ export type MausAvatarProps = {faceColor?: MascotFaceColor | null;/** A custom `#rrggbb` body colour; it wins over `color` for the body only. */bodyColor?: string | null;+ /** Fluffy fur on a body the engine draws (the shapes and objects); the cursor and festival bodies stay flat. */+ material?: MascotMaterial | null;/** Whose face this is; a decorative mascot has none. */kind?: AvatarKind;};@@ -139,6 +141,7 @@ function MausAvatarComponent(props: MausAvatarProps, ref: React.Ref<MausAvatarHa<ObjectAvatardefinition={definition}fill={customFill(props.bodyColor) ?? vivid(MAUS_COLORS[color] ?? MAUS_COLORS.green)}+ material={mascotMaterialSchema.safeParse(props.material).data}faceColor={props.faceColor}size={size}state={state}@@ -252,6 +255,7 @@ export type BotAvatarProps = Omit<MausAvatarProps, "color" | "gradient"> & {mascotBody?: BotBodyId | null;mascotFaceColor?: MascotFaceColor | null;mascotBodyColor?: string | null;+ mascotMaterial?: MascotMaterial | null;};};@@ -291,6 +295,7 @@ export function BotAvatar({ bot, size = 44, label, readable = false, ...mascotPrcolor={bot.color}faceColor={bot.mascotFaceColor}bodyColor={bot.mascotBodyColor}+ material={bot.mascotMaterial}gradient={readable ? roomAvatarGradient(bot.color) : undefined}size={size}label={label ?? bot.name}diff --git a/src/components/BotProfileAvatarCard.tsx b/src/components/BotProfileAvatarCard.tsxindex d96de58d96..8f6c79f401 100644--- a/src/components/BotProfileAvatarCard.tsx+++ b/src/components/BotProfileAvatarCard.tsx@@ -20,6 +20,7 @@ import { bodyName, colorName, expressionName, festivalName } from "@/lib/mascot-import { MascotBodyColorSwatch } from "./MascotBodyColorSwatch";import { AvatarCredit } from "./AvatarCredit";import { MascotFaceColorPicker } from "./MascotFaceColorPicker";+import { MascotMaterialPicker } from "./MascotMaterialPicker";export function BotProfileAvatarCard({bot,@@ -120,6 +121,7 @@ export function BotProfileAvatarCard({{crop === "mascot" && (<><MascotFaceColorPicker bot={bot} disabled={busy} onPatch={onPatch} />+ <MascotMaterialPicker bot={bot} disabled={busy} onPatch={onPatch} /><div className="mb-2 mt-4 text-[12px] font-medium uppercase tracking-[0.08em] text-ink-secondary">{t("botIdentity.expression")}</div>@@ -138,7 +140,7 @@ export function BotProfileAvatarCard({title={expressionName(expression)}aria-label={t("mascot.useExpression", { expression: expressionName(expression) })}>- <MausAvatar color={bot.color} faceColor={bot.mascotFaceColor} bodyColor={bot.mascotBodyColor} bodyId={bot.mascotBody ?? undefined} state={expression} size={42} animated={false} />+ <MausAvatar color={bot.color} faceColor={bot.mascotFaceColor} material={bot.mascotMaterial} bodyColor={bot.mascotBodyColor} bodyId={bot.mascotBody ?? undefined} state={expression} size={42} animated={false} /></button>))}</div>@@ -234,7 +236,7 @@ function BodyButton({ id, name, bot, busy, onPatch }: {selected ? "bg-control text-ink" : "text-ink-secondary hover:bg-control/60",)}>- <MausAvatar color={bot.color} faceColor={bot.mascotFaceColor} bodyColor={bot.mascotBodyColor} bodyId={id} size={34} animated={false} trackPointer={false} />+ <MausAvatar color={bot.color} faceColor={bot.mascotFaceColor} material={bot.mascotMaterial} bodyColor={bot.mascotBodyColor} bodyId={id} size={34} animated={false} trackPointer={false} /></button>);}diff --git a/src/components/BotSettingsDialog.simple.test.ts b/src/components/BotSettingsDialog.simple.test.tsindex 1f7436ec69..e7a82467d5 100644--- a/src/components/BotSettingsDialog.simple.test.ts+++ b/src/components/BotSettingsDialog.simple.test.ts@@ -150,6 +150,7 @@ const { SignedInSites } = await import("./SignedInSites");const { AvatarImageGenerator } = await import("./AvatarImageGenerator");const { AvatarFraming } = await import("./avatar-editing");const { MascotFaceColorPicker } = await import("./MascotFaceColorPicker");+const { MascotMaterialPicker } = await import("./MascotMaterialPicker");const { MascotBodyColorSwatch } = await import("./MascotBodyColorSwatch");const { Switch } = await import("./SettingsPrimitives");const { OrgSkillsCard } = await import("./bot-settings/OrgSkillsCard");@@ -570,7 +571,7 @@ describe("the avatar editor", () => {it("resets the mascot as the Advanced card does", () => {click(find(editor(makeBot()), "data-avatar-reset"));- expect(patch).toHaveBeenLastCalledWith({ avatarCrop: "mascot", color: "green", mascotExpression: null, mascotBody: "cursor", mascotFaceColor: null, mascotBodyColor: null });+ expect(patch).toHaveBeenLastCalledWith({ avatarCrop: "mascot", color: "green", mascotExpression: null, mascotBody: "cursor", mascotFaceColor: null, mascotBodyColor: null, mascotMaterial: null });});it("picks a custom body color after the swatches, and a named swatch clears it", () => {@@ -603,6 +604,31 @@ describe("the avatar editor", () => {expect(patch).toHaveBeenLastCalledWith({ mascotFaceColor: "white" });});+ it("offers Fluffy only on an engine-drawn body, and Flat clears it", () => {+ const fur = (bot: Bot) => {+ const props = ofType(editor(bot), MascotMaterialPicker)!.props as Parameters<typeof MascotMaterialPicker>[0];+ return capture(() => MascotMaterialPicker(props));+ };+ expect(fur(makeBot()).html).toBe("");+ fresh();+ expect(fur(makeBot({ mascotBody: "cursor" })).html).toBe("");+ fresh();+ const bare = fur(makeBot({ mascotBody: "blob" }));+ expect(bare.html).toContain(">Finish<");+ const choices = segment(bare, "data-avatar-material");+ expect(choices.value).toBe("off");+ expect(choices.options.map((option) => [option.value, option.label])).toEqual([+ ["off", "Flat"], ["fluffy", "Fluffy"],+ ]);+ choices.onChange("fluffy");+ expect(patch).toHaveBeenLastCalledWith({ mascotMaterial: "fluffy" });+ fresh();+ const furred = segment(fur(makeBot({ mascotBody: "obj-mug", mascotMaterial: "fluffy" })), "data-avatar-material");+ expect(furred.value).toBe("fluffy");+ furred.onChange("off");+ expect(patch).toHaveBeenLastCalledWith({ mascotMaterial: null });+ });+it("generates with the shared generator, and uploads with shape and framing", () => {const bot = makeBot();click(find(editor(bot), "data-avatar-tab", "generate"));diff --git a/src/components/MascotMaterialPicker.tsx b/src/components/MascotMaterialPicker.tsxnew file mode 100644index 0000000000..89dbfd9802--- /dev/null+++ b/src/components/MascotMaterialPicker.tsx@@ -0,0 +1,27 @@+import { t } from "@/lib/i18n";+import type { Bot } from "@/state/store";+import { MASCOT_MATERIALS } from "../../shared/bot-avatar";+import { engineBody } from "../../shared/object-bodies";+import type { AvatarPatch } from "./avatar-editing";+import { Segmented } from "./bot-panel/rows";++/** Flat or fluffy for the engine-drawn bodies; the cursor and festival bodies are always flat, so the row hides for them. */+export function MascotMaterialPicker({ bot, disabled, onPatch }: {+ bot: Bot;+ disabled: boolean;+ onPatch: (patch: AvatarPatch) => void;+}) {+ if (!engineBody(bot.mascotBody)) return null;+ return (+ <div className="mt-3">+ <div className="mb-1.5 text-[12px] text-ink-secondary">{t("botIdentity.material")}</div>+ <Segmented+ attr="data-avatar-material"+ label={t("botIdentity.material")}+ value={bot.mascotMaterial ?? "off"}+ onChange={(value) => onPatch({ mascotMaterial: value === "off" ? null : value })}+ options={(["off", ...MASCOT_MATERIALS] as const).map((value) => ({ value, label: t(`botIdentity.material.${value}`), disabled }))}+ />+ </div>+ );+}diff --git a/src/components/ObjectAvatar.tsx b/src/components/ObjectAvatar.tsxindex 238e3d2b9d..be8ce266d0 100644--- a/src/components/ObjectAvatar.tsx+++ b/src/components/ObjectAvatar.tsx@@ -1,7 +1,7 @@import { memo, useEffect, useRef, useState } from "react";import type { MausState } from "@/lib/mascot";import { avatarMarks, type AvatarKind } from "@/lib/avatar-marks";-import { mascotFaceInk, type MascotFaceColor } from "../../shared/bot-avatar";+import { mascotFaceInk, type MascotFaceColor, type MascotMaterial } from "../../shared/bot-avatar";import { mountAvatar, type AvatarOptions, type MountedAvatar } from "../../packages/phone-protocol/src/open-bot-avatar/dom/index.ts";import type { AvatarDefinition, AvatarMood, AvatarState } from "../../packages/phone-protocol/src/open-bot-avatar/types.ts";import { DONE_TURN_S } from "../../packages/phone-protocol/src/open-bot-avatar/motion.ts";@@ -56,6 +56,7 @@ export type ObjectAvatarProps = {/** Body colour as a hex. */fill: string;faceColor?: MascotFaceColor | null;+ material?: MascotMaterial;size?: number;state?: MausState;trackPointer?: boolean;@@ -64,7 +65,7 @@ export type ObjectAvatarProps = {kind?: AvatarKind;};-function ObjectAvatarComponent({ definition, fill, faceColor, size = 44, state = "idle", trackPointer = true, animated, label, kind }: ObjectAvatarProps) {+function ObjectAvatarComponent({ definition, fill, faceColor, material, size = 44, state = "idle", trackPointer = true, animated, label, kind }: ObjectAvatarProps) {const reduced = usePrefersReducedMotion();const cheering = useFinishCheer(state);const live = !reduced && (animated ?? (ACTIVE_STATES.has(state) || cheering));@@ -73,6 +74,7 @@ function ObjectAvatarComponent({ definition, fill, faceColor, size = 44, state =definition,color: fill,eyeColor: mascotFaceInk(faceColor),+ material,followPointer: trackPointer,still: !live,label: label ?? "",diff --git a/src/components/OtherPlaceBots.tsx b/src/components/OtherPlaceBots.tsxindex 9fd70c5acf..3c571da5c7 100644--- a/src/components/OtherPlaceBots.tsx+++ b/src/components/OtherPlaceBots.tsx@@ -3,7 +3,7 @@import { useState } from "react";import { Cloud } from "lucide-react";import { BOT_BODY_IDS, type BotBodyId } from "../../shared/bot-body";-import { MASCOT_FACE_COLORS, mascotBodyColorSchema, type MascotFaceColor } from "../../shared/bot-avatar";+import { MASCOT_FACE_COLORS, mascotBodyColorSchema, mascotMaterialSchema, type MascotFaceColor } from "../../shared/bot-avatar";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { useAdvancedMode } from "@/lib/interface-mode";@@ -42,7 +42,8 @@ function avatarOf(row: PlaceBotRow) {const body = (BOT_BODY_IDS as readonly string[]).includes(row.mascotBody ?? "") ? row.mascotBody as BotBodyId : null;const face = (MASCOT_FACE_COLORS as readonly string[]).includes(row.mascotFaceColor ?? "") ? row.mascotFaceColor as MascotFaceColor : null;const tint = mascotBodyColorSchema.safeParse(row.mascotBodyColor).data ?? null;- return { name: row.name, color, mascotBody: body, mascotFaceColor: face, mascotBodyColor: tint };+ const material = mascotMaterialSchema.safeParse(row.mascotMaterial).data ?? null;+ return { name: row.name, color, mascotBody: body, mascotFaceColor: face, mascotBodyColor: tint, mascotMaterial: material };}function OtherPlaceBotRow({ row, dim, iconOnly, simple }: { row: PlaceBotRow; dim: boolean; iconOnly: boolean; simple: boolean }) {diff --git a/src/components/avatar-editing.tsx b/src/components/avatar-editing.tsxindex 8fa7473b8f..dc808bc397 100644--- a/src/components/avatar-editing.tsx+++ b/src/components/avatar-editing.tsx@@ -18,10 +18,10 @@ import { useBotEditor } from "./bot-settings/BotEditorContext";import { useStoreActions } from "@/state/store-select";export type AvatarPatch = Partial<- Pick<Bot, "avatarCrop" | "avatarUrl" | "avatarZoom" | "avatarFocusX" | "avatarFocusY" | "color" | "mascotExpression" | "mascotBody" | "mascotFaceColor" | "mascotBodyColor">+ Pick<Bot, "avatarCrop" | "avatarUrl" | "avatarZoom" | "avatarFocusX" | "avatarFocusY" | "color" | "mascotExpression" | "mascotBody" | "mascotFaceColor" | "mascotBodyColor" | "mascotMaterial">>;-export const RESET_MASCOT_PATCH: AvatarPatch = { avatarCrop: "mascot", color: "green", mascotExpression: null, mascotBody: "cursor", mascotFaceColor: null, mascotBodyColor: null };+export const RESET_MASCOT_PATCH: AvatarPatch = { avatarCrop: "mascot", color: "green", mascotExpression: null, mascotBody: "cursor", mascotFaceColor: null, mascotBodyColor: null, mascotMaterial: null };export const CROP_LABEL = {mascot: "Mascot",diff --git a/src/components/bot-panel/AvatarEditorCard.tsx b/src/components/bot-panel/AvatarEditorCard.tsxindex d23b107f06..602cd2c812 100644--- a/src/components/bot-panel/AvatarEditorCard.tsx+++ b/src/components/bot-panel/AvatarEditorCard.tsx@@ -15,6 +15,7 @@ import { AvatarImageGenerator } from "../AvatarImageGenerator";import { AvatarFraming, OrganizationAvatarIcons, RESET_MASCOT_PATCH, useAvatarImage, type AvatarPatch } from "../avatar-editing";import { Segmented } from "./rows";import { MascotFaceColorPicker } from "../MascotFaceColorPicker";+import { MascotMaterialPicker } from "../MascotMaterialPicker";import { MascotBodyColorSwatch } from "../MascotBodyColorSwatch";import { AvatarCredit } from "../AvatarCredit";import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";@@ -92,7 +93,7 @@ export function AvatarEditorCard({ bot, activeState, onPatch, onClose }: {!showsImage && body === id ? "bg-ink/[0.08] ring-[1.5px] ring-inset ring-ink/25" : "hover:bg-ink/[0.05]",)}>- <MausAvatar color={bot.color} faceColor={bot.mascotFaceColor} bodyColor={bot.mascotBodyColor} bodyId={id} size={40} animated={false} trackPointer={false} />+ <MausAvatar color={bot.color} faceColor={bot.mascotFaceColor} material={bot.mascotMaterial} bodyColor={bot.mascotBodyColor} bodyId={id} size={40} animated={false} trackPointer={false} /></button>);@@ -186,6 +187,7 @@ export function AvatarEditorCard({ bot, activeState, onPatch, onClose }: {/></div><MascotFaceColorPicker bot={bot} disabled={busy} onPatch={pickMascot} />+ <MascotMaterialPicker bot={bot} disabled={busy} onPatch={pickMascot} /><buttontype="button"data-avatar-morediff --git a/src/components/bot-settings/useBotSettingsDerived.ts b/src/components/bot-settings/useBotSettingsDerived.tsindex 184dc42b5f..4c2ef3455d 100644--- a/src/components/bot-settings/useBotSettingsDerived.ts+++ b/src/components/bot-settings/useBotSettingsDerived.ts@@ -23,6 +23,7 @@ export type BotPatch = Partial<| "mascotBody"| "mascotFaceColor"| "mascotBodyColor"+ | "mascotMaterial"| "avatarUrl"| "avatarCrop"| "avatarZoom"diff --git a/src/lib/drawn-bots.ts b/src/lib/drawn-bots.tsindex 49af99196e..45dc68da26 100644--- a/src/lib/drawn-bots.ts+++ b/src/lib/drawn-bots.ts@@ -3,7 +3,7 @@ import type { Bot } from "@/state/store";const drawn = (bot: Bot) => [// title and chiefOfStaff: the @-mention menu describes each bot by them.bot.id, bot.name, bot.title, bot.chiefOfStaff, bot.hidden, bot.sidebarHidden, JSON.stringify(bot.defaultBot ?? null), bot.color, bot.mascotBody, bot.mascotExpression,- bot.mascotFaceColor, bot.mascotBodyColor, bot.avatarUrl, bot.avatarCrop, bot.avatarZoom, bot.avatarFocusX, bot.avatarFocusY,+ bot.mascotFaceColor, bot.mascotBodyColor, bot.mascotMaterial, bot.avatarUrl, bot.avatarCrop, bot.avatarZoom, bot.avatarFocusX, bot.avatarFocusY,].join("\u0001");/** For a reader that draws other bots only by name, look and whether they are shown: a turn changing none of thatdiff --git a/src/locales/en.json b/src/locales/en.jsonindex 9fd29fd621..89657744c8 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -7607,6 +7607,9 @@"botIdentity.faceColor.white": "White","botIdentity.faceColor.black": "Black","botIdentity.faceColor.default": "Body default",+ "botIdentity.material": "Finish",+ "botIdentity.material.off": "Flat",+ "botIdentity.material.fluffy": "Fluffy","botIdentity.avatar": "Avatar","botIdentity.resetMascot": "Reset mascot","botIdentity.uploadImage": "Upload image",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 5f3f82e0e3..6bc37f1d02 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -7251,6 +7251,9 @@"botIdentity.faceColor.white": "Brancos","botIdentity.faceColor.black": "Pretos","botIdentity.faceColor.default": "Padrão do corpo",+ "botIdentity.material": "Acabamento",+ "botIdentity.material.off": "Liso",+ "botIdentity.material.fluffy": "Fofo","botIdentity.avatar": "Avatar","botIdentity.resetMascot": "Redefinir mascote","botIdentity.uploadImage": "Enviar imagem",diff --git a/src/state/bot-patch-queue.ts b/src/state/bot-patch-queue.tsindex d0558bb375..4c2b366d20 100644--- a/src/state/bot-patch-queue.ts+++ b/src/state/bot-patch-queue.ts@@ -16,6 +16,7 @@ export type BotUpdatePatch = Partial<| "mascotBody"| "mascotFaceColor"| "mascotBodyColor"+ | "mascotMaterial"| "avatarUrl"| "avatarCrop"| "avatarZoom"diff --git a/src/state/store.tsx b/src/state/store.tsxindex 9fd0e33a1f..699521d319 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -273,7 +273,7 @@ export interface TaskUsage {context?: { tokens: number; window?: number };}-export interface Bot extends DefaultBotFields, Pick<WireBot, "mascotFaceColor" | "mascotBodyColor" | "access" | "yourAccess" | "onlyPeopleAdded"> {+export interface Bot extends DefaultBotFields, Pick<WireBot, "mascotFaceColor" | "mascotBodyColor" | "mascotMaterial" | "access" | "yourAccess" | "onlyPeopleAdded"> {toolScope?: ToolScope;waitingForTeammates?: boolean;id: string;