{
  "files": [
    {
      "path": "src/registry/items/dot-matrix/dot-matrix.tsx",
      "content": "\"use client\";\n\nimport { createParts, usePart, usePrimitive, type PartProps } from \"@ui-sdk/react/primitive\";\nimport { useSyncExternalStore, type CSSProperties } from \"react\";\n\nimport type { DotMatrixLatticeName, DotMatrixLatticeSpec } from \"./dot-matrix-lattice\";\nimport { coreOf, type Declarations } from \"./dot-matrix-look\";\nimport { dotMatrixMessages, type DotMatrixMessages } from \"./dot-matrix-messages\";\nimport type { DotMatrixPatternName } from \"./dot-matrix-patterns\";\nimport type { DotMatrixLook } from \"./dot-matrix-preset\";\nimport { dotMatrixPrimitive, type DotMatrixStatus } from \"./dot-matrix-primitive\";\nimport type { DotMatrixRenderer } from \"./dot-matrix-renderer\";\nimport type { ScenePattern } from \"./dot-matrix-scene\";\n\nconst { Stage } = createParts(dotMatrixPrimitive, { stage: \"span\" });\n\nconst DOT_KEYS: string[] = [];\n\nfunction dotKey(place: number): string {\n  for (let next = DOT_KEYS.length; next <= place; next += 1) {\n    DOT_KEYS.push(`dot-${next}`);\n  }\n  return DOT_KEYS[place] ?? \"\";\n}\n\nfunction noSubscription(): () => void {\n  return () => {};\n}\n\nfunction useServerFrame(): boolean {\n  return useSyncExternalStore(\n    noSubscription,\n    () => {\n      return false;\n    },\n    () => {\n      return true;\n    },\n  );\n}\n\nfunction reactStyle(...looks: readonly (Declarations | undefined)[]): CSSProperties {\n  const style: Record<string, string> = {};\n  for (const look of looks) {\n    for (const [property, value] of Object.entries(look ?? {})) {\n      style[property.replaceAll(/-([a-z])/gu, (_, letter: string) => letter.toUpperCase())] = value;\n    }\n  }\n  return style;\n}\n\ntype DotMatrixProps = Omit<PartProps<\"output\">, \"children\" | \"color\"> & {\n  pattern?: DotMatrixPatternName | ScenePattern;\n  lattice?: DotMatrixLatticeName | DotMatrixLatticeSpec;\n  size?: number;\n  color?: string;\n  look?: DotMatrixLook;\n  value?: number;\n  state?: DotMatrixStatus;\n  active?: boolean;\n  enter?: boolean;\n  renderer?: DotMatrixRenderer;\n  messages?: DotMatrixMessages;\n};\n\nexport function DotMatrix({\n  pattern,\n  lattice,\n  size,\n  color,\n  look,\n  value,\n  state,\n  active,\n  enter,\n  renderer,\n  messages = dotMatrixMessages,\n  ...props\n}: DotMatrixProps) {\n  const serverFrame = useServerFrame();\n  const handle = usePrimitive(dotMatrixPrimitive, {\n    pattern: pattern ?? look?.pattern,\n    lattice: lattice ?? look?.lattice,\n    size,\n    grid: look?.grid,\n    dot: look?.dot,\n    glow: look?.glow,\n    floor: look?.floor,\n    speed: look?.speed,\n    status: state,\n    color,\n    colors: look?.colors,\n    value,\n    active,\n    enter,\n    morph: look?.morph,\n    renderer,\n    messages,\n  });\n  return usePart(\n    handle,\n    \"root\",\n    {},\n    {\n      ...props,\n      children: (\n        <Stage>\n          {({ lights, places, look: dots }) => {\n            if (!serverFrame) {\n              return undefined;\n            }\n            const cell = reactStyle(dots.cell);\n            const floor = dots.floor === undefined ? undefined : reactStyle(dots.floor);\n            const glow = reactStyle(dots.light);\n            const mark = dots.mark === undefined ? undefined : reactStyle(dots.mark);\n            const core = reactStyle(dots.core);\n            return lights.map((light, place) => {\n              const hot = coreOf(light);\n              return (\n                <span key={dotKey(place)} style={{ ...cell, ...reactStyle(places[place]) }}>\n                  {floor === undefined ? undefined : <span style={floor} />}\n                  {light > 0 ? (\n                    <span style={{ ...glow, opacity: light }}>\n                      {mark === undefined ? undefined : <span style={mark} />}\n                    </span>\n                  ) : undefined}\n                  {hot > 0 ? <span style={{ ...core, opacity: hot }} /> : undefined}\n                </span>\n              );\n            });\n          }}\n        </Stage>\n      ),\n    },\n    \"output\",\n  );\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix.tsx"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-primitive.ts",
      "content": "import { announce, css, definePrimitive, prepareAnnouncements } from \"@ui-sdk/core\";\n\nimport { bakeSoon } from \"./dot-matrix-bake-pool\";\nimport { canvasRenderer } from \"./dot-matrix-canvas\";\nimport { unwatchCover, watchCover } from \"./dot-matrix-cover\";\nimport { DOT_MATRIX_DOTS, type DotMatrixDot } from \"./dot-matrix-dots\";\nimport {\n  boxOf,\n  densityFor,\n  DOT_MATRIX_LATTICES,\n  latticeFor,\n  pitchOf,\n  type DotMatrixLattice,\n  type DotMatrixLatticeName,\n  type DotMatrixLatticeSpec,\n} from \"./dot-matrix-lattice\";\nimport { cellLook, placeLook, type CellLook, type Declarations } from \"./dot-matrix-look\";\nimport { dotMatrixMessages, type DotMatrixMessages } from \"./dot-matrix-messages\";\nimport {\n  darkTrack,\n  DOT_MATRIX_MORPHS,\n  morphTrack,\n  type DotMatrixMorph,\n  type DotMatrixShowing,\n} from \"./dot-matrix-morph\";\nimport {\n  DOT_MATRIX_PATTERN_NAMES,\n  patternOf,\n  type DotMatrixPatternName,\n} from \"./dot-matrix-patterns\";\nimport type { DotMatrixPlayer, DotMatrixRenderer } from \"./dot-matrix-renderer\";\nimport type { ScenePattern } from \"./dot-matrix-scene\";\nimport { bakedTrack, frameAt, stillTrack, type DotMatrixTrack } from \"./dot-matrix-track\";\n\nexport type DotMatrixStatus = \"running\" | \"paused\";\n\nexport type DotMatrixOptions = {\n  pattern?: DotMatrixPatternName | ScenePattern;\n  lattice?: DotMatrixLatticeName | DotMatrixLatticeSpec;\n  size?: number;\n  grid?: number;\n  dot?: DotMatrixDot;\n  glow?: number;\n  floor?: number;\n  speed?: number;\n  status?: DotMatrixStatus;\n  color?: string;\n  colors?: readonly string[] | string;\n  value?: number;\n  active?: boolean;\n  enter?: boolean;\n  morph?: DotMatrixMorph | \"none\";\n  renderer?: DotMatrixRenderer;\n  messages?: DotMatrixMessages;\n};\n\nconst STATUSES: readonly DotMatrixStatus[] = [\"running\", \"paused\"];\nconst MORPHS: readonly (DotMatrixMorph | \"none\")[] = [...DOT_MATRIX_MORPHS, \"none\"];\n\nconst MORPH_MS = 560;\n\nfunction oneOf<Value>(list: readonly Value[], value: Value | undefined, fallback: Value): Value {\n  return value !== undefined && list.includes(value) ? value : fallback;\n}\n\nfunction atLeast(value: number | undefined, min: number, fallback: number): number {\n  return value !== undefined && Number.isFinite(value) && value >= min ? value : fallback;\n}\n\nfunction patternOption(pattern: DotMatrixOptions[\"pattern\"]): DotMatrixPatternName | ScenePattern {\n  if (typeof pattern === \"object\") {\n    return pattern;\n  }\n  return oneOf(DOT_MATRIX_PATTERN_NAMES, pattern, \"orbit\");\n}\n\nfunction latticeOption(\n  lattice: DotMatrixOptions[\"lattice\"],\n): DotMatrixLatticeName | DotMatrixLatticeSpec {\n  if (typeof lattice === \"object\") {\n    return lattice;\n  }\n  return oneOf(DOT_MATRIX_LATTICES, lattice, \"square\");\n}\n\nfunction colorsOf(colors: readonly string[] | string | undefined): readonly string[] {\n  if (typeof colors === \"string\") {\n    return colors.split(\",\").map((color) => {\n      return color.trim();\n    });\n  }\n  return colors ?? [];\n}\n\nfunction paletteOf(colors: readonly string[] | string | undefined): readonly string[] | undefined {\n  const list = colorsOf(colors);\n  return list.length > 1 ? list.slice(0, 8) : undefined;\n}\n\nfunction settings(options: DotMatrixOptions) {\n  return {\n    pattern: patternOption(options.pattern),\n    lattice: latticeOption(options.lattice),\n    size: atLeast(options.size, 8, 20),\n    grid: options.grid === undefined ? undefined : Math.round(atLeast(options.grid, 1, 9)),\n    dot: oneOf(DOT_MATRIX_DOTS, options.dot, \"round\"),\n    glow: Math.min(1, atLeast(options.glow, 0, 1)),\n    floor: Math.min(1, atLeast(options.floor, 0, 1)),\n    speed: atLeast(options.speed, 0.01, 1),\n    status: oneOf(STATUSES, options.status, \"running\"),\n    color: options.color ?? colorsOf(options.colors)[0],\n    colors: paletteOf(options.colors),\n    input: Math.min(1, atLeast(options.value, 0, 0)),\n    active: options.active !== false,\n    enter: options.enter === true,\n    morph: oneOf(MORPHS, options.morph, \"wave\"),\n    renderer: options.renderer ?? canvasRenderer,\n    messages: options.messages ?? dotMatrixMessages,\n  };\n}\n\ntype Settings = ReturnType<typeof settings>;\n\nfunction latticeOfSettings(state: Settings): DotMatrixLattice {\n  const pattern = patternOf(state.pattern);\n  return latticeFor(state.lattice, state.grid ?? densityFor(state.size, pattern.most ?? 9));\n}\n\nconst PATTERN_IDS = new WeakMap<ScenePattern, number>();\nconst PATTERN_COUNT = { seen: 0 };\n\nfunction patternKey(pattern: DotMatrixPatternName | ScenePattern): string {\n  if (typeof pattern === \"string\") {\n    return pattern;\n  }\n  const known = PATTERN_IDS.get(pattern);\n  if (known !== undefined) {\n    return `custom-${known}`;\n  }\n  PATTERN_COUNT.seen += 1;\n  const id = PATTERN_COUNT.seen;\n  PATTERN_IDS.set(pattern, id);\n  return `custom-${id}`;\n}\n\ntype Drawn = Readonly<{ look: string; content: string; color: string }>;\n\nfunction sameDrawn(a: Drawn, b: Drawn): boolean {\n  return a.look === b.look && a.content === b.content && a.color === b.color;\n}\n\nfunction drawnOf(state: Settings): Drawn {\n  return {\n    look: [state.size, state.dot, state.glow, state.floor, state.renderer.name].join(\":\"),\n    content: [patternKey(state.pattern), latticeOfSettings(state).key, state.active].join(\":\"),\n    color: [state.color ?? \"current\", ...(state.colors ?? [])].join(\"|\"),\n  };\n}\n\ntype Layer = Readonly<{ el: HTMLElement; player: DotMatrixPlayer }>;\n\ntype MatrixState = Settings & {\n  mounted: boolean;\n  onScreen: boolean;\n  visible: boolean;\n  covered: boolean;\n  drawn: Drawn | undefined;\n  shown: Drawn | undefined;\n  layer: Layer | undefined;\n  showing: DotMatrixShowing | undefined;\n  handoff: ReturnType<typeof setTimeout> | undefined;\n  entering: boolean;\n};\n\nfunction mountLayer(\n  root: HTMLElement,\n  state: Settings,\n  track: DotMatrixTrack,\n  from?: string,\n): Layer {\n  const el = root.ownerDocument.createElement(\"span\");\n  el.dataset.slot = \"dot-matrix-layer\";\n  el.setAttribute(\"aria-hidden\", \"true\");\n  Object.assign(el.style, { position: \"absolute\", inset: \"0\" });\n  if (state.color !== undefined) {\n    el.style.color = state.color;\n  }\n  root.append(el);\n  const player = state.renderer.mount(el, {\n    track,\n    dot: state.dot,\n    glow: state.glow,\n    floor: state.floor,\n    speed: state.speed,\n    size: state.size,\n    input: state.input,\n    ...(state.colors === undefined ? {} : { colors: state.colors }),\n    ...(from === undefined ? {} : { from }),\n  });\n  return { el, player };\n}\n\nfunction removeLayer(layer: Layer | undefined): void {\n  layer?.player.destroy();\n  layer?.el.remove();\n}\n\nfunction heard(el: Element): boolean {\n  return el.closest('[aria-hidden=\"true\"]') === null;\n}\n\nfunction pageTime(doc: Document): number {\n  const time = doc.timeline.currentTime;\n  return typeof time === \"number\" ? time : performance.now();\n}\n\ntype StageFrame = Readonly<{\n  lights: readonly number[];\n  places: readonly Declarations[];\n  look: CellLook;\n}>;\n\nexport const dotMatrixPrimitive = definePrimitive({\n  name: \"dot-matrix\",\n  options: {\n    pattern: (attribute: string | null) => attribute ?? undefined,\n    lattice: (attribute: string | null) => attribute ?? undefined,\n    size: \"number\",\n    grid: \"number\",\n    dot: \"string\",\n    glow: \"number\",\n    floor: \"number\",\n    speed: \"number\",\n    status: \"string\",\n    color: \"string\",\n    colors: \"list\",\n    value: \"number\",\n    active: \"boolean\",\n    enter: \"boolean\",\n    morph: \"string\",\n    renderer: \"value\",\n    messages: \"value\",\n  },\n  state: (options: DotMatrixOptions): MatrixState => {\n    return {\n      ...settings(options),\n      mounted: false,\n      onScreen: false,\n      visible: true,\n      covered: false,\n      drawn: undefined,\n      shown: undefined,\n      layer: undefined,\n      showing: undefined,\n      handoff: undefined,\n      entering: false,\n    };\n  },\n  live: [\n    \"onScreen\",\n    \"visible\",\n    \"covered\",\n    \"drawn\",\n    \"shown\",\n    \"layer\",\n    \"showing\",\n    \"handoff\",\n    \"entering\",\n  ],\n  sync: settings,\n  controlled: [],\n  api: () => {\n    return {};\n  },\n  agent: { actions: [] },\n  slots: (slot) => {\n    return {\n      root: slot({\n        attrs: (state) => {\n          const outcome = patternOf(state.pattern).outcome ?? \"loading\";\n          const box = boxOf(latticeOfSettings(state), state.size);\n          return {\n            \"aria-label\": state.messages[outcome],\n            \"data-pattern\": patternKey(state.pattern),\n            \"data-state\": state.status,\n            style: css({\n              position: \"relative\",\n              display: \"inline-block\",\n              \"flex-shrink\": \"0\",\n              \"vertical-align\": \"middle\",\n              contain: \"layout\",\n              width: `${box.width.toFixed(2)}px`,\n              height: `${box.height}px`,\n            }),\n          };\n        },\n        bind: (el, part) => {\n          const doc = el.ownerDocument;\n          const life = { alive: true };\n          const running = () => {\n            const state = part.store.get();\n            return state.onScreen && state.visible && !state.covered && state.status === \"running\";\n          };\n          const play = () => {\n            const { layer, speed, input, entering } = part.store.get();\n            layer?.player.setSpeed(speed);\n            layer?.player.setInput(input);\n            if (entering && running()) {\n              part.store.set({ entering: false });\n              swap();\n              return;\n            }\n            if (running()) {\n              layer?.player.play();\n            } else {\n              layer?.player.pause();\n            }\n          };\n          const show = (\n            track: DotMatrixTrack,\n            start: number | undefined,\n            shown: Drawn,\n            from?: string,\n          ) => {\n            const state = part.store.get();\n            const previous = state.layer;\n            const layer = mountLayer(el, state, track, from);\n            removeLayer(previous);\n            part.store.set({\n              layer,\n              showing: { track, start, input: state.input },\n              shown,\n              mounted: true,\n            });\n            play();\n          };\n          const arrive = (target: DotMatrixTrack, drawn: Drawn) => {\n            const state = part.store.get();\n            const { morph, showing, shown } = state;\n            const now = pageTime(doc);\n            if (\n              morph === \"none\" ||\n              showing === undefined ||\n              shown?.look !== drawn.look ||\n              !running()\n            ) {\n              show(target, target.once ? now : undefined, drawn);\n              return;\n            }\n            const from =\n              shown.color === drawn.color || state.layer === undefined\n                ? undefined\n                : getComputedStyle(state.layer.el).color;\n            const track = morphTrack(showing, target, {\n              now,\n              speed: state.speed,\n              kind: morph,\n              duration: MORPH_MS,\n              input: state.input,\n            });\n            show(track, now, drawn, from);\n            if (!target.once) {\n              part.store.set({\n                handoff: setTimeout(() => {\n                  part.store.set({ handoff: undefined });\n                  show(target, undefined, drawn);\n                }, MORPH_MS),\n              });\n            }\n          };\n          function swap(): void {\n            const state = part.store.get();\n            clearTimeout(state.handoff);\n            const pattern = patternOf(state.pattern);\n            const lattice = latticeOfSettings(state);\n            const drawn = drawnOf(state);\n            part.store.set({ drawn, handoff: undefined });\n            if (state.enter && state.showing === undefined) {\n              show(darkTrack(lattice, pattern.duration), pageTime(doc), {\n                ...drawn,\n                content: \"dark\",\n              });\n              part.store.set({ entering: true });\n              return;\n            }\n            const target = state.active\n              ? bakedTrack(pattern, lattice)\n              : darkTrack(lattice, pattern.duration);\n            if (target !== undefined) {\n              arrive(target, drawn);\n              return;\n            }\n            if (state.showing === undefined || state.shown?.look !== drawn.look) {\n              show(stillTrack(pattern, lattice, state.input), pageTime(doc), drawn);\n            }\n            bakeSoon(pattern, lattice)\n              .then((track) => {\n                const { drawn: wanted } = part.store.get();\n                if (life.alive && wanted !== undefined && sameDrawn(wanted, drawn)) {\n                  arrive(track, drawn);\n                }\n                return track;\n              })\n              .catch((cause: unknown) => {\n                reportError(\n                  new Error(`Dot Matrix: the pattern \"${drawn.content}\" failed to bake.`, {\n                    cause,\n                  }),\n                );\n              });\n          }\n          const observer = new IntersectionObserver((entries) => {\n            part.store.set({ onScreen: entries.at(-1)?.isIntersecting ?? false });\n          });\n          observer.observe(el);\n          const onVisibility = () => {\n            part.store.set({ visible: doc.visibilityState === \"visible\" });\n          };\n          doc.addEventListener(\"visibilitychange\", onVisibility);\n          onVisibility();\n          watchCover(el, (covered) => {\n            part.store.set({ covered });\n          });\n          if (heard(el)) {\n            prepareAnnouncements(doc);\n          }\n          const unsubscribe = part.store.subscribe((_liveOnly, _delivered, changed) => {\n            const next = part.store.get();\n            const { outcome } = patternOf(next.pattern);\n            if (changed.includes(\"pattern\") && outcome !== undefined && heard(el)) {\n              announce(next.messages[outcome], { doc });\n            }\n            if (next.drawn !== undefined && sameDrawn(drawnOf(next), next.drawn)) {\n              play();\n            } else {\n              swap();\n            }\n          });\n          swap();\n          return () => {\n            life.alive = false;\n            unsubscribe();\n            observer.disconnect();\n            doc.removeEventListener(\"visibilitychange\", onVisibility);\n            unwatchCover(el);\n            const { layer, handoff } = part.store.get();\n            clearTimeout(handoff);\n            removeLayer(layer);\n          };\n        },\n      }),\n      stage: slot<object, StageFrame>({\n        present: (state) => {\n          return !state.mounted;\n        },\n        state: (state) => {\n          const pattern = patternOf(state.pattern);\n          const lattice = latticeOfSettings(state);\n          const track = bakedTrack(pattern, lattice) ?? stillTrack(pattern, lattice, state.input);\n          return {\n            lights:\n              state.enter || !state.active\n                ? frameAt(darkTrack(lattice, 1000), 0)\n                : frameAt(track, 0, state.input),\n            places: Array.from({ length: lattice.count }, (_, dot) => {\n              return placeLook(lattice, dot);\n            }),\n            look: cellLook(state.dot, state.glow, pitchOf(lattice, state.size), state.floor),\n          };\n        },\n        attrs: (state) => {\n          return {\n            \"aria-hidden\": \"true\",\n            style: css({ position: \"absolute\", inset: \"0\", color: state.color }),\n          };\n        },\n      }),\n    };\n  },\n});\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-primitive.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-canvas.ts",
      "content": "import type { DotForm } from \"./dot-matrix-dots\";\nimport { coreOf, paletteWeight } from \"./dot-matrix-look\";\nimport { cssOf, haloOf, type DotMatrixPaint, type Rgb } from \"./dot-matrix-paint\";\nimport type { DotMatrixRenderer } from \"./dot-matrix-renderer\";\nimport { SCALE_MAX, valueAt } from \"./dot-matrix-track\";\nimport { mountView, type DotMatrixView } from \"./dot-matrix-view\";\n\ntype SpritePart = \"floor\" | \"light\" | \"core\";\n\nconst SPRITES = new Map<string, HTMLCanvasElement>();\nconst SPRITE_LIMIT = 192;\n\nfunction spriteCanvas(doc: Document, side: number): [HTMLCanvasElement, CanvasRenderingContext2D] {\n  const canvas = doc.createElement(\"canvas\");\n  canvas.width = side;\n  canvas.height = side;\n  const context = canvas.getContext(\"2d\");\n  if (context === null) {\n    throw new Error(`Dot Matrix: no 2D canvas context for a ${side}px dot sprite.`);\n  }\n  return [canvas, context];\n}\n\nfunction spriteOf(\n  doc: Document,\n  side: number,\n  soften: number,\n  draw: (context: CanvasRenderingContext2D) => void,\n): HTMLCanvasElement {\n  const [sprite, context] = spriteCanvas(doc, side);\n  if (soften <= 0) {\n    draw(context);\n    return sprite;\n  }\n  const [sharp, sharpContext] = spriteCanvas(doc, side);\n  draw(sharpContext);\n  context.filter = `blur(${soften}px)`;\n  context.drawImage(sharp, 0, 0);\n  return sprite;\n}\n\nfunction inkDot(\n  context: CanvasRenderingContext2D,\n  form: DotForm,\n  side: number,\n  size: number,\n  color: string,\n): void {\n  const left = (side - size) / 2;\n  context.beginPath();\n  if (form.kind === \"ring\") {\n    const stroke = size * form.width;\n    context.arc(side / 2, side / 2, (size - stroke) / 2, 0, Math.PI * 2);\n    context.lineWidth = stroke;\n    context.strokeStyle = color;\n    context.stroke();\n    return;\n  }\n  if (form.kind === \"polygon\") {\n    for (const [x, y] of form.points) {\n      context.lineTo(left + x * size, left + y * size);\n    }\n    context.closePath();\n  } else {\n    context.roundRect(left, left, size, size, form.corner * size);\n  }\n  context.fillStyle = color;\n  context.fill();\n}\n\nfunction spriteFor(\n  view: DotMatrixView,\n  paint: DotMatrixPaint,\n  part: SpritePart,\n  color: Rgb,\n  side: number,\n): HTMLCanvasElement {\n  const { dpr } = view;\n  const { dot, glow } = view.scene;\n  const key = [part, ...color, paint.dark, dot, glow, view.pitch, dpr].join(\":\");\n  const hit = SPRITES.get(key);\n  if (hit !== undefined) {\n    return hit;\n  }\n  const size = paint.size * dpr;\n  const draw = (context: CanvasRenderingContext2D) => {\n    if (part === \"floor\") {\n      inkDot(context, paint.form, side, size, cssOf(color, paint.floor));\n      return;\n    }\n    if (part === \"core\") {\n      inkDot(context, paint.form, side, size, cssOf(color));\n      return;\n    }\n    for (const halo of [paint.wide, paint.tight]) {\n      if (halo.blur > 0 && halo.alpha > 0) {\n        context.shadowColor = cssOf(color, halo.alpha);\n        context.shadowBlur = halo.blur * dpr;\n        inkDot(context, paint.form, side, size, cssOf(color));\n      }\n    }\n    context.shadowColor = \"transparent\";\n    inkDot(context, paint.form, side, size, cssOf(color));\n  };\n  const sprite = spriteOf(view.layer.ownerDocument, side, paint.soften * dpr, draw);\n  if (SPRITES.size >= SPRITE_LIMIT) {\n    SPRITES.delete(SPRITES.keys().next().value ?? \"\");\n  }\n  SPRITES.set(key, sprite);\n  return sprite;\n}\n\ntype Frame = {\n  light: HTMLCanvasElement[];\n  core: HTMLCanvasElement[];\n  x: number;\n  y: number;\n  grow: number;\n  turn: number;\n  reach: number;\n};\n\nconst FRAME: Frame = { light: [], core: [], x: 0, y: 0, grow: 1, turn: 0, reach: 0 };\n\nfunction drawPlaced(view: DotMatrixView, sprite: HTMLCanvasElement): void {\n  const { context, dpr } = view;\n  const { x, y, grow, turn, reach } = FRAME;\n  const cos = Math.cos(turn) * grow * dpr;\n  const sin = Math.sin(turn) * grow * dpr;\n  context.setTransform(cos, sin, -sin, cos, x * dpr, y * dpr);\n  context.drawImage(sprite, -reach, -reach, reach * 2, reach * 2);\n}\n\nfunction drawPalette(\n  view: DotMatrixView,\n  sprites: readonly HTMLCanvasElement[],\n  share: number,\n  tint: number,\n): void {\n  for (let index = 0; index < sprites.length; index += 1) {\n    const alpha = share * paletteWeight(sprites.length, index, tint);\n    const sprite = sprites[index];\n    if (alpha > 0 && sprite !== undefined) {\n      view.context.globalAlpha = alpha;\n      drawPlaced(view, sprite);\n    }\n  }\n}\n\nfunction drawCanvas(view: DotMatrixView): void {\n  const { context, canvas, scene, paint, centers, dpr, progress, input } = view;\n  if (paint === undefined) {\n    return;\n  }\n  const { track } = scene;\n  const reach = paint.size / 2 + Math.ceil(haloOf(scene.dot, scene.glow, view.pitch)) + 1;\n  const pixels = Math.ceil(reach * 2 * dpr);\n  const floor = spriteFor(view, paint, \"floor\", paint.color, pixels);\n  FRAME.light.length = 0;\n  FRAME.core.length = 0;\n  for (const [index, color] of paint.palette.entries()) {\n    FRAME.light.push(spriteFor(view, paint, \"light\", color, pixels));\n    FRAME.core.push(spriteFor(view, paint, \"core\", paint.cores[index] ?? color, pixels));\n  }\n  const before =\n    paint.from === undefined || track.hue === undefined\n      ? undefined\n      : spriteFor(view, paint, \"light\", paint.from, pixels);\n  FRAME.reach = reach;\n  context.setTransform(1, 0, 0, 1, 0, 0);\n  context.globalAlpha = 1;\n  context.clearRect(0, 0, canvas.width, canvas.height);\n  for (let dot = 0; dot < track.lattice.count; dot += 1) {\n    FRAME.x = centers[dot * 2] ?? 0;\n    FRAME.y = centers[dot * 2 + 1] ?? 0;\n    FRAME.grow = 1;\n    FRAME.turn = 0;\n    context.globalAlpha = 1;\n    drawPlaced(view, floor);\n    const level = valueAt(track, \"light\", dot, progress, input);\n    FRAME.grow = valueAt(track, \"scale\", dot, progress, input) * SCALE_MAX;\n    if (level <= 0 || FRAME.grow <= 0) {\n      continue;\n    }\n    FRAME.turn = valueAt(track, \"angle\", dot, progress, input) * Math.PI * 2;\n    const tint = valueAt(track, \"tint\", dot, progress, input);\n    const hue = before === undefined ? 1 : valueAt(track, \"hue\", dot, progress, input);\n    drawPalette(view, FRAME.light, level * hue, tint);\n    if (before !== undefined && hue < 1) {\n      context.globalAlpha = level * (1 - hue);\n      drawPlaced(view, before);\n    }\n    drawPalette(view, FRAME.core, coreOf(level), tint);\n  }\n}\n\nexport const canvasRenderer: DotMatrixRenderer = {\n  name: \"canvas\",\n  mount: (layer, scene) => {\n    return mountView(layer, scene, { draw: drawCanvas });\n  },\n};\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-canvas.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-view.ts",
      "content": "import { joinClock, leaveClock, type ClockClient } from \"./dot-matrix-clock\";\nimport { clamp01 } from \"./dot-matrix-field\";\nimport {\n  boxOf,\n  pitchOf,\n  placeOf,\n  type DotMatrixBox,\n  type DotMatrixLattice,\n} from \"./dot-matrix-lattice\";\nimport { bleedOf, paintOf, type DotMatrixPaint } from \"./dot-matrix-paint\";\nimport type { DotMatrixPlayer, DotMatrixScene } from \"./dot-matrix-renderer\";\nimport { unwatchTheme, watchTheme } from \"./dot-matrix-theme\";\n\nexport type DotMatrixView = {\n  readonly layer: HTMLElement;\n  readonly scene: DotMatrixScene;\n  readonly painter: DotMatrixPainter;\n  readonly canvas: HTMLCanvasElement;\n  readonly context: CanvasRenderingContext2D;\n  readonly box: DotMatrixBox;\n  readonly pitch: number;\n  readonly bleed: number;\n  readonly centers: Float32Array;\n  readonly dpr: number;\n  readonly client: ClockClient;\n  readonly restyle: () => void;\n  paint: DotMatrixPaint | undefined;\n  stale: boolean;\n  speed: number;\n  input: number;\n  playing: boolean;\n  progress: number;\n  last: number;\n};\n\nexport type DotMatrixPainter = Readonly<{\n  draw: (view: DotMatrixView) => void;\n  release?: (view: DotMatrixView) => void;\n}>;\n\nfunction stepView(view: DotMatrixView, now: number): void {\n  const { duration, once } = view.scene.track;\n  if (once) {\n    const elapsed = Math.max(0, now - view.last) * view.speed;\n    view.progress = Math.min(1, view.progress + elapsed / duration);\n  } else {\n    view.progress = (now * view.speed) / duration;\n  }\n  view.last = now;\n}\n\nfunction canvasFor(\n  layer: HTMLElement,\n  box: DotMatrixBox,\n  bleed: number,\n  dpr: number,\n): HTMLCanvasElement {\n  const canvas = layer.ownerDocument.createElement(\"canvas\");\n  const width = box.width + bleed * 2;\n  const height = box.height + bleed * 2;\n  canvas.width = Math.ceil(width * dpr);\n  canvas.height = Math.ceil(height * dpr);\n  Object.assign(canvas.style, {\n    position: \"absolute\",\n    left: `${-bleed}px`,\n    top: `${-bleed}px`,\n    width: `${width}px`,\n    height: `${height}px`,\n    pointerEvents: \"none\",\n  });\n  layer.append(canvas);\n  return canvas;\n}\n\nfunction centersOf(lattice: DotMatrixLattice, box: DotMatrixBox, bleed: number): Float32Array {\n  const centers = new Float32Array(lattice.count * 2);\n  for (let dot = 0; dot < lattice.count; dot += 1) {\n    const [x, y] = placeOf(lattice, dot);\n    centers[dot * 2] = bleed + x * box.width;\n    centers[dot * 2 + 1] = bleed + y * box.height;\n  }\n  return centers;\n}\n\nfunction ticking(view: DotMatrixView): boolean {\n  return view.playing && !(view.scene.track.once && view.progress >= 1);\n}\n\nfunction frameView(view: DotMatrixView, now: number): void {\n  stepView(view, now);\n  if (view.paint !== undefined) {\n    view.painter.draw(view);\n  }\n  if (!ticking(view)) {\n    leaveClock(view.client);\n  }\n}\n\ntype Refresh = { views: Set<DotMatrixView>; queued: boolean };\n\nconst REFRESH: Refresh = { views: new Set(), queued: false };\n\nfunction refresh(): void {\n  REFRESH.queued = false;\n  const views = [...REFRESH.views];\n  REFRESH.views.clear();\n  for (const view of views) {\n    if (view.stale) {\n      view.paint = paintOf(view.layer, view.scene, view.pitch);\n      view.stale = false;\n    }\n  }\n  for (const view of views) {\n    view.painter.draw(view);\n  }\n}\n\nfunction refreshSoon(view: DotMatrixView, restyle: boolean): void {\n  view.stale ||= restyle;\n  REFRESH.views.add(view);\n  if (!REFRESH.queued) {\n    REFRESH.queued = true;\n    queueMicrotask(refresh);\n  }\n}\n\nfunction playView(view: DotMatrixView): void {\n  if (view.playing) {\n    return;\n  }\n  view.playing = true;\n  view.last = performance.now();\n  joinClock(view.client);\n}\n\nfunction pauseView(view: DotMatrixView): void {\n  view.playing = false;\n  leaveClock(view.client);\n}\n\nfunction inputView(view: DotMatrixView, input: number): void {\n  view.input = clamp01(input);\n  if (!ticking(view)) {\n    refreshSoon(view, false);\n  }\n}\n\nfunction destroyView(view: DotMatrixView): void {\n  pauseView(view);\n  REFRESH.views.delete(view);\n  unwatchTheme(view.restyle);\n  view.painter.release?.(view);\n  view.canvas.remove();\n}\n\nexport function mountView(\n  layer: HTMLElement,\n  scene: DotMatrixScene,\n  painter: DotMatrixPainter,\n): DotMatrixPlayer {\n  const { lattice } = scene.track;\n  const doc = layer.ownerDocument;\n  const { size } = scene;\n  const box = boxOf(lattice, size);\n  const pitch = pitchOf(lattice, size);\n  const bleed = bleedOf(scene.dot, scene.glow, pitch, scene.track);\n  const dpr = doc.defaultView?.devicePixelRatio ?? 1;\n  const canvas = canvasFor(layer, box, bleed, dpr);\n  const context = canvas.getContext(\"2d\");\n  if (context === null) {\n    throw new Error(`Dot Matrix: no 2D canvas context for a ${lattice.key} loader.`);\n  }\n  const view: DotMatrixView = {\n    layer,\n    scene,\n    painter,\n    canvas,\n    context,\n    box,\n    pitch,\n    bleed,\n    centers: centersOf(lattice, box, bleed),\n    dpr,\n    client: {\n      frame: (now) => {\n        frameView(view, now);\n      },\n    },\n    restyle: () => {\n      refreshSoon(view, true);\n    },\n    paint: undefined,\n    stale: true,\n    speed: scene.speed,\n    input: clamp01(scene.input),\n    playing: false,\n    progress: 0,\n    last: 0,\n  };\n  watchTheme(doc, view.restyle);\n  refreshSoon(view, true);\n  return {\n    play: () => {\n      playView(view);\n    },\n    pause: () => {\n      pauseView(view);\n    },\n    setSpeed: (speed) => {\n      view.speed = speed;\n    },\n    setInput: (input) => {\n      inputView(view, input);\n    },\n    destroy: () => {\n      destroyView(view);\n    },\n  };\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-view.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-paint.ts",
      "content": "import { DOTS, type DotForm, type DotMatrixDot } from \"./dot-matrix-dots\";\nimport { floorOf, LOOK, softenOf } from \"./dot-matrix-look\";\nimport type { DotMatrixScene } from \"./dot-matrix-renderer\";\nimport { darkAt } from \"./dot-matrix-theme\";\nimport { SCALE_MAX, type DotMatrixTrack } from \"./dot-matrix-track\";\n\nexport type Rgb = readonly [number, number, number];\n\ntype DotMatrixHalo = Readonly<{ blur: number; alpha: number }>;\n\nexport type DotMatrixPaint = Readonly<{\n  color: Rgb;\n  palette: readonly Rgb[];\n  cores: readonly Rgb[];\n  from: Rgb | undefined;\n  dark: boolean;\n  floor: number;\n  tight: DotMatrixHalo;\n  wide: DotMatrixHalo;\n  size: number;\n  form: DotForm;\n  corner: number;\n  soften: number;\n}>;\n\nexport function haloOf(dot: DotMatrixDot, glow: number, pitch: number): number {\n  return pitch * LOOK.halo.wide.reach * glow * 1.5 + softenOf(dot, pitch) * 3;\n}\n\nexport function bleedOf(dot: DotMatrixDot, glow: number, pitch: number, track: DotMatrixTrack) {\n  const half = (pitch * DOTS[dot].fill) / 2;\n  const corner = track.angle === undefined ? half : half * Math.SQRT2;\n  const grow = track.scale === undefined ? 1 : SCALE_MAX;\n  return Math.ceil((corner + haloOf(dot, glow, pitch)) * grow - half);\n}\n\ntype Probe = { context: CanvasRenderingContext2D | undefined; colors: Map<string, Rgb> };\n\nconst PROBE: Probe = { context: undefined, colors: new Map() };\n\nfunction probeContext(doc: Document): CanvasRenderingContext2D {\n  PROBE.context ??=\n    doc.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true }) ?? undefined;\n  if (PROBE.context === undefined) {\n    throw new Error(\"Dot Matrix: no 2D canvas context to read colors.\");\n  }\n  return PROBE.context;\n}\n\nfunction rgbOf(doc: Document, color: string): Rgb | undefined {\n  const hit = PROBE.colors.get(color);\n  if (hit !== undefined) {\n    return hit;\n  }\n  const context = probeContext(doc);\n  context.fillStyle = \"#000\";\n  context.fillStyle = color;\n  const first = context.fillStyle;\n  context.fillStyle = \"#fff\";\n  context.fillStyle = color;\n  if (context.fillStyle !== first) {\n    return undefined;\n  }\n  context.clearRect(0, 0, 1, 1);\n  context.fillRect(0, 0, 1, 1);\n  const [red = 0, green = 0, blue = 0] = context.getImageData(0, 0, 1, 1).data;\n  const rgb: Rgb = [red, green, blue];\n  PROBE.colors.set(color, rgb);\n  return rgb;\n}\n\nconst VAR_PATTERN = /^var\\(\\s*(--[\\w-]+)\\s*(?:,\\s*(.+))?\\)$/u;\n\ntype ColorContext = Readonly<{\n  layer: HTMLElement;\n  style: CSSStyleDeclaration | undefined;\n  current: Rgb;\n}>;\n\nfunction sceneColor(context: ColorContext, color: string, depth = 0): Rgb {\n  const { layer, style, current } = context;\n  const value = color.trim();\n  if (value.toLowerCase() === \"currentcolor\") {\n    return current;\n  }\n  const doc = layer.ownerDocument;\n  const parsed = rgbOf(doc, value);\n  if (parsed !== undefined) {\n    return parsed;\n  }\n  const [, name, fallback] = VAR_PATTERN.exec(value) ?? [];\n  if (name !== undefined && style !== undefined && depth < 4) {\n    const own = style.getPropertyValue(name).trim();\n    return sceneColor(context, own === \"\" ? (fallback ?? \"currentColor\") : own, depth + 1);\n  }\n  const probe = doc.createElement(\"span\");\n  probe.style.display = \"none\";\n  probe.style.color = value;\n  layer.append(probe);\n  const computed = doc.defaultView?.getComputedStyle(probe).color ?? \"\";\n  probe.remove();\n  return rgbOf(doc, computed) ?? current;\n}\n\nconst toLinear = (channel: number) => {\n  const value = channel / 255;\n  return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;\n};\n\nconst toChannel = (value: number) => {\n  const srgb = value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055;\n  return Math.round(Math.min(1, Math.max(0, srgb)) * 255);\n};\n\nfunction oklabOf(rgb: Rgb): Rgb {\n  const [red, green, blue] = [toLinear(rgb[0]), toLinear(rgb[1]), toLinear(rgb[2])];\n  const long = Math.cbrt(0.4122214708 * red + 0.5363325363 * green + 0.0514459929 * blue);\n  const mid = Math.cbrt(0.2119034982 * red + 0.6806995451 * green + 0.1073969566 * blue);\n  const short = Math.cbrt(0.0883024619 * red + 0.2817188376 * green + 0.6299787005 * blue);\n  return [\n    0.2104542553 * long + 0.793617785 * mid - 0.0040720468 * short,\n    1.9779984951 * long - 2.428592205 * mid + 0.4505937099 * short,\n    0.0259040371 * long + 0.7827717662 * mid - 0.808675766 * short,\n  ];\n}\n\nfunction rgbOfOklab([lightness, a, b]: Rgb): Rgb {\n  const long = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3;\n  const mid = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3;\n  const short = (lightness - 0.0894841775 * a - 1.291485548 * b) ** 3;\n  return [\n    toChannel(4.0767416621 * long - 3.3077115913 * mid + 0.2309699292 * short),\n    toChannel(-1.2684380046 * long + 2.6097574011 * mid - 0.3413193965 * short),\n    toChannel(-0.0041960863 * long - 0.7034186147 * mid + 1.707614701 * short),\n  ];\n}\n\nexport function mixOklab(color: Rgb, share: number, other: Rgb): Rgb {\n  const [from, to] = [oklabOf(color), oklabOf(other)];\n  return rgbOfOklab([\n    from[0] * share + to[0] * (1 - share),\n    from[1] * share + to[1] * (1 - share),\n    from[2] * share + to[2] * (1 - share),\n  ]);\n}\n\nfunction cornerOf(form: DotForm, size: number): number {\n  if (form.kind === \"box\") {\n    return size * form.corner;\n  }\n  return form.kind === \"ring\" ? size / 2 : 0;\n}\n\nfunction coreColor(color: Rgb, dark: boolean): Rgb {\n  return dark\n    ? mixOklab(color, LOOK.core.dark, [255, 255, 255])\n    : mixOklab(color, LOOK.core.light, [0, 0, 0]);\n}\n\nexport function paintOf(layer: HTMLElement, scene: DotMatrixScene, pitch: number): DotMatrixPaint {\n  const { dot, glow, track } = scene;\n  const doc = layer.ownerDocument;\n  const style = doc.defaultView?.getComputedStyle(layer);\n  const color = rgbOf(doc, style?.color ?? \"#000\") ?? [0, 0, 0];\n  const dark = darkAt(layer, style?.getPropertyValue(\"color-scheme\") ?? \"normal\");\n  const context: ColorContext = { layer, style, current: color };\n  const palette =\n    track.tint === undefined || scene.colors === undefined || scene.colors.length === 0\n      ? [color]\n      : scene.colors.map((each) => {\n          return sceneColor(context, each);\n        });\n  const { form, fill } = DOTS[dot];\n  const size = pitch * fill;\n  return {\n    color,\n    palette,\n    cores: palette.map((each) => {\n      return coreColor(each, dark);\n    }),\n    from: scene.from === undefined ? undefined : sceneColor(context, scene.from),\n    dark,\n    floor: floorOf(pitch, dark) * scene.floor,\n    tight: {\n      blur: pitch * LOOK.halo.tight.reach * glow,\n      alpha: (dark ? LOOK.halo.tight.dark : LOOK.halo.tight.light) * glow,\n    },\n    wide: {\n      blur: pitch * LOOK.halo.wide.reach * glow,\n      alpha: (dark ? LOOK.halo.wide.dark : LOOK.halo.wide.light) * glow,\n    },\n    size,\n    form,\n    corner: cornerOf(form, size),\n    soften: softenOf(dot, pitch),\n  };\n}\n\nexport function cssOf(color: Rgb, alpha = 1): string {\n  return `rgb(${color[0]} ${color[1]} ${color[2]} / ${alpha})`;\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-paint.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-clock.ts",
      "content": "export type ClockClient = Readonly<{ frame: (now: number) => void }>;\n\ntype Clock = {\n  clients: Set<ClockClient>;\n  request: number;\n};\n\nconst CLOCK: Clock = { clients: new Set(), request: 0 };\n\nfunction tick(now: number): void {\n  CLOCK.request = 0;\n  for (const client of CLOCK.clients) {\n    client.frame(now);\n  }\n  if (CLOCK.clients.size > 0 && CLOCK.request === 0) {\n    CLOCK.request = requestAnimationFrame(tick);\n  }\n}\n\nexport function joinClock(client: ClockClient): void {\n  CLOCK.clients.add(client);\n  if (CLOCK.request === 0) {\n    CLOCK.request = requestAnimationFrame(tick);\n  }\n}\n\nexport function leaveClock(client: ClockClient): void {\n  CLOCK.clients.delete(client);\n  if (CLOCK.clients.size === 0 && CLOCK.request !== 0) {\n    cancelAnimationFrame(CLOCK.request);\n    CLOCK.request = 0;\n  }\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-clock.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-theme.ts",
      "content": "type ThemeWatch = {\n  listeners: Set<() => void>;\n  observer: MutationObserver | undefined;\n  key: string;\n  media: MediaQueryList | undefined;\n  schemes: WeakMap<Document, Map<string, boolean>>;\n};\n\nconst THEME_ATTRIBUTES = [\"class\", \"style\", \"data-color-scheme\", \"data-theme\"];\n\nfunction themeKey(root: HTMLElement): string {\n  return [\n    root.className,\n    root.dataset.colorScheme,\n    root.dataset.theme,\n    root.style.colorScheme,\n    root.style.color,\n  ].join(\"|\");\n}\n\nconst THEME: ThemeWatch = {\n  listeners: new Set(),\n  observer: undefined,\n  key: \"\",\n  media: undefined,\n  schemes: new WeakMap(),\n};\n\nfunction forgetSchemes(): void {\n  THEME.schemes = new WeakMap();\n}\n\nfunction notify(): void {\n  forgetSchemes();\n  for (const listener of THEME.listeners) {\n    listener();\n  }\n}\n\nexport function watchTheme(doc: Document, listener: () => void): void {\n  THEME.listeners.add(listener);\n  if (THEME.observer !== undefined) {\n    return;\n  }\n  const root = doc.documentElement;\n  THEME.key = themeKey(root);\n  THEME.observer = new MutationObserver(() => {\n    const key = themeKey(root);\n    if (key !== THEME.key) {\n      THEME.key = key;\n      notify();\n    }\n  });\n  THEME.observer.observe(doc.documentElement, {\n    attributes: true,\n    attributeFilter: THEME_ATTRIBUTES,\n  });\n  THEME.media = doc.defaultView?.matchMedia(\"(prefers-color-scheme: dark)\");\n  THEME.media?.addEventListener(\"change\", notify);\n}\n\nexport function unwatchTheme(listener: () => void): void {\n  THEME.listeners.delete(listener);\n  if (THEME.listeners.size > 0) {\n    return;\n  }\n  THEME.observer?.disconnect();\n  THEME.media?.removeEventListener(\"change\", notify);\n  THEME.observer = undefined;\n  THEME.media = undefined;\n  forgetSchemes();\n}\n\nexport function darkAt(layer: HTMLElement, scheme: string): boolean {\n  const doc = layer.ownerDocument;\n  const view = doc.defaultView;\n  if (view === null) {\n    return false;\n  }\n  const reads = THEME.schemes.get(doc) ?? new Map<string, boolean>();\n  THEME.schemes.set(doc, reads);\n  const hit = reads.get(scheme);\n  if (hit !== undefined) {\n    return hit;\n  }\n  let dark: boolean;\n  if (view.CSS.supports(\"color\", \"light-dark(#000, #fff)\")) {\n    const probe = doc.createElement(\"span\");\n    probe.style.display = \"none\";\n    probe.style.color = \"light-dark(rgb(0, 0, 0), rgb(255, 255, 255))\";\n    layer.append(probe);\n    dark = view.getComputedStyle(probe).color !== \"rgb(0, 0, 0)\";\n    probe.remove();\n  } else {\n    dark = view.matchMedia(\"(prefers-color-scheme: dark)\").matches;\n  }\n  reads.set(scheme, dark);\n  return dark;\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-theme.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-cover.ts",
      "content": "type CoverWatch = {\n  listeners: Map<Element, (covered: boolean) => void>;\n  observer: MutationObserver | undefined;\n  inert: boolean;\n};\n\nconst COVER: CoverWatch = { listeners: new Map(), observer: undefined, inert: false };\n\nfunction coveredNow(el: Element, modals: readonly Element[]): boolean {\n  return (\n    modals.length > 0 &&\n    modals.every((modal) => {\n      return !modal.contains(el);\n    })\n  );\n}\n\nfunction openModals(doc: Document): Element[] {\n  if (!COVER.inert) {\n    return [];\n  }\n  return [...doc.querySelectorAll('[aria-modal=\"true\"]')].filter((modal) => {\n    return modal.getClientRects().length > 0;\n  });\n}\n\nfunction check(doc: Document): void {\n  COVER.inert = doc.querySelector(\"[inert]\") !== null;\n  const modals = openModals(doc);\n  for (const [el, listener] of COVER.listeners) {\n    listener(coveredNow(el, modals));\n  }\n}\n\nexport function watchCover(el: Element, listener: (covered: boolean) => void): void {\n  const doc = el.ownerDocument;\n  COVER.listeners.set(el, listener);\n  if (COVER.observer === undefined) {\n    COVER.observer = new MutationObserver(() => {\n      check(doc);\n    });\n    COVER.observer.observe(doc.documentElement, {\n      attributes: true,\n      attributeFilter: [\"inert\", \"hidden\", \"aria-modal\"],\n      subtree: true,\n    });\n    COVER.inert = doc.querySelector(\"[inert]\") !== null;\n  }\n  listener(coveredNow(el, openModals(doc)));\n}\n\nexport function unwatchCover(el: Element): void {\n  COVER.listeners.delete(el);\n  if (COVER.listeners.size > 0) {\n    return;\n  }\n  COVER.observer?.disconnect();\n  COVER.observer = undefined;\n  COVER.inert = false;\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-cover.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-look.ts",
      "content": "import { DOTS, polygonOf, type DotMatrixDot } from \"./dot-matrix-dots\";\nimport { placeOf, type DotMatrixLattice } from \"./dot-matrix-lattice\";\n\nexport type Declarations = Readonly<Record<string, string>>;\n\nexport type CellLook = Readonly<{\n  cell: Declarations;\n  floor: Declarations | undefined;\n  light: Declarations;\n  mark: Declarations | undefined;\n  core: Declarations;\n}>;\n\nexport const LOOK = {\n  floor: { light: 0.12, dark: 0.14, smallLight: 0.08, smallDark: 0.1, smallPitch: 5 },\n  core: { light: 0.7, dark: 0.25 },\n  halo: {\n    tight: { reach: 0.35, light: 0.3, dark: 0.9 },\n    wide: { reach: 1.1, light: 0.15, dark: 0.55 },\n  },\n  blur: { share: 0.08, max: 3 },\n} as const;\n\nexport function floorOf(pitch: number, dark: boolean): number {\n  const small = pitch < LOOK.floor.smallPitch;\n  if (dark) {\n    return small ? LOOK.floor.smallDark : LOOK.floor.dark;\n  }\n  return small ? LOOK.floor.smallLight : LOOK.floor.light;\n}\n\nexport function softenOf(dot: DotMatrixDot, pitch: number): number {\n  const { form } = DOTS[dot];\n  return form.kind === \"box\" && form.soft === true\n    ? Math.min(pitch * LOOK.blur.share, LOOK.blur.max)\n    : 0;\n}\n\nexport const CORE_FROM = 0.62;\n\nexport function coreOf(light: number): number {\n  return light <= CORE_FROM ? 0 : (light - CORE_FROM) / (1 - CORE_FROM);\n}\n\nfunction mix(share: number, other = \"transparent\"): string {\n  return `color-mix(in oklab, currentColor ${Math.round(share)}%, ${other})`;\n}\n\nexport function glowTints(glow: number) {\n  return {\n    tight: `light-dark(${mix(100 * LOOK.halo.tight.light * glow)}, ${mix(100 * LOOK.halo.tight.dark * glow)})`,\n    wide: `light-dark(${mix(100 * LOOK.halo.wide.light * glow)}, ${mix(100 * LOOK.halo.wide.dark * glow)})`,\n  };\n}\n\nexport function floorColor(pitch: number, floor = 1): string {\n  return `light-dark(${mix(100 * floorOf(pitch, false) * floor)}, ${mix(100 * floorOf(pitch, true) * floor)})`;\n}\n\nexport const CORE_COLOR = `light-dark(${mix(100 * LOOK.core.light, \"black\")}, ${mix(100 * LOOK.core.dark, \"white\")})`;\n\nfunction paintOf(dot: DotMatrixDot, color: string, width: number) {\n  const { form } = DOTS[dot];\n  if (form.kind === \"ring\") {\n    return {\n      background: \"transparent\",\n      border: `${(width * form.width).toFixed(2)}px solid ${color}`,\n      \"border-radius\": \"50%\",\n      \"clip-path\": \"none\",\n    };\n  }\n  if (form.kind === \"polygon\") {\n    return {\n      background: color,\n      border: \"0\",\n      \"border-radius\": \"0\",\n      \"clip-path\": `polygon(${polygonOf(form.points, \"%\")})`,\n    };\n  }\n  return {\n    background: color,\n    border: \"0\",\n    \"border-radius\": `${form.corner * 100}%`,\n    \"clip-path\": \"none\",\n  };\n}\n\nexport function cellLook(dot: DotMatrixDot, glow: number, pitch: number, floor = 1): CellLook {\n  const width = pitch * DOTS[dot].fill;\n  const tight = (pitch * LOOK.halo.tight.reach * glow).toFixed(2);\n  const wide = (pitch * LOOK.halo.wide.reach * glow).toFixed(2);\n  const fill = { position: \"absolute\", inset: \"0\", \"box-sizing\": \"border-box\" };\n  const tints = glowTints(glow);\n  const soften = softenOf(dot, pitch);\n  const polygon = DOTS[dot].form.kind === \"polygon\";\n  const cell = {\n    position: \"absolute\",\n    width: `${width.toFixed(2)}px`,\n    height: `${width.toFixed(2)}px`,\n    translate: \"-50% -50%\",\n    filter: soften > 0 ? `blur(${soften.toFixed(2)}px)` : \"none\",\n  };\n  if (polygon) {\n    return {\n      cell,\n      floor: { ...fill, ...paintOf(dot, floorColor(pitch, floor), width) },\n      light: {\n        ...fill,\n        filter:\n          glow > 0\n            ? `drop-shadow(0 0 ${tight}px ${tints.tight}) drop-shadow(0 0 ${wide}px ${tints.wide})`\n            : \"none\",\n      },\n      mark: { ...fill, ...paintOf(dot, \"currentColor\", width) },\n      core: { ...fill, ...paintOf(dot, CORE_COLOR, width) },\n    };\n  }\n  const { form } = DOTS[dot];\n  const over = form.kind === \"ring\" ? { inset: `-${(width * form.width).toFixed(2)}px` } : {};\n  return {\n    cell: { ...cell, ...paintOf(dot, floorColor(pitch, floor), width), \"box-sizing\": \"border-box\" },\n    floor: undefined,\n    light: {\n      ...fill,\n      ...over,\n      ...paintOf(dot, \"currentColor\", width),\n      \"box-shadow\":\n        glow > 0 ? `0 0 ${tight}px ${tints.tight}, 0 0 ${wide}px ${tints.wide}` : \"none\",\n    },\n    mark: undefined,\n    core: {\n      ...fill,\n      ...over,\n      ...paintOf(dot, CORE_COLOR, width),\n    },\n  };\n}\n\nexport function placeLook(lattice: DotMatrixLattice, index: number) {\n  const [x, y] = placeOf(lattice, index);\n  return { left: `${(x * 100).toFixed(3)}%`, top: `${(y * 100).toFixed(3)}%` };\n}\n\nexport function applyLook(el: ElementCSSInlineStyle, look: Declarations): void {\n  for (const [property, value] of Object.entries(look)) {\n    el.style.setProperty(property, value);\n  }\n}\n\nexport function paletteWeight(count: number, index: number, tint: number): number {\n  if (count <= 1) {\n    return index === 0 ? 1 : 0;\n  }\n  return Math.max(0, 1 - Math.abs(tint * (count - 1) - index));\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-look.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-renderer.ts",
      "content": "import type { DotMatrixDot } from \"./dot-matrix-dots\";\nimport type { DotMatrixTrack } from \"./dot-matrix-track\";\n\nexport type DotMatrixScene = Readonly<{\n  track: DotMatrixTrack;\n  dot: DotMatrixDot;\n  glow: number;\n  floor: number;\n  speed: number;\n  size: number;\n  colors?: readonly string[];\n  from?: string;\n  input: number;\n}>;\n\nexport type DotMatrixPlayer = Readonly<{\n  play: () => void;\n  pause: () => void;\n  setSpeed: (speed: number) => void;\n  setInput: (input: number) => void;\n  destroy: () => void;\n}>;\n\nexport type DotMatrixRenderer = Readonly<{\n  name: string;\n  mount: (layer: HTMLElement, scene: DotMatrixScene) => DotMatrixPlayer;\n}>;\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-renderer.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-track.ts",
      "content": "import { programOf, type Program, type Sampler } from \"./dot-matrix-compile\";\nimport { atDot, clamp01, sampleContext } from \"./dot-matrix-field\";\nimport type { DotMatrixLattice } from \"./dot-matrix-lattice\";\nimport type { ScenePattern } from \"./dot-matrix-scene\";\n\nexport type DotMatrixTrack = Readonly<{\n  lattice: DotMatrixLattice;\n  frames: number;\n  duration: number;\n  once: boolean;\n  steps: number;\n  light: Uint8Array;\n  scale?: Uint8Array;\n  angle?: Uint8Array;\n  tint?: Uint8Array;\n  hue?: Uint8Array;\n}>;\n\nexport type DotMatrixChannel = \"light\" | \"scale\" | \"angle\" | \"tint\" | \"hue\";\n\nexport const SCALE_MAX = 1.6;\n\nexport const CHANNEL_REST: Readonly<Record<DotMatrixChannel, number>> = {\n  light: 0,\n  scale: 1 / SCALE_MAX,\n  angle: 0,\n  tint: 0,\n  hue: 1,\n};\n\nexport const BAKE_FPS = 30;\n\ntype Fill = readonly [Sampler, Uint8Array];\n\nexport type Bake = {\n  track: DotMatrixTrack;\n  program: Program;\n  fills: readonly Fill[];\n  next: number;\n  done: Promise<DotMatrixTrack> | undefined;\n};\n\nconst bakes = new WeakMap<ScenePattern, Map<string, Bake>>();\n\nfunction framesOf(scene: ScenePattern): number {\n  return Math.max(2, Math.round((scene.duration / 1000) * BAKE_FPS));\n}\n\nexport function bakeOf(scene: ScenePattern, lattice: DotMatrixLattice): Bake {\n  const byLattice = bakes.get(scene) ?? new Map<string, Bake>();\n  bakes.set(scene, byLattice);\n  const hit = byLattice.get(lattice.key);\n  if (hit !== undefined) {\n    return hit;\n  }\n  const program = programOf(scene);\n  const frames = framesOf(scene);\n  const steps = Math.max(1, Math.round(scene.input ?? 1));\n  const size = steps * lattice.count * frames;\n  const fills: Fill[] = [];\n  const fill = (sampler: Sampler | undefined) => {\n    if (sampler === undefined) {\n      return undefined;\n    }\n    const data = new Uint8Array(size);\n    fills.push([sampler, data]);\n    return data;\n  };\n  const light = new Uint8Array(size);\n  fills.push([program.light, light]);\n  const [scale, angle, tint] = [fill(program.scale), fill(program.angle), fill(program.tint)];\n  const track: DotMatrixTrack = {\n    lattice,\n    frames,\n    duration: scene.duration,\n    once: scene.once === true,\n    steps,\n    light,\n    ...(scale === undefined ? {} : { scale }),\n    ...(angle === undefined ? {} : { angle }),\n    ...(tint === undefined ? {} : { tint }),\n  };\n  const bake: Bake = { track, program, fills, next: 0, done: undefined };\n  byLattice.set(lattice.key, bake);\n  return bake;\n}\n\nconst CONTEXT = sampleContext();\n\nexport function bakeUnit(bake: Bake): void {\n  const { track, fills } = bake;\n  const { lattice, frames, steps, once } = track;\n  const unit = bake.next;\n  bake.next += 1;\n  if (unit >= steps * lattice.count) {\n    return;\n  }\n  if (unit === 0) {\n    bake.program.prepare(lattice, frames);\n  }\n  const step = Math.floor(unit / lattice.count);\n  atDot(CONTEXT, lattice, unit % lattice.count);\n  CONTEXT.frames = frames;\n  CONTEXT.input = steps > 1 ? step / (steps - 1) : 0;\n  const base = unit * frames;\n  for (let frame = 0; frame < frames; frame += 1) {\n    CONTEXT.t = once ? frame / (frames - 1) : frame / frames;\n    for (const [sampler, data] of fills) {\n      data[base + frame] = Math.round(clamp01(sampler(CONTEXT)) * 255);\n    }\n  }\n}\n\nexport function finished(bake: Bake): boolean {\n  return bake.next >= bake.track.steps * bake.track.lattice.count;\n}\n\nexport function bakeTrack(scene: ScenePattern, lattice: DotMatrixLattice): DotMatrixTrack {\n  const bake = bakeOf(scene, lattice);\n  while (!finished(bake)) {\n    bakeUnit(bake);\n  }\n  return bake.track;\n}\n\nexport function bakedTrack(\n  scene: ScenePattern,\n  lattice: DotMatrixLattice,\n): DotMatrixTrack | undefined {\n  const bake = bakes.get(scene)?.get(lattice.key);\n  return bake !== undefined && finished(bake) ? bake.track : undefined;\n}\n\nexport function stillTrack(\n  scene: ScenePattern,\n  lattice: DotMatrixLattice,\n  input: number,\n): DotMatrixTrack {\n  const program = programOf(scene);\n  const frames = framesOf(scene);\n  program.prepare(lattice, frames);\n  const light = new Uint8Array(lattice.count * 2);\n  CONTEXT.frames = frames;\n  CONTEXT.t = 0;\n  CONTEXT.input = clamp01(input);\n  for (let dot = 0; dot < lattice.count; dot += 1) {\n    atDot(CONTEXT, lattice, dot);\n    const value = Math.round(clamp01(program.light(CONTEXT)) * 255);\n    light[dot * 2] = value;\n    light[dot * 2 + 1] = value;\n  }\n  return { lattice, frames: 2, duration: scene.duration, once: true, steps: 1, light };\n}\n\nfunction framePlace(track: DotMatrixTrack, t: number): readonly [number, number, number] {\n  const { frames, once } = track;\n  const at = once ? clamp01(t) * (frames - 1) : (t - Math.floor(t)) * frames;\n  const from = Math.floor(at);\n  const a = once ? Math.min(from, frames - 1) : from % frames;\n  const b = once ? Math.min(from + 1, frames - 1) : (from + 1) % frames;\n  return [a, b, at - from];\n}\n\nexport function valueAt(\n  track: DotMatrixTrack,\n  channel: DotMatrixChannel,\n  dot: number,\n  t: number,\n  input = 0,\n): number {\n  const data = track[channel];\n  if (data === undefined) {\n    return CHANNEL_REST[channel];\n  }\n  const { frames, steps } = track;\n  const { count } = track.lattice;\n  const [a, b, share] = framePlace(track, t);\n  const at = clamp01(input) * (steps - 1);\n  const low = Math.floor(at);\n  const high = Math.min(low + 1, steps - 1);\n  const sample = (step: number) => {\n    const base = (step * count + dot) * frames;\n    const from = data[base + a] ?? 0;\n    return from + ((data[base + b] ?? 0) - from) * share;\n  };\n  const lowValue = sample(low);\n  return (lowValue + (sample(high) - lowValue) * (at - low)) / 255;\n}\n\nexport function levelAt(track: DotMatrixTrack, dot: number, t: number, input = 0): number {\n  return valueAt(track, \"light\", dot, t, input);\n}\n\nexport function frameAt(track: DotMatrixTrack, t: number, input = 0): number[] {\n  return Array.from({ length: track.lattice.count }, (_, dot) => {\n    return Math.round(levelAt(track, dot, t, input) * 1000) / 1000;\n  });\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-track.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-bake-pool.ts",
      "content": "import type { BakeReply, BakeRequest } from \"./dot-matrix-bake-worker\";\nimport type { DotMatrixLattice } from \"./dot-matrix-lattice\";\nimport type { ScenePattern } from \"./dot-matrix-scene\";\nimport { bakeOf, bakeUnit, finished, type Bake, type DotMatrixTrack } from \"./dot-matrix-track\";\n\n\nconst SLICE_MS = 4;\n\nfunction whenIdle(step: () => void): void {\n  if (typeof requestIdleCallback === \"function\") {\n    requestIdleCallback(step, { timeout: 100 });\n  } else {\n    setTimeout(step, 0);\n  }\n}\n\nfunction bakeSlices(bake: Bake, resolve: (track: DotMatrixTrack) => void): void {\n  const until = performance.now() + SLICE_MS;\n  while (!finished(bake) && performance.now() < until) {\n    bakeUnit(bake);\n  }\n  if (finished(bake)) {\n    resolve(bake.track);\n  } else {\n    whenIdle(() => {\n      bakeSlices(bake, resolve);\n    });\n  }\n}\n\nfunction bakeIdle(bake: Bake): Promise<DotMatrixTrack> {\n  return bake.program.ready.then(() => {\n    return new Promise<DotMatrixTrack>((resolve) => {\n      bakeSlices(bake, resolve);\n    });\n  });\n}\n\ntype Waiter = Readonly<{\n  bake: Bake;\n  resolve: (track: DotMatrixTrack) => void;\n  fail: (cause: Error) => void;\n}>;\n\ntype WorkerPool = {\n  worker: Worker | undefined;\n  broken: boolean;\n  next: number;\n  waiting: Map<number, Waiter>;\n};\n\nconst WORKER: WorkerPool = {\n  worker: undefined,\n  broken: typeof Worker !== \"function\",\n  next: 0,\n  waiting: new Map(),\n};\n\nfunction onReply(reply: BakeReply): void {\n  const waiter = WORKER.waiting.get(reply.id);\n  WORKER.waiting.delete(reply.id);\n  if (waiter === undefined) {\n    return;\n  }\n  if (\"problem\" in reply) {\n    waiter.fail(new Error(`Dot Matrix: a pattern failed to bake in the worker: ${reply.problem}`));\n    return;\n  }\n  const { track } = waiter.bake;\n  track.light.set(reply.light);\n  for (const channel of [\"scale\", \"angle\", \"tint\"] as const) {\n    const data = reply[channel];\n    if (data !== undefined) {\n      track[channel]?.set(data);\n    }\n  }\n  waiter.bake.next = track.steps * track.lattice.count;\n  waiter.resolve(track);\n}\n\nfunction workerOf(): Worker | undefined {\n  if (WORKER.broken) {\n    return undefined;\n  }\n  if (WORKER.worker !== undefined) {\n    return WORKER.worker;\n  }\n  try {\n    const worker = new Worker(new URL(\"./dot-matrix-bake-worker.ts\", import.meta.url), {\n      type: \"module\",\n    });\n    worker.addEventListener(\"message\", (event: MessageEvent<BakeReply>) => {\n      onReply(event.data);\n    });\n    worker.addEventListener(\"error\", () => {\n      WORKER.broken = true;\n      WORKER.worker = undefined;\n      for (const waiter of WORKER.waiting.values()) {\n        void bakeIdle(waiter.bake).then(waiter.resolve);\n      }\n      WORKER.waiting.clear();\n    });\n    WORKER.worker = worker;\n    return worker;\n  } catch (cause) {\n    WORKER.broken = true;\n    reportError(\n      new Error(\"Dot Matrix: the bake worker did not start; baking on the page in idle time.\", {\n        cause,\n      }),\n    );\n    return undefined;\n  }\n}\n\nexport function bakeSoon(scene: ScenePattern, lattice: DotMatrixLattice): Promise<DotMatrixTrack> {\n  const bake = bakeOf(scene, lattice);\n  if (bake.done !== undefined) {\n    return bake.done;\n  }\n  const worker = workerOf();\n  if (worker === undefined) {\n    bake.done = bakeIdle(bake);\n    return bake.done;\n  }\n  bake.done = new Promise<DotMatrixTrack>((resolve, reject) => {\n    WORKER.next += 1;\n    WORKER.waiting.set(WORKER.next, { bake, resolve, fail: reject });\n    const request: BakeRequest = {\n      id: WORKER.next,\n      scene,\n      lattice: { cols: lattice.cols, rows: lattice.rows, mask: lattice.mask, hex: lattice.hex },\n    };\n    worker.postMessage(request, []);\n  });\n  return bake.done;\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-bake-pool.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-patterns.ts",
      "content": "import type { SceneField, SceneForm, ScenePattern, SceneRef, SceneValue } from \"./dot-matrix-scene\";\n\n\nconst TAU = Math.PI * 2;\n\nfunction ref(name: SceneRef): SceneValue {\n  return { fn: \"ref\", name };\n}\n\nconst T = ref(\"t\");\nconst UNIT = ref(\"unit\");\nconst WIDTH = ref(\"width\");\nconst HEIGHT = ref(\"height\");\n\nfunction add(...of: SceneValue[]): SceneValue {\n  return { fn: \"add\", of };\n}\nfunction mul(...of: SceneValue[]): SceneValue {\n  return { fn: \"mul\", of };\n}\nfunction sub(a: SceneValue, b: SceneValue): SceneValue {\n  return { fn: \"sub\", a, b };\n}\nfunction div(a: SceneValue, b: SceneValue): SceneValue {\n  return { fn: \"div\", a, b };\n}\nfunction sin(of: SceneValue): SceneValue {\n  return { fn: \"sin\", of };\n}\nfunction cos(of: SceneValue): SceneValue {\n  return { fn: \"cos\", of };\n}\nfunction keys(\n  stops: readonly (readonly [number, number])[],\n  ease: \"inOut\" | \"out\" = \"inOut\",\n): SceneValue {\n  return { fn: \"keys\", stops, ease };\n}\n\nfunction disc(radius: SceneValue, x: SceneValue, y: SceneValue): SceneForm {\n  return { form: \"place\", of: { form: \"circle\", radius }, x, y };\n}\n\nfunction orbiting(size: SceneValue, radius: SceneValue, angle: SceneValue): SceneForm {\n  return disc(size, mul(sin(angle), radius), mul(-1, cos(angle), radius));\n}\n\ntype PaintExtra = Omit<Extract<SceneField, { op: \"paint\" }>, \"op\" | \"form\">;\n\nfunction fitted(form: SceneForm, extra: PaintExtra = {}): SceneField {\n  return { op: \"fit\", of: { op: \"paint\", form, ...extra } };\n}\n\nfunction trail(of: SceneField, length: number, samples: number): SceneField {\n  return { op: \"trail\", of, length, samples };\n}\n\nfunction coverage(d: SceneValue): SceneValue {\n  return { fn: \"clamp\", of: sub(0.75, div(d, UNIT)) };\n}\n\n\nconst orbit: ScenePattern = {\n  duration: 1400,\n  light: {\n    op: \"fit\",\n    of: trail(\n      {\n        op: \"paint\",\n        form: {\n          form: \"repeat\",\n          count: 2,\n          of: orbiting(0.17, 0.62, add({ fn: \"spin\", turns: 1 }, mul(ref(\"i\"), Math.PI))),\n        },\n      },\n      0.3,\n      8,\n    ),\n  },\n};\n\nconst GROWTH = 3.9;\nconst SWEEP = keys([\n  [0, 0.5],\n  [0.5, 0.5 + GROWTH],\n  [1, 0.5],\n]);\nconst TAIL = add(\n  mul(T, TAU * 2 - GROWTH),\n  keys([\n    [0, 0],\n    [0.5, 0],\n    [1, GROWTH],\n  ]),\n);\nconst spinner: ScenePattern = {\n  duration: 1600,\n  light: fitted({\n    form: \"arc\",\n    radius: 0.62,\n    start: add(TAIL, mul(SWEEP, 0.5)),\n    sweep: SWEEP,\n    width: 0.26,\n  }),\n};\n\nfunction ringAt(offset: number): SceneField {\n  const k: SceneValue = { fn: \"mod\", a: add(T, offset), b: 1 };\n  return {\n    op: \"paint\",\n    form: { form: \"arc\", radius: add(0.08, mul(k, 0.92)), start: 0, sweep: TAU, width: 0.3 },\n    light: { fn: \"pow\", a: sub(1, k), b: 0.8 },\n  };\n}\n\nconst pulse: ScenePattern = {\n  duration: 1800,\n  light: { op: \"fit\", of: { op: \"brightest\", of: [ringAt(0), ringAt(0.5)] } },\n};\n\nconst breathe: ScenePattern = {\n  duration: 2400,\n  light: fitted(\n    { form: \"circle\", radius: { fn: \"pulse\", low: 0.22, high: 0.62 } },\n    { light: { fn: \"pulse\", low: 0.45, high: 1 }, glow: 1.2 },\n  ),\n};\n\nconst scan: ScenePattern = {\n  duration: 1800,\n  light: trail(\n    {\n      op: \"paint\",\n      form: {\n        form: \"place\",\n        of: { form: \"box\", w: mul(UNIT, 0.45), h: add(HEIGHT, UNIT) },\n        x: mul(\n          keys([\n            [0, -1],\n            [0.5, 1],\n            [1, -1],\n          ]),\n          add(WIDTH, UNIT),\n        ),\n      },\n    },\n    0.14,\n    6,\n  ),\n};\n\nconst BEHIND: SceneValue = { fn: \"mod\", a: sub(mul(T, TAU), ref(\"angle\")), b: TAU };\n\nconst radar: ScenePattern = {\n  duration: 2000,\n  light: {\n    op: \"fit\",\n    of: {\n      op: \"light\",\n      value: mul(\n        { fn: \"clamp\", of: add(0.5, div(sub(0.95, ref(\"r\")), UNIT)) },\n        {\n          fn: \"max\",\n          of: [\n            coverage(mul({ fn: \"min\", of: [BEHIND, sub(TAU, BEHIND)] }, ref(\"r\"))),\n            mul(0.7, {\n              fn: \"pow\",\n              a: { fn: \"clamp\", of: sub(1, div(BEHIND, Math.PI * 0.9)) },\n              b: 3,\n            }),\n          ],\n        },\n      ),\n    },\n  },\n};\n\nconst WIND: SceneValue = {\n  fn: \"ease\",\n  name: \"inOut\",\n  of: sub(1, { fn: \"abs\", of: sub(mul(T, 2), 1) }),\n};\n\nconst spiral: ScenePattern = {\n  duration: 2200,\n  light: {\n    op: \"fit\",\n    of: trail(\n      { op: \"paint\", form: orbiting(0.15, add(0.15, mul(WIND, 0.62)), mul(WIND, TAU * 1.75)) },\n      0.16,\n      8,\n    ),\n  },\n};\n\nconst SQUASH: SceneValue = add(\n  1,\n  mul(0.35, { fn: \"smooth\", from: 0.12, to: 0, of: { fn: \"min\", of: [T, sub(1, T)] } }),\n);\n\nconst bounce: ScenePattern = {\n  duration: 1100,\n  light: fitted({\n    form: \"place\",\n    of: { form: \"box\", w: mul(0.24, SQUASH), h: div(0.24, SQUASH), r: div(0.24, SQUASH) },\n    y: add(\n      sub(HEIGHT, 0.24),\n      mul(-1, { fn: \"pow\", a: sin(mul(T, Math.PI)), b: 0.8 }, add(sub(HEIGHT, 0.24), 0.6)),\n      sub(0.24, div(0.24, SQUASH)),\n    ),\n  }),\n};\n\nconst LEVEL: SceneValue = add(\n  0.12,\n  mul(0.78, {\n    fn: \"pow\",\n    a: { fn: \"noise\", x: mul(ref(\"col\"), 1.7), y: 0.3, z: mul(T, 5), period: 5 },\n    b: 1.6,\n  }),\n);\n\nconst equalizer: ScenePattern = {\n  duration: 1600,\n  light: {\n    op: \"light\",\n    value: add(\n      0.5,\n      div(sub(ref(\"v\"), sub(HEIGHT, mul(LEVEL, 2, add(HEIGHT, mul(UNIT, 0.5))))), UNIT),\n    ),\n  },\n};\n\nconst HOP: SceneValue = {\n  fn: \"pow\",\n  a: sin(\n    mul(Math.PI, {\n      fn: \"min\",\n      of: [1, div({ fn: \"mod\", a: sub(T, mul(ref(\"i\"), 0.14)), b: 1 }, 0.45)],\n    }),\n  ),\n  b: 2,\n};\n\nconst typing: ScenePattern = {\n  duration: 1400,\n  light: {\n    op: \"paint\",\n    form: {\n      form: \"repeat\",\n      count: 3,\n      of: disc(\n        0.2,\n        mul(sub(ref(\"i\"), 1), { fn: \"min\", of: [0.55, mul(WIDTH, 0.55)] }),\n        mul(-1, HOP, { fn: \"min\", of: [0.42, mul(HEIGHT, 0.9)] }),\n      ),\n    },\n  },\n};\n\nconst wave: ScenePattern = {\n  duration: 1800,\n  light: {\n    op: \"light\",\n    value: coverage(\n      sub(\n        {\n          fn: \"abs\",\n          of: sub(\n            ref(\"v\"),\n            mul({ fn: \"max\", of: [HEIGHT, UNIT] }, 0.7, sin(sub(mul(ref(\"u\"), 2.6), mul(T, TAU)))),\n          ),\n        },\n        mul(UNIT, 0.45),\n      ),\n    ),\n  },\n};\n\nconst DROP: SceneValue = {\n  fn: \"mod\",\n  a: add(mul(T, add(1, { fn: \"floor\", of: mul(ref(\"seed\"), 2) })), ref(\"seed\")),\n  b: 1,\n};\n\nconst rain: ScenePattern = {\n  duration: 1600,\n  light: trail(\n    {\n      op: \"particles\",\n      count: 7,\n      x: sub(\n        mul({ fn: \"floor\", of: add(0.5, mul(div(ref(\"i\"), 6), 2, div(WIDTH, UNIT))) }, UNIT),\n        WIDTH,\n      ),\n      y: add(sub(-0.5, HEIGHT), mul(DROP, add(mul(HEIGHT, 2), 1))),\n      size: mul(UNIT, 0.4),\n    },\n    0.08,\n    5,\n  ),\n};\n\nconst sparkle: ScenePattern = {\n  duration: 2400,\n  light: { op: \"sparkle\", density: 0.2, speed: 2 },\n};\n\nconst plasma: ScenePattern = {\n  duration: 4000,\n  most: 13,\n  light: {\n    op: \"light\",\n    value: {\n      fn: \"smooth\",\n      from: 0.38,\n      to: 0.82,\n      of: {\n        fn: \"noise\",\n        x: add(mul(ref(\"u\"), 2.2), 4),\n        y: add(mul(ref(\"v\"), 2.2), 4),\n        z: mul(T, 3),\n        period: 3,\n      },\n    },\n  },\n};\n\nconst ANGLE: SceneValue = mul(T, TAU);\n\nconst metaballs: ScenePattern = {\n  duration: 3200,\n  light: fitted(\n    {\n      form: \"smoothUnion\",\n      k: 0.42,\n      of: [\n        disc(0.26, mul(sin(ANGLE), 0.45), mul(cos(mul(ANGLE, 2)), 0.32)),\n        disc(0.22, mul(cos(ANGLE), 0.5), mul(sin(ANGLE), 0.45)),\n        disc(0.2, mul(sin(mul(ANGLE, -2)), 0.35), mul(cos(mul(ANGLE, -1)), 0.5)),\n      ],\n    },\n    { glow: 0.6 },\n  ),\n};\n\nconst forms: ScenePattern = {\n  duration: 4800,\n  light: fitted({\n    form: \"place\",\n    angle: mul(T, Math.PI),\n    of: {\n      form: \"cycle\",\n      of: [\n        { form: \"circle\", radius: 0.6 },\n        { form: \"box\", w: 0.5, h: 0.5, r: 0.08 },\n        { form: \"place\", of: { form: \"polygon\", sides: 3, radius: 0.72 }, y: 0.12 },\n        { form: \"star\", tips: 5, radius: 0.75, depth: 0.48 },\n      ],\n    },\n  }),\n};\n\nconst RINGS: SceneField = {\n  op: \"fit\",\n  of: {\n    op: \"light\",\n    value: mul(\n      { fn: \"pow\", a: { fn: \"clamp\", of: sin(sub(mul(ref(\"r\"), 9), mul(T, TAU * 2))) }, b: 2 },\n      { fn: \"exp\", of: mul(ref(\"r\"), -1.4) },\n    ),\n  },\n};\n\nconst ripple: ScenePattern = { duration: 2000, most: 13, light: RINGS };\n\nconst snake: ScenePattern = {\n  duration: 2400,\n  light: trail(\n    {\n      op: \"paint\",\n      form: {\n        form: \"dot\",\n        radius: mul(UNIT, 0.45),\n        along: [\n          [-1, -1],\n          [1, -1],\n          [1, 1],\n          [-1, 1],\n        ],\n        at: T,\n        closed: true,\n        stretch: true,\n      },\n    },\n    0.22,\n    10,\n  ),\n};\n\nconst PHASE: SceneValue = add(mul(T, TAU), mul(ref(\"v\"), 2.6));\nconst STRAND: SceneValue = mul(sin(PHASE), { fn: \"min\", of: [0.7, mul(WIDTH, 0.8)] });\n\nfunction strandAt(x: SceneValue, depth: SceneValue): SceneValue {\n  return mul(coverage(sub({ fn: \"abs\", of: sub(ref(\"u\"), x) }, mul(UNIT, 0.3))), depth);\n}\n\nconst helix: ScenePattern = {\n  duration: 2000,\n  light: {\n    op: \"light\",\n    value: {\n      fn: \"max\",\n      of: [\n        strandAt(STRAND, add(0.55, mul(0.45, cos(PHASE)))),\n        strandAt(mul(STRAND, -1), sub(0.55, mul(0.45, cos(PHASE)))),\n      ],\n    },\n  },\n};\n\nconst heartbeat: ScenePattern = {\n  duration: 1800,\n  light: trail(\n    {\n      op: \"paint\",\n      form: {\n        form: \"dot\",\n        radius: mul(UNIT, 0.45),\n        along: [\n          [-1, 0],\n          [-0.35, 0],\n          [-0.2, -0.25],\n          [-0.08, 0.75],\n          [0.06, -0.95],\n          [0.2, 0.3],\n          [0.32, 0],\n          [1, 0],\n        ],\n        at: T,\n        stretch: true,\n      },\n    },\n    0.3,\n    12,\n  ),\n};\n\nconst SURFACE: SceneValue = add(\n  mul(\n    -1,\n    keys([\n      [0, -1.15],\n      [0.45, 0.45],\n      [0.6, 0.45],\n      [1, -1.15],\n    ]),\n    add(HEIGHT, UNIT),\n  ),\n  mul(0.12, sin(add(mul(ref(\"u\"), 3.5), mul(T, TAU * 2)))),\n);\n\nconst fill: ScenePattern = {\n  duration: 2800,\n  light: { op: \"light\", value: coverage(sub(SURFACE, ref(\"v\"))) },\n};\n\n\nconst FILLED: SceneValue = sub(\n  mul(ref(\"input\"), add(mul(WIDTH, 2), UNIT)),\n  add(WIDTH, mul(UNIT, 0.5)),\n);\n\nconst progress: ScenePattern = {\n  duration: 1600,\n  input: 33,\n  light: {\n    op: \"brightest\",\n    of: [\n      { op: \"light\", value: coverage(sub(ref(\"u\"), FILLED)) },\n      { op: \"gain\", of: { op: \"sparkle\", density: 0.12, speed: 2 }, by: 0.35 },\n    ],\n  },\n};\n\nconst progressRing: ScenePattern = {\n  duration: 1600,\n  input: 33,\n  light: fitted(\n    {\n      form: \"arc\",\n      radius: 0.66,\n      start: mul(ref(\"input\"), Math.PI),\n      sweep: mul(ref(\"input\"), TAU),\n      width: 0.24,\n    },\n    { light: add(0.75, mul(0.25, { fn: \"pulse\", low: 0, high: 1, beats: 2 })) },\n  ),\n};\n\nconst LOUD: SceneValue = mul(\n  add(HEIGHT, UNIT),\n  add(\n    0.08,\n    mul(\n      ref(\"input\"),\n      add(0.35, mul(0.65, { fn: \"noise\", x: mul(ref(\"col\"), 1.3), y: 0, z: mul(T, 4), period: 4 })),\n    ),\n  ),\n);\n\nconst voice: ScenePattern = {\n  duration: 1200,\n  input: 9,\n  light: { op: \"light\", value: coverage(sub({ fn: \"abs\", of: ref(\"v\") }, LOUD)) },\n};\n\n\nconst marquee: ScenePattern = {\n  duration: 4000,\n  light: { op: \"text\", text: \"LOADING\", font: \"5x7\", scroll: 1 },\n};\n\nconst life: ScenePattern = {\n  duration: 4000,\n  most: 13,\n  light: { op: \"life\", density: 0.35, steps: 12 },\n};\nconst sand: ScenePattern = { duration: 4000, most: 13, light: { op: \"sand\", rate: 0.5 } };\nconst flock: ScenePattern = { duration: 4000, most: 13, light: { op: \"flock\", count: 6 } };\nconst reaction: ScenePattern = { duration: 5000, most: 13, light: { op: \"reaction\" } };\n\nconst swell: ScenePattern = { duration: 2000, light: RINGS, scale: RINGS };\n\nconst FLIGHT: SceneValue = { fn: \"mod\", a: add(T, ref(\"seed\")), b: 1 };\n\nconst confetti: ScenePattern = {\n  duration: 2400,\n  light: trail(\n    {\n      op: \"particles\",\n      count: 8,\n      x: mul(sin(mul(ref(\"seed\"), TAU)), FLIGHT, 1.1),\n      y: mul(-1, cos(mul(ref(\"seed\"), TAU)), FLIGHT, 1.1),\n      size: mul(UNIT, 0.45),\n      light: sub(1, FLIGHT),\n    },\n    0.06,\n    4,\n  ),\n  angle: {\n    op: \"light\",\n    value: { fn: \"mod\", a: add(mul(T, 2), mul(ref(\"index\"), 0.13)), b: 1 },\n  },\n};\n\nconst spectrum: ScenePattern = {\n  duration: 3000,\n  light: {\n    op: \"light\",\n    value: add(\n      0.35,\n      mul(0.65, {\n        fn: \"pow\",\n        a: { fn: \"clamp\", of: sin(add(mul(ref(\"u\"), 3), mul(T, TAU))) },\n        b: 1.5,\n      }),\n    ),\n  },\n  tint: {\n    op: \"light\",\n    value: { fn: \"mod\", a: add(mul(ref(\"u\"), 0.25), mul(ref(\"v\"), 0.15), T), b: 1 },\n  },\n};\n\n\nconst check: ScenePattern = {\n  duration: 900,\n  once: true,\n  outcome: \"success\",\n  light: fitted(\n    {\n      form: \"polyline\",\n      points: [\n        [-0.58, 0.02],\n        [-0.16, 0.44],\n        [0.6, -0.42],\n      ],\n      width: 0.27,\n      upTo: keys(\n        [\n          [0.05, 0],\n          [0.55, 1],\n        ],\n        \"out\",\n      ),\n    },\n    {\n      light: keys([\n        [0, 0.75],\n        [0.55, 1],\n        [1, 0.92],\n      ]),\n      glow: 0.5,\n    },\n  ),\n};\n\nconst LATE: SceneValue = { fn: \"max\", of: [0, sub(T, 0.6)] };\n\nfunction stroke(\n  a: readonly [number, number],\n  b: readonly [number, number],\n  from: number,\n  to: number,\n): SceneForm {\n  return {\n    form: \"polyline\",\n    points: [a, b],\n    width: 0.27,\n    upTo: keys(\n      [\n        [from, 0],\n        [to, 1],\n      ],\n      \"out\",\n    ),\n  };\n}\n\nconst cross: ScenePattern = {\n  duration: 900,\n  once: true,\n  outcome: \"failure\",\n  light: fitted(\n    {\n      form: \"place\",\n      x: mul(sin(mul(LATE, 40)), 0.12, sub(1, { fn: \"ease\", name: \"out\", of: div(LATE, 0.4) })),\n      of: {\n        form: \"union\",\n        of: [\n          stroke([-0.5, -0.5], [0.5, 0.5], 0.05, 0.35),\n          stroke([0.5, -0.5], [-0.5, 0.5], 0.3, 0.6),\n        ],\n      },\n    },\n    { glow: 0.5 },\n  ),\n};\n\nexport const DOT_MATRIX_PATTERNS = {\n  orbit,\n  spinner,\n  pulse,\n  breathe,\n  scan,\n  radar,\n  spiral,\n  bounce,\n  equalizer,\n  typing,\n  wave,\n  rain,\n  sparkle,\n  plasma,\n  metaballs,\n  forms,\n  ripple,\n  snake,\n  helix,\n  heartbeat,\n  fill,\n  progress,\n  progressRing,\n  voice,\n  marquee,\n  life,\n  sand,\n  flock,\n  reaction,\n  swell,\n  confetti,\n  spectrum,\n  check,\n  cross,\n} as const satisfies Readonly<Record<string, ScenePattern>>;\n\nexport type DotMatrixPatternName = keyof typeof DOT_MATRIX_PATTERNS;\n\nexport const DOT_MATRIX_PATTERN_NAMES = Object.keys(DOT_MATRIX_PATTERNS).filter(\n  (name): name is DotMatrixPatternName => {\n    return name in DOT_MATRIX_PATTERNS;\n  },\n);\n\nexport function patternOf(pattern: DotMatrixPatternName | ScenePattern): ScenePattern {\n  return typeof pattern === \"string\" ? DOT_MATRIX_PATTERNS[pattern] : pattern;\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-patterns.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-field.ts",
      "content": "import type { DotMatrixLattice } from \"./dot-matrix-lattice\";\n\nexport type SampleContext = {\n  t: number;\n  input: number;\n  u: number;\n  v: number;\n  unit: number;\n  width: number;\n  height: number;\n  index: number;\n  col: number;\n  row: number;\n  i: number;\n  count: number;\n  seed: number;\n  lattice: DotMatrixLattice | undefined;\n  frames: number;\n};\n\nexport function sampleContext(): SampleContext {\n  return {\n    t: 0,\n    input: 0,\n    u: 0,\n    v: 0,\n    unit: 1,\n    width: 1,\n    height: 1,\n    index: 0,\n    col: 0,\n    row: 0,\n    i: 0,\n    count: 1,\n    seed: 0,\n    lattice: undefined,\n    frames: 1,\n  };\n}\n\nexport function atDot(context: SampleContext, lattice: DotMatrixLattice, index: number): void {\n  context.lattice = lattice;\n  context.index = index;\n  context.u = lattice.us[index] ?? 0;\n  context.v = lattice.vs[index] ?? 0;\n  context.col = lattice.xs[index] ?? 0;\n  context.row = lattice.ys[index] ?? 0;\n  context.unit = lattice.unit;\n  context.width = lattice.width;\n  context.height = lattice.height;\n}\n\nexport function clamp01(value: number): number {\n  return value < 0 ? 0 : value > 1 ? 1 : value;\n}\n\nexport function smoothStep(from: number, to: number, value: number): number {\n  const k = clamp01((value - from) / (to - from || 1));\n  return k * k * (3 - 2 * k);\n}\n\nexport function wrap(value: number, size: number): number {\n  return ((value % size) + size) % size;\n}\n\nexport function mix(from: number, to: number, k: number): number {\n  return from + (to - from) * k;\n}\n\nexport function hash(n: number): number {\n  const x = Math.sin(n * 127.1 + 311.7) * 43_758.5453;\n  return x - Math.floor(x);\n}\n\nfunction corner(x: number, y: number, z: number): number {\n  return hash(x * 57 + y * 113 + z * 199);\n}\n\nfunction fade(k: number): number {\n  return 0.5 - Math.cos(Math.PI * k) / 2;\n}\n\nexport function noise(x: number, y: number, z: number, period = 0): number {\n  const fx = Math.floor(x);\n  const fy = Math.floor(y);\n  const fz = Math.floor(z);\n  const sx = fade(x - fx);\n  const sy = fade(y - fy);\n  const z0 = period > 0 ? wrap(fz, period) : fz;\n  const z1 = period > 0 ? wrap(fz + 1, period) : fz + 1;\n  const layer = (w: number) => {\n    const top = mix(corner(fx, fy, w), corner(fx + 1, fy, w), sx);\n    const bottom = mix(corner(fx, fy + 1, w), corner(fx + 1, fy + 1, w), sx);\n    return mix(top, bottom, sy);\n  };\n  return mix(layer(z0), layer(z1), fade(z - fz));\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-field.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-lattice.ts",
      "content": "export type DotMatrixMask = \"rect\" | \"circle\" | \"rounded\" | \"capsule\" | \"ring\";\n\nexport type DotMatrixLatticeSpec = Readonly<{\n  cols: number;\n  rows: number;\n  mask?: DotMatrixMask;\n  hex?: boolean;\n}>;\n\nexport type DotMatrixLattice = Readonly<{\n  cols: number;\n  rows: number;\n  mask: DotMatrixMask;\n  hex: boolean;\n  count: number;\n  xs: Int16Array;\n  ys: Int16Array;\n  us: Float32Array;\n  vs: Float32Array;\n  unit: number;\n  width: number;\n  height: number;\n  rowStep: number;\n  key: string;\n}>;\n\nexport type DotMatrixBox = Readonly<{ width: number; height: number }>;\n\nconst HEX_ROW = Math.sqrt(3) / 2;\n\ntype MaskTest = (u: number, v: number, hu: number, hv: number, slack: number) => boolean;\n\nfunction roundedTest(share: number): MaskTest {\n  return (u, v, hu, hv, slack) => {\n    const corner = (Math.min(hu, hv) + slack) * share;\n    const dx = Math.max(Math.abs(u) - (hu + slack - corner), 0);\n    const dy = Math.max(Math.abs(v) - (hv + slack - corner), 0);\n    return Math.hypot(dx, dy) <= corner;\n  };\n}\n\nconst MASKS: Readonly<Record<DotMatrixMask, MaskTest>> = {\n  rect: () => {\n    return true;\n  },\n  circle: (u, v, hu, hv, slack) => {\n    return Math.hypot(u, v) <= Math.min(hu, hv) + slack;\n  },\n  ring: (u, v, hu, hv, slack) => {\n    const radius = Math.min(hu, hv) + slack;\n    const r = Math.hypot(u, v);\n    return r <= radius && r >= radius * 0.5;\n  },\n  rounded: roundedTest(0.55),\n  capsule: roundedTest(1),\n};\n\nconst cache = new Map<string, DotMatrixLattice>();\n\nexport function latticeOf(spec: DotMatrixLatticeSpec): DotMatrixLattice {\n  const cols = Math.max(1, Math.round(spec.cols));\n  const rows = Math.max(1, Math.round(spec.rows));\n  const mask = spec.mask ?? \"rect\";\n  const hex = spec.hex === true;\n  const key = `${cols}x${rows}:${mask}${hex ? \":hex\" : \"\"}`;\n  const hit = cache.get(key);\n  if (hit !== undefined) {\n    return hit;\n  }\n  const rowStep = hex ? HEX_ROW : 1;\n  const center = hex ? 0.25 : 0;\n  const unit = 2 / Math.max(cols - 1 + center * 2, (rows - 1) * rowStep, 1);\n  const hu = ((cols - 1) / 2 + center) * unit;\n  const hv = ((rows - 1) / 2) * unit * rowStep;\n  const xs: number[] = [];\n  const ys: number[] = [];\n  const us: number[] = [];\n  const vs: number[] = [];\n  for (let y = 0; y < rows; y += 1) {\n    const shift = (hex && y % 2 === 1 ? 0.5 : 0) - center;\n    for (let x = 0; x < cols; x += 1) {\n      const u = (x + shift - (cols - 1) / 2) * unit;\n      const v = (y - (rows - 1) / 2) * unit * rowStep;\n      if (MASKS[mask](u, v, hu, hv, unit * 0.5)) {\n        xs.push(x);\n        ys.push(y);\n        us.push(u);\n        vs.push(v);\n      }\n    }\n  }\n  const lattice: DotMatrixLattice = {\n    cols,\n    rows,\n    mask,\n    hex,\n    count: us.length,\n    xs: Int16Array.from(xs),\n    ys: Int16Array.from(ys),\n    us: Float32Array.from(us),\n    vs: Float32Array.from(vs),\n    unit,\n    width: hu,\n    height: hv,\n    rowStep,\n    key,\n  };\n  cache.set(key, lattice);\n  return lattice;\n}\n\nexport function pitchOf(lattice: DotMatrixLattice, size: number): number {\n  return size / ((lattice.rows - 1) * lattice.rowStep + 1);\n}\n\nexport function boxOf(lattice: DotMatrixLattice, size: number): DotMatrixBox {\n  const pitch = pitchOf(lattice, size);\n  return { width: (lattice.cols + (lattice.hex ? 0.5 : 0)) * pitch, height: size };\n}\n\nexport function placeOf(lattice: DotMatrixLattice, index: number): readonly [number, number] {\n  const spanU = lattice.width + lattice.unit / 2;\n  const spanV = lattice.height + lattice.unit / 2;\n  return [\n    ((lattice.us[index] ?? 0) + spanU) / (2 * spanU),\n    ((lattice.vs[index] ?? 0) + spanV) / (2 * spanV),\n  ];\n}\n\nexport const DOT_MATRIX_LATTICES = [\n  \"square\",\n  \"circle\",\n  \"rounded\",\n  \"ring\",\n  \"capsule\",\n  \"bar\",\n  \"hex\",\n] as const;\n\nexport type DotMatrixLatticeName = (typeof DOT_MATRIX_LATTICES)[number];\n\nconst LAYOUTS: Readonly<Record<DotMatrixLatticeName, (n: number) => DotMatrixLatticeSpec>> = {\n  square: (n) => {\n    return { cols: n, rows: n };\n  },\n  circle: (n) => {\n    return { cols: n, rows: n, mask: \"circle\" };\n  },\n  rounded: (n) => {\n    return { cols: n, rows: n, mask: \"rounded\" };\n  },\n  ring: (n) => {\n    return { cols: n, rows: n, mask: \"ring\" };\n  },\n  capsule: (n) => {\n    return { cols: n * 2 + 1, rows: n, mask: \"capsule\" };\n  },\n  bar: (n) => {\n    return { cols: n * 3, rows: n };\n  },\n  hex: (n) => {\n    return { cols: n, rows: n + 2, mask: \"circle\", hex: true };\n  },\n};\n\nconst MIN_PITCH = 4;\n\nexport function densityFor(size: number, most: number): number {\n  const fit = Math.floor(size / MIN_PITCH);\n  return Math.max(3, Math.min(most % 2 === 0 ? most - 1 : most, fit % 2 === 0 ? fit - 1 : fit));\n}\n\nexport function latticeFor(\n  layout: DotMatrixLatticeName | DotMatrixLatticeSpec,\n  n: number,\n): DotMatrixLattice {\n  return latticeOf(typeof layout === \"string\" ? LAYOUTS[layout](n) : layout);\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-lattice.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-dots.ts",
      "content": "export type DotForm =\n  | Readonly<{ kind: \"box\"; corner: number; soft?: boolean }>\n  | Readonly<{ kind: \"ring\"; width: number }>\n  | Readonly<{ kind: \"polygon\"; points: readonly (readonly [number, number])[] }>;\n\nexport const DOT_MATRIX_DOTS = [\n  \"round\",\n  \"square\",\n  \"pixel\",\n  \"triangle\",\n  \"diamond\",\n  \"star\",\n  \"plus\",\n  \"ring\",\n  \"dash\",\n] as const;\n\nexport type DotMatrixDot = (typeof DOT_MATRIX_DOTS)[number];\n\nfunction starPoints(tips: number, depth: number): (readonly [number, number])[] {\n  return Array.from({ length: tips * 2 }, (_, index) => {\n    const angle = (index * Math.PI) / tips;\n    const r = index % 2 === 0 ? 0.5 : 0.5 * depth;\n    return [0.5 + Math.sin(angle) * r, 0.52 - Math.cos(angle) * r] as const;\n  });\n}\n\nexport const DOTS: Readonly<Record<DotMatrixDot, Readonly<{ form: DotForm; fill: number }>>> = {\n  round: { form: { kind: \"box\", corner: 0.5 }, fill: 0.7 },\n  square: { form: { kind: \"box\", corner: 0.28 }, fill: 0.78 },\n  pixel: { form: { kind: \"box\", corner: 0.12, soft: true }, fill: 0.86 },\n  triangle: {\n    form: {\n      kind: \"polygon\",\n      points: [\n        [0.5, 0.06],\n        [0.98, 0.9],\n        [0.02, 0.9],\n      ],\n    },\n    fill: 0.9,\n  },\n  diamond: {\n    form: {\n      kind: \"polygon\",\n      points: [\n        [0.5, 0],\n        [1, 0.5],\n        [0.5, 1],\n        [0, 0.5],\n      ],\n    },\n    fill: 0.86,\n  },\n  star: { form: { kind: \"polygon\", points: starPoints(5, 0.46) }, fill: 0.98 },\n  plus: {\n    form: {\n      kind: \"polygon\",\n      points: [\n        [0.34, 0],\n        [0.66, 0],\n        [0.66, 0.34],\n        [1, 0.34],\n        [1, 0.66],\n        [0.66, 0.66],\n        [0.66, 1],\n        [0.34, 1],\n        [0.34, 0.66],\n        [0, 0.66],\n        [0, 0.34],\n        [0.34, 0.34],\n      ],\n    },\n    fill: 0.82,\n  },\n  ring: { form: { kind: \"ring\", width: 0.3 }, fill: 0.78 },\n  dash: {\n    form: {\n      kind: \"polygon\",\n      points: [\n        [0, 0.34],\n        [1, 0.34],\n        [1, 0.66],\n        [0, 0.66],\n      ],\n    },\n    fill: 0.84,\n  },\n};\n\nexport function polygonOf(\n  points: readonly (readonly [number, number])[],\n  size: number | \"%\",\n): string {\n  return points\n    .map(([x, y]) => {\n      return size === \"%\"\n        ? `${(x * 100).toFixed(1)}% ${(y * 100).toFixed(1)}%`\n        : `${(x * size).toFixed(2)},${(y * size).toFixed(2)}`;\n    })\n    .join(size === \"%\" ? \", \" : \" \");\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-dots.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-ease.ts",
      "content": "\nexport type Ease = (k: number) => number;\n\nexport const EASE = {\n  linear: (k: number) => {\n    return k;\n  },\n  in: (k: number) => {\n    return k * k * k;\n  },\n  out: (k: number) => {\n    return 1 - (1 - k) ** 3;\n  },\n  inOut: (k: number) => {\n    return k < 0.5 ? 4 * k * k * k : 1 - (-2 * k + 2) ** 3 / 2;\n  },\n  sine: (k: number) => {\n    return 0.5 - Math.cos(Math.PI * k) / 2;\n  },\n  outBack: (k: number) => {\n    return 1 + 2.70158 * (k - 1) ** 3 + 1.70158 * (k - 1) ** 2;\n  },\n  spring: (k: number) => {\n    return 1 - Math.cos(k * Math.PI * 4.5) * Math.exp(-k * 6);\n  },\n} as const satisfies Record<string, Ease>;\n\nexport type EaseName = keyof typeof EASE;\n\nexport const EASE_NAMES = Object.keys(EASE).filter((name): name is EaseName => {\n  return name in EASE;\n});\n\nexport function valueAtStops(\n  stops: readonly (readonly [number, number])[],\n  ease: Ease,\n  t: number,\n): number {\n  const [first] = stops;\n  if (first === undefined || t <= first[0]) {\n    return first?.[1] ?? 0;\n  }\n  for (let index = 1; index < stops.length; index += 1) {\n    const to = stops[index];\n    const from = stops[index - 1];\n    if (to !== undefined && from !== undefined && t <= to[0]) {\n      return from[1] + (to[1] - from[1]) * ease((t - from[0]) / (to[0] - from[0] || 1));\n    }\n  }\n  return stops.at(-1)?.[1] ?? first[1];\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-ease.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-sdf.ts",
      "content": "import { clamp01, wrap } from \"./dot-matrix-field\";\n\n\nexport type Point = readonly [number, number];\n\nexport function angleOf(u: number, v: number): number {\n  return Math.atan2(u, -v);\n}\n\nexport function sdBox(x: number, y: number, w: number, h: number, r: number): number {\n  const qx = Math.abs(x) - w + r;\n  const qy = Math.abs(y) - h + r;\n  return Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) + Math.min(Math.max(qx, qy), 0) - r;\n}\n\nexport function sdSegment(x: number, y: number, [ax, ay]: Point, [bx, by]: Point): number {\n  const px = x - ax;\n  const py = y - ay;\n  const dx = bx - ax;\n  const dy = by - ay;\n  const along = clamp01((px * dx + py * dy) / (dx * dx + dy * dy || 1));\n  return Math.hypot(px - dx * along, py - dy * along);\n}\n\nfunction lengthOf(points: readonly Point[]): number {\n  let total = 0;\n  for (let index = 1; index < points.length; index += 1) {\n    const a = points[index - 1];\n    const b = points[index];\n    if (a !== undefined && b !== undefined) {\n      total += Math.hypot(b[0] - a[0], b[1] - a[1]);\n    }\n  }\n  return total;\n}\n\nexport function sdPolyline(x: number, y: number, points: readonly Point[], upTo: number): number {\n  let left = lengthOf(points) * clamp01(upTo);\n  let nearest = Number.POSITIVE_INFINITY;\n  for (let index = 1; index < points.length && left > 0; index += 1) {\n    const a = points[index - 1];\n    const b = points[index];\n    if (a === undefined || b === undefined) {\n      break;\n    }\n    const length = Math.hypot(b[0] - a[0], b[1] - a[1]);\n    const share = Math.min(1, left / (length || 1));\n    nearest = Math.min(\n      nearest,\n      sdSegment(x, y, a, [a[0] + (b[0] - a[0]) * share, a[1] + (b[1] - a[1]) * share]),\n    );\n    left -= length;\n  }\n  return nearest;\n}\n\nexport function pointAlong(points: readonly Point[], k: number, closed: boolean): Point {\n  const path = closed && points[0] !== undefined ? [...points, points[0]] : points;\n  let left = lengthOf(path) * wrap(k, 1);\n  for (let index = 1; index < path.length; index += 1) {\n    const a = path[index - 1];\n    const b = path[index];\n    if (a === undefined || b === undefined) {\n      break;\n    }\n    const length = Math.hypot(b[0] - a[0], b[1] - a[1]);\n    if (left <= length) {\n      const share = left / (length || 1);\n      return [a[0] + (b[0] - a[0]) * share, a[1] + (b[1] - a[1]) * share];\n    }\n    left -= length;\n  }\n  return path.at(-1) ?? [0, 0];\n}\n\nexport function sdArc(x: number, y: number, radius: number, start: number, sweep: number): number {\n  const half = Math.min(Math.abs(sweep), Math.PI * 2) / 2;\n  const angle = wrap(angleOf(x, y) - start + Math.PI, Math.PI * 2) - Math.PI;\n  if (Math.abs(angle) <= half) {\n    return Math.abs(Math.hypot(x, y) - radius);\n  }\n  const end = start + Math.sign(angle) * half;\n  return Math.hypot(x - Math.sin(end) * radius, y + Math.cos(end) * radius);\n}\n\nexport function sdPolygon(x: number, y: number, sides: number, radius: number): number {\n  const wedge = (Math.PI * 2) / Math.max(3, sides);\n  const angle = wrap(angleOf(x, y), wedge) - wedge / 2;\n  return Math.hypot(x, y) * Math.cos(angle) - radius * Math.cos(wedge / 2);\n}\n\nexport function sdStar(x: number, y: number, tips: number, radius: number, depth: number): number {\n  const wedge = (Math.PI * 2) / Math.max(2, tips);\n  const angle = Math.abs(wrap(angleOf(x, y) + wedge / 2, wedge) - wedge / 2);\n  const r = Math.hypot(x, y);\n  const px = Math.sin(angle) * r;\n  const py = Math.cos(angle) * r;\n  const notch: Point = [Math.sin(wedge / 2) * radius * depth, Math.cos(wedge / 2) * radius * depth];\n  const d = sdSegment(px, py, [0, radius], notch);\n  const side = px * (notch[1] - radius) - (py - radius) * notch[0];\n  return side > 0 ? -d : d;\n}\n\nexport function smoothMin(a: number, b: number, k: number): number {\n  const h = clamp01(0.5 + (0.5 * (b - a)) / (k || 1e-6));\n  return b + (a - b) * h - k * h * (1 - h);\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-sdf.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-scene.ts",
      "content": "import type { EaseName } from \"./dot-matrix-ease\";\nimport type { Point } from \"./dot-matrix-sdf\";\n\n\ntype Kind =\n  | \"value\"\n  | \"values\"\n  | \"number\"\n  | \"stops\"\n  | \"ease\"\n  | \"ref\"\n  | \"form\"\n  | \"forms\"\n  | \"field\"\n  | \"fields\"\n  | \"points\"\n  | \"string\"\n  | \"boolean\"\n  | \"font\"\n  | \"image\"\n  | \"images\";\n\ntype Spec = Readonly<Record<string, Readonly<Record<string, Kind | `${Kind}?`>>>>;\n\nexport const SCENE_REFS = [\n  \"t\",\n  \"input\",\n  \"u\",\n  \"v\",\n  \"r\",\n  \"angle\",\n  \"width\",\n  \"height\",\n  \"unit\",\n  \"index\",\n  \"seed\",\n  \"i\",\n  \"count\",\n  \"col\",\n  \"row\",\n] as const;\n\nexport type SceneRef = (typeof SCENE_REFS)[number];\n\nexport const SCENE_FONTS = [\"5x7\", \"3x5\"] as const;\n\nexport type SceneFont = (typeof SCENE_FONTS)[number];\n\nexport const VALUE_SPEC = {\n  keys: { stops: \"stops\", ease: \"ease?\" },\n  spin: { turns: \"number\", offset: \"value?\" },\n  pulse: { low: \"value\", high: \"value\", beats: \"number?\", phase: \"value?\" },\n  ref: { name: \"ref\" },\n  add: { of: \"values\" },\n  mul: { of: \"values\" },\n  min: { of: \"values\" },\n  max: { of: \"values\" },\n  sub: { a: \"value\", b: \"value\" },\n  div: { a: \"value\", b: \"value\" },\n  pow: { a: \"value\", b: \"value\" },\n  mod: { a: \"value\", b: \"value\" },\n  sin: { of: \"value\" },\n  cos: { of: \"value\" },\n  abs: { of: \"value\" },\n  exp: { of: \"value\" },\n  floor: { of: \"value\" },\n  clamp: { of: \"value\" },\n  hash: { of: \"value\" },\n  mix: { from: \"value\", to: \"value\", k: \"value\" },\n  smooth: { from: \"value\", to: \"value\", of: \"value\" },\n  ease: { name: \"ease\", of: \"value\" },\n  noise: { x: \"value\", y: \"value\", z: \"value\", period: \"number?\" },\n} as const satisfies Spec;\n\nexport const FORM_SPEC = {\n  circle: { radius: \"value\" },\n  box: { w: \"value\", h: \"value\", r: \"value?\" },\n  segment: { x1: \"value\", y1: \"value\", x2: \"value\", y2: \"value\", width: \"value\" },\n  polyline: { points: \"points\", width: \"value\", upTo: \"value?\" },\n  dot: { radius: \"value\", along: \"points\", at: \"value\", closed: \"boolean?\", stretch: \"boolean?\" },\n  arc: { radius: \"value\", start: \"value\", sweep: \"value\", width: \"value\" },\n  polygon: { sides: \"number\", radius: \"value\" },\n  star: { tips: \"number\", radius: \"value\", depth: \"value?\" },\n  cross: { size: \"value\", width: \"value\" },\n  union: { of: \"forms\" },\n  smoothUnion: { of: \"forms\", k: \"value\" },\n  subtract: { a: \"form\", b: \"form\" },\n  morph: { a: \"form\", b: \"form\", k: \"value\" },\n  cycle: { of: \"forms\", hold: \"number?\" },\n  outline: { of: \"form\", width: \"value\" },\n  place: { of: \"form\", x: \"value?\", y: \"value?\", angle: \"value?\", scale: \"value?\" },\n  repeat: { of: \"form\", count: \"number\" },\n} as const satisfies Spec;\n\nexport const FIELD_SPEC = {\n  paint: { form: \"form\", light: \"value?\", glow: \"number?\", bold: \"number?\" },\n  light: { value: \"value\" },\n  trail: { of: \"field\", length: \"number?\", samples: \"number?\" },\n  brightest: { of: \"fields\" },\n  sum: { of: \"fields\" },\n  gain: { of: \"field\", by: \"value\" },\n  fit: { of: \"field\" },\n  time: { of: \"field\", speed: \"value?\", offset: \"value?\" },\n  sequence: { of: \"fields\", blend: \"number?\" },\n  particles: { count: \"number\", x: \"value\", y: \"value\", size: \"value\", light: \"value?\" },\n  sparkle: { density: \"number?\", speed: \"number?\" },\n  text: { text: \"string\", font: \"font?\", x: \"value?\", y: \"value?\", scroll: \"number?\" },\n  image: { src: \"image\", invert: \"boolean?\" },\n  frames: { src: \"images\", invert: \"boolean?\" },\n  life: { seed: \"number?\", density: \"number?\", steps: \"number?\" },\n  sand: { seed: \"number?\", rate: \"number?\" },\n  flock: { seed: \"number?\", count: \"number?\" },\n  reaction: { seed: \"number?\", feed: \"number?\", kill: \"number?\" },\n} as const satisfies Spec;\n\ntype KindTypes = {\n  value: SceneValue;\n  values: readonly SceneValue[];\n  number: number;\n  stops: readonly (readonly [number, number])[];\n  ease: EaseName;\n  ref: SceneRef;\n  form: SceneForm;\n  forms: readonly SceneForm[];\n  field: SceneField;\n  fields: readonly SceneField[];\n  points: readonly Point[];\n  string: string;\n  boolean: boolean;\n  font: SceneFont;\n  image: string;\n  images: readonly string[];\n};\n\ntype Required<Params> = {\n  readonly [\n    Key in keyof Params as Params[Key] extends `${string}?` ? never : Key\n  ]: Params[Key] extends keyof KindTypes ? KindTypes[Params[Key]] : never;\n};\n\ntype Optional<Params> = {\n  readonly [\n    Key in keyof Params as Params[Key] extends `${string}?` ? Key : never\n  ]?: Params[Key] extends `${infer Name extends keyof KindTypes}?` ? KindTypes[Name] : never;\n};\n\ntype NodeOf<Tag extends string, Table> = {\n  [Name in keyof Table]: Readonly<Record<Tag, Name>> &\n    Required<Table[Name]> &\n    Optional<Table[Name]>;\n}[keyof Table];\n\nexport type SceneValue = number | NodeOf<\"fn\", typeof VALUE_SPEC>;\nexport type SceneForm = NodeOf<\"form\", typeof FORM_SPEC>;\nexport type SceneField = NodeOf<\"op\", typeof FIELD_SPEC>;\n\nexport type ScenePattern = Readonly<{\n  duration: number;\n  once?: boolean;\n  most?: number;\n  outcome?: \"success\" | \"failure\";\n  input?: number;\n  light: SceneField;\n  scale?: SceneField;\n  angle?: SceneField;\n  tint?: SceneField;\n}>;\n\nexport const SCENE_FAMILIES = {\n  value: { tag: \"fn\", spec: VALUE_SPEC },\n  form: { tag: \"form\", spec: FORM_SPEC },\n  field: { tag: \"op\", spec: FIELD_SPEC },\n} as const;\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-scene.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-compile.ts",
      "content": "import { EASE, valueAtStops } from \"./dot-matrix-ease\";\nimport {\n  clamp01,\n  hash,\n  mix,\n  noise,\n  smoothStep,\n  wrap,\n  type SampleContext,\n} from \"./dot-matrix-field\";\nimport { DOT_FONTS, glyphOf } from \"./dot-matrix-font\";\nimport { loadImageSamples, sampleImage, type ImageSamples } from \"./dot-matrix-image\";\nimport type { DotMatrixLattice } from \"./dot-matrix-lattice\";\nimport type {\n  FIELD_SPEC,\n  FORM_SPEC,\n  SceneField,\n  SceneForm,\n  ScenePattern,\n  SceneRef,\n  SceneValue,\n  VALUE_SPEC,\n} from \"./dot-matrix-scene\";\nimport {\n  angleOf,\n  pointAlong,\n  sdArc,\n  sdBox,\n  sdPolygon,\n  sdPolyline,\n  sdSegment,\n  sdStar,\n  smoothMin,\n} from \"./dot-matrix-sdf\";\nimport { simulate, type SimulationKind, type SimulationParams } from \"./dot-matrix-simulate\";\n\nexport type Sampler = (context: SampleContext) => number;\ntype FormSampler = (context: SampleContext, x: number, y: number) => number;\n\nexport type Program = Readonly<{\n  light: Sampler;\n  scale: Sampler | undefined;\n  angle: Sampler | undefined;\n  tint: Sampler | undefined;\n  prepare: (lattice: DotMatrixLattice, frames: number) => void;\n  ready: Promise<void>;\n}>;\n\ntype Kit = {\n  value: (node: SceneValue) => Sampler;\n  form: (node: SceneForm) => FormSampler;\n  field: (node: SceneField) => Sampler;\n  prepares: ((lattice: DotMatrixLattice, frames: number) => void)[];\n  loads: Promise<void>[];\n};\n\ntype ValueNodes = { [Name in keyof typeof VALUE_SPEC]: Extract<SceneValue, { fn: Name }> };\ntype FormNodes = { [Name in keyof typeof FORM_SPEC]: Extract<SceneForm, { form: Name }> };\ntype FieldNodes = { [Name in keyof typeof FIELD_SPEC]: Extract<SceneField, { op: Name }> };\n\nconst TAU = Math.PI * 2;\n\nconst REFS: Readonly<Record<SceneRef, (context: SampleContext) => number>> = {\n  t: (context) => context.t,\n  input: (context) => context.input,\n  u: (context) => context.u,\n  v: (context) => context.v,\n  r: (context) => Math.hypot(context.u, context.v),\n  angle: (context) => wrap(angleOf(context.u, context.v), TAU),\n  width: (context) => context.width,\n  height: (context) => context.height,\n  unit: (context) => context.unit,\n  index: (context) => context.index,\n  seed: (context) => context.seed,\n  i: (context) => context.i,\n  count: (context) => context.count,\n  col: (context) => context.col,\n  row: (context) => context.row,\n};\n\nfunction fold(\n  samplers: readonly Sampler[],\n  start: number,\n  join: (a: number, b: number) => number,\n): Sampler {\n  return (context) => {\n    let total = start;\n    for (const sampler of samplers) {\n      total = join(total, sampler(context));\n    }\n    return total;\n  };\n}\n\nfunction unary(kit: Kit, node: SceneValue, math: (x: number) => number): Sampler {\n  const of = kit.value(node);\n  return (context) => math(of(context));\n}\n\nfunction binary(\n  kit: Kit,\n  a: SceneValue,\n  b: SceneValue,\n  math: (x: number, y: number) => number,\n): Sampler {\n  const left = kit.value(a);\n  const right = kit.value(b);\n  return (context) => math(left(context), right(context));\n}\n\nconst VALUES: { [Name in keyof ValueNodes]: (node: ValueNodes[Name], kit: Kit) => Sampler } = {\n  keys: (node) => {\n    const ease = EASE[node.ease ?? \"inOut\"];\n    return (context) => valueAtStops(node.stops, ease, context.t);\n  },\n  spin: (node, kit) => {\n    const offset = kit.value(node.offset ?? 0);\n    return (context) => context.t * TAU * node.turns + offset(context);\n  },\n  pulse: (node, kit) => {\n    const low = kit.value(node.low);\n    const high = kit.value(node.high);\n    const phase = kit.value(node.phase ?? 0);\n    const beats = node.beats ?? 1;\n    return (context) => {\n      const k = 0.5 - Math.cos(TAU * (context.t * beats + phase(context))) / 2;\n      return mix(low(context), high(context), k);\n    };\n  },\n  ref: (node) => REFS[node.name],\n  add: (node, kit) => fold(node.of.map(kit.value), 0, (a, b) => a + b),\n  mul: (node, kit) => fold(node.of.map(kit.value), 1, (a, b) => a * b),\n  min: (node, kit) => fold(node.of.map(kit.value), Number.POSITIVE_INFINITY, Math.min),\n  max: (node, kit) => fold(node.of.map(kit.value), Number.NEGATIVE_INFINITY, Math.max),\n  sub: (node, kit) => binary(kit, node.a, node.b, (a, b) => a - b),\n  div: (node, kit) => binary(kit, node.a, node.b, (a, b) => (b === 0 ? 0 : a / b)),\n  pow: (node, kit) => binary(kit, node.a, node.b, (a, b) => Math.abs(a) ** b),\n  mod: (node, kit) => binary(kit, node.a, node.b, (a, b) => (b === 0 ? 0 : wrap(a, b))),\n  sin: (node, kit) => unary(kit, node.of, Math.sin),\n  cos: (node, kit) => unary(kit, node.of, Math.cos),\n  abs: (node, kit) => unary(kit, node.of, Math.abs),\n  exp: (node, kit) => unary(kit, node.of, Math.exp),\n  floor: (node, kit) => unary(kit, node.of, Math.floor),\n  clamp: (node, kit) => unary(kit, node.of, clamp01),\n  hash: (node, kit) => unary(kit, node.of, hash),\n  mix: (node, kit) => {\n    const from = kit.value(node.from);\n    const to = kit.value(node.to);\n    const k = kit.value(node.k);\n    return (context) => mix(from(context), to(context), k(context));\n  },\n  smooth: (node, kit) => {\n    const from = kit.value(node.from);\n    const to = kit.value(node.to);\n    const of = kit.value(node.of);\n    return (context) => smoothStep(from(context), to(context), of(context));\n  },\n  ease: (node, kit) => {\n    const curve = EASE[node.name];\n    return unary(kit, node.of, (x) => curve(clamp01(x)));\n  },\n  noise: (node, kit) => {\n    const x = kit.value(node.x);\n    const y = kit.value(node.y);\n    const z = kit.value(node.z);\n    return (context) => noise(x(context), y(context), z(context), node.period ?? 0);\n  },\n};\n\nfunction forms(kit: Kit, list: readonly SceneForm[]): FormSampler[] {\n  return list.map(kit.form);\n}\n\nconst FORMS: { [Name in keyof FormNodes]: (node: FormNodes[Name], kit: Kit) => FormSampler } = {\n  circle: (node, kit) => {\n    const radius = kit.value(node.radius);\n    return (context, x, y) => Math.hypot(x, y) - radius(context);\n  },\n  box: (node, kit) => {\n    const w = kit.value(node.w);\n    const h = kit.value(node.h);\n    const r = kit.value(node.r ?? 0);\n    return (context, x, y) => sdBox(x, y, w(context), h(context), r(context));\n  },\n  segment: (node, kit) => {\n    const [x1, y1, x2, y2, width] = [node.x1, node.y1, node.x2, node.y2, node.width].map(kit.value);\n    return (context, x, y) => {\n      const a = [x1?.(context) ?? 0, y1?.(context) ?? 0] as const;\n      const b = [x2?.(context) ?? 0, y2?.(context) ?? 0] as const;\n      return sdSegment(x, y, a, b) - (width?.(context) ?? 0) / 2;\n    };\n  },\n  polyline: (node, kit) => {\n    const width = kit.value(node.width);\n    const upTo = kit.value(node.upTo ?? 1);\n    return (context, x, y) => sdPolyline(x, y, node.points, upTo(context)) - width(context) / 2;\n  },\n  dot: (node, kit) => {\n    const radius = kit.value(node.radius);\n    const at = kit.value(node.at);\n    const closed = node.closed === true;\n    const stretch = node.stretch === true;\n    return (context, x, y) => {\n      const [px, py] = pointAlong(node.along, at(context), closed);\n      const sx = stretch ? px * context.width : px;\n      const sy = stretch ? py * context.height : py;\n      return Math.hypot(x - sx, y - sy) - radius(context);\n    };\n  },\n  arc: (node, kit) => {\n    const [radius, start, sweep, width] = [node.radius, node.start, node.sweep, node.width].map(\n      kit.value,\n    );\n    return (context, x, y) => {\n      const d = sdArc(x, y, radius?.(context) ?? 0, start?.(context) ?? 0, sweep?.(context) ?? 0);\n      return d - (width?.(context) ?? 0) / 2;\n    };\n  },\n  polygon: (node, kit) => {\n    const radius = kit.value(node.radius);\n    return (context, x, y) => sdPolygon(x, y, node.sides, radius(context));\n  },\n  star: (node, kit) => {\n    const radius = kit.value(node.radius);\n    const depth = kit.value(node.depth ?? 0.45);\n    return (context, x, y) => sdStar(x, y, node.tips, radius(context), depth(context));\n  },\n  cross: (node, kit) => {\n    const size = kit.value(node.size);\n    const width = kit.value(node.width);\n    return (context, x, y) => {\n      const arm = size(context);\n      const half = width(context) / 2;\n      return Math.min(sdBox(x, y, arm, half, half), sdBox(x, y, half, arm, half));\n    };\n  },\n  union: (node, kit) => {\n    const list = forms(kit, node.of);\n    return (context, x, y) => {\n      let d = Number.POSITIVE_INFINITY;\n      for (const each of list) {\n        d = Math.min(d, each(context, x, y));\n      }\n      return d;\n    };\n  },\n  smoothUnion: (node, kit) => {\n    const list = forms(kit, node.of);\n    const k = kit.value(node.k);\n    return (context, x, y) => {\n      const soft = k(context);\n      let d = Number.POSITIVE_INFINITY;\n      for (const each of list) {\n        const next = each(context, x, y);\n        d = d === Number.POSITIVE_INFINITY ? next : smoothMin(d, next, soft);\n      }\n      return d;\n    };\n  },\n  subtract: (node, kit) => {\n    const a = kit.form(node.a);\n    const b = kit.form(node.b);\n    return (context, x, y) => Math.max(a(context, x, y), -b(context, x, y));\n  },\n  morph: (node, kit) => {\n    const a = kit.form(node.a);\n    const b = kit.form(node.b);\n    const k = kit.value(node.k);\n    return (context, x, y) => mix(a(context, x, y), b(context, x, y), k(context));\n  },\n  cycle: (node, kit) => {\n    const list = forms(kit, node.of);\n    const hold = node.hold ?? 0.45;\n    return (context, x, y) => {\n      const stage = context.t * list.length;\n      const from = Math.floor(stage);\n      const k = EASE.inOut(smoothStep(hold, 1, stage - from));\n      const a = list[from % list.length];\n      const b = list[(from + 1) % list.length];\n      return mix(a?.(context, x, y) ?? 1, b?.(context, x, y) ?? 1, k);\n    };\n  },\n  outline: (node, kit) => {\n    const of = kit.form(node.of);\n    const width = kit.value(node.width);\n    return (context, x, y) => Math.abs(of(context, x, y)) - width(context) / 2;\n  },\n  place: (node, kit) => {\n    const of = kit.form(node.of);\n    const [px, py, angle, scale] = [node.x ?? 0, node.y ?? 0, node.angle ?? 0, node.scale ?? 1].map(\n      kit.value,\n    );\n    return (context, x, y) => {\n      const grown = scale?.(context) ?? 1;\n      const s = grown === 0 ? 1 : grown;\n      const turn = angle?.(context) ?? 0;\n      const dx = (x - (px?.(context) ?? 0)) / s;\n      const dy = (y - (py?.(context) ?? 0)) / s;\n      const cos = Math.cos(turn);\n      const sin = Math.sin(turn);\n      return of(context, dx * cos + dy * sin, -dx * sin + dy * cos) * s;\n    };\n  },\n  repeat: (node, kit) => {\n    const of = kit.form(node.of);\n    return (context, x, y) => {\n      const saved = [context.i, context.count, context.seed] as const;\n      let d = Number.POSITIVE_INFINITY;\n      for (let copy = 0; copy < node.count; copy += 1) {\n        context.i = copy;\n        context.count = node.count;\n        context.seed = hash(copy + 1);\n        d = Math.min(d, of(context, x, y));\n      }\n      [context.i, context.count, context.seed] = saved;\n      return d;\n    };\n  },\n};\n\nfunction atTime(context: SampleContext, t: number, sample: Sampler): number {\n  const saved = context.t;\n  context.t = t;\n  const light = sample(context);\n  context.t = saved;\n  return light;\n}\n\nfunction simulationField(kind: SimulationKind, params: SimulationParams, kit: Kit): Sampler {\n  const baked = new Map<string, Float32Array>();\n  kit.prepares.push((lattice, frames) => {\n    const key = `${lattice.key}:${frames}`;\n    if (!baked.has(key)) {\n      baked.set(key, simulate(kind, lattice, frames, params));\n    }\n  });\n  return (context) => {\n    const data =\n      context.lattice === undefined\n        ? undefined\n        : baked.get(`${context.lattice.key}:${context.frames}`);\n    const frame = Math.round(wrap(context.t, 1) * context.frames) % context.frames;\n    return data?.[context.index * context.frames + frame] ?? 0;\n  };\n}\n\nfunction imageField(sources: readonly string[], invert: boolean, kit: Kit): Sampler {\n  const images: (ImageSamples | undefined)[] = sources.map(() => undefined);\n  kit.loads.push(\n    Promise.all(\n      sources.map(async (src, place) => {\n        images[place] = await loadImageSamples(src);\n      }),\n    ).then(() => undefined),\n  );\n  return (context) => {\n    const image = images[Math.floor(wrap(context.t, 1) * images.length) % images.length];\n    const light = image === undefined ? 0 : sampleImage(image, context);\n    return invert ? 1 - light : light;\n  };\n}\n\nconst GRAPHEMES = new Intl.Segmenter();\n\nconst FIELDS: { [Name in keyof FieldNodes]: (node: FieldNodes[Name], kit: Kit) => Sampler } = {\n  paint: (node, kit) => {\n    const form = kit.form(node.form);\n    const light = kit.value(node.light ?? 1);\n    const glow = node.glow ?? 0;\n    const bold = node.bold ?? 0.25;\n    return (context) => {\n      const d = form(context, context.u, context.v) / context.unit - bold;\n      const fill = clamp01(0.5 - d);\n      const halo = glow > 0 && d > 0 ? Math.exp(-d / glow) * 0.45 : 0;\n      return Math.max(fill, halo) * light(context);\n    };\n  },\n  light: (node, kit) => {\n    const value = kit.value(node.value);\n    return (context) => clamp01(value(context));\n  },\n  trail: (node, kit) => {\n    const of = kit.field(node.of);\n    const length = node.length ?? 0.12;\n    const samples = Math.max(1, node.samples ?? 6);\n    return (context) => {\n      let light = of(context);\n      for (let step = 1; step <= samples; step += 1) {\n        const back = atTime(context, wrap(context.t - (length * step) / samples, 1), of);\n        light = Math.max(light, back * (1 - step / (samples + 1)) ** 1.6);\n      }\n      return light;\n    };\n  },\n  brightest: (node, kit) => fold(node.of.map(kit.field), 0, Math.max),\n  sum: (node, kit) => {\n    const total = fold(node.of.map(kit.field), 0, (a, b) => a + b);\n    return (context) => clamp01(total(context));\n  },\n  gain: (node, kit) => {\n    const of = kit.field(node.of);\n    const by = kit.value(node.by);\n    return (context) => clamp01(of(context) * by(context));\n  },\n  fit: (node, kit) => {\n    const of = kit.field(node.of);\n    return (context) => {\n      const scale = Math.min(context.width, context.height) || 1;\n      const saved = [context.u, context.v, context.unit, context.width, context.height] as const;\n      context.u /= scale;\n      context.v /= scale;\n      context.unit /= scale;\n      context.width /= scale;\n      context.height /= scale;\n      const light = of(context);\n      [context.u, context.v, context.unit, context.width, context.height] = saved;\n      return light;\n    };\n  },\n  time: (node, kit) => {\n    const of = kit.field(node.of);\n    const speed = kit.value(node.speed ?? 1);\n    const offset = kit.value(node.offset ?? 0);\n    return (context) => atTime(context, wrap(context.t * speed(context) + offset(context), 1), of);\n  },\n  sequence: (node, kit) => {\n    const list = node.of.map(kit.field);\n    const blend = node.blend ?? 0.15;\n    return (context) => {\n      const stage = wrap(context.t, 1) * list.length;\n      const from = Math.floor(stage) % list.length;\n      const local = stage - Math.floor(stage);\n      const now = atTime(context, local, list[from] ?? (() => 0));\n      if (blend <= 0 || local < 1 - blend) {\n        return now;\n      }\n      const next = atTime(context, 0, list[(from + 1) % list.length] ?? (() => 0));\n      return mix(now, next, smoothStep(1 - blend, 1, local));\n    };\n  },\n  particles: (node, kit) => {\n    const [x, y, size, light] = [node.x, node.y, node.size, node.light ?? 1].map(kit.value);\n    return (context) => {\n      const saved = [context.i, context.count, context.seed] as const;\n      let total = 0;\n      for (let copy = 0; copy < node.count; copy += 1) {\n        context.i = copy;\n        context.count = node.count;\n        context.seed = hash(copy + 1);\n        const px = x?.(context) ?? 0;\n        const py = y?.(context) ?? 0;\n        const d =\n          (Math.hypot(context.u - px, context.v - py) - (size?.(context) ?? 0)) / context.unit;\n        total = Math.max(total, clamp01(0.5 - d) * (light?.(context) ?? 1));\n      }\n      [context.i, context.count, context.seed] = saved;\n      return total;\n    };\n  },\n  sparkle: (node) => {\n    const density = node.density ?? 0.15;\n    const speed = Math.max(1, Math.round(node.speed ?? 2));\n    return (context) => {\n      const beat = context.t * speed + hash(context.index + 7);\n      const round = Math.floor(beat);\n      const lit = hash(context.index * 3 + wrap(round, speed)) < density;\n      return lit ? Math.sin((beat - round) * Math.PI) ** 2 : 0;\n    };\n  },\n  text: (node, kit) => {\n    const font = DOT_FONTS[node.font ?? \"5x7\"];\n    const chars = Array.from(GRAPHEMES.segment(node.text), (part) => part.segment);\n    const advance = font.width + 1;\n    const span = Math.max(0, chars.length * advance - 1);\n    const x = kit.value(node.x ?? 0);\n    const y = kit.value(node.y ?? 0);\n    const scroll = node.scroll ?? 0;\n    const litAt = (gx: number, gy: number) => {\n      if (gx < 0 || gy < 0 || gy >= font.height || gx >= span) {\n        return 0;\n      }\n      const glyph = glyphOf(font, chars[Math.floor(gx / advance)] ?? \" \");\n      return glyph[gy]?.[gx % advance] === \"1\" ? 1 : 0;\n    };\n    return (context) => {\n      const cols = context.lattice?.cols ?? 1;\n      const rows = context.lattice?.rows ?? 1;\n      const left =\n        scroll > 0 ? cols - wrap(context.t * scroll, 1) * (span + cols) : (cols - span) / 2;\n      const gx = context.col - left - x(context);\n      const gy = Math.round(context.row - (rows - font.height) / 2 - y(context));\n      const base = Math.floor(gx);\n      return mix(litAt(base, gy), litAt(base + 1, gy), gx - base);\n    };\n  },\n  image: (node, kit) => imageField([node.src], node.invert === true, kit),\n  frames: (node, kit) => imageField(node.src, node.invert === true, kit),\n  life: (node, kit) => simulationField(\"life\", node, kit),\n  sand: (node, kit) => simulationField(\"sand\", node, kit),\n  flock: (node, kit) => simulationField(\"flock\", node, kit),\n  reaction: (node, kit) => simulationField(\"reaction\", node, kit),\n};\n\nfunction compileValue<Name extends keyof ValueNodes>(\n  name: Name,\n  node: ValueNodes[Name],\n  kit: Kit,\n): Sampler {\n  return VALUES[name](node, kit);\n}\nfunction compileForm<Name extends keyof FormNodes>(\n  name: Name,\n  node: FormNodes[Name],\n  kit: Kit,\n): FormSampler {\n  return FORMS[name](node, kit);\n}\nfunction compileField<Name extends keyof FieldNodes>(\n  name: Name,\n  node: FieldNodes[Name],\n  kit: Kit,\n): Sampler {\n  return FIELDS[name](node, kit);\n}\n\nfunction compileScene(scene: ScenePattern): Program {\n  const kit: Kit = {\n    value: (node: SceneValue) => {\n      if (typeof node === \"number\") {\n        return () => node;\n      }\n      return compileValue(node.fn, node, kit);\n    },\n    form: (node: SceneForm) => compileForm(node.form, node, kit),\n    field: (node: SceneField) => compileField(node.op, node, kit),\n    prepares: [],\n    loads: [],\n  };\n  const optional = (node: SceneField | undefined) =>\n    node === undefined ? undefined : kit.field(node);\n  const program: Program = {\n    light: kit.field(scene.light),\n    scale: optional(scene.scale),\n    angle: optional(scene.angle),\n    tint: optional(scene.tint),\n    prepare: (lattice, frames) => {\n      for (const prepare of kit.prepares) {\n        prepare(lattice, frames);\n      }\n    },\n    ready: Promise.all(kit.loads).then(() => undefined),\n  };\n  return program;\n}\n\nconst PROGRAMS = new WeakMap<ScenePattern, Program>();\n\nexport function programOf(scene: ScenePattern): Program {\n  const hit = PROGRAMS.get(scene);\n  if (hit !== undefined) {\n    return hit;\n  }\n  const program = compileScene(scene);\n  PROGRAMS.set(scene, program);\n  return program;\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-compile.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-preset.ts",
      "content": "import { DOT_MATRIX_DOTS, type DotMatrixDot } from \"./dot-matrix-dots\";\nimport { EASE_NAMES } from \"./dot-matrix-ease\";\nimport { jsonOf, type Json, type JsonObject } from \"./dot-matrix-json\";\nimport {\n  DOT_MATRIX_LATTICES,\n  type DotMatrixLatticeName,\n  type DotMatrixLatticeSpec,\n} from \"./dot-matrix-lattice\";\nimport { DOT_MATRIX_MORPHS, type DotMatrixMorph } from \"./dot-matrix-morph\";\nimport { DOT_MATRIX_PATTERN_NAMES, type DotMatrixPatternName } from \"./dot-matrix-patterns\";\nimport { SCENE_FAMILIES, SCENE_FONTS, SCENE_REFS, type ScenePattern } from \"./dot-matrix-scene\";\n\nexport type DotMatrixPreset = Readonly<{\n  kind: typeof PRESET_KIND;\n  version: typeof PRESET_VERSION;\n  name: string;\n  description?: string;\n  pattern: DotMatrixPatternName | ScenePattern;\n  lattice?: DotMatrixLatticeName | DotMatrixLatticeSpec;\n  dot?: DotMatrixDot;\n  glow?: number;\n  floor?: number;\n  speed?: number;\n  colors?: readonly string[];\n  morph?: DotMatrixMorph | \"none\";\n  grid?: number;\n}>;\n\nexport type DotMatrixLook = Partial<\n  Pick<\n    DotMatrixPreset,\n    \"pattern\" | \"lattice\" | \"dot\" | \"glow\" | \"floor\" | \"speed\" | \"colors\" | \"morph\" | \"grid\"\n  >\n>;\n\nexport const PRESET_KIND = \"dot-matrix-preset\";\nexport const PRESET_VERSION = 1;\n\nexport type PresetResult =\n  | Readonly<{ ok: true; preset: DotMatrixPreset }>\n  | Readonly<{ ok: false; problems: readonly string[] }>;\n\nconst LIMITS = {\n  depth: 40,\n  nodes: 4000,\n  copies: 64,\n  samples: 16,\n  inputSteps: 65,\n  duration: [100, 30_000],\n  sides: 32,\n  text: 200,\n  imageBytes: 600_000,\n  colors: 8,\n  lattice: 64,\n} as const;\n\nconst CAPS: Readonly<Record<string, readonly [number, number]>> = {\n  count: [1, LIMITS.copies],\n  samples: [1, LIMITS.samples],\n  sides: [3, LIMITS.sides],\n  tips: [2, LIMITS.sides],\n  steps: [1, 64],\n};\n\nconst COLOR =\n  /^(?:#[\\da-f]{3,8}|[a-z]{3,20}|(?:rgba?|hsla?|oklch|oklab|lab|lch|hwb)\\([\\d\\s.,%/+-]{1,80}\\))$/iu;\n\nconst IMAGE = /^data:image\\/(?:png|jpeg|gif|webp);base64,[\\d+/=a-z]+$/iu;\n\ntype Walk = { problems: string[]; nodes: number };\n\nfunction isRecord(value: Json | undefined): value is JsonObject {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isNumber(value: Json | undefined): value is number {\n  return typeof value === \"number\";\n}\n\nfunction isText(value: Json | undefined): value is string {\n  return typeof value === \"string\";\n}\n\nfunction isList(value: Json | undefined): value is readonly Json[] {\n  return Array.isArray(value);\n}\n\nfunction isPairs(value: Json | undefined): boolean {\n  return (\n    isList(value) &&\n    value.length <= 256 &&\n    value.every((pair) => {\n      return isList(pair) && pair.length === 2 && pair.every(isNumber);\n    })\n  );\n}\n\nfunction checkKind(\n  kind: string,\n  value: Json | undefined,\n  path: string,\n  name: string,\n  walk: Walk,\n  depth: number,\n): void {\n  const fail = (what: string) => {\n    walk.problems.push(`${path}: ${what}`);\n  };\n  switch (kind) {\n    case \"value\":\n    case \"form\":\n    case \"field\": {\n      checkNode(kind, value, path, walk, depth + 1);\n      return;\n    }\n    case \"values\":\n    case \"forms\":\n    case \"fields\": {\n      if (!isList(value) || value.length === 0 || value.length > LIMITS.copies) {\n        fail(`must be a list of 1 to ${LIMITS.copies} nodes`);\n        return;\n      }\n      for (const [index, each] of value.entries()) {\n        checkNode(kind.slice(0, -1), each, `${path}[${index}]`, walk, depth + 1);\n      }\n      return;\n    }\n    case \"number\": {\n      const [low, high] = Object.hasOwn(CAPS, name) ? (CAPS[name] ?? [-1e6, 1e6]) : [-1e6, 1e6];\n      if (!isNumber(value) || value < low || value > high) {\n        fail(`must be a number from ${low} to ${high}`);\n      }\n      return;\n    }\n    case \"stops\":\n    case \"points\": {\n      if (!isPairs(value)) {\n        fail(\"must be a list of [x, y] number pairs\");\n      }\n      return;\n    }\n    case \"boolean\": {\n      if (typeof value !== \"boolean\") {\n        fail(\"must be true or false\");\n      }\n      return;\n    }\n    case \"string\": {\n      if (typeof value !== \"string\" || value.length > LIMITS.text) {\n        fail(`must be text of at most ${LIMITS.text} characters`);\n      }\n      return;\n    }\n    case \"ease\":\n    case \"ref\":\n    case \"font\": {\n      const list: readonly string[] =\n        kind === \"ease\" ? EASE_NAMES : kind === \"ref\" ? SCENE_REFS : SCENE_FONTS;\n      if (typeof value !== \"string\" || !list.includes(value)) {\n        fail(`must be one of ${list.join(\", \")}`);\n      }\n      return;\n    }\n    case \"image\":\n    case \"images\": {\n      const list: Json | undefined = kind === \"image\" && value !== undefined ? [value] : value;\n      if (\n        !isList(list) ||\n        list.length === 0 ||\n        list.length > 64 ||\n        !list.every((each) => {\n          return isText(each) && each.length <= LIMITS.imageBytes && IMAGE.test(each);\n        })\n      ) {\n        fail(`must be PNG, JPEG, GIF or WebP data URLs of at most ${LIMITS.imageBytes} characters`);\n      }\n      return;\n    }\n    default: {\n      fail(`has an unknown parameter kind \"${kind}\"`);\n    }\n  }\n}\n\nfunction checkNode(\n  family: string,\n  node: Json | undefined,\n  path: string,\n  walk: Walk,\n  depth: number,\n): void {\n  walk.nodes += 1;\n  if (depth > LIMITS.depth || walk.nodes > LIMITS.nodes) {\n    walk.problems.push(`${path}: the scene is too deep or too large`);\n    return;\n  }\n  if (family === \"value\" && isNumber(node)) {\n    return;\n  }\n  const entry =\n    family === \"value\"\n      ? SCENE_FAMILIES.value\n      : family === \"form\"\n        ? SCENE_FAMILIES.form\n        : SCENE_FAMILIES.field;\n  const params: Readonly<Record<string, Readonly<Record<string, string>>>> = entry.spec;\n  const raw = isRecord(node) ? node[entry.tag] : undefined;\n  const tag = isText(raw) ? raw : \"\";\n  const spec = Object.hasOwn(params, tag) ? params[tag] : undefined;\n  if (!isRecord(node) || spec === undefined) {\n    walk.problems.push(\n      `${path}: must be a ${family} node with \"${entry.tag}\" one of ${Object.keys(params).join(\", \")}`,\n    );\n    return;\n  }\n  for (const key of Object.keys(node)) {\n    if (key !== entry.tag && !(key in spec)) {\n      walk.problems.push(`${path}.${key}: is not a parameter of \"${tag}\"`);\n    }\n  }\n  for (const [name, kind] of Object.entries(spec)) {\n    const optional = kind.endsWith(\"?\");\n    if (node[name] === undefined) {\n      if (!optional) {\n        walk.problems.push(`${path}.${name}: is missing`);\n      }\n    } else {\n      checkKind(\n        optional ? kind.slice(0, -1) : kind,\n        node[name],\n        `${path}.${name}`,\n        name,\n        walk,\n        depth,\n      );\n    }\n  }\n}\n\nfunction checkScene(scene: Json | undefined, path: string, walk: Walk): void {\n  if (!isRecord(scene)) {\n    walk.problems.push(`${path}: must be a built-in name or a scene object`);\n    return;\n  }\n  const [low, high] = LIMITS.duration;\n  if (!isNumber(scene.duration) || scene.duration < low || scene.duration > high) {\n    walk.problems.push(`${path}.duration: must be ${low} to ${high} ms`);\n  }\n  if (\n    scene.input !== undefined &&\n    (!isNumber(scene.input) || scene.input < 2 || scene.input > LIMITS.inputSteps)\n  ) {\n    walk.problems.push(`${path}.input: must be 2 to ${LIMITS.inputSteps} steps`);\n  }\n  if (\n    scene.most !== undefined &&\n    (!isNumber(scene.most) || scene.most < 3 || scene.most > LIMITS.lattice)\n  ) {\n    walk.problems.push(`${path}.most: must be 3 to ${LIMITS.lattice}`);\n  }\n  if (scene.once !== undefined && typeof scene.once !== \"boolean\") {\n    walk.problems.push(`${path}.once: must be true or false`);\n  }\n  if (scene.outcome !== undefined && scene.outcome !== \"success\" && scene.outcome !== \"failure\") {\n    walk.problems.push(`${path}.outcome: must be \"success\" or \"failure\"`);\n  }\n  const known = new Set([\n    \"duration\",\n    \"once\",\n    \"most\",\n    \"outcome\",\n    \"input\",\n    \"light\",\n    \"scale\",\n    \"angle\",\n    \"tint\",\n  ]);\n  for (const key of Object.keys(scene)) {\n    if (!known.has(key)) {\n      walk.problems.push(`${path}.${key}: is not a part of a scene`);\n    }\n  }\n  checkNode(\"field\", scene.light, `${path}.light`, walk, 0);\n  for (const channel of [\"scale\", \"angle\", \"tint\"] as const) {\n    if (scene[channel] !== undefined) {\n      checkNode(\"field\", scene[channel], `${path}.${channel}`, walk, 0);\n    }\n  }\n}\n\nfunction checkLook(input: JsonObject, walk: Walk): void {\n  const oneOf = (key: string, list: readonly string[]) => {\n    const value = input[key];\n    if (value !== undefined && (typeof value !== \"string\" || !list.includes(value))) {\n      walk.problems.push(`$.${key}: must be one of ${list.join(\", \")}`);\n    }\n  };\n  oneOf(\"dot\", DOT_MATRIX_DOTS);\n  oneOf(\"morph\", [...DOT_MATRIX_MORPHS, \"none\"]);\n  const { lattice, glow, floor, speed, grid, colors } = input;\n  if (typeof lattice === \"string\") {\n    oneOf(\"lattice\", DOT_MATRIX_LATTICES);\n  } else if (lattice !== undefined) {\n    const spec = isRecord(lattice) ? lattice : {};\n    const size = (value: Json | undefined) =>\n      isNumber(value) && value >= 1 && value <= LIMITS.lattice;\n    if (!size(spec.cols) || !size(spec.rows)) {\n      walk.problems.push(\n        `$.lattice: must be a layout name or { cols, rows } from 1 to ${LIMITS.lattice}`,\n      );\n    }\n  }\n  if (glow !== undefined && (!isNumber(glow) || glow < 0 || glow > 1)) {\n    walk.problems.push(\"$.glow: must be 0 to 1\");\n  }\n  if (floor !== undefined && (!isNumber(floor) || floor < 0 || floor > 1)) {\n    walk.problems.push(\"$.floor: must be 0 to 1\");\n  }\n  if (speed !== undefined && (!isNumber(speed) || speed < 0.05 || speed > 10)) {\n    walk.problems.push(\"$.speed: must be 0.05 to 10\");\n  }\n  if (grid !== undefined && (!isNumber(grid) || grid < 1 || grid > LIMITS.lattice)) {\n    walk.problems.push(`$.grid: must be 1 to ${LIMITS.lattice}`);\n  }\n  if (\n    colors !== undefined &&\n    (!isList(colors) ||\n      colors.length === 0 ||\n      colors.length > LIMITS.colors ||\n      !colors.every((color) => isText(color) && COLOR.test(color)))\n  ) {\n    walk.problems.push(\n      `$.colors: must be 1 to ${LIMITS.colors} plain CSS colors (hex, a name, or rgb()/oklch()…)`,\n    );\n  }\n}\n\nfunction isPreset(input: Json, walk: Walk): input is JsonObject & DotMatrixPreset {\n  if (!isRecord(input) || input.kind !== PRESET_KIND) {\n    walk.problems.push(`$.kind: must be \"${PRESET_KIND}\"`);\n    return false;\n  }\n  if (input.version !== PRESET_VERSION) {\n    walk.problems.push(`$.version: must be ${PRESET_VERSION}; this preset is from another version`);\n    return false;\n  }\n  const { name, description, pattern } = input;\n  if (typeof name !== \"string\" || name.length === 0 || name.length > 80) {\n    walk.problems.push(\"$.name: must be text of 1 to 80 characters\");\n  }\n  if (description !== undefined && (typeof description !== \"string\" || description.length > 400)) {\n    walk.problems.push(\"$.description: must be text of at most 400 characters\");\n  }\n  if (typeof pattern === \"string\") {\n    if (!DOT_MATRIX_PATTERN_NAMES.some((each) => each === pattern)) {\n      walk.problems.push(`$.pattern: \"${pattern}\" is not a built-in pattern`);\n    }\n  } else {\n    checkScene(pattern, \"$.pattern\", walk);\n  }\n  checkLook(input, walk);\n  for (const key of Object.keys(input)) {\n    if (!PRESET_KEYS.has(key)) {\n      walk.problems.push(`$.${key}: is not a part of a preset`);\n    }\n  }\n  return walk.problems.length === 0;\n}\n\nconst PRESET_KEYS = new Set([\n  \"kind\",\n  \"version\",\n  \"name\",\n  \"description\",\n  \"pattern\",\n  \"lattice\",\n  \"dot\",\n  \"glow\",\n  \"floor\",\n  \"speed\",\n  \"colors\",\n  \"morph\",\n  \"grid\",\n]);\n\nexport function decodePreset(input: unknown): PresetResult {\n  let json: Json | undefined;\n  try {\n    json = jsonOf(input);\n  } catch (cause) {\n    return {\n      ok: false,\n      problems: [`$: must be plain JSON (${cause instanceof Error ? cause.message : \"a cycle\"})`],\n    };\n  }\n  if (json === undefined) {\n    return { ok: false, problems: [\"$: must be plain JSON\"] };\n  }\n  const walk: Walk = { problems: [], nodes: 0 };\n  return isPreset(json, walk) ? { ok: true, preset: json } : { ok: false, problems: walk.problems };\n}\n\nexport function parsePreset(text: string): PresetResult {\n  if (text.length > 2_000_000) {\n    return { ok: false, problems: [\"$: the preset is larger than 2 MB\"] };\n  }\n  try {\n    const json: unknown = JSON.parse(text);\n    return decodePreset(json);\n  } catch (cause) {\n    return {\n      ok: false,\n      problems: [\n        `$: the text is not JSON (${cause instanceof Error ? cause.message : String(cause)})`,\n      ],\n    };\n  }\n}\n\nexport function encodePreset(preset: DotMatrixPreset): string {\n  return `${JSON.stringify(preset, undefined, 2)}\\n`;\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-preset.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-json.ts",
      "content": "export type Json = null | boolean | number | string | readonly Json[] | JsonObject;\nexport type JsonObject = { readonly [key: string]: Json };\n\nexport function jsonOf(value: unknown): Json | undefined {\n  if (value === null || typeof value === \"boolean\" || typeof value === \"string\") {\n    return value;\n  }\n  if (typeof value === \"number\") {\n    return Number.isFinite(value) ? value : undefined;\n  }\n  if (Array.isArray(value)) {\n    const items: Json[] = [];\n    for (const each of value) {\n      const item = jsonOf(each);\n      if (item === undefined) {\n        return undefined;\n      }\n      items.push(item);\n    }\n    return items;\n  }\n  if (typeof value === \"object\" && Object.getPrototypeOf(value) === Object.prototype) {\n    const object: Record<string, Json> = {};\n    for (const [key, each] of Object.entries(value)) {\n      const item = jsonOf(each);\n      if (item === undefined) {\n        return undefined;\n      }\n      object[key] = item;\n    }\n    return object;\n  }\n  return undefined;\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-json.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-image.ts",
      "content": "import { clamp01, type SampleContext } from \"./dot-matrix-field\";\n\nexport type ImageSamples = Readonly<{\n  width: number;\n  height: number;\n  sums: Float64Array;\n}>;\n\nfunction sumsOf(pixels: Uint8ClampedArray, width: number, height: number): Float64Array {\n  const sums = new Float64Array((width + 1) * (height + 1));\n  for (let y = 0; y < height; y += 1) {\n    let row = 0;\n    for (let x = 0; x < width; x += 1) {\n      const at = (y * width + x) * 4;\n      const luma =\n        (0.2126 * (pixels[at] ?? 0) +\n          0.7152 * (pixels[at + 1] ?? 0) +\n          0.0722 * (pixels[at + 2] ?? 0)) /\n        255;\n      row += luma * ((pixels[at + 3] ?? 0) / 255);\n      sums[(y + 1) * (width + 1) + x + 1] = (sums[y * (width + 1) + x + 1] ?? 0) + row;\n    }\n  }\n  return sums;\n}\n\nconst READ_SIZE = 256;\n\nexport async function loadImageSamples(src: string): Promise<ImageSamples> {\n  if (typeof createImageBitmap !== \"function\" || typeof OffscreenCanvas !== \"function\") {\n    return { width: 1, height: 1, sums: new Float64Array(4) };\n  }\n  const response = await fetch(src);\n  if (!response.ok) {\n    throw new Error(\n      `Dot Matrix: the image \"${src.slice(0, 80)}\" did not load (${response.status}).`,\n    );\n  }\n  const bitmap = await createImageBitmap(await response.blob());\n  const scale = Math.min(1, READ_SIZE / Math.max(bitmap.width, bitmap.height));\n  const width = Math.max(1, Math.round(bitmap.width * scale));\n  const height = Math.max(1, Math.round(bitmap.height * scale));\n  const context = new OffscreenCanvas(width, height).getContext(\"2d\");\n  if (context === null) {\n    throw new Error(\"Dot Matrix: no 2D canvas context to read an image.\");\n  }\n  context.drawImage(bitmap, 0, 0, width, height);\n  bitmap.close();\n  return {\n    width,\n    height,\n    sums: sumsOf(context.getImageData(0, 0, width, height).data, width, height),\n  };\n}\n\nfunction sumAt(image: ImageSamples, x: number, y: number): number {\n  const cx = Math.max(0, Math.min(image.width, Math.round(x)));\n  const cy = Math.max(0, Math.min(image.height, Math.round(y)));\n  return image.sums[cy * (image.width + 1) + cx] ?? 0;\n}\n\nexport function sampleImage(image: ImageSamples, context: SampleContext): number {\n  const boxWidth = 2 * context.width + context.unit;\n  const boxHeight = 2 * context.height + context.unit;\n  const perPixel = Math.max(boxWidth / image.width, boxHeight / image.height);\n  const px = context.u / perPixel + image.width / 2;\n  const py = context.v / perPixel + image.height / 2;\n  const half = context.unit / perPixel / 2;\n  const [x0, x1, y0, y1] = [px - half, px + half, py - half, py + half];\n  const area = Math.max(1, (Math.round(x1) - Math.round(x0)) * (Math.round(y1) - Math.round(y0)));\n  const sum =\n    sumAt(image, x1, y1) - sumAt(image, x0, y1) - sumAt(image, x1, y0) + sumAt(image, x0, y0);\n  return clamp01(sum / area);\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-image.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-font.ts",
      "content": "import type { SceneFont } from \"./dot-matrix-scene\";\n\nexport type DotFont = Readonly<{\n  width: number;\n  height: number;\n  glyphs: Readonly<Record<string, readonly string[]>>;\n}>;\n\nconst FONT_5X7: DotFont = {\n  width: 5,\n  height: 7,\n  glyphs: {\n    \" \": [\"00000\", \"00000\", \"00000\", \"00000\", \"00000\", \"00000\", \"00000\"],\n    \"!\": [\"00100\", \"00100\", \"00100\", \"00100\", \"00000\", \"00000\", \"00100\"],\n    '\"': [\"01010\", \"01010\", \"01010\", \"00000\", \"00000\", \"00000\", \"00000\"],\n    \"#\": [\"01010\", \"01010\", \"11111\", \"01010\", \"11111\", \"01010\", \"01010\"],\n    $: [\"00100\", \"01111\", \"10100\", \"01110\", \"00101\", \"11110\", \"00100\"],\n    \"%\": [\"11000\", \"11001\", \"00010\", \"00100\", \"01000\", \"10011\", \"00011\"],\n    \"&\": [\"01100\", \"10010\", \"10100\", \"01000\", \"10101\", \"10010\", \"01101\"],\n    \"'\": [\"01100\", \"00100\", \"01000\", \"00000\", \"00000\", \"00000\", \"00000\"],\n    \"(\": [\"00010\", \"00100\", \"01000\", \"01000\", \"01000\", \"00100\", \"00010\"],\n    \")\": [\"01000\", \"00100\", \"00010\", \"00010\", \"00010\", \"00100\", \"01000\"],\n    \"*\": [\"00000\", \"00100\", \"10101\", \"01110\", \"10101\", \"00100\", \"00000\"],\n    \"+\": [\"00000\", \"00100\", \"00100\", \"11111\", \"00100\", \"00100\", \"00000\"],\n    \",\": [\"00000\", \"00000\", \"00000\", \"00000\", \"01100\", \"00100\", \"01000\"],\n    \"-\": [\"00000\", \"00000\", \"00000\", \"11111\", \"00000\", \"00000\", \"00000\"],\n    \".\": [\"00000\", \"00000\", \"00000\", \"00000\", \"00000\", \"01100\", \"01100\"],\n    \"/\": [\"00000\", \"00001\", \"00010\", \"00100\", \"01000\", \"10000\", \"00000\"],\n    \"0\": [\"01110\", \"10001\", \"10011\", \"10101\", \"11001\", \"10001\", \"01110\"],\n    \"1\": [\"00100\", \"01100\", \"00100\", \"00100\", \"00100\", \"00100\", \"01110\"],\n    \"2\": [\"01110\", \"10001\", \"00001\", \"00010\", \"00100\", \"01000\", \"11111\"],\n    \"3\": [\"11111\", \"00010\", \"00100\", \"00010\", \"00001\", \"10001\", \"01110\"],\n    \"4\": [\"00010\", \"00110\", \"01010\", \"10010\", \"11111\", \"00010\", \"00010\"],\n    \"5\": [\"11111\", \"10000\", \"11110\", \"00001\", \"00001\", \"10001\", \"01110\"],\n    \"6\": [\"00110\", \"01000\", \"10000\", \"11110\", \"10001\", \"10001\", \"01110\"],\n    \"7\": [\"11111\", \"00001\", \"00010\", \"00100\", \"01000\", \"01000\", \"01000\"],\n    \"8\": [\"01110\", \"10001\", \"10001\", \"01110\", \"10001\", \"10001\", \"01110\"],\n    \"9\": [\"01110\", \"10001\", \"10001\", \"01111\", \"00001\", \"00010\", \"01100\"],\n    \":\": [\"00000\", \"01100\", \"01100\", \"00000\", \"01100\", \"01100\", \"00000\"],\n    \";\": [\"00000\", \"01100\", \"01100\", \"00000\", \"01100\", \"00100\", \"01000\"],\n    \"<\": [\"00010\", \"00100\", \"01000\", \"10000\", \"01000\", \"00100\", \"00010\"],\n    \"=\": [\"00000\", \"00000\", \"11111\", \"00000\", \"11111\", \"00000\", \"00000\"],\n    \">\": [\"01000\", \"00100\", \"00010\", \"00001\", \"00010\", \"00100\", \"01000\"],\n    \"?\": [\"01110\", \"10001\", \"00001\", \"00010\", \"00100\", \"00000\", \"00100\"],\n    \"@\": [\"01110\", \"10001\", \"00001\", \"01101\", \"10101\", \"10101\", \"01110\"],\n    A: [\"01110\", \"10001\", \"10001\", \"10001\", \"11111\", \"10001\", \"10001\"],\n    B: [\"11110\", \"10001\", \"10001\", \"11110\", \"10001\", \"10001\", \"11110\"],\n    C: [\"01110\", \"10001\", \"10000\", \"10000\", \"10000\", \"10001\", \"01110\"],\n    D: [\"11100\", \"10010\", \"10001\", \"10001\", \"10001\", \"10010\", \"11100\"],\n    E: [\"11111\", \"10000\", \"10000\", \"11110\", \"10000\", \"10000\", \"11111\"],\n    F: [\"11111\", \"10000\", \"10000\", \"11110\", \"10000\", \"10000\", \"10000\"],\n    G: [\"01110\", \"10001\", \"10000\", \"10111\", \"10001\", \"10001\", \"01111\"],\n    H: [\"10001\", \"10001\", \"10001\", \"11111\", \"10001\", \"10001\", \"10001\"],\n    I: [\"01110\", \"00100\", \"00100\", \"00100\", \"00100\", \"00100\", \"01110\"],\n    J: [\"00111\", \"00010\", \"00010\", \"00010\", \"00010\", \"10010\", \"01100\"],\n    K: [\"10001\", \"10010\", \"10100\", \"11000\", \"10100\", \"10010\", \"10001\"],\n    L: [\"10000\", \"10000\", \"10000\", \"10000\", \"10000\", \"10000\", \"11111\"],\n    M: [\"10001\", \"11011\", \"10101\", \"10101\", \"10001\", \"10001\", \"10001\"],\n    N: [\"10001\", \"10001\", \"11001\", \"10101\", \"10011\", \"10001\", \"10001\"],\n    O: [\"01110\", \"10001\", \"10001\", \"10001\", \"10001\", \"10001\", \"01110\"],\n    P: [\"11110\", \"10001\", \"10001\", \"11110\", \"10000\", \"10000\", \"10000\"],\n    Q: [\"01110\", \"10001\", \"10001\", \"10001\", \"10101\", \"10010\", \"01101\"],\n    R: [\"11110\", \"10001\", \"10001\", \"11110\", \"10100\", \"10010\", \"10001\"],\n    S: [\"01111\", \"10000\", \"10000\", \"01110\", \"00001\", \"00001\", \"11110\"],\n    T: [\"11111\", \"00100\", \"00100\", \"00100\", \"00100\", \"00100\", \"00100\"],\n    U: [\"10001\", \"10001\", \"10001\", \"10001\", \"10001\", \"10001\", \"01110\"],\n    V: [\"10001\", \"10001\", \"10001\", \"10001\", \"10001\", \"01010\", \"00100\"],\n    W: [\"10001\", \"10001\", \"10001\", \"10101\", \"10101\", \"10101\", \"01010\"],\n    X: [\"10001\", \"10001\", \"01010\", \"00100\", \"01010\", \"10001\", \"10001\"],\n    Y: [\"10001\", \"10001\", \"10001\", \"01010\", \"00100\", \"00100\", \"00100\"],\n    Z: [\"11111\", \"00001\", \"00010\", \"00100\", \"01000\", \"10000\", \"11111\"],\n    \"[\": [\"01110\", \"01000\", \"01000\", \"01000\", \"01000\", \"01000\", \"01110\"],\n    \"\\\\\": [\"00000\", \"10000\", \"01000\", \"00100\", \"00010\", \"00001\", \"00000\"],\n    \"]\": [\"01110\", \"00010\", \"00010\", \"00010\", \"00010\", \"00010\", \"01110\"],\n    \"^\": [\"00100\", \"01010\", \"10001\", \"00000\", \"00000\", \"00000\", \"00000\"],\n    _: [\"00000\", \"00000\", \"00000\", \"00000\", \"00000\", \"00000\", \"11111\"],\n    \"`\": [\"01000\", \"00100\", \"00010\", \"00000\", \"00000\", \"00000\", \"00000\"],\n    a: [\"00000\", \"00000\", \"01110\", \"00001\", \"01111\", \"10001\", \"01111\"],\n    b: [\"10000\", \"10000\", \"10110\", \"11001\", \"10001\", \"10001\", \"11110\"],\n    c: [\"00000\", \"00000\", \"01110\", \"10000\", \"10000\", \"10001\", \"01110\"],\n    d: [\"00001\", \"00001\", \"01101\", \"10011\", \"10001\", \"10001\", \"01111\"],\n    e: [\"00000\", \"00000\", \"01110\", \"10001\", \"11111\", \"10000\", \"01110\"],\n    f: [\"00110\", \"01001\", \"01000\", \"11100\", \"01000\", \"01000\", \"01000\"],\n    g: [\"00000\", \"01111\", \"10001\", \"10001\", \"01111\", \"00001\", \"01110\"],\n    h: [\"10000\", \"10000\", \"10110\", \"11001\", \"10001\", \"10001\", \"10001\"],\n    i: [\"00100\", \"00000\", \"01100\", \"00100\", \"00100\", \"00100\", \"01110\"],\n    j: [\"00010\", \"00000\", \"00110\", \"00010\", \"00010\", \"10010\", \"01100\"],\n    k: [\"10000\", \"10000\", \"10010\", \"10100\", \"11000\", \"10100\", \"10010\"],\n    l: [\"01100\", \"00100\", \"00100\", \"00100\", \"00100\", \"00100\", \"01110\"],\n    m: [\"00000\", \"00000\", \"11010\", \"10101\", \"10101\", \"10001\", \"10001\"],\n    n: [\"00000\", \"00000\", \"10110\", \"11001\", \"10001\", \"10001\", \"10001\"],\n    o: [\"00000\", \"00000\", \"01110\", \"10001\", \"10001\", \"10001\", \"01110\"],\n    p: [\"00000\", \"11110\", \"10001\", \"10001\", \"11110\", \"10000\", \"10000\"],\n    q: [\"00000\", \"01111\", \"10001\", \"10001\", \"01111\", \"00001\", \"00001\"],\n    r: [\"00000\", \"00000\", \"10110\", \"11001\", \"10000\", \"10000\", \"10000\"],\n    s: [\"00000\", \"00000\", \"01110\", \"10000\", \"01110\", \"00001\", \"11110\"],\n    t: [\"01000\", \"01000\", \"11100\", \"01000\", \"01000\", \"01001\", \"00110\"],\n    u: [\"00000\", \"00000\", \"10001\", \"10001\", \"10001\", \"10011\", \"01101\"],\n    v: [\"00000\", \"00000\", \"10001\", \"10001\", \"10001\", \"01010\", \"00100\"],\n    w: [\"00000\", \"00000\", \"10001\", \"10001\", \"10101\", \"10101\", \"01010\"],\n    x: [\"00000\", \"00000\", \"10001\", \"01010\", \"00100\", \"01010\", \"10001\"],\n    y: [\"00000\", \"10001\", \"10001\", \"10001\", \"01111\", \"00001\", \"01110\"],\n    z: [\"00000\", \"00000\", \"11111\", \"00010\", \"00100\", \"01000\", \"11111\"],\n    \"{\": [\"00010\", \"00100\", \"00100\", \"01000\", \"00100\", \"00100\", \"00010\"],\n    \"|\": [\"00100\", \"00100\", \"00100\", \"00100\", \"00100\", \"00100\", \"00100\"],\n    \"}\": [\"01000\", \"00100\", \"00100\", \"00010\", \"00100\", \"00100\", \"01000\"],\n    \"~\": [\"00000\", \"00000\", \"01000\", \"10101\", \"00010\", \"00000\", \"00000\"],\n    \"°\": [\"01100\", \"10010\", \"10010\", \"01100\", \"00000\", \"00000\", \"00000\"],\n    \"•\": [\"00000\", \"00000\", \"01110\", \"01110\", \"01110\", \"00000\", \"00000\"],\n    \"…\": [\"00000\", \"00000\", \"00000\", \"00000\", \"00000\", \"00000\", \"10101\"],\n    \"→\": [\"00000\", \"00100\", \"00010\", \"11111\", \"00010\", \"00100\", \"00000\"],\n    \"←\": [\"00000\", \"00100\", \"01000\", \"11111\", \"01000\", \"00100\", \"00000\"],\n    \"✓\": [\"00000\", \"00001\", \"00001\", \"00010\", \"10100\", \"01000\", \"00000\"],\n    \"✗\": [\"00000\", \"10001\", \"01010\", \"00100\", \"01010\", \"10001\", \"00000\"],\n  },\n};\n\nconst FONT_3X5: DotFont = {\n  width: 3,\n  height: 5,\n  glyphs: {\n    \" \": [\"000\", \"000\", \"000\", \"000\", \"000\"],\n    \"0\": [\"111\", \"101\", \"101\", \"101\", \"111\"],\n    \"1\": [\"010\", \"110\", \"010\", \"010\", \"111\"],\n    \"2\": [\"111\", \"001\", \"111\", \"100\", \"111\"],\n    \"3\": [\"111\", \"001\", \"111\", \"001\", \"111\"],\n    \"4\": [\"101\", \"101\", \"111\", \"001\", \"001\"],\n    \"5\": [\"111\", \"100\", \"111\", \"001\", \"111\"],\n    \"6\": [\"111\", \"100\", \"111\", \"101\", \"111\"],\n    \"7\": [\"111\", \"001\", \"001\", \"001\", \"001\"],\n    \"8\": [\"111\", \"101\", \"111\", \"101\", \"111\"],\n    \"9\": [\"111\", \"101\", \"111\", \"001\", \"111\"],\n    A: [\"010\", \"101\", \"111\", \"101\", \"101\"],\n    B: [\"110\", \"101\", \"110\", \"101\", \"110\"],\n    C: [\"011\", \"100\", \"100\", \"100\", \"011\"],\n    D: [\"110\", \"101\", \"101\", \"101\", \"110\"],\n    E: [\"111\", \"100\", \"110\", \"100\", \"111\"],\n    F: [\"111\", \"100\", \"110\", \"100\", \"100\"],\n    G: [\"011\", \"100\", \"101\", \"101\", \"011\"],\n    H: [\"101\", \"101\", \"111\", \"101\", \"101\"],\n    I: [\"111\", \"010\", \"010\", \"010\", \"111\"],\n    J: [\"001\", \"001\", \"001\", \"101\", \"010\"],\n    K: [\"101\", \"101\", \"110\", \"101\", \"101\"],\n    L: [\"100\", \"100\", \"100\", \"100\", \"111\"],\n    M: [\"101\", \"111\", \"111\", \"101\", \"101\"],\n    N: [\"110\", \"101\", \"101\", \"101\", \"101\"],\n    O: [\"010\", \"101\", \"101\", \"101\", \"010\"],\n    P: [\"110\", \"101\", \"110\", \"100\", \"100\"],\n    Q: [\"010\", \"101\", \"101\", \"110\", \"011\"],\n    R: [\"110\", \"101\", \"110\", \"101\", \"101\"],\n    S: [\"011\", \"100\", \"010\", \"001\", \"110\"],\n    T: [\"111\", \"010\", \"010\", \"010\", \"010\"],\n    U: [\"101\", \"101\", \"101\", \"101\", \"111\"],\n    V: [\"101\", \"101\", \"101\", \"101\", \"010\"],\n    W: [\"101\", \"101\", \"111\", \"111\", \"101\"],\n    X: [\"101\", \"101\", \"010\", \"101\", \"101\"],\n    Y: [\"101\", \"101\", \"010\", \"010\", \"010\"],\n    Z: [\"111\", \"001\", \"010\", \"100\", \"111\"],\n    \".\": [\"000\", \"000\", \"000\", \"000\", \"010\"],\n    \",\": [\"000\", \"000\", \"000\", \"010\", \"100\"],\n    \":\": [\"000\", \"010\", \"000\", \"010\", \"000\"],\n    \";\": [\"000\", \"010\", \"000\", \"010\", \"100\"],\n    \"!\": [\"010\", \"010\", \"010\", \"000\", \"010\"],\n    \"?\": [\"110\", \"001\", \"010\", \"000\", \"010\"],\n    \"-\": [\"000\", \"000\", \"111\", \"000\", \"000\"],\n    \"+\": [\"000\", \"010\", \"111\", \"010\", \"000\"],\n    \"=\": [\"000\", \"111\", \"000\", \"111\", \"000\"],\n    \"/\": [\"001\", \"001\", \"010\", \"100\", \"100\"],\n    \"%\": [\"101\", \"001\", \"010\", \"100\", \"101\"],\n    \"(\": [\"010\", \"100\", \"100\", \"100\", \"010\"],\n    \")\": [\"010\", \"001\", \"001\", \"001\", \"010\"],\n    \"'\": [\"010\", \"010\", \"000\", \"000\", \"000\"],\n    '\"': [\"101\", \"101\", \"000\", \"000\", \"000\"],\n    \"#\": [\"101\", \"111\", \"101\", \"111\", \"101\"],\n    \"*\": [\"000\", \"101\", \"010\", \"101\", \"000\"],\n    \"<\": [\"001\", \"010\", \"100\", \"010\", \"001\"],\n    \">\": [\"100\", \"010\", \"001\", \"010\", \"100\"],\n    _: [\"000\", \"000\", \"000\", \"000\", \"111\"],\n  },\n};\n\nexport const DOT_FONTS: Readonly<Record<SceneFont, DotFont>> = {\n  \"5x7\": FONT_5X7,\n  \"3x5\": FONT_3X5,\n};\n\nexport function glyphOf(font: DotFont, char: string): readonly string[] {\n  return (\n    font.glyphs[char] ??\n    font.glyphs[char.toUpperCase()] ??\n    font.glyphs[\"?\"] ??\n    Array.from({ length: font.height }, () => \"0\".repeat(font.width))\n  );\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-font.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-simulate.ts",
      "content": "import { clamp01, hash, mix, smoothStep, wrap } from \"./dot-matrix-field\";\nimport type { DotMatrixLattice } from \"./dot-matrix-lattice\";\n\nexport type SimulationKind = \"life\" | \"sand\" | \"flock\" | \"reaction\";\n\nexport type SimulationParams = Readonly<{\n  seed?: number;\n  density?: number;\n  steps?: number;\n  rate?: number;\n  count?: number;\n  feed?: number;\n  kill?: number;\n}>;\n\ntype Board = {\n  cols: number;\n  rows: number;\n  cells: number;\n  frames: number;\n  total: number;\n  seed: number;\n  light: Float32Array;\n};\n\nfunction random(seed: number, n: number): number {\n  return hash(n * 1.618034 + seed * 1013.7);\n}\n\nfunction whole(value: number | undefined, fallback: number, least: number): number {\n  return Math.max(least, Math.round(Number.isFinite(value) ? (value ?? fallback) : fallback));\n}\n\nfunction ratio(value: number | undefined, fallback: number): number {\n  return Number.isFinite(value) ? (value ?? fallback) : fallback;\n}\n\nfunction lifeStep(boards: Uint8Array, from: number, to: number, cols: number, rows: number): void {\n  for (let y = 0; y < rows; y += 1) {\n    const up = ((y + rows - 1) % rows) * cols;\n    const mid = y * cols;\n    const down = ((y + 1) % rows) * cols;\n    for (let x = 0; x < cols; x += 1) {\n      const left = (x + cols - 1) % cols;\n      const right = (x + 1) % cols;\n      const near =\n        (boards[from + up + left] ?? 0) +\n        (boards[from + up + x] ?? 0) +\n        (boards[from + up + right] ?? 0) +\n        (boards[from + mid + left] ?? 0) +\n        (boards[from + mid + right] ?? 0) +\n        (boards[from + down + left] ?? 0) +\n        (boards[from + down + x] ?? 0) +\n        (boards[from + down + right] ?? 0);\n      const alive = (boards[from + mid + x] ?? 0) === 1;\n      boards[to + mid + x] = near === 3 || (alive && near === 2) ? 1 : 0;\n    }\n  }\n}\n\nfunction sameBoard(boards: Uint8Array, a: number, b: number, cells: number): boolean {\n  for (let c = 0; c < cells; c += 1) {\n    if (boards[a + c] !== boards[b + c]) {\n      return false;\n    }\n  }\n  return true;\n}\n\nfunction lifeLight(board: Board, params: SimulationParams): void {\n  const { cols, rows, cells, frames, total, seed, light } = board;\n  const density = clamp01(ratio(params.density, 0.35));\n  const steps = whole(params.steps, 12, 1);\n  const perGeneration = frames / steps;\n  const generations = Math.ceil(total / perGeneration) + 2;\n  const boards = new Uint8Array(cells * generations);\n  for (let c = 0; c < cells; c += 1) {\n    boards[c] = random(seed, c) < density ? 1 : 0;\n  }\n  const fewest = Math.max(3, Math.round(cells * 0.04));\n  for (let g = 1; g < generations; g += 1) {\n    const to = g * cells;\n    lifeStep(boards, to - cells, to, cols, rows);\n    let alive = 0;\n    for (let c = 0; c < cells; c += 1) {\n      alive += boards[to + c] ?? 0;\n    }\n    const still = sameBoard(boards, to, to - cells, cells);\n    const blinks = g >= 2 && sameBoard(boards, to, to - cells * 2, cells);\n    if (alive < fewest || still || blinks) {\n      for (let c = 0; c < cells; c += 1) {\n        if (random(seed, g * 7919 + c) < density * 0.4) {\n          boards[to + c] = 1;\n        }\n      }\n    }\n  }\n  for (let f = 0; f < total; f += 1) {\n    const at = f / perGeneration;\n    const g = Math.floor(at);\n    const k = smoothStep(0, 1, at - g);\n    const from = g * cells;\n    const out = f * cells;\n    for (let c = 0; c < cells; c += 1) {\n      light[out + c] = mix(boards[from + c] ?? 0, boards[from + cells + c] ?? 0, k);\n    }\n  }\n}\n\nconst SAND_POUR = 0.55;\nconst SAND_DRAIN = 0.68;\nconst SAND_TRAIL = 0.45;\nconst SAND_TICK = 2;\n\nfunction sandSlide(sand: Uint8Array, cols: number, here: number, x: number, side: number): boolean {\n  const to = here + cols + side;\n  if (x + side < 0 || x + side >= cols || sand[to] !== 0) {\n    return false;\n  }\n  sand[here] = 0;\n  sand[to] = 1;\n  return true;\n}\n\nfunction sandStep(sand: Uint8Array, cols: number, rows: number, tick: number): void {\n  const flip = tick % 2 === 1;\n  for (let y = rows - 2; y >= 0; y -= 1) {\n    for (let i = 0; i < cols; i += 1) {\n      const x = flip ? cols - 1 - i : i;\n      const here = y * cols + x;\n      if (sand[here] !== 1) {\n        continue;\n      }\n      const below = here + cols;\n      if (sand[below] === 0) {\n        sand[here] = 0;\n        sand[below] = 1;\n        continue;\n      }\n      const side = (x + y + tick) % 2 === 0 ? 1 : -1;\n      if (!sandSlide(sand, cols, here, x, side)) {\n        sandSlide(sand, cols, here, x, -side);\n      }\n    }\n  }\n}\n\nfunction sandLight(board: Board, params: SimulationParams): void {\n  const { cols, rows, cells, frames, total, seed, light } = board;\n  const rate = Math.max(0, ratio(params.rate, 0.5));\n  const pour = Math.max(1, Math.round(frames * SAND_POUR));\n  const drain = Math.round(frames * SAND_DRAIN);\n  const chance = clamp01((rate * rows * SAND_TICK) / pour);\n  const sand = new Uint8Array(cells);\n  const past = new Uint8Array(cells);\n  const floor = (rows - 1) * cols;\n  for (let f = 0; f < total; f += 1) {\n    const sub = f % SAND_TICK;\n    if (sub === 0) {\n      past.set(sand);\n      const phase = f % frames;\n      if (phase >= drain) {\n        sand.fill(0, floor, cells);\n      }\n      sandStep(sand, cols, rows, f / SAND_TICK);\n      if (phase < pour) {\n        for (let x = 0; x < cols; x += 1) {\n          if (sand[x] === 0 && random(seed, f * cols + x) < chance) {\n            sand[x] = 1;\n          }\n        }\n      }\n    }\n    const k = (sub + 1) / SAND_TICK;\n    const out = f * cells;\n    for (let c = 0; c < cells; c += 1) {\n      const before = f > 0 ? (light[out - cells + c] ?? 0) * SAND_TRAIL : 0;\n      light[out + c] = Math.max(mix(past[c] ?? 0, sand[c] ?? 0, k), before);\n    }\n  }\n}\n\ntype Flock = {\n  count: number;\n  px: Float32Array;\n  py: Float32Array;\n  vx: Float32Array;\n  vy: Float32Array;\n  spanU: number;\n  spanV: number;\n  unit: number;\n};\n\nfunction wrapOffset(delta: number, span: number): number {\n  return delta - span * Math.round(delta / span);\n}\n\nconst BOID = {\n  see: 4,\n  avoid: 1.6,\n  fastest: 0.3,\n  slowest: 0.14,\n  align: 0.06,\n  cohere: 0.01,\n  separate: 0.05,\n  wander: 0.025,\n} as const;\n\nfunction flockStep(flock: Flock, seed: number, tick: number): void {\n  const { count, px, py, vx, vy, spanU, spanV, unit } = flock;\n  const see = BOID.see * unit;\n  const avoid = BOID.avoid * unit;\n  for (let i = 0; i < count; i += 1) {\n    const x = px[i] ?? 0;\n    const y = py[i] ?? 0;\n    let near = 0;\n    let alignX = 0;\n    let alignY = 0;\n    let centerX = 0;\n    let centerY = 0;\n    let awayX = 0;\n    let awayY = 0;\n    for (let j = 0; j < count; j += 1) {\n      if (j === i) {\n        continue;\n      }\n      const dx = wrapOffset((px[j] ?? 0) - x, spanU);\n      const dy = wrapOffset((py[j] ?? 0) - y, spanV);\n      const d = Math.hypot(dx, dy);\n      if (d < see) {\n        near += 1;\n        alignX += vx[j] ?? 0;\n        alignY += vy[j] ?? 0;\n        centerX += dx;\n        centerY += dy;\n      }\n      if (d < avoid && d > 0) {\n        const push = (avoid - d) / (avoid * d);\n        awayX -= dx * push;\n        awayY -= dy * push;\n      }\n    }\n    let ax = awayX * BOID.separate * unit;\n    let ay = awayY * BOID.separate * unit;\n    if (near > 0) {\n      ax += (alignX / near - (vx[i] ?? 0)) * BOID.align + (centerX / near) * BOID.cohere;\n      ay += (alignY / near - (vy[i] ?? 0)) * BOID.align + (centerY / near) * BOID.cohere;\n    }\n    const turn = (random(seed, tick * 97 + i) - 0.5) * Math.PI * 2;\n    ax += Math.cos(turn) * BOID.wander * unit;\n    ay += Math.sin(turn) * BOID.wander * unit;\n    let nx = (vx[i] ?? 0) + ax;\n    let ny = (vy[i] ?? 0) + ay;\n    const speed = Math.hypot(nx, ny) || 1;\n    const fit = Math.min(BOID.fastest * unit, Math.max(BOID.slowest * unit, speed)) / speed;\n    nx *= fit;\n    ny *= fit;\n    vx[i] = nx;\n    vy[i] = ny;\n  }\n  for (let i = 0; i < count; i += 1) {\n    px[i] = wrap((px[i] ?? 0) + (vx[i] ?? 0) + spanU / 2, spanU) - spanU / 2;\n    py[i] = wrap((py[i] ?? 0) + (vy[i] ?? 0) + spanV / 2, spanV) - spanV / 2;\n  }\n}\n\nconst FLOCK_WARM = 60;\nconst BOID_RADIUS = 0.8;\nconst BOID_EDGE = 0.5;\nconst FLOCK_TRAIL = 0.6;\n\nfunction flockLight(board: Board, lattice: DotMatrixLattice, params: SimulationParams): void {\n  const { cols, cells, total, seed, light } = board;\n  const count = whole(params.count, 6, 1);\n  const { unit } = lattice;\n  const flock: Flock = {\n    count,\n    px: new Float32Array(count),\n    py: new Float32Array(count),\n    vx: new Float32Array(count),\n    vy: new Float32Array(count),\n    spanU: lattice.width * 2 + unit,\n    spanV: lattice.height * 2 + unit * lattice.rowStep,\n    unit,\n  };\n  for (let i = 0; i < count; i += 1) {\n    flock.px[i] = (random(seed, i * 4) - 0.5) * flock.spanU;\n    flock.py[i] = (random(seed, i * 4 + 1) - 0.5) * flock.spanV;\n    const angle = random(seed, i * 4 + 2) * Math.PI * 2;\n    flock.vx[i] = Math.cos(angle) * BOID.fastest * unit;\n    flock.vy[i] = Math.sin(angle) * BOID.fastest * unit;\n  }\n  for (let tick = 0; tick < FLOCK_WARM; tick += 1) {\n    flockStep(flock, seed, tick - FLOCK_WARM);\n  }\n  const inner = (BOID_RADIUS - BOID_EDGE) * unit;\n  const outer = (BOID_RADIUS + BOID_EDGE) * unit;\n  for (let f = 0; f < total; f += 1) {\n    flockStep(flock, seed, f);\n    const out = f * cells;\n    for (let dot = 0; dot < lattice.count; dot += 1) {\n      const c = (lattice.ys[dot] ?? 0) * cols + (lattice.xs[dot] ?? 0);\n      const u = lattice.us[dot] ?? 0;\n      const v = lattice.vs[dot] ?? 0;\n      let lit = f > 0 ? (light[out - cells + c] ?? 0) * FLOCK_TRAIL : 0;\n      for (let i = 0; i < count; i += 1) {\n        const dx = wrapOffset(u - (flock.px[i] ?? 0), flock.spanU);\n        const dy = wrapOffset(v - (flock.py[i] ?? 0), flock.spanV);\n        lit = Math.max(lit, 1 - smoothStep(inner, outer, Math.hypot(dx, dy)));\n      }\n      light[out + c] = lit;\n    }\n  }\n}\n\nconst REACTION_SCALE = 3;\nconst REACTION_WARM = 250;\nconst REACTION_DROPS = 3;\nconst ERASER = { radius: 2.2, speed: 0.12, bite: 0.25 } as const;\nconst LIGHT_BINS = 256;\nconst LIGHT_LOW = 0.35;\nconst LIGHT_HIGH = 0.985;\n\ntype Reaction = {\n  cols: number;\n  rows: number;\n  a: Float32Array;\n  b: Float32Array;\n  nextA: Float32Array;\n  nextB: Float32Array;\n  left: Int32Array;\n  right: Int32Array;\n  up: Int32Array;\n  down: Int32Array;\n  feed: number;\n  kill: number;\n};\n\nfunction reactionStep(state: Reaction): void {\n  const { cols, rows, a, b, nextA, nextB, left, right, feed, kill } = state;\n  for (let y = 0; y < rows; y += 1) {\n    const up = state.up[y] ?? 0;\n    const mid = y * cols;\n    const down = state.down[y] ?? 0;\n    for (let x = 0; x < cols; x += 1) {\n      const l = left[x] ?? 0;\n      const r = right[x] ?? 0;\n      const ca = a[mid + x] ?? 0;\n      const cb = b[mid + x] ?? 0;\n      const lapA =\n        ((a[up + x] ?? 0) + (a[down + x] ?? 0) + (a[mid + l] ?? 0) + (a[mid + r] ?? 0)) * 0.2 +\n        ((a[up + l] ?? 0) + (a[up + r] ?? 0) + (a[down + l] ?? 0) + (a[down + r] ?? 0)) * 0.05 -\n        ca;\n      const lapB =\n        ((b[up + x] ?? 0) + (b[down + x] ?? 0) + (b[mid + l] ?? 0) + (b[mid + r] ?? 0)) * 0.2 +\n        ((b[up + l] ?? 0) + (b[up + r] ?? 0) + (b[down + l] ?? 0) + (b[down + r] ?? 0)) * 0.05 -\n        cb;\n      const react = ca * cb * cb;\n      nextA[mid + x] = clamp01(ca + lapA - react + feed * (1 - ca));\n      nextB[mid + x] = clamp01(cb + lapB * 0.5 + react - (kill + feed) * cb);\n    }\n  }\n  state.a = nextA;\n  state.b = nextB;\n  state.nextA = a;\n  state.nextB = b;\n}\n\nfunction reactionDrop(state: Reaction, seed: number, n: number, size: number): void {\n  const x0 = Math.floor(random(seed, n * 2) * state.cols);\n  const y0 = Math.floor(random(seed, n * 2 + 1) * state.rows);\n  for (let y = 0; y < size; y += 1) {\n    for (let x = 0; x < size; x += 1) {\n      const at = ((y0 + y) % state.rows) * state.cols + ((x0 + x) % state.cols);\n      state.a[at] = 0;\n      state.b[at] = 1;\n    }\n  }\n}\n\nfunction reactionErase(state: Reaction, cx: number, cy: number, radius: number): void {\n  const { cols, rows, a, b } = state;\n  const reach = Math.ceil(radius);\n  for (let dy = -reach; dy <= reach; dy += 1) {\n    for (let dx = -reach; dx <= reach; dx += 1) {\n      const x = Math.floor(cx) + dx;\n      const y = Math.floor(cy) + dy;\n      const fall = 1 - smoothStep(radius * 0.5, radius, Math.hypot(x - cx, y - cy));\n      if (fall <= 0) {\n        continue;\n      }\n      const at = wrap(y, rows) * cols + wrap(x, cols);\n      const k = ERASER.bite * fall;\n      b[at] = (b[at] ?? 0) * (1 - k);\n      a[at] = mix(a[at] ?? 0, 1, k);\n    }\n  }\n}\n\nfunction neighbors(size: number, step: number, stride: number): Int32Array {\n  const table = new Int32Array(size);\n  for (let i = 0; i < size; i += 1) {\n    table[i] = ((i + step + size) % size) * stride;\n  }\n  return table;\n}\n\nfunction stretchLight(light: Float32Array, low: number, high: number): void {\n  const span = high - low || 1;\n  const bins = new Uint32Array(LIGHT_BINS);\n  for (let i = 0; i < light.length; i += 1) {\n    const bin = Math.floor((((light[i] ?? 0) - low) / span) * (LIGHT_BINS - 1));\n    bins[bin] = (bins[bin] ?? 0) + 1;\n  }\n  let seen = 0;\n  let from = -1;\n  let to = LIGHT_BINS - 1;\n  for (let bin = 0; bin < LIGHT_BINS; bin += 1) {\n    seen += bins[bin] ?? 0;\n    if (from < 0 && seen >= light.length * LIGHT_LOW) {\n      from = bin;\n    }\n    if (seen >= light.length * LIGHT_HIGH) {\n      to = bin;\n      break;\n    }\n  }\n  const lo = low + (Math.max(from, 0) / (LIGHT_BINS - 1)) * span;\n  const hi = Math.max(low + (to / (LIGHT_BINS - 1)) * span, lo + span * 0.05);\n  for (let i = 0; i < light.length; i += 1) {\n    light[i] = smoothStep(lo, hi, light[i] ?? 0);\n  }\n}\n\nfunction reactionLight(board: Board, params: SimulationParams): void {\n  const { cols, rows, cells, total, seed, light } = board;\n  const steps = whole(params.steps, 8, 1);\n  const width = cols * REACTION_SCALE;\n  const height = rows * REACTION_SCALE;\n  const places = width * height;\n  const state: Reaction = {\n    cols: width,\n    rows: height,\n    a: new Float32Array(places).fill(1),\n    b: new Float32Array(places),\n    nextA: new Float32Array(places),\n    nextB: new Float32Array(places),\n    left: neighbors(width, -1, 1),\n    right: neighbors(width, 1, 1),\n    up: neighbors(height, -1, width),\n    down: neighbors(height, 1, width),\n    feed: ratio(params.feed, 0.037),\n    kill: ratio(params.kill, 0.06),\n  };\n  const drops = REACTION_DROPS;\n  for (let n = 0; n < drops; n += 1) {\n    reactionDrop(state, seed, n, 3);\n  }\n  for (let i = 0; i < REACTION_WARM; i += 1) {\n    reactionStep(state);\n  }\n  const heading = random(seed, drops * 2 + 1) * Math.PI * 2;\n  const speed = ERASER.speed * REACTION_SCALE;\n  const startX = random(seed, drops * 2 + 2) * width;\n  const startY = random(seed, drops * 2 + 3) * height;\n  const share = 1 / (REACTION_SCALE * REACTION_SCALE);\n  let low = 1;\n  let high = 0;\n  let alive = 1;\n  for (let f = 0; f < total; f += 1) {\n    const cx = startX + Math.cos(heading) * speed * f;\n    const cy = startY + Math.sin(heading) * speed * f;\n    if (alive < 0.01) {\n      reactionDrop(state, seed, drops + f, REACTION_SCALE * 2);\n    }\n    reactionErase(state, wrap(cx, width), wrap(cy, height), ERASER.radius * REACTION_SCALE);\n    for (let i = 0; i < steps; i += 1) {\n      reactionStep(state);\n    }\n    alive = 0;\n    const out = f * cells;\n    for (let y = 0; y < rows; y += 1) {\n      for (let x = 0; x < cols; x += 1) {\n        let sum = 0;\n        for (let sy = 0; sy < REACTION_SCALE; sy += 1) {\n          const row = (y * REACTION_SCALE + sy) * width + x * REACTION_SCALE;\n          for (let sx = 0; sx < REACTION_SCALE; sx += 1) {\n            sum += state.b[row + sx] ?? 0;\n          }\n        }\n        const mean = sum * share;\n        light[out + y * cols + x] = mean;\n        alive = Math.max(alive, mean);\n        low = Math.min(low, mean);\n        high = Math.max(high, mean);\n      }\n    }\n  }\n  stretchLight(light, low, high);\n}\n\nconst JOIN_SHARE = 0.25;\n\nexport function simulate(\n  kind: SimulationKind,\n  lattice: DotMatrixLattice,\n  frames: number,\n  params: SimulationParams,\n): Float32Array {\n  const loop = Math.max(1, Math.round(frames));\n  const join = Math.max(1, Math.round(loop * JOIN_SHARE));\n  const cells = lattice.cols * lattice.rows;\n  const board: Board = {\n    cols: lattice.cols,\n    rows: lattice.rows,\n    cells,\n    frames: loop,\n    total: loop + join,\n    seed: ratio(params.seed, 1),\n    light: new Float32Array(cells * (loop + join)),\n  };\n  if (kind === \"life\") {\n    lifeLight(board, params);\n  } else if (kind === \"sand\") {\n    sandLight(board, params);\n  } else if (kind === \"flock\") {\n    flockLight(board, lattice, params);\n  } else {\n    reactionLight(board, params);\n  }\n  const data = new Float32Array(lattice.count * loop);\n  const { light } = board;\n  for (let dot = 0; dot < lattice.count; dot += 1) {\n    const c = (lattice.ys[dot] ?? 0) * lattice.cols + (lattice.xs[dot] ?? 0);\n    const row = dot * loop;\n    for (let f = 0; f < loop; f += 1) {\n      const head = light[f * cells + c] ?? 0;\n      if (f < join) {\n        const tail = light[(loop + f) * cells + c] ?? 0;\n        data[row + f] = clamp01(mix(tail, head, smoothStep(0, 1, (f + 1) / (join + 1))));\n      } else {\n        data[row + f] = clamp01(head);\n      }\n    }\n  }\n  return data;\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-simulate.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-bake-worker.ts",
      "content": "import { programOf } from \"./dot-matrix-compile\";\nimport { latticeOf, type DotMatrixLatticeSpec } from \"./dot-matrix-lattice\";\nimport type { ScenePattern } from \"./dot-matrix-scene\";\nimport { bakeTrack } from \"./dot-matrix-track\";\n\nexport type BakeRequest = Readonly<{\n  id: number;\n  scene: ScenePattern;\n  lattice: DotMatrixLatticeSpec;\n}>;\n\nexport type BakeReply =\n  | Readonly<{\n      id: number;\n      light: Uint8Array;\n      scale: Uint8Array | undefined;\n      angle: Uint8Array | undefined;\n      tint: Uint8Array | undefined;\n    }>\n  | Readonly<{ id: number; problem: string }>;\n\nglobalThis.addEventListener(\"message\", (event: MessageEvent<BakeRequest>) => {\n  void bakeAndReply(event.data);\n});\n\nasync function bakeAndReply({ id, scene, lattice }: BakeRequest): Promise<void> {\n  try {\n    await programOf(scene).ready;\n    const track = bakeTrack(scene, latticeOf(lattice));\n    const reply: BakeReply = {\n      id,\n      light: track.light,\n      scale: track.scale,\n      angle: track.angle,\n      tint: track.tint,\n    };\n    const moved = [track.light, track.scale, track.angle, track.tint].flatMap((data) => {\n      return data === undefined ? [] : [data.buffer];\n    });\n    globalThis.postMessage(reply, { transfer: moved });\n  } catch (cause) {\n    const reply: BakeReply = {\n      id,\n      problem: cause instanceof Error ? cause.message : String(cause),\n    };\n    globalThis.postMessage(reply, { transfer: [] });\n  }\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-bake-worker.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-morph.ts",
      "content": "import { EASE } from \"./dot-matrix-ease\";\nimport { clamp01, hash, mix, smoothStep } from \"./dot-matrix-field\";\nimport type { DotMatrixLattice } from \"./dot-matrix-lattice\";\nimport { angleOf } from \"./dot-matrix-sdf\";\nimport {\n  BAKE_FPS,\n  CHANNEL_REST,\n  valueAt,\n  type DotMatrixChannel,\n  type DotMatrixTrack,\n} from \"./dot-matrix-track\";\n\nexport const DOT_MATRIX_MORPHS = [\"wave\", \"implode\", \"sweep\", \"dissolve\", \"flow\", \"fly\"] as const;\n\nexport type DotMatrixMorph = (typeof DOT_MATRIX_MORPHS)[number];\n\ntype FadeMorph = Exclude<DotMatrixMorph, \"fly\">;\n\ntype MorphStyle = Readonly<{\n  order: (u: number, v: number, lattice: DotMatrixLattice, index: number) => number;\n  flash: number;\n}>;\n\nfunction reachOf(lattice: DotMatrixLattice): number {\n  return Math.hypot(lattice.width, lattice.height) || 1;\n}\n\nconst STYLES: Readonly<Record<FadeMorph, MorphStyle>> = {\n  wave: {\n    order: (u, v, lattice) => {\n      return Math.hypot(u, v) / reachOf(lattice);\n    },\n    flash: 0.45,\n  },\n  implode: {\n    order: (u, v, lattice) => {\n      return 1 - Math.hypot(u, v) / reachOf(lattice);\n    },\n    flash: 0.4,\n  },\n  sweep: {\n    order: (u, _v, lattice) => {\n      return (u + lattice.width) / (2 * lattice.width || 1);\n    },\n    flash: 0.4,\n  },\n  dissolve: {\n    order: (_u, _v, _lattice, index) => {\n      return hash(index + 0.5);\n    },\n    flash: 0.3,\n  },\n  flow: {\n    order: () => {\n      return 0;\n    },\n    flash: 0,\n  },\n};\n\nconst SPREAD = 0.55;\n\nexport type DotMatrixShowing = Readonly<{\n  track: DotMatrixTrack;\n  start: number | undefined;\n  input: number;\n}>;\n\nfunction progressOf(showing: DotMatrixShowing, now: number, speed: number): number {\n  const { track, start } = showing;\n  if (start === undefined) {\n    const at = (now * speed) / track.duration;\n    return at - Math.floor(at);\n  }\n  return clamp01(((now - start) * speed) / track.duration);\n}\n\nfunction mapping(from: DotMatrixLattice, to: DotMatrixLattice): Int32Array {\n  const map = new Int32Array(to.count);\n  if (from.key === to.key) {\n    return map.map((_, index) => {\n      return index;\n    });\n  }\n  const reach = Math.max(from.unit, to.unit) * 0.75;\n  for (let index = 0; index < to.count; index += 1) {\n    const u = to.us[index] ?? 0;\n    const v = to.vs[index] ?? 0;\n    let nearest = -1;\n    let best = reach;\n    for (let other = 0; other < from.count; other += 1) {\n      const d = Math.hypot((from.us[other] ?? 0) - u, (from.vs[other] ?? 0) - v);\n      if (d < best) {\n        best = d;\n        nearest = other;\n      }\n    }\n    map[index] = nearest;\n  }\n  return map;\n}\n\nexport type MorphOptions = Readonly<{\n  now: number;\n  speed: number;\n  kind: DotMatrixMorph;\n  duration: number;\n  input: number;\n}>;\n\nconst LOOK_CHANNELS = [\"scale\", \"angle\", \"tint\"] as const;\n\nfunction morphShell(\n  from: DotMatrixTrack,\n  to: DotMatrixTrack,\n  frames: number,\n  total: number,\n): DotMatrixTrack {\n  const size = to.lattice.count * frames;\n  const extra: Partial<Record<DotMatrixChannel, Uint8Array>> = {};\n  for (const channel of LOOK_CHANNELS) {\n    if (from[channel] !== undefined || to[channel] !== undefined) {\n      extra[channel] = new Uint8Array(size);\n    }\n  }\n  return {\n    lattice: to.lattice,\n    frames,\n    duration: total,\n    once: true,\n    steps: 1,\n    light: new Uint8Array(size),\n    hue: new Uint8Array(size),\n    ...extra,\n  };\n}\n\ntype MorphClock = Readonly<{\n  frames: number;\n  total: number;\n  span: number;\n  old: (frame: number) => number;\n  next: (frame: number) => number;\n  progress: (frame: number) => number;\n}>;\n\nfunction clockOf(from: DotMatrixShowing, to: DotMatrixTrack, options: MorphOptions): MorphClock {\n  const { now, speed, duration } = options;\n  const span = duration * speed;\n  const total = to.once ? Math.max(span, to.duration) : span;\n  const frames = Math.max(2, Math.round((total / 1000) * BAKE_FPS) + 1);\n  const msOf = (frame: number) => (frame / (frames - 1)) * total;\n  return {\n    frames,\n    total,\n    span,\n    old: (frame) => progressOf(from, now + msOf(frame) / speed, speed),\n    next: (frame) =>\n      to.once ? clamp01(msOf(frame) / to.duration) : (now * speed + msOf(frame)) / to.duration,\n    progress: (frame) => clamp01(msOf(frame) / span),\n  };\n}\n\nfunction mixLook(\n  track: DotMatrixTrack,\n  sources: Readonly<{ from: DotMatrixShowing; to: DotMatrixTrack; map: Int32Array }>,\n  at: Readonly<{ frame: number; old: number; next: number; input: number }>,\n  dot: number,\n  k: number,\n): void {\n  for (const channel of LOOK_CHANNELS) {\n    const data = track[channel];\n    if (data !== undefined) {\n      const source = sources.map[dot] ?? -1;\n      const a =\n        source < 0\n          ? CHANNEL_REST[channel]\n          : valueAt(sources.from.track, channel, source, at.old, sources.from.input);\n      const b = valueAt(sources.to, channel, dot, at.next, at.input);\n      data[dot * track.frames + at.frame] = Math.round(clamp01(mix(a, b, k)) * 255);\n    }\n  }\n}\n\nfunction fadeMorph(\n  from: DotMatrixShowing,\n  to: DotMatrixTrack,\n  options: MorphOptions,\n  kind: FadeMorph,\n): DotMatrixTrack {\n  const style = STYLES[kind];\n  const clock = clockOf(from, to, options);\n  const track = morphShell(from.track, to, clock.frames, clock.total);\n  const { lattice } = to;\n  const map = mapping(from.track.lattice, lattice);\n  for (let frame = 0; frame < clock.frames; frame += 1) {\n    const at = { frame, old: clock.old(frame), next: clock.next(frame), input: options.input };\n    const progress = clock.progress(frame);\n    for (let dot = 0; dot < lattice.count; dot += 1) {\n      const order = style.order(lattice.us[dot] ?? 0, lattice.vs[dot] ?? 0, lattice, dot);\n      const k = EASE.inOut(clamp01((progress - order * SPREAD) / (1 - SPREAD)));\n      const source = map[dot] ?? -1;\n      const a = source < 0 ? 0 : valueAt(from.track, \"light\", source, at.old, from.input);\n      const b = valueAt(to, \"light\", dot, at.next, options.input);\n      const front = style.flash * 4 * k * (1 - k);\n      track.light[dot * clock.frames + frame] = Math.round(clamp01(mix(a, b, k) + front) * 255);\n      if (track.hue !== undefined) {\n        track.hue[dot * clock.frames + frame] = Math.round(smoothStep(0.3, 0.7, k) * 255);\n      }\n      mixLook(track, { from, to, map }, at, dot, k);\n    }\n  }\n  return track;\n}\n\ntype Spark = Readonly<{ u: number; v: number; light: number }>;\n\nfunction sparkOrder(a: Spark, b: Spark): number {\n  return angleOf(a.u, a.v) - angleOf(b.u, b.v) || Math.hypot(a.u, a.v) - Math.hypot(b.u, b.v);\n}\n\nfunction sparksOf(lattice: DotMatrixLattice, lightOf: (dot: number) => number): Spark[] {\n  const sparks: Spark[] = [];\n  for (let dot = 0; dot < lattice.count; dot += 1) {\n    const light = lightOf(dot);\n    if (light > 0.12) {\n      const spark = { u: lattice.us[dot] ?? 0, v: lattice.vs[dot] ?? 0, light };\n      let low = 0;\n      let high = sparks.length;\n      while (low < high) {\n        const middle = (low + high) >> 1;\n        const there = sparks[middle];\n        if (there !== undefined && sparkOrder(there, spark) <= 0) {\n          low = middle + 1;\n        } else {\n          high = middle;\n        }\n      }\n      sparks.splice(low, 0, spark);\n    }\n  }\n  return sparks;\n}\n\nfunction flyMorph(\n  from: DotMatrixShowing,\n  to: DotMatrixTrack,\n  options: MorphOptions,\n): DotMatrixTrack {\n  const clock = clockOf(from, to, options);\n  const { lattice } = to;\n  const before = sparksOf(from.track.lattice, (dot) =>\n    valueAt(from.track, \"light\", dot, clock.old(0), from.input),\n  );\n  const after = sparksOf(lattice, (dot) =>\n    valueAt(to, \"light\", dot, clock.next(clock.frames - 1), options.input),\n  );\n  if (before.length === 0 || after.length === 0) {\n    return fadeMorph(from, to, options, \"flow\");\n  }\n  const track = morphShell(from.track, to, clock.frames, clock.total);\n  const map = mapping(from.track.lattice, lattice);\n  const pairs = Math.max(before.length, after.length);\n  const radius = lattice.unit * 0.55;\n  for (let frame = 0; frame < clock.frames; frame += 1) {\n    const k = EASE.inOut(clock.progress(frame));\n    const at = { frame, old: clock.old(frame), next: clock.next(frame), input: options.input };\n    for (let dot = 0; dot < lattice.count; dot += 1) {\n      const u = lattice.us[dot] ?? 0;\n      const v = lattice.vs[dot] ?? 0;\n      let light = 0;\n      for (let pair = 0; pair < pairs; pair += 1) {\n        const a = before[Math.floor((pair * before.length) / pairs)];\n        const b = after[Math.floor((pair * after.length) / pairs)];\n        if (a !== undefined && b !== undefined) {\n          const d =\n            (Math.hypot(u - mix(a.u, b.u, k), v - mix(a.v, b.v, k)) - radius) / lattice.unit;\n          light = Math.max(light, clamp01(0.5 - d) * mix(a.light, b.light, k));\n        }\n      }\n      const settle = smoothStep(0.8, 1, clock.progress(frame));\n      const live = valueAt(to, \"light\", dot, at.next, options.input);\n      track.light[dot * clock.frames + frame] = Math.round(clamp01(mix(light, live, settle)) * 255);\n      if (track.hue !== undefined) {\n        track.hue[dot * clock.frames + frame] = Math.round(smoothStep(0.3, 0.7, k) * 255);\n      }\n      mixLook(track, { from, to, map }, at, dot, k);\n    }\n  }\n  return track;\n}\n\nexport function morphTrack(\n  from: DotMatrixShowing,\n  to: DotMatrixTrack,\n  options: MorphOptions,\n): DotMatrixTrack {\n  return options.kind === \"fly\"\n    ? flyMorph(from, to, options)\n    : fadeMorph(from, to, options, options.kind);\n}\n\nexport function darkTrack(lattice: DotMatrixLattice, duration: number): DotMatrixTrack {\n  return {\n    lattice,\n    frames: 2,\n    duration,\n    once: true,\n    steps: 1,\n    light: new Uint8Array(lattice.count * 2),\n  };\n}\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-morph.ts"
    },
    {
      "path": "src/registry/items/dot-matrix/dot-matrix-messages.ts",
      "content": "export type DotMatrixMessages = Readonly<{\n  loading: string;\n  success: string;\n  failure: string;\n}>;\n\nexport const dotMatrixMessages: DotMatrixMessages = {\n  loading: \"Loading\",\n  success: \"Done\",\n  failure: \"Something went wrong\",\n};\n",
      "type": "registry:ui",
      "target": "@ui/dot-matrix/dot-matrix-messages.ts"
    }
  ],
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "dot-matrix",
  "title": "Dot Matrix",
  "description": "A dot matrix effects engine: 34 patterns as JSON presets, 7 lattices, 9 dot kinds, morphs, text, simulations.",
  "dependencies": [
    "@ui-sdk/core@0.1.0-beta.23",
    "@ui-sdk/react@0.1.0-beta.23"
  ],
  "meta": {
    "added": "2026-11-30"
  },
  "categories": [
    "dot-matrix"
  ],
  "type": "registry:ui"
}
