Cotton code
231 lines · 10.3 KB · TypeScriptRaw
/** * Pictures the seed paints itself, pixel by pixel, from its own stream: a * portrait is a person's initials on a colour (no face), a photo a simple * scene (hills, sea, a skyline, a table, a wood), a cover or poster bands * and shapes. PNG written here (zlib from Node), so the same seed makes the * same bytes and the same sha256 on every machine. */import { deflateSync } from "node:zlib";import type { Rng } from "./rng.ts";export interface Picture {  bytes: Uint8Array;  width: number;  height: number;}type Rgb = [number, number, number];class Canvas {  readonly px: Uint8Array;  readonly w: number;  readonly h: number;  constructor(w: number, h: number) {    this.w = w;    this.h = h;    this.px = new Uint8Array(w * h * 3);  }  set(x: number, y: number, c: Rgb): void {    if (x < 0 || y < 0 || x >= this.w || y >= this.h) return;    const i = (y * this.w + x) * 3;    this.px[i] = c[0];    this.px[i + 1] = c[1];    this.px[i + 2] = c[2];  }  rect(x0: number, y0: number, x1: number, y1: number, c: Rgb): void {    for (let y = Math.max(0, Math.floor(y0)); y < Math.min(this.h, Math.ceil(y1)); y += 1) for (let x = Math.max(0, Math.floor(x0)); x < Math.min(this.w, Math.ceil(x1)); x += 1) this.set(x, y, c);  }  circle(cx: number, cy: number, r: number, c: Rgb): void {    for (let y = Math.floor(cy - r); y <= cy + r; y += 1) for (let x = Math.floor(cx - r); x <= cx + r; x += 1) if ((x - cx) ** 2 + (y - cy) ** 2 <= r * r) this.set(x, y, c);  }  /** A vertical gradient over rows [y0, y1). */  gradient(y0: number, y1: number, top: Rgb, bottom: Rgb): void {    for (let y = y0; y < y1; y += 1) {      const t = (y - y0) / Math.max(1, y1 - y0 - 1);      this.rect(0, y, this.w, y + 1, mix(top, bottom, t));    }  }  /** Fill below a curve `top(x)` down to the bottom edge. */  below(top: (x: number) => number, c: Rgb): void {    for (let x = 0; x < this.w; x += 1) this.rect(x, top(x), x + 1, this.h, c);  }  png(): Picture {    return { bytes: encodePng(this.w, this.h, this.px), width: this.w, height: this.h };  }}function mix(a: Rgb, b: Rgb, t: number): Rgb {  return [Math.round(a[0] + (b[0] - a[0]) * t), Math.round(a[1] + (b[1] - a[1]) * t), Math.round(a[2] + (b[2] - a[2]) * t)];}function hsl(h: number, s: number, l: number): Rgb {  const k = (n: number): number => (n + h / 30) % 12;  const a = s * Math.min(l, 1 - l);  const f = (n: number): number => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));  return [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)];}// ── PNG ─────────────────────────────────────────────────────────────────const CRC = (() => {  const table = new Uint32Array(256);  for (let n = 0; n < 256; n += 1) {    let c = n;    for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;    table[n] = c >>> 0;  }  return table;})();function crc32(bytes: Uint8Array): number {  let c = 0xffffffff;  for (const b of bytes) c = CRC[(c ^ b) & 0xff]! ^ (c >>> 8);  return (c ^ 0xffffffff) >>> 0;}function chunk(type: string, data: Uint8Array): Buffer {  const head = Buffer.alloc(8);  head.writeUInt32BE(data.length, 0);  head.write(type, 4, "ascii");  const crc = Buffer.alloc(4);  crc.writeUInt32BE(crc32(Buffer.concat([head.subarray(4), data])), 0);  return Buffer.concat([head, data, crc]);}/** An 8-bit RGB PNG, every row unfiltered. */export function encodePng(w: number, h: number, rgb: Uint8Array): Uint8Array {  const raw = Buffer.alloc((w * 3 + 1) * h);  for (let y = 0; y < h; y += 1) {    raw[y * (w * 3 + 1)] = 0;    Buffer.from(rgb.buffer, rgb.byteOffset + y * w * 3, w * 3).copy(raw, y * (w * 3 + 1) + 1);  }  const ihdr = Buffer.alloc(13);  ihdr.writeUInt32BE(w, 0);  ihdr.writeUInt32BE(h, 4);  ihdr[8] = 8;  ihdr[9] = 2;  const signature = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);  return new Uint8Array(Buffer.concat([signature, chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw, { level: 9 })), chunk("IEND", new Uint8Array(0))]));}// ── letters ─────────────────────────────────────────────────────────────/** A 5×7 face for the initials: each letter seven rows of five bits. */const GLYPHS: Record<string, number[]> = {  A: [14, 17, 17, 31, 17, 17, 17], B: [30, 17, 17, 30, 17, 17, 30], C: [14, 17, 16, 16, 16, 17, 14], D: [30, 17, 17, 17, 17, 17, 30],  E: [31, 16, 16, 30, 16, 16, 31], F: [31, 16, 16, 30, 16, 16, 16], G: [14, 17, 16, 23, 17, 17, 15], H: [17, 17, 17, 31, 17, 17, 17],  I: [14, 4, 4, 4, 4, 4, 14], J: [7, 2, 2, 2, 2, 18, 12], K: [17, 18, 20, 24, 20, 18, 17], L: [16, 16, 16, 16, 16, 16, 31],  M: [17, 27, 21, 21, 17, 17, 17], N: [17, 17, 25, 21, 19, 17, 17], O: [14, 17, 17, 17, 17, 17, 14], P: [30, 17, 17, 30, 16, 16, 16],  Q: [14, 17, 17, 17, 21, 18, 13], R: [30, 17, 17, 30, 20, 18, 17], S: [15, 16, 16, 14, 1, 1, 30], T: [31, 4, 4, 4, 4, 4, 4],  U: [17, 17, 17, 17, 17, 17, 14], V: [17, 17, 17, 17, 17, 10, 4], W: [17, 17, 17, 21, 21, 21, 10], X: [17, 17, 10, 4, 10, 17, 17],  Y: [17, 17, 10, 4, 4, 4, 4], Z: [31, 1, 2, 4, 8, 16, 31],};function letters(c: Canvas, text: string, cx: number, cy: number, scale: number, ink: Rgb): void {  const chars = [...text.toUpperCase()].filter((ch) => GLYPHS[ch]);  const width = chars.length * 6 * scale - scale;  let x0 = Math.round(cx - width / 2);  const y0 = Math.round(cy - (7 * scale) / 2);  for (const ch of chars) {    const rows = GLYPHS[ch]!;    rows.forEach((bits, row) => {      for (let col = 0; col < 5; col += 1) if (bits & (1 << (4 - col))) c.rect(x0 + col * scale, y0 + row * scale, x0 + (col + 1) * scale, y0 + (row + 1) * scale, ink);    });    x0 += 6 * scale;  }}// ── what the seed paints ────────────────────────────────────────────────/** A person's portrait: their initials, cream on a colour of their own. */export function portrait(rng: Rng, initials: string): Picture {  const c = new Canvas(256, 256);  const hue = rng.int(0, 359);  c.gradient(0, 256, hsl(hue, 0.45, 0.52), hsl((hue + 25) % 360, 0.5, 0.38));  letters(c, initials, 128, 128, 14, [250, 244, 230]);  return c.png();}export type SceneKind = "hills" | "sea" | "skyline" | "table" | "wood";export const SCENES: readonly SceneKind[] = ["hills", "sea", "skyline", "table", "wood"];/** A photograph's stand-in: a small painted scene. */export function scene(rng: Rng, kind: SceneKind, w = 480, h = 360): Picture {  const c = new Canvas(w, h);  const evening = rng.chance(0.3);  const sky: [Rgb, Rgb] = evening ? [hsl(rng.int(260, 290), 0.4, 0.35), hsl(rng.int(15, 35), 0.8, 0.65)] : [hsl(rng.int(195, 215), 0.6, 0.55), hsl(rng.int(190, 205), 0.5, 0.85)];  const horizon = Math.round(h * (0.45 + rng.next() * 0.2));  if (kind === "table") {    c.gradient(0, horizon, hsl(rng.int(20, 50), 0.25, 0.8), hsl(rng.int(20, 50), 0.25, 0.65));    c.gradient(horizon, h, hsl(rng.int(20, 35), 0.45, 0.45), hsl(rng.int(20, 35), 0.45, 0.3));    const n = rng.int(2, 5);    for (let i = 0; i < n; i += 1) c.circle(w * (0.2 + 0.6 * rng.next()), horizon + h * 0.12, h * (0.06 + rng.next() * 0.07), hsl(rng.int(0, 359), 0.65, 0.5));    return c.png();  }  c.gradient(0, horizon, sky[0], sky[1]);  c.circle(w * (0.15 + rng.next() * 0.7), horizon * (0.25 + rng.next() * 0.4), h * (0.05 + rng.next() * 0.05), evening ? [255, 214, 150] : [255, 248, 220]);  if (kind === "sea") {    c.gradient(horizon, h, hsl(rng.int(195, 210), 0.55, 0.4), hsl(rng.int(190, 205), 0.6, 0.22));    for (let y = horizon + 6; y < h; y += rng.int(8, 16)) c.rect(rng.int(0, w / 2), y, rng.int(w / 2, w), y + 1, hsl(200, 0.4, 0.7));  } else if (kind === "skyline") {    c.rect(0, horizon, w, h, hsl(220, 0.1, 0.25));    for (let x = 0; x < w; ) {      const bw = rng.int(24, 60);      const top = horizon - rng.int(20, Math.round(horizon * 0.7));      const tone = hsl(rng.int(200, 240), 0.12, 0.2 + rng.next() * 0.15);      c.rect(x, top, x + bw - 3, h, tone);      for (let wy = top + 8; wy < h - 8; wy += 12) for (let wx = x + 5; wx < x + bw - 10; wx += 10) if (rng.chance(evening ? 0.45 : 0.15)) c.rect(wx, wy, wx + 4, wy + 5, [250, 222, 140]);      x += bw;    }  } else {    const layers = kind === "wood" ? 2 : 3;    for (let l = 0; l < layers; l += 1) {      const amp = h * (0.04 + rng.next() * 0.06);      const freq = 0.004 + rng.next() * 0.01;      const phase = rng.next() * 6.28;      const base = horizon + l * h * 0.1;      c.below((x) => base - amp * Math.sin(x * freq + phase), hsl(rng.int(85, 140), 0.35, 0.42 - l * 0.08));    }    if (kind === "wood") {      const trees = rng.int(8, 16);      for (let i = 0; i < trees; i += 1) {        const tx = rng.int(0, w);        const th = rng.int(Math.round(h * 0.2), Math.round(h * 0.45));        const ty = horizon + rng.int(0, Math.round(h * 0.25));        const green = hsl(rng.int(100, 150), 0.4, 0.22 + rng.next() * 0.1);        for (let y = 0; y < th; y += 1) c.rect(tx - (y * 0.3) / 1, ty - th + y, tx + (y * 0.3) / 1, ty - th + y + 1, green);        c.rect(tx - 3, ty, tx + 3, ty + 12, [92, 64, 44]);      }    }  }  return c.png();}/** A book cover, film poster or record sleeve: bands and a shape on a colour, and the title's initials. */export function cover(rng: Rng, title: string, w: number, h: number): Picture {  const c = new Canvas(w, h);  const hue = rng.int(0, 359);  c.gradient(0, h, hsl(hue, 0.5, 0.45), hsl((hue + 40) % 360, 0.55, 0.25));  const bands = rng.int(1, 3);  for (let i = 0; i < bands; i += 1) {    const y = rng.int(0, h - 20);    c.rect(0, y, w, y + rng.int(6, 22), hsl((hue + 180) % 360, 0.4, 0.7));  }  c.circle(w * (0.3 + rng.next() * 0.4), h * (0.3 + rng.next() * 0.2), Math.min(w, h) * (0.12 + rng.next() * 0.12), hsl((hue + 90) % 360, 0.6, 0.6));  const initials = title    .split(/\s+/)    .filter((word) => /^[A-Za-z]/.test(word) && !["the", "a", "an", "of", "and", "on", "in", "to", "at", "over", "under", "from", "where"].includes(word.toLowerCase()))    .map((word) => word[0]!)    .join("")    .slice(0, 3);  letters(c, initials, w / 2, h * 0.78, Math.max(3, Math.round(w / 40)), [250, 244, 230]);  return c.png();}