Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased

- `@botharness/pixel-avatar` 0.5.0: Custom Parts. A `PixelCustomPart` in the `headpiece` slot has a back layer drawn behind the hair and a front layer over it. Its cells reference an appearance color slot or a fixed color plus a tone step, so a part recolors with the Avatar, and it follows the head through turns. `withHeadpiece` embeds a copy in the recipe as asset version 3, which older consumers reject so they can show a saved snapshot. `customPartId` is a SHA-256 of the canonical content, and `paintPartLayer`, `fillPartLayer` (4-connected) and `mirrorPartX` provide the drawing algorithms. Every earlier recipe renders unchanged.
- `@botharness/pixel-avatar` 0.4.0: elf, dwarf, orc and flower species, an optional `beard` (`short`, `full`, `braided`) that always leaves the speaking mouth visible, armor/robe/tunic/cloak outfits and helmet/hood headwear (version 2 only, in `AVATAR_PARTS_V2`), and the flower's `petals` (`trumpet`, `daisy`, `sunflower`, `tulip`, `sakura`) and `flowerBase` (`leaves`, `pot`) in `AVATAR_EXTRA_PARTS`. A flower has simple bead eyes and its own mouth instead of a person's face. Petals take hair and per-side hair colors; a pot takes the shirt color. `hiddenChoices(recipe)` lists saved choices a species or headwear keeps but does not draw (a flower's hair, outfit, headwear, beard, eyes, brows, nose, cheeks and glasses, hair under a helmet or hood, a dwarf's nose part). `createSeededRecipeV2` / `seededRecipeV2` seed a version 2 face from a name across every species, with optional beards, version 2 outfits and flower parts; version 1 seeds are unchanged, so a consumer picks the seed version per identity. Version 1 recipes and every 0.3.0 goblin recipe render unchanged.
- `@botharness/pixel-avatar` 0.3.0: Avatar Species and split side hair as asset version 2. `withSpecies(recipe, species)` adds a `species` (`human` or `goblin`), a separate `rightSideHair` and optional `leftSideHairColor`/`rightSideHairColor`, moving a suggested skin color to the new species' `AVATAR_SPECIES_SWATCHES`. The goblin has pointed ears drawn over hair and small tusks, and keeps every head turn and speech mouth layer. Version 1 recipes, seeded faces and the existing golden output are unchanged, and a human version 2 recipe renders exactly like its version 1 source. Older consumers reject version 2 recipes through `isPixelAvatarRecipe`, so they can fall back to a saved snapshot.
- `@botharness/pixel-banner` 0.1.0 (new): seeded 3:1 pixel nature banners for profile headers in ten scenes. A `{ scene, seed }` recipe renders 150×50 pixels and scales them ×10 to exactly 1500×500 RGBA with no smoothing; `seededBannerRecipe(name)` gives the same banner for the same name, and a golden test locks every scene's output.
Expand Down
2 changes: 2 additions & 0 deletions packages/avatar/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,7 @@ const svg = pixelAvatarSvg(recipe); // 32×32 viewBox, crisp edges, no ids or sc
- `AVATAR_HAIR_PARTS`, `AVATAR_RANGES`, `detailedRecipe(recipe)`: optional finer controls. A recipe may carry `bangs`, `sideHair`, `backHair`, `spacing`, `height` and `hairLength`, all six or none; `detailedRecipe` derives them from the plain `hair` so an editor can start from what is on screen. Recipes without them render exactly as before.
- `AVATAR_SPECIES`, `AVATAR_SPECIES_SWATCHES`, `AVATAR_PIECE_COLORS`, `withSpecies(recipe, species)`: Avatar Species (`human`, `goblin`) on the same rig, as asset version 2. `withSpecies` keeps every choice, splits side hair into `sideHair` (left) and `rightSideHair`, and accepts optional `leftSideHairColor`/`rightSideHairColor`, where left and right are as seen on screen. Consumers built before version 2 reject these recipes with `isPixelAvatarRecipe` and can show a saved snapshot instead.
- `AVATAR_PARTS_V2`, `AVATAR_EXTRA_PARTS`, `hiddenChoices(recipe)`: version 2 adds elf, dwarf, orc and flower species, armor/robe/tunic/cloak outfits, helmet/hood headwear, an optional `beard`, and a flower's `petals` and `flowerBase`. `hiddenChoices` names saved choices the current species or headwear keeps but does not draw, so an editor can say so instead of discarding them.
- `PixelCustomPart`, `withHeadpiece(recipe, part)`, `customPartId`, `isPixelCustomPart`: a Human-drawn Custom Part in the `headpiece` slot (the top 32×16 of the tile). Its back layer is drawn behind the hair and its front layer over it, and both follow the head through turns. Each cell is `[x, y, color, tone]`, where `color` is an appearance color slot (`hairColor`, `skinColor`, `eyeColor`, `shirtColor`), so the part recolors with the Avatar, or a fixed `#rrggbb`, and `tone` is a step from −2 to 2 on the rig's shade ramp (`partToneColor`). A recipe wearing a part embeds its own copy as asset version 3. `customPartId` is the SHA-256 of the canonical content; names, authors and origins belong to the consumer's library.
- `emptyPartLayer`, `paintPartLayer`, `fillPartLayer`, `mirrorPartX`, `partLayer`, `partCells`, `createCustomPart`: drawing on dense layers, with pencil and eraser strokes, 4-connected flood fill and mirroring across the Avatar centerline.
- `faceCells`, `pixelSymbolCells`, `symbolArtCells`: pixels for [`@botharness/pixel-morph`](../morph).
- `pixelAvatarSvg(recipe, { turns, classPrefix })`: optional pre-rendered head turns, and rig layer classes (`<prefix>-body`, `-head`, `-face`, `-gaze`, `-blink`) for CSS animation.
2 changes: 1 addition & 1 deletion packages/avatar/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@botharness/pixel-avatar",
"version": "0.4.0",
"version": "0.5.0",
"description": "Seeded, editable 32×32 chibi pixel avatars with state symbols that morph in and out",
"keywords": [
"agent-ui",
Expand Down
31 changes: 29 additions & 2 deletions packages/avatar/src/figure.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { escapeAttribute, type PixelCell } from '@botharness/pixel-morph';
import type { PartCell, PartTone } from './part.js';
import { AVATAR_PIECE_COLORS, type PixelAvatarRecipe } from './recipe.js';

type Cell = string | undefined;
Expand Down Expand Up @@ -46,6 +47,17 @@ const mix = (base: string, tint: string, k: number) => {
const t = channels(tint);
return hex(channels(base).map((v, i) => v * (1 - k) + t[i]! * k));
};
const TONES: Record<PartTone, (color: string) => string> = {
[-2]: (c) => shade(c, 0.62),
[-1]: (c) => shade(c, 0.8),
0: (c) => c,
1: (c) => mix(c, WHITE, 0.25),
2: (c) => mix(c, WHITE, 0.5),
};
/** The color a Custom Part cell shows at a tone step on the rig's shade ramp. */
export function partToneColor(color: string, tone: PartTone): string {
return TONES[tone](color.toLowerCase());
}
function paint(grid: Grid, test: Mask, color: string): void {
for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) if (test(x, y)) grid[y]![x] = color;
}
Expand Down Expand Up @@ -903,6 +915,19 @@ export function pixelFigure(
shade(hairColor, 0.68),
);

const headpiece = recipe.assetVersion === 3 ? recipe.headpiece : undefined;
const placeCells = (grid: Grid, cells: readonly PartCell[]) => {
const placed = cells.map(([x, y, color, tone]) => {
const dx = x + 0.5 - C;
const far = turned && d * dx < 0 && Math.abs(dx) >= 5;
const base = color.startsWith('#') ? color.toLowerCase() : recipe[color as 'hairColor'];
return { x: x + s + (far ? d : 0), y, c: TONES[tone](base), far };
});
for (const cell of [...placed.filter((p) => p.far), ...placed.filter((p) => !p.far)])
if (cell.x >= 0 && cell.x < N) grid[cell.y]![cell.x] = cell.c;
};
if (headpiece) placeCells(back, headpiece.back);

const head = blank();
paint(head, face, skin);
const h = recipe.height ?? 0;
Expand Down Expand Up @@ -1013,8 +1038,10 @@ export function pixelFigure(
return out;
};

const crown = blank();
if (headpiece) placeCells(crown, headpiece.front);
const figure = blank();
for (const layer of [back, body, shadeHair(head)])
for (const layer of [back, body, shadeHair(head), crown])
for (let y = 0; y < N; y++)
for (let x = 0; x < N; x++) if (layer[y]![x]) figure[y]![x] = layer[y]![x];

Expand Down Expand Up @@ -1183,7 +1210,7 @@ export function pixelFigure(
for (let x = 0; x < N; x++) {
const c = full[y]![x];
if (!c) continue;
if (y >= 22 && !head[y]![x] && !back[y]![x]) bodyCells[y]![x] = c;
if (y >= 22 && !head[y]![x] && !back[y]![x] && !crown[y]![x]) bodyCells[y]![x] = c;
else headCells[y]![x] = c;
}
const cells: PixelCell[] = [];
Expand Down
27 changes: 27 additions & 0 deletions packages/avatar/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export type { PixelCell } from '@botharness/pixel-morph';
export {
partToneColor,
pixelFigure,
pixelTileColor,
type PixelGrid,
Expand Down Expand Up @@ -38,7 +39,33 @@ export {
type PixelAvatarRecipe,
type PixelAvatarRecipeV1,
type PixelAvatarRecipeV2,
type PixelAvatarRecipeV3,
withHeadpiece,
} from './recipe.js';
export {
MAX_PART_FIXED_COLORS,
PART_LAYERS,
PART_SLOTS,
PART_TONES,
canonicalCustomPart,
createCustomPart,
customPartId,
emptyPartLayer,
fillPartLayer,
isPixelCustomPart,
mirrorPartX,
paintPartLayer,
partCells,
partLayer,
type PartCell,
type PartColor,
type PartInk,
type PartLayer,
type PartLayerName,
type PartSlot,
type PartTone,
type PixelCustomPart,
} from './part.js';
export { seededRandom } from './random.js';
export { AVATAR_TURNS, faceCells, pixelAvatarSvg, type PixelAvatarSvgOptions } from './svg.js';
export { PIXEL_SYMBOLS, pixelSymbolCells, symbolArtCells, type PixelSymbol } from './symbols.js';
231 changes: 231 additions & 0 deletions packages/avatar/src/part.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
import { AVATAR_COLORS, type AvatarColor } from './recipe.js';

/**
* Custom Part slots. A headpiece covers the top of the tile, around the hair: its back layer is
* drawn behind the hair and its front layer over it. Cells are in tile coordinates, so the
* Avatar centerline sits between x = 15 and x = 16.
*/
export const PART_SLOTS = {
headpiece: { width: 32, height: 16 },
} as const;
export type PartSlot = keyof typeof PART_SLOTS;
/** Tone steps on the rig's shade ramp: two darker, the color itself, two lighter. */
export const PART_TONES = [-2, -1, 0, 1, 2] as const;
export type PartTone = (typeof PART_TONES)[number];
/** An appearance color slot (it follows the Avatar's color) or a fixed `#rrggbb` color. */
export type PartColor = AvatarColor | `#${string}`;
/** One painted cell: `[x, y, color, tone]`. */
export type PartCell = readonly [x: number, y: number, color: PartColor, tone: PartTone];
export const PART_LAYERS = ['front', 'back'] as const;
export type PartLayerName = (typeof PART_LAYERS)[number];
/** Most fixed colors one part may use. */
export const MAX_PART_FIXED_COLORS = 16;

/**
* A Human-drawn Custom Part. Its content is immutable and its identity is `customPartId`;
* name, author, origin and parent are metadata kept outside it.
*/
export interface PixelCustomPart {
slot: PartSlot;
front: readonly PartCell[];
back: readonly PartCell[];
}

/** A dense layer for drawing: `layer[y][x]` is a color and tone, or `null` when empty. */
export type PartInk = { color: PartColor; tone: PartTone };
export type PartLayer = (PartInk | null)[][];

const FIXED = /^#[\da-f]{6}$/iu;
const isColor = (value: unknown): value is PartColor =>
typeof value === 'string' &&
((AVATAR_COLORS as readonly string[]).includes(value) || FIXED.test(value));

export function isPixelCustomPart(value: unknown): value is PixelCustomPart {
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
const r = value as Record<string, unknown>;
if (Object.keys(r).length !== 3 || !Object.hasOwn(PART_SLOTS, r['slot'] as string)) return false;
const { width, height } = PART_SLOTS[r['slot'] as PartSlot];
const fixed = new Set<string>();
for (const name of PART_LAYERS) {
const cells = r[name];
if (!Array.isArray(cells) || cells.length > width * height) return false;
const seen = new Set<number>();
for (const cell of cells as unknown[]) {
if (!Array.isArray(cell) || cell.length !== 4) return false;
const [x, y, color, tone] = cell as unknown[];
if (
!Number.isInteger(x) ||
!Number.isInteger(y) ||
(x as number) < 0 ||
(x as number) >= width ||
(y as number) < 0 ||
(y as number) >= height ||
!isColor(color) ||
!(PART_TONES as readonly unknown[]).includes(tone)
)
return false;
const key = (y as number) * width + (x as number);
if (seen.has(key)) return false;
seen.add(key);
if (color.startsWith('#')) fixed.add(color.toLowerCase());
}
}
return fixed.size <= MAX_PART_FIXED_COLORS;
}

const canonicalCells = (cells: readonly PartCell[]): PartCell[] =>
cells
.map(
([x, y, color, tone]) =>
[x, y, color.startsWith('#') ? (color.toLowerCase() as PartColor) : color, tone] as const,
)
.sort((a, b) => a[1] - b[1] || a[0] - b[0]);

/** The part with cells in row order and fixed colors in lowercase. */
export function canonicalCustomPart(part: PixelCustomPart): PixelCustomPart {
return { slot: part.slot, front: canonicalCells(part.front), back: canonicalCells(part.back) };
}

/** Content identity: a SHA-256 of the canonical slot, cells and color references. */
export function customPartId(part: PixelCustomPart): string {
return sha256(JSON.stringify(canonicalCustomPart(part)));
}

export function emptyPartLayer(slot: PartSlot): PartLayer {
const { width, height } = PART_SLOTS[slot];
return Array.from({ length: height }, () => Array<PartInk | null>(width).fill(null));
}

export function partLayer(slot: PartSlot, cells: readonly PartCell[]): PartLayer {
const layer = emptyPartLayer(slot);
for (const [x, y, color, tone] of cells) layer[y]![x] = { color, tone };
return layer;
}

export function partCells(layer: PartLayer): PartCell[] {
return layer.flatMap((row, y) =>
row.flatMap((ink, x) => (ink ? [[x, y, ink.color, ink.tone] as const] : [])),
);
}

/** Builds a canonical part from two drawn layers. */
export function createCustomPart(
slot: PartSlot,
layers: Record<PartLayerName, PartLayer>,
): PixelCustomPart {
return canonicalCustomPart({
slot,
front: partCells(layers.front),
back: partCells(layers.back),
});
}

/** The column mirrored across the Avatar centerline. */
export function mirrorPartX(slot: PartSlot, x: number): number {
return PART_SLOTS[slot].width - 1 - x;
}

const same = (a: PartInk | null, b: PartInk | null) =>
a === b || (a !== null && b !== null && a.color === b.color && a.tone === b.tone);

/** Sets cells (pencil with ink, eraser with `null`), optionally mirrored across the centerline. */
export function paintPartLayer(
slot: PartSlot,
layer: PartLayer,
points: readonly (readonly [number, number])[],
ink: PartInk | null,
mirror = false,
): PartLayer {
const out = layer.map((row) => [...row]);
const { width, height } = PART_SLOTS[slot];
for (const [x, y] of points)
for (const px of mirror ? [x, mirrorPartX(slot, x)] : [x])
if (px >= 0 && px < width && y >= 0 && y < height) out[y]![px] = ink;
return out;
}

/**
* 4-connected flood fill from a cell: every cell reachable through cells equal to the start
* becomes `ink`. With `mirror`, the mirrored start is filled too.
*/
export function fillPartLayer(
slot: PartSlot,
layer: PartLayer,
x: number,
y: number,
ink: PartInk | null,
mirror = false,
): PartLayer {
const { width, height } = PART_SLOTS[slot];
let out = layer.map((row) => [...row]);
for (const sx of mirror ? [x, mirrorPartX(slot, x)] : [x]) {
if (sx < 0 || sx >= width || y < 0 || y >= height) continue;
const target = out[y]![sx]!;
if (same(target, ink)) continue;
const next = out.map((row) => [...row]);
const stack: [number, number][] = [[sx, y]];
while (stack.length) {
const [cx, cy] = stack.pop()!;
if (cx < 0 || cx >= width || cy < 0 || cy >= height) continue;
if (!same(next[cy]![cx]!, target)) continue;
next[cy]![cx] = ink;
stack.push([cx + 1, cy], [cx - 1, cy], [cx, cy + 1], [cx, cy - 1]);
}
out = next;
}
return out;
}

const K = Uint32Array.from(
'428a2f98 71374491 b5c0fbcf e9b5dba5 3956c25b 59f111f1 923f82a4 ab1c5ed5 d807aa98 12835b01 243185be 550c7dc3 72be5d74 80deb1fe 9bdc06a7 c19bf174 e49b69c1 efbe4786 0fc19dc6 240ca1cc 2de92c6f 4a7484aa 5cb0a9dc 76f988da 983e5152 a831c66d b00327c8 bf597fc7 c6e00bf3 d5a79147 06ca6351 14292967 27b70a85 2e1b2138 4d2c6dfc 53380d13 650a7354 766a0abb 81c2c92e 92722c85 a2bfe8a1 a81a664b c24b8b70 c76c51a3 d192e819 d6990624 f40e3585 106aa070 19a4c116 1e376c08 2748774c 34b0bcb5 391c0cb3 4ed8aa4a 5b9cca4f 682e6ff3 748f82ee 78a5636f 84c87814 8cc70208 90befffa a4506ceb bef9a3f7 c67178f2'
.split(' ')
.map((h) => Number.parseInt(h, 16)),
);

function sha256(text: string): string {
const bytes = new TextEncoder().encode(text);
const length = Math.ceil((bytes.length + 9) / 64) * 64;
const data = new Uint8Array(length);
data.set(bytes);
data[bytes.length] = 0x80;
const view = new DataView(data.buffer);
view.setUint32(length - 8, Math.floor((bytes.length * 8) / 2 ** 32));
view.setUint32(length - 4, (bytes.length * 8) >>> 0);
const h = Uint32Array.from([
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
const w = new Uint32Array(64);
const rotr = (v: number, n: number) => (v >>> n) | (v << (32 - n));
for (let offset = 0; offset < length; offset += 64) {
for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4);
for (let i = 16; i < 64; i++) {
const a = w[i - 15]!;
const b = w[i - 2]!;
const s0 = rotr(a, 7) ^ rotr(a, 18) ^ (a >>> 3);
const s1 = rotr(b, 17) ^ rotr(b, 19) ^ (b >>> 10);
w[i] = (w[i - 16]! + s0 + w[i - 7]! + s1) >>> 0;
}
let [a, b, c, d, e, f, g, k] = h as unknown as number[];
for (let i = 0; i < 64; i++) {
const t1 =
(k! +
(rotr(e!, 6) ^ rotr(e!, 11) ^ rotr(e!, 25)) +
((e! & f!) ^ (~e! & g!)) +
K[i]! +
w[i]!) >>>
0;
const t2 =
((rotr(a!, 2) ^ rotr(a!, 13) ^ rotr(a!, 22)) + ((a! & b!) ^ (a! & c!) ^ (b! & c!))) >>> 0;
k = g;
g = f;
f = e;
e = (d! + t1) >>> 0;
d = c;
c = b;
b = a;
a = (t1 + t2) >>> 0;
}
[a, b, c, d, e, f, g, k].forEach((v, i) => (h[i] = (h[i]! + v!) >>> 0));
}
return [...h].map((v) => v.toString(16).padStart(8, '0')).join('');
}
Loading
Loading