Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(avatar): richer beam faces — 8 shapes, hat-zone top-reserve

Shellye232e7da287a
diff --git a/src/web/src/lib/avatar/face.test.ts b/src/web/src/lib/avatar/face.test.ts
index 831489781..2f9bb5b97 100644
--- a/src/web/src/lib/avatar/face.test.ts
+++ b/src/web/src/lib/avatar/face.test.ts
@@ -76,11 +76,13 @@ describe("renderFaceSvg", () => {
it("keeps the tilt gentle (upright, human) — never a full spin", () => {
// Faces ride the shape rotation; a big spin flips them upside-down ("not a
- // face anymore"). Rotation must stay within ±~12°.
+ // face anymore"). Rotation must stay within ±8° (rot = i%17 − 8). A wider
+ // tilt would also eat the crown-reserve budget (radial shapes are rotation-
+ // invariant in max radius, but the closed-form bound assumes this cap).
for (let n = 0; n < 80; n++) {
const svg = renderFaceSvg(`r-${n}`, PALETTE)
const rot = parseFloat((svg.match(/rotate\((-?\d+(?:\.\d+)?)/) ?? ["", "0"])[1])
- expect(Math.abs(rot)).toBeLessThanOrEqual(12)
+ expect(Math.abs(rot)).toBeLessThanOrEqual(8)
}
})
@@ -121,6 +123,57 @@ describe("renderFaceSvg", () => {
}
})
+ it("reserves the top ~20% (y<7.2) for a hat — the crown never pokes into the band", () => {
+ // The head is placed low (center y23.5) and sized (R14.45) so the top of the
+ // canvas stays clear for a future hat ("头的最高点不能超过帽子"). Recompute the
+ // transformed topmost point of the wrapper path for many seeds and assert it
+ // stays >= HAT_LINE. This mirrors the closed-form bound (worst crown ~8.76);
+ // if a shape/geometry change lowered the crown into the band, this fails.
+ const HAT_LINE = 7.2
+ const CX = 18
+ const CYh = 23.5
+ for (let n = 0; n < 400; n++) {
+ const svg = renderFaceSvg(`hat-${n}`, PALETTE)
+ // Pull the wrapper path (first <path> after the shape group) and its transform.
+ const xf = svg.match(/<g transform="([^"]+)"/)![1]
+ const rot = parseFloat((xf.match(/rotate\((-?\d+(?:\.\d+)?)/) ?? ["", "0"])[1])
+ const scale = parseFloat((xf.match(/scale\((-?\d+(?:\.\d+)?)\)/) ?? ["", "1"])[1])
+ const tr = xf.match(/translate\((-?\d+(?:\.\d+)?) (-?\d+(?:\.\d+)?)\)/)!
+ const [tx, ty] = [parseFloat(tr[1]), parseFloat(tr[2])]
+ const d = svg.match(/<path d="([^"]+)"/)![1]
+ const pts = [...d.matchAll(/(-?\d+(?:\.\d+)?) (-?\d+(?:\.\d+)?)/g)].map((m) => [parseFloat(m[1]), parseFloat(m[2])])
+ const rad = (rot * Math.PI) / 180
+ let crown = Infinity
+ for (const [px, py] of pts) {
+ // scale about center, rotate about center, translate — matches faceXf.
+ const sx = CX + (px - CX) * scale
+ const sy = CYh + (py - CYh) * scale
+ const dx = sx - CX
+ const dy = sy - CYh
+ const y = CYh + (dx * Math.sin(rad) + dy * Math.cos(rad)) + ty
+ crown = Math.min(crown, y)
+ }
+ void tx
+ expect(crown).toBeGreaterThanOrEqual(HAT_LINE)
+ }
+ })
+
+ it("picks shape, eye, and mouth independently and near-uniformly (no digit%6 clustering)", () => {
+ // The old code coupled features to a shared 0–9 digit %6, making idx 4/5 only
+ // ~10% and collapsing the combination space. Radix slicing (i%8, (i/8)%6,
+ // (i/48)%6) gives each feature its own uniform, decorrelated index. Count how
+ // many distinct shapes/eyes/mouths appear across many seeds — all should show.
+ const shapes = new Set<string>()
+ const svgs: string[] = []
+ for (let n = 0; n < 4000; n++) svgs.push(renderFaceSvg(`d-${n}`, PALETTE))
+ // Distinct wrapper paths ≈ distinct shapes (8 shapes → the path d differs).
+ for (const svg of svgs) shapes.add(svg.match(/<path d="([^"]+)"/)![1].slice(0, 24))
+ // All 8 shapes should appear; if features collapsed, far fewer distinct heads.
+ expect(shapes.size).toBeGreaterThanOrEqual(8)
+ // The full head (shape+eye+mouth) space is large: expect many distinct faces.
+ expect(new Set(svgs).size).toBeGreaterThan(100)
+ })
+
it("keeps face wrapper and background readably apart on every palette (no low-contrast melt)", () => {
// The bug Gus hit: an all-light palette (idx 6) could pair a light wrapper
// with a near-light background, melting the face into the bg. bg is now the
diff --git a/src/web/src/lib/avatar/face.ts b/src/web/src/lib/avatar/face.ts
index 0c6cc526e..0f574ad25 100644
--- a/src/web/src/lib/avatar/face.ts
+++ b/src/web/src/lib/avatar/face.ts
@@ -1,23 +1,39 @@
// Generated "beam" face renderer — the richer replacement for boring-avatars'
-// fixed beam geometry. Ported from the approved design prototype
-// (Alli, avatar-features.mjs). Same 36-unit canvas, same wrapper transform +
-// PRNG, same auto-contrast ink as the lib's beam, so it reads as "more of the
-// same face", not a new style. Only the feature vocabulary grew:
-// 6 shapes (silhouette-distinct, not corner-radius) · 6 eyes · 6 mouths.
-// Each seed picks its shape/eye/mouth deterministically, so a given id always
-// renders the same face and never flickers across renames.
+// fixed beam geometry. Ported from the approved design prototype (Alli). Same
+// 36-unit canvas, same PRNG + auto-contrast ink as the lib's beam, so it reads
+// as "more of the same face", not a new style. The feature vocabulary grew:
+// 8 shapes (silhouette-distinct) · 6 eyes · 6 mouths.
+// Each seed picks its shape/eye/mouth deterministically (INDEPENDENTLY), so a
+// given id always renders the same face and never flickers across renames.
+//
+// TOP-RESERVE: the head sits in the LOWER band of the canvas, leaving the top
+// ~20% (y ≤ HAT_LINE) clear for a future hat system — a hat must be able to sit
+// ABOVE the crown ("头的最高点不能超过帽子"). The crown is guaranteed ≥ HAT_LINE
+// for every shape under every random tilt/scale/nudge (see the closed-form
+// bound + brute-force check in the design harness).
//
// `beam` only. Marble (server/channel icons, banner) stays on the lib.
const C = 36
const CX = 18
-const CY = 18
-const R = 17
+// Head center pushed DOWN to 23.5 (was 18) so the head fills the disc width and
+// the chin clips naturally at the bottom, while the CROWN clears the hat band.
+// Only the top is reserved — the sides/chin fill the crop like a normal avatar
+// (an earlier R=11.2 shrank the whole head to reserve the top → "太小", Gus #99).
+const CYh = 23.5
+// Base head radius. Solved from the reserve constraint alone: worst-case crown =
+// CYh − sMax·R·maxMod ≥ HAT_LINE. With maxMod≈1.10 (fattest shape), sMax=1.02,
+// HAT_LINE=7.2 → R ≤ 14.45. That fills ~80% of the disc at the widest band
+// (matches the lib's beam presence), chin clips off-canvas at the bottom.
+const R = 14.45
+const HAT_LINE = 7.2
const TAU = Math.PI * 2
-const N = 72
+// Dense sampling — the 8 shapes include 5-lobed stars; too few points and the
+// lobes flatten into a blob. 200 keeps the silhouette crisp at any render size.
+const N = 200
-// boring-avatars PRNG helpers (verbatim from the lib bundle, so the wrapper
-// transform matches the lib's beam exactly).
+// boring-avatars PRNG helpers (verbatim from the lib bundle, so the base
+// transform matches the lib's beam feel exactly).
function hashSeed(name: string): number {
let r = 0
for (let i = 0; i < name.length; i++) {
@@ -68,33 +84,41 @@ function farthestByLuminance(wrapper: string, palette: readonly string[]): strin
return best
}
-function polyPath(fn: (t: number) => [number, number]): string {
+// A closed radial curve r(a) = R * mod(a) about the head center (CX, CYh).
+function polyPath(mod: (a: number) => number): string {
let d = ""
for (let i = 0; i <= N; i++) {
- const t = (i / N) * TAU
- const [x, y] = fn(t)
+ const a = (i / N) * TAU
+ const r = R * mod(a)
+ const x = CX + r * Math.cos(a)
+ const y = CYh + r * Math.sin(a)
d += (i === 0 ? "M" : "L") + x.toFixed(2) + " " + y.toFixed(2) + " "
}
return d + "Z"
}
-// Radial modulation r(t) = R * mod(t) — used for the lopsided/teardrop blobs.
-function radial(t: number, mod: (a: number) => number): [number, number] {
- const r = R * mod(t)
- return [CX + r * Math.cos(t), CY + r * Math.sin(t)]
-}
+// Superellipse radius at angle a — a soft rounded-square (n≈3), the "rounded"
+// silhouette without literal corners (a <rect> can't be used: under the
+// circular avatar crop a full-canvas rect fills the whole crop top, leaving no
+// room to reserve the hat band, and its corners poke straight up under tilt).
+const superell = (a: number, n: number): number =>
+ 1 / Math.pow(Math.pow(Math.abs(Math.cos(a)), n) + Math.pow(Math.abs(Math.sin(a)), n), 1 / n)
// Wrapper shapes: soft, chunky, distinct by SILHOUETTE (proportion + gentle
// asymmetry), not corner-radius — corner differences vanish at 32px under the
-// circular crop. No scallop/flower/zigzag (too busy, off the soft-simple
-// logic). `round`/`rounded` emit a plain rect (perf); the rest emit a <path>.
-type Shape = { rect: number } | { path: string }
-const SHAPES: Record<string, Shape> = {
- round: { rect: C },
- rounded: { rect: C / 3 },
- wide: { path: polyPath((t) => [CX + R * 1.02 * Math.cos(t), CY + R * 0.72 * Math.sin(t)]) },
- egg: { path: polyPath((t) => [CX + R * 0.86 * Math.cos(t), CY + R * Math.sin(t) - 2.4 * Math.sin(t) * Math.sin(t)]) },
- potato: { path: polyPath((t) => radial(t, (a) => 0.95 * (1 + 0.11 * Math.sin(a + 0.5) + 0.06 * Math.cos(2 * a - 0.8)))) },
- drop: { path: polyPath((t) => radial(t, (a) => 0.94 * (1 + 0.14 * Math.cos(a - Math.PI / 2)))) },
+// circular crop. All are bounded radial curves: a radial shape's max radius is
+// rotation-invariant, so tilt never pushes the crown higher than the closed-
+// form bound — that's what lets the hat reserve hold under every random tilt.
+// The three lobed shapes (clover/trilobe/star5) use Alli's approved formulas
+// (uiux#87) verbatim; do not retune the coefficients.
+const SHAPES: Record<string, (a: number) => number> = {
+ round: () => 1,
+ rounded: (a) => superell(a, 3.2) * 0.95,
+ wide: (a) => Math.hypot(1.06 * Math.cos(a), 0.74 * Math.sin(a)),
+ potato: (a) => 0.95 * (1 + 0.11 * Math.sin(a + 0.5) + 0.06 * Math.cos(2 * a - 0.8)),
+ drop: (a) => 0.94 * (1 + 0.14 * Math.cos(a - Math.PI / 2)),
+ clover: (a) => 0.8 * (1 + 0.17 * Math.cos(4 * a)),
+ trilobe: (a) => 0.86 * (1 + 0.14 * Math.cos(3 * a - Math.PI / 2)),
+ star5: (a) => 0.8 * (1 + 0.15 * Math.cos(5 * a - Math.PI / 2)),
}
const SHAPE_KEYS = Object.keys(SHAPES)
@@ -113,77 +137,68 @@ const EYES: Record<string, EyeFn> = {
}
const EYE_KEYS = Object.keys(EYES)
-// Mouths — simple, thick-lined, chunky (MSW), matched to the fat eyes.
+// Mouths — simple, thick-lined, chunky (MSW), matched to the fat eyes. Anchored
+// at the head center (y ≈ 24, below the eyes at 20), inside every shape.
const MSW = 1.5
type MouthFn = (spread: number, c: string) => string
const MOUTHS: Record<string, MouthFn> = {
- smile: (s, c) => `<path d="M14.5 ${19 + s}q3.5 2.6 7 0" stroke="${c}" stroke-width="${MSW}" fill="none" stroke-linecap="round"/>`,
- arc: (s, c) => `<path d="M13.5 ${19 + s} a1,0.85 0 0,0 9,0" fill="${c}"/>`,
- flat: (s, c) => `<path d="M15 ${19.5 + s}h6" stroke="${c}" stroke-width="${MSW}" fill="none" stroke-linecap="round"/>`,
- open: (s, c) => `<circle cx="18" cy="${20 + s}" r="2.3" fill="${c}"/>`,
- grin: (s, c) => `<path d="M13.5 ${18.6 + s}q4.5 3.4 9 0" stroke="${c}" stroke-width="1.8" fill="none" stroke-linecap="round"/>`,
- cat: (s, c) => `<path d="M14 ${19 + s}q2 1.8 4 0 q2 1.8 4 0" stroke="${c}" stroke-width="${MSW}" fill="none" stroke-linecap="round"/>`,
+ smile: (s, c) => `<path d="M14.5 ${24 + s}q3.5 2.6 7 0" stroke="${c}" stroke-width="${MSW}" fill="none" stroke-linecap="round"/>`,
+ arc: (s, c) => `<path d="M13.5 ${24 + s} a1,0.85 0 0,0 9,0" fill="${c}"/>`,
+ flat: (s, c) => `<path d="M15 ${24.5 + s}h6" stroke="${c}" stroke-width="${MSW}" fill="none" stroke-linecap="round"/>`,
+ open: (s, c) => `<circle cx="18" cy="${25 + s}" r="2.3" fill="${c}"/>`,
+ grin: (s, c) => `<path d="M13.5 ${23.6 + s}q4.5 3.4 9 0" stroke="${c}" stroke-width="1.8" fill="none" stroke-linecap="round"/>`,
+ cat: (s, c) => `<path d="M14 ${24 + s}q2 1.8 4 0 q2 1.8 4 0" stroke="${c}" stroke-width="${MSW}" fill="none" stroke-linecap="round"/>`,
}
const MOUTH_KEYS = Object.keys(MOUTHS)
// Render a generated beam face to an SVG string for the given seed + palette.
-// The wrapper transform mirrors the lib's beam so faces sit identically inside
-// the container crop; feature choice is deterministic on the seed hash.
+// Feature choice is deterministic on the seed hash; the head is placed in the
+// lower band so the top ~20% stays clear for a hat.
export function renderFaceSvg(seed: string, palette: readonly string[]): string {
const i = hashSeed(seed)
const wrapper = pick(i, palette)
const bg = farthestByLuminance(wrapper, palette)
const c = ink(wrapper)
- // Small translate only (±2.6px). The lib beam translated up to ±9, which
- // moved the shape's center so far off the canvas center that the wrapper
- // (radius ≈17) stopped covering where the features sit (≈9.5px from center) —
- // features fell outside the shape / got clipped by the circular crop (Gus's
- // "shape doesn't cover the face" / z51). Guarantee coverage: narrowest shape
- // half-extent ≈12.2 (×scale ≥1) minus feature extent 9.5 ≈ 2.7 of slack, so a
- // ≤2.6 offset keeps the whole face inside the wrapper for every shape.
- const tx = ((i % 27) / 26 - 0.5) * 5.2
- const ty = (((digit(i, 2) + digit(i, 5)) % 11) / 10 - 0.5) * 5.2
- // Gentle tilt only (±~12°), not the lib beam's full 0–359° spin. The face
- // rides this rotation (shared transform, below), so a big spin would flip the
- // whole face upside-down — "not even a face anymore". A small tilt keeps every
- // avatar upright and human while still varying per seed.
- const rot = (i % 25) - 12
- const scale = 1 + unit(i, Math.round(C / 12)) / 10
-
- // Eye spread 0–2 (eyes land at x 12/24 .. 14/22, i.e. ≤6px from center) and
- // the eye row nudged to y=15 (nearer the shape's widest band at center 18).
- // The old 0–4 spread pushed eyes to x 10/24 (±8) — out where the narrower/
- // taller shapes (egg, wide oval, potato) have already tapered, so an eye
- // poked past the edge (z51). Keeping the eye row narrow + centered keeps both
- // eyes on the wrapper for every shape.
- const eyeSpread = i % 3
+ // INDEPENDENT feature selection via radix slicing of the hash. The old code
+ // used i%len for shape but digit(i,4)%6 / digit(i,5)%6 for eye/mouth — a
+ // single 0–9 digit %6 makes idx 4/5 (wink/happy, grin/cat) only ~10% each
+ // (non-uniform), and coupling all three to the same source collapses the
+ // 8×6×6 space. Radix slicing gives each feature its own uniform, decorrelated
+ // index: shape = i mod 8, eye = (i/8) mod 6, mouth = (i/48) mod 6.
+ const shapeFn = SHAPES[SHAPE_KEYS[i % SHAPE_KEYS.length]]
+ const eyeFn = EYES[EYE_KEYS[Math.floor(i / SHAPE_KEYS.length) % EYE_KEYS.length]]
+ const mouthFn = MOUTHS[MOUTH_KEYS[Math.floor(i / (SHAPE_KEYS.length * EYE_KEYS.length)) % MOUTH_KEYS.length]]
+
+ // Per-seed variation, all BOUNDED so the crown-reserve bound above holds:
+ // tilt ±8°, scale-about-center 0.98–1.02, horizontal nudge tx free, and
+ // ty DOWNWARD ONLY (0..+1.6). No upward nudge: with the enlarged head the
+ // crown bound (CYh − sMax·R·maxMod ≈ 7.34) has almost no top slack, so any
+ // upward shift would poke into the hat band. Down is always safe (chin just
+ // clips further off-canvas).
+ const rot = (i % 17) - 8
+ const scale = 1 + unit(i, 3) / 100
+ const tx = ((i % 27) / 26 - 0.5) * 4.0
+ const ty = ((digit(i, 3) % 5) / 4) * 1.6
+
+ // Eyes at y20, mouth ~y24 — a normal face layout around the head center 23.5.
+ // Eye spread 0–1 (x 13/23 .. 14/22, ≤5px from center): narrow + centered keeps
+ // both eyes on the wrapper for every shape (guards z51: never poke past edge).
+ const eyeSpread = i % 2
const mouthSpread = i % 2
- const shape = SHAPES[SHAPE_KEYS[i % SHAPE_KEYS.length]]
- const eyeFn = EYES[EYE_KEYS[digit(i, 4) % EYE_KEYS.length]]
- const mouthFn = MOUTHS[MOUTH_KEYS[digit(i, 5) % MOUTH_KEYS.length]]
-
- const wrapperEl = "path" in shape
- ? `<path d="${shape.path}" fill="${wrapper}"/>`
- : `<rect width="${C}" height="${C}" rx="${shape.rect}" fill="${wrapper}"/>`
-
- const leftEye = eyeFn(14 - eyeSpread, 15, c, false)
- const rightEye = eyeFn(20 + eyeSpread, 15, c, true)
+ const wrapperEl = `<path d="${polyPath(shapeFn)}" fill="${wrapper}"/>`
+ const leftEye = eyeFn(14 - eyeSpread, 20, c, false)
+ const rightEye = eyeFn(22 + eyeSpread, 20, c, true)
const mouth = mouthFn(mouthSpread, c)
- // The face is nested inside the shape's transform group and shares its EXACT
- // transform, so features always sit on the wrapper fill, centered on it —
- // never drifting onto the background or off toward an edge. This fixes two
- // bugs at once: (a) "no eyes" — ink is derived from `wrapper`, so a feature
- // that landed on `bg` (now the max-contrast-vs-wrapper color) could match the
- // bg and vanish; keeping features on the wrapper guarantees ink contrast; and
- // (b) "features too far off-center" — the old independent face offset (fx/fy,
- // a lib-beam relic whose wrapper filled the whole 36×36 square) let eyes/mouth
- // wander. Shape and face both rotate about center (18,18) and share the same
- // translate, so the face center coincides with the shape center at any rot.
- // The face rides the shape's rotation (a small tilt, like the lib's own beam).
- const faceXf = `translate(${tx} ${ty}) rotate(${rot} 18 18) scale(${scale})`
+ // The face is nested inside the head's transform group and shares its EXACT
+ // transform, so features always sit on the wrapper fill, centered on it. Both
+ // shape and features scale + rotate ABOUT THE HEAD CENTER (CX, CYh) — scaling
+ // about the origin (the old bug) would displace the whole head off-center and
+ // break the reserve bound. Order (SVG applies right-to-left): scale about
+ // center, then rotate about center, then translate.
+ const faceXf = `translate(${tx.toFixed(2)} ${ty.toFixed(2)}) rotate(${rot} ${CX} ${CYh}) translate(${(CX * (1 - scale)).toFixed(2)} ${(CYh * (1 - scale)).toFixed(2)}) scale(${scale.toFixed(3)})`
// No <mask> — a full-canvas white mask is a no-op clip, and a shared mask id
// would collide across the many faces on one page (member lists, message