{
  "name": "tower",
  "title": "Tower",
  "type": "registry:component",
  "description": "A procedural city tower from a seeded shape grammar: podium, setback, shaft and crown, with street, service, podium, tower and crown bands drawn by one shared facade shader (shop bays, lit windows with rooms behind them, trims, posters and leaks), so towers batch. Four eras (concrete, tenement, glass, makeshift) set the massing and dressing. Faces listed in `frontage` get relief and the facade kit: shop names, blade and roof signs, awnings, shutters, AC units, pipes, vending machines, cables across the street and light pooled on the pavement. Lit after dusk at the world's luminance levels. Colliders over the footprint and along each street face.",
  "dependencies": [
    "@react-three/fiber@^9.6.1",
    "@react-three/rapier@^2.2.0",
    "@runek/core@^0.18.0",
    "three@^0.184.0"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "Tower.tsx",
      "content": "import { CuboidCollider, RigidBody } from '@react-three/rapier'\nimport {\n  lazyModule,\n  shareMaterial,\n  useGround,\n  useLight,\n  useNodeRenderer,\n  useWorld,\n  type Vec3,\n} from '@runek/core'\nimport { useLayoutEffect, useMemo } from 'react'\nimport {\n  BufferGeometry,\n  Float32BufferAttribute,\n  ShaderMaterial,\n  UniformsLib,\n  UniformsUtils,\n} from 'three'\nimport { useLadder } from './city/glow'\nimport { KitBuilder } from './city/kit'\nimport { TOWER_FRAG, TOWER_VERT } from './city/towerFacade'\nimport {\n  buildTower,\n  ERAS,\n  onFace,\n  planTower,\n  type TowerEra,\n  type TowerFace,\n  type TowerWindows,\n} from './city/towerGrammar'\nimport { knotLight, mainShop, towerKit } from './city/towerKit'\nimport { applyTowerLight, nightFactor, towerUniforms } from './city/towerLight'\nimport { useKitParts } from './city/useKit'\n\nexport type { TowerEra, TowerFace, TowerWindows } from './city/towerGrammar'\n\n// The facade's node (TSL) material, loaded only under a node renderer.\nconst towerNodes = lazyModule(() => import('./nodes/tower'))\n\nexport interface TowerProps {\n  /** Position of the tower's base centre [x, y, z] in units (1 unit = 1 m, Y-up). */\n  position?: Vec3\n  /** Rotation [x, y, z] in radians. Towers stand upright: only the turn about Y is meant to be used. */\n  rotation?: Vec3\n  /** Seeds the massing, the window pattern, which windows are lit, every prop and sign, and any unset look props. */\n  seed?: number\n  /** Ground footprint along local X, in units. The podium fills it and the collider matches it. */\n  width?: number\n  /** Ground footprint along local Z, in units. */\n  depth?: number\n  /** Height to the roof, in units. Rooftop plant and masts stand above it. */\n  height?: number\n  /** Window layout: `grid` (apartments), `office` (small dense panes), `ribbon` (continuous bands) or `glass` (curtain wall). Seeded by era when unset. */\n  windows?: TowerWindows\n  /** Share of windows lit at night, 0 to 1. Seeded when unset. */\n  lit?: number\n  /** Neon trim along the parapets and crown, and the color of the tower's main sign, lit at the world's `sign` luminance level. `\"none\"` for a plain tower. Seeded when unset. */\n  trim?: string\n  /** Also run the trim colour up the corners. */\n  cornerStrips?: boolean\n  /** Shop bays along the ground floor. */\n  shopfronts?: boolean\n  /** Wall colour. Defaults to the world palette's `wall`. */\n  color?: string\n  /** Which era built it: `concrete` (squat, heavy, stencilled), `tenement` (balconies, sign frames, drum lanterns), `glass` (a thin glass slab with a clock in its crown) or `makeshift` (cages, shacks, cable). Seeded among the first, second and last when unset. */\n  era?: TowerEra\n  /** Podium height in units, for a tower tall and wide enough to have a shaft (at least 34 high and 10 across). Seeded between 15 and 25 when unset. */\n  podium?: number\n  /** The faces that front a street: `+z`, `+x`, `-z`, `-x` in the tower's own frame. Each gets piers, a fascia, signs and the instanced kit props, and the first one listed carries the tower's big sign. Empty by default, so a tower costs one merged mesh until it is told where the street is. */\n  frontage?: TowerFace[]\n  /** The shop name on the main sign. Seeded when unset. */\n  name?: string\n  /** Wall to wall distance across the street in units. Above 0, cables sag across it from the first face in `frontage`. */\n  cableSpan?: number\n  /** Ask the world for a real light in front of the main shop. Pooled, so only the ones that matter to the view are lit. */\n  light?: boolean\n}\n\n/**\n * A procedural city tower: a podium, a setback, a shaft and a crown, emitted by a seeded shape\n * grammar as one mesh. A shader draws every facade band (street, service, podium, tower, crown)\n * from per-vertex data in wall metres, so all towers share one material and the static batcher\n * merges them. Faces listed in `frontage` also get real relief and the facade kit: signs, AC\n * units, pipes, vents, awnings, shutters, vending machines and cables, all drawn by the world's\n * shared instanced meshes. At night every emitter takes its brightness from the world's\n * luminance levels (`sign`, `tube`, `screen`). Dark by day. One cuboid collider over the ground footprint, plus one along each street face\n * at the pier line and one per vending machine, so nothing a walker can reach stands outside a\n * collider. Relief above the piers (fascia, awnings, balconies, cornices) has none.\n */\nexport function Tower({\n  position = [0, 0, 0],\n  rotation = [0, 0, 0],\n  seed = 1,\n  width = 16,\n  depth = 16,\n  height = 60,\n  windows,\n  lit,\n  trim,\n  cornerStrips,\n  shopfronts = true,\n  color,\n  era,\n  podium,\n  frontage = NO_FRONTAGE,\n  name,\n  cableSpan = 0,\n  light = false,\n}: TowerProps) {\n  const { unit, palette, time } = useWorld()\n  const w = width * unit\n  const d = depth * unit\n  const h = height * unit\n  const fronts = frontage.join(',')\n\n  const plan = useMemo(\n    () =>\n      planTower({\n        seed,\n        width: w,\n        depth: d,\n        height: h,\n        windows,\n        lit,\n        trim,\n        cornerStrips,\n        shopfronts,\n        era,\n        podium: podium === undefined ? undefined : podium * unit,\n        frontage: fronts ? (fronts.split(',') as TowerFace[]) : [],\n      }),\n    [seed, w, h, d, windows, lit, trim, cornerStrips, shopfronts, era, podium, unit, fronts],\n  )\n  const wallHex = color ?? palette.wall\n  const geometry = useMemo(() => {\n    const mesh = buildTower(plan, wallHex)\n    const g = new BufferGeometry()\n    g.setIndex(mesh.index)\n    g.setAttribute('position', new Float32BufferAttribute(mesh.position, 3))\n    g.setAttribute('normal', new Float32BufferAttribute(mesh.normal, 3))\n    g.setAttribute('aUv', new Float32BufferAttribute(mesh.aUv, 2))\n    g.setAttribute('aRect', new Float32BufferAttribute(mesh.aRect, 4))\n    g.setAttribute('aCell', new Float32BufferAttribute(mesh.aCell, 4))\n    g.setAttribute('aWall', new Float32BufferAttribute(mesh.aWall, 3))\n    g.setAttribute('aTrim', new Float32BufferAttribute(mesh.aTrim, 3))\n    g.setAttribute('aLook', new Float32BufferAttribute(mesh.aLook, 4))\n    g.computeBoundingSphere()\n    g.computeBoundingBox()\n    return g\n  }, [plan, wallHex])\n  useLayoutEffect(() => () => geometry.dispose(), [geometry])\n\n  // WebGPURenderer (either backend) only draws node materials: use the TSL port there.\n  const nodes = useNodeRenderer() ? towerNodes() : null\n  const night = Math.round(nightFactor(time.hours) * 10) / 10\n  const material = nodes ? nodes.towerNodeMaterial(night) : towerMaterial(night)\n  const ladder = useLadder()\n  useLayoutEffect(() => applyTowerLight(ladder), [ladder])\n\n  // A glass tower's crown shows the world's time, to the last ten minutes.\n  const clock = plan.era === 2 ? clockText(time.hours) : ''\n  const span = cableSpan * unit\n  // Where the street stands in front of each face: a pavement is a step up from the road, and\n  // the light a shop leaves on the ground has to lie on top of it.\n  const groundAt = useGround()\n  const [px, py, pz] = position\n  const turn = rotation[1]\n  const street = useMemo(() => {\n    const cos = Math.cos(turn)\n    const sin = Math.sin(turn)\n    return [0, 1, 2, 3]\n      .map((face) => {\n        const [x, z] = onFace(face, 0, 0, w, d, (face % 2 === 0 ? w : d) / 2, 1.5 * unit)\n        const rise = groundAt(px + x * cos + z * sin, pz - x * sin + z * cos) - py\n        // A floor a storey up is a roof over the street, not the street.\n        return rise > 0 && rise < 0.6 * unit ? Math.round(rise * 1000) / 1000 : 0\n      })\n      .join(',')\n  }, [groundAt, px, py, pz, turn, w, d, unit])\n  const parts = useMemo(() => {\n    const k = new KitBuilder()\n    towerKit(k, plan, { name, cableSpan: span, clock, street: street.split(',').map(Number) })\n    return k\n  }, [plan, name, span, clock, street])\n  const kit = useKitParts(parts, [position, rotation])\n  // The kit's solids (the pier line of each street face, vending machines) come out of the same\n  // seeded run as its instances. The clock redraws the kit every ten minutes: keep the colliders.\n  const solidKey = JSON.stringify(parts.solids)\n  const solids = useMemo(() => parts.solids, [solidKey])\n\n  const lightAt = useMemo(() => knotLight(plan), [plan])\n  const lamp = plan.trim !== 'none' ? plan.trim : '#ffa64d'\n  const emitter = useLight(\n    { color: lamp, intensity: 3, distance: 18 * unit, decay: 1.6 },\n    light && lightAt !== null,\n  )\n\n  return (\n    <RigidBody type=\"fixed\" colliders={false} position={position} rotation={rotation}>\n      <mesh geometry={geometry} material={material} receiveShadow />\n      <group ref={kit} />\n      {lightAt && <object3D ref={emitter.ref} position={lightAt} />}\n      <CuboidCollider args={[w / 2, h / 2, d / 2]} position={[0, h / 2, 0]} />\n      {solids.map((s, i) => (\n        <CuboidCollider key={i} args={s.half} position={s.position} rotation={[0, s.rotY, 0]} />\n      ))}\n    </RigidBody>\n  )\n}\n\nTower.groundSitting = true\n\nconst NO_FRONTAGE: TowerFace[] = []\n\n/** What a tower is known by on the street. */\nexport interface TowerShop {\n  /** The name on its main sign. */\n  name: string\n  /** The era that built it, given or seeded. */\n  era: TowerEra\n  /** Where that shop's front stands, at the ground: in the tower's own frame, in units. */\n  at: Vec3\n}\n\n/**\n * The shop a tower is known by, worked out from its props alone, for anything that has to say\n * what a tower is without drawing it. The props mean what they mean to `Tower`, defaults and\n * all. `out` is how far off the wall the point stands, in units. Null for a tower with no shop\n * to name: one with no `frontage`, or none with a named shop in it.\n */\nexport function towerShop(\n  {\n    seed = 1,\n    width = 16,\n    depth = 16,\n    height = 60,\n    windows,\n    lit,\n    trim,\n    cornerStrips,\n    shopfronts = true,\n    era,\n    podium,\n    frontage = NO_FRONTAGE,\n    name,\n  }: TowerProps,\n  unit = 1,\n  out = 0,\n): TowerShop | null {\n  const plan = planTower({\n    seed,\n    width: width * unit,\n    depth: depth * unit,\n    height: height * unit,\n    windows,\n    lit,\n    trim,\n    cornerStrips,\n    shopfronts,\n    era,\n    podium: podium === undefined ? undefined : podium * unit,\n    frontage,\n  })\n  const shop = mainShop(plan, name, out * unit)\n  return (\n    shop && { name: shop.name, era: ERAS[plan.era], at: [shop.at[0] / unit, 0, shop.at[2] / unit] }\n  )\n}\n\nfunction clockText(hours: number) {\n  const t = ((hours % 24) + 24) % 24\n  const hh = Math.floor(t)\n  const mm = Math.floor(((t - hh) * 60) / 10) * 10\n  return `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}`\n}\n\nconst materials = new Map<number, ShaderMaterial>()\n\n/** One shared material per night level. Per-tower looks ride in vertex attributes. */\nfunction towerMaterial(night: number) {\n  const key = Math.round(night * 10) / 10\n  let m = materials.get(key)\n  if (!m) {\n    m = new ShaderMaterial({\n      uniforms: {\n        ...UniformsUtils.merge([UniformsLib.fog, { uNight: { value: key } }]),\n        ...towerUniforms,\n      },\n      vertexShader: TOWER_VERT,\n      fragmentShader: TOWER_FRAG,\n      fog: true,\n    })\n    // One material for every tower that draws at this night level: the batcher may merge them.\n    m.name = `runek:tower:${key}`\n    materials.set(key, shareMaterial(m))\n  }\n  return m\n}\n",
      "type": "registry:component"
    },
    {
      "path": "city/kit.ts",
      "content": "// The facade kit's shared draw: every AC unit, pipe, cable, vent, awning, shutter, sign and\n// vending machine in a world is an instance in one of three InstancedMeshes, so a street full of\n// props costs three draws however many towers it has. A fourth holds the light those signs leave\n// on the ground.\n//\n// `near` holds the parts worth reflecting in the wet street (signs, tubes, awnings, shutters).\n// `small` holds the rest and is left out of the world's mirrors (`skipMirrors`).\n// `glyph` holds sign letters, cut from an atlas drawn in code at load from the world's fonts.\n// `splat` holds soft additive pools on the street in front of lit signs and door lamps. They are\n// not real lights: a shop's glow reads on the pavement without spending one of the world's few.\n//\n// Components describe their parts in local space with a KitBuilder (a pure function of props and\n// seed) and hand them to `useKit`, which registers them in world space with the scene's Kit.\n\nimport { skipMirrors } from '@runek/core'\nimport {\n  AdditiveBlending,\n  BoxGeometry,\n  Color,\n  DataTexture,\n  InstancedBufferAttribute,\n  InstancedMesh,\n  LinearFilter,\n  LinearMipmapLinearFilter,\n  type Material,\n  Matrix4,\n  PlaneGeometry,\n  RGBAFormat,\n  type Scene,\n  ShaderMaterial,\n  UniformsLib,\n  UniformsUtils,\n  Vector3,\n} from 'three'\nimport { emissiveColor } from './glow'\nimport { FOG_FADE } from './haze'\nimport { towerUniforms } from './towerLight'\n\n/** Floats per box or glyph instance: a 4x4 matrix, then two vec4s. */\nexport const KIT_STRIDE = 24\n/** How a part is lit: matte under street light, or an emitter on a ladder rung. */\nexport const GLOW = { matte: 0, sign: 1, tube: 2, glass: 3 } as const\n/** Surface detail drawn by the box shader from the face's size in metres. */\nexport const DETAIL = {\n  none: 0,\n  slats: 1,\n  fan: 2,\n  vending: 3,\n  stripes: 4,\n  cage: 5,\n  panel: 6,\n} as const\n\nconst GLYPHS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-.:'&/!?#\"\nconst ADVANCE: Record<string, number> = {\n  I: 0.42,\n  '1': 0.55,\n  '.': 0.34,\n  ':': 0.34,\n  \"'\": 0.3,\n  '!': 0.4,\n  ' ': 0.45,\n  M: 0.95,\n  W: 1.0,\n  '-': 0.6,\n  '+': 0.7,\n}\n/** Advance of one glyph, in letter heights. */\nexport const glyphAdvance = (ch: string) => ADVANCE[ch] ?? 0.8\n/** A glyph's quad side, in letter heights (the cap height fills half a cell). */\nconst GLYPH_QUAD = 2\n\nconst m4 = new Matrix4()\nconst m4b = new Matrix4()\nconst v3 = new Vector3()\n\n/** A box that stops a walker, in the component's local space. Upright, turned about Y only. */\nexport interface KitSolid {\n  /** Centre [x, y, z]. */\n  position: [number, number, number]\n  /** Half extents along the box's own X, Y and Z. */\n  half: [number, number, number]\n  /** Turn about Y, in radians. */\n  rotY: number\n}\n\n/** Collects a component's kit parts in its local space. */\nexport class KitBuilder {\n  near: number[] = []\n  small: number[] = []\n  glyph: number[] = []\n  splat: number[] = []\n  /** What a walker should bump into. The kit meshes do not read it: the component that owns the builder makes the colliders. */\n  solids: KitSolid[] = []\n  private frame = new Matrix4()\n  private stack: Matrix4[] = []\n\n  /** Enter a local frame at (x, y, z) turned `rotY` about Y. Parts added until `pop` sit in it. */\n  push(x: number, y: number, z: number, rotY = 0) {\n    this.stack.push(this.frame.clone())\n    this.frame.multiply(m4.makeRotationY(rotY).setPosition(x, y, z))\n    return this\n  }\n  pop() {\n    this.frame.copy(this.stack.pop() ?? new Matrix4())\n    return this\n  }\n\n  /**\n   * Mark a box centred at (x, y, z) of size (sx, sy, sz) in the current frame as solid. It draws\n   * nothing. Parts record their own (a vending machine's case), so a component that places them\n   * gets colliders that follow the same seeded layout as the instances.\n   */\n  solid(x: number, y: number, z: number, sx: number, sy: number, sz: number) {\n    const e = this.frame.elements\n    v3.set(x, y, z).applyMatrix4(this.frame)\n    this.solids.push({\n      position: [v3.x, v3.y, v3.z],\n      half: [sx / 2, sy / 2, sz / 2],\n      rotY: Math.atan2(e[8], e[0]),\n    })\n    return this\n  }\n\n  private write(\n    out: number[],\n    local: Matrix4,\n    color: string,\n    glow: number,\n    a: number,\n    b: number,\n    c: number,\n    d: number,\n  ) {\n    m4b.multiplyMatrices(this.frame, local)\n    const col = glow === GLOW.matte ? new Color(color) : emissiveColor(color, 1)\n    out.push(...m4b.elements, col.r, col.g, col.b, glow, a, b, c, d)\n  }\n\n  /**\n   * A box centred at (x, y, z) of size (sx, sy, sz). `glow` picks matte or a ladder rung, `t` the\n   * place along that rung (0 to 1), `detail` a surface pattern. `shear` leans the box: its top\n   * moves that far along local Z per metre of height (an awning's slope). `rise` lifts its far\n   * end: that many metres of height per metre of local Z (a cable's slope).\n   */\n  box(\n    small: boolean,\n    x: number,\n    y: number,\n    z: number,\n    sx: number,\n    sy: number,\n    sz: number,\n    color: string,\n    {\n      glow = GLOW.matte as number,\n      t = 0.5,\n      detail = DETAIL.none as number,\n      seed = 0,\n      rotY = 0,\n      shear = 0,\n      rise = 0,\n    } = {},\n  ) {\n    m4.makeRotationY(rotY).setPosition(x, y, z)\n    const s = new Matrix4().makeScale(sx, sy, sz)\n    if (shear) s.elements[6] = shear * sy // local Z gains shear per unit of local Y\n    if (rise) s.elements[9] = rise * sz // local Y gains rise per unit of local Z\n    m4.multiply(s)\n    this.write(small ? this.small : this.near, m4, color, glow, t, detail, seed, 0)\n    return this\n  }\n\n  /**\n   * Light left on the ground: a soft half disc lying flat at height y, its straight edge centred\n   * on (x, z) and running along local X for `sx`, reaching `sz` out along local +Z (away from\n   * the wall the light comes from). `t` is its place on the street-under-sign rung.\n   */\n  lightSplat(\n    x: number,\n    y: number,\n    z: number,\n    sx: number,\n    sz: number,\n    color: string,\n    { t = 0.5 } = {},\n  ) {\n    // A unit plane laid flat: its top edge (uv.y = 1) ends up on the -Z side, at the wall.\n    m4.makeRotationX(-Math.PI / 2)\n      .scale(v3.set(sx, sz, 1))\n      .setPosition(x, y, z + sz / 2)\n    this.write(this.splat, m4, color, GLOW.sign, t, 0, 0, 0)\n    return this\n  }\n\n  /** Width of `text` set at letter height `h`. */\n  static textWidth(text: string, h: number, tracking = 0.06) {\n    let w = 0\n    for (const ch of text) w += (glyphAdvance(ch) + tracking) * h\n    return w - tracking * h\n  }\n\n  /**\n   * A line of text centred on (x, y, z), facing local +Z after `rotY`, letters `h` tall.\n   * `outline` draws bent-tube letters, `body` uses the world's body font (stencil codes).\n   * `vertical` stacks the letters downward from y.\n   */\n  text(\n    text: string,\n    x: number,\n    y: number,\n    z: number,\n    h: number,\n    color: string,\n    {\n      glow = GLOW.sign as number,\n      t = 0.5,\n      rotY = 0,\n      outline = false,\n      body = false,\n      vertical = false,\n      tracking = 0.06,\n    } = {},\n  ) {\n    const q = h * GLYPH_QUAD\n    const channel = body ? 2 : outline ? 1 : 0\n    const width = vertical ? 0 : KitBuilder.textWidth(text, h, tracking)\n    let cursor = -width / 2\n    let row = 0\n    for (const ch of text.toUpperCase()) {\n      const adv = glyphAdvance(ch) * h\n      const index = GLYPHS.indexOf(ch)\n      if (index >= 0) {\n        const lx = vertical ? 0 : cursor + adv / 2\n        const ly = vertical ? -row * h * 1.28 : 0\n        m4.makeRotationY(rotY)\n        m4.multiply(new Matrix4().makeTranslation(lx, ly, 0)).multiply(\n          new Matrix4().makeScale(q, q, 1),\n        )\n        m4.elements[12] += x\n        m4.elements[13] += y\n        m4.elements[14] += z\n        this.write(this.glyph, m4, color, glow, t, index, channel, 0)\n      }\n      cursor += adv + tracking * h\n      if (ch !== ' ' || vertical) row++\n    }\n    return this\n  }\n}\n\n// ---------------------------------------------------------------------------------------------\n// Glyph atlas\n\nconst ATLAS = 1024\nconst CELL = ATLAS / 8\nconst atlasData = new Uint8Array(ATLAS * ATLAS * 4)\nlet atlasTexture: DataTexture | null = null\nconst fontsAsked = new Set<string>()\n\nfunction drawAtlas(display: string, body: string) {\n  const canvas = document.createElement('canvas')\n  canvas.width = canvas.height = ATLAS\n  const ctx = canvas.getContext('2d', { willReadFrequently: true })\n  if (!ctx) return\n  const pass = (family: string, weight: number, stroke: boolean, channel: number) => {\n    ctx.clearRect(0, 0, ATLAS, ATLAS)\n    ctx.fillStyle = ctx.strokeStyle = 'white'\n    ctx.textAlign = 'center'\n    ctx.textBaseline = 'alphabetic'\n    ctx.lineJoin = ctx.lineCap = 'round'\n    // Size the font so a capital is exactly half a cell tall, whatever the face.\n    ctx.font = `${weight} 100px ${family}`\n    const cap = ctx.measureText('H').actualBoundingBoxAscent || 70\n    const px = (100 * CELL * 0.5) / cap\n    ctx.font = `${weight} ${px}px ${family}`\n    ctx.lineWidth = CELL * 0.05\n    for (let i = 0; i < GLYPHS.length; i++) {\n      const cx = (i % 8) * CELL + CELL / 2\n      const cy = Math.floor(i / 8) * CELL + CELL * 0.75\n      if (stroke) ctx.strokeText(GLYPHS[i], cx, cy)\n      else ctx.fillText(GLYPHS[i], cx, cy)\n    }\n    const img = ctx.getImageData(0, 0, ATLAS, ATLAS).data\n    for (let p = 0; p < ATLAS * ATLAS; p++) atlasData[p * 4 + channel] = img[p * 4 + 3]\n  }\n  pass(display, 600, false, 0)\n  pass(display, 600, true, 1)\n  pass(body, 500, false, 2)\n  for (let p = 0; p < ATLAS * ATLAS; p++) atlasData[p * 4 + 3] = 255\n  if (atlasTexture) atlasTexture.needsUpdate = true\n}\n\n/** The sign glyph atlas: R display fill, G display outline, B body fill. Redrawn when the world's fonts arrive. */\nexport function glyphAtlas(fonts?: { display?: string; body?: string }) {\n  const families = { display: 'sans-serif', body: 'monospace' }\n  if (!atlasTexture) {\n    atlasTexture = new DataTexture(atlasData, ATLAS, ATLAS, RGBAFormat)\n    atlasTexture.magFilter = LinearFilter\n    atlasTexture.minFilter = LinearMipmapLinearFilter\n    atlasTexture.generateMipmaps = true\n    if (typeof document !== 'undefined') drawAtlas(families.display, families.body)\n    atlasTexture.needsUpdate = true\n  }\n  if (typeof document === 'undefined' || typeof FontFace === 'undefined') return atlasTexture\n  const key = `${fonts?.display}|${fonts?.body}`\n  if (fonts && !fontsAsked.has(key)) {\n    fontsAsked.add(key)\n    const load = (name: string, url?: string) =>\n      url\n        ? new FontFace(name, `url(${url})`).load().then(\n            (f) => {\n              ;(document.fonts as unknown as { add(face: FontFace): void }).add(f)\n              return `\"${name}\"`\n            },\n            () => null,\n          )\n        : Promise.resolve(null)\n    void Promise.all([\n      load('runek-kit-display', fonts.display),\n      load('runek-kit-body', fonts.body),\n    ]).then(([d, b]) => {\n      if (d || b)\n        drawAtlas(d ? `${d}, sans-serif` : families.display, b ? `${b}, monospace` : families.body)\n    })\n  }\n  return atlasTexture\n}\n\n// ---------------------------------------------------------------------------------------------\n// Materials (WebGL). The WebGPU twins live in kitNode.ts.\n\n/** Uniforms the kit shares with every tower, plus its own night level. */\nexport const kitUniforms = {\n  ...towerUniforms,\n  uNight: { value: 1 },\n  tAtlas: { value: null as DataTexture | null },\n}\n\nconst PARS = /* glsl */ `\nuniform float uNight;\nuniform float uWallGain;\nuniform vec3 uGlow;\nuniform vec2 uSign;\nuniform vec2 uTube;\nuniform vec2 uShop;\nfloat rung(vec2 r, float t) { return r.x * pow(r.y / r.x, t); }\nfloat kitRung(float glow, float t) { return glow < 1.5 ? rung(uSign, t) : (glow < 2.5 ? rung(uTube, t) : rung(uShop, t)); }\n`\n\nconst BOX_VERT = /* glsl */ `\nattribute vec4 aColor;\nattribute vec4 aKit;\nvarying vec4 vColor;\nvarying vec4 vKit;\nvarying vec2 vUvM;\nvarying vec2 vFace;\nvarying vec3 vLN;\nvarying vec3 vWN;\nvarying float vWorldY;\n#include <fog_pars_vertex>\nvoid main() {\n  vColor = aColor; vKit = aKit; vLN = normal;\n  mat4 im = instanceMatrix;\n  vec3 s = vec3(length(im[0].xyz), length(im[1].xyz), length(im[2].xyz));\n  vec3 an = abs(normal);\n  vFace = an.x > 0.5 ? s.zy : (an.y > 0.5 ? s.xz : s.xy);\n  vUvM = uv * vFace;\n  vWN = normalize(mat3(modelMatrix) * mat3(im) * normal);\n  vec4 wp = modelMatrix * im * vec4(position, 1.0);\n  vWorldY = wp.y;\n  vec4 mvPosition = viewMatrix * wp;\n  gl_Position = projectionMatrix * mvPosition;\n  #include <fog_vertex>\n}`\n\nconst BOX_FRAG = /* glsl */ `\n${PARS}\nvarying vec4 vColor;\nvarying vec4 vKit;\nvarying vec2 vUvM;\nvarying vec2 vFace;\nvarying vec3 vLN;\nvarying vec3 vWN;\nvarying float vWorldY;\n#include <fog_pars_fragment>\nfloat pulseInt(float x, float a, float b) { return floor(x) * (b - a) + clamp(fract(x), a, b) - a; }\n// Box-filtered periodic pulse: coverage of [a, b] in each unit cell over a footprint w.\nfloat pulse(float x, float a, float b, float w) {\n  w = max(w, 1e-4);\n  return (pulseInt(x + 0.5 * w, a, b) - pulseInt(x - 0.5 * w, a, b)) / w;\n}\nfloat band(float x, float a, float b, float w) {\n  return clamp((min(x + 0.5 * w, b) - max(x - 0.5 * w, a)) / max(w, 1e-4), 0.0, 1.0);\n}\nvoid main() {\n  float glow = vColor.a, t = vKit.x, detail = vKit.y, sd = vKit.z;\n  vec2 m = vUvM, fw = fwidth(vUvM);\n  float side = 1.0 - step(0.5, abs(vLN.y));\n  float front = step(0.5, vLN.z);\n  float tone = 1.0;\n  if (detail > 0.5 && detail < 1.5) {\n    tone = mix(0.55, 1.0, pulse(m.y / 0.11, 0.0, 0.7, fw.y / 0.11)) * side + (1.0 - side);\n  } else if (detail < 2.5 && detail > 1.5) {\n    // An outdoor unit: a fan ring behind fins on the front, a seam round the case.\n    vec2 c = (m - vec2(vFace.x * 0.38, vFace.y * 0.5)) / (vFace.y * 0.4);\n    float disc = 1.0 - smoothstep(0.92, 1.0, length(c));\n    float fins = pulse(m.y / 0.045, 0.0, 0.5, fw.y / 0.045);\n    tone = mix(1.0, mix(0.25, 0.6, fins) * (0.6 + 0.4 * smoothstep(0.15, 0.3, length(c))), disc * front);\n    tone *= mix(1.0, 0.7, (1.0 - front) * side * band(m.y, vFace.y - 0.05, vFace.y, fw.y));\n  } else if (detail < 3.5 && detail > 2.5) {\n    // A vending window: rows of lit goods.\n    tone = mix(0.2, 1.0, pulse(m.y / 0.26, 0.12, 1.0, fw.y / 0.26) * pulse(m.x / 0.13, 0.2, 1.0, fw.x / 0.13));\n  } else if (detail < 4.5 && detail > 3.5) {\n    tone = mix(0.55, 1.0, pulse(m.x / 0.7, 0.0, 0.5, fw.x / 0.7));\n  } else if (detail < 5.5 && detail > 4.5) {\n    float wire = 1.0 - pulse(m.x / 0.09, 0.0, 0.8, fw.x / 0.09) * pulse(m.y / 0.09, 0.0, 0.8, fw.y / 0.09);\n    tone = mix(0.35, 1.3, wire);\n  } else if (detail > 5.5) {\n    float rim = 1.0 - band(m.x, 0.05, vFace.x - 0.05, fw.x) * band(m.y, 0.05, vFace.y - 0.05, fw.y);\n    tone = mix(1.0, 2.2, rim * (1.0 - step(0.5, abs(vLN.x))));\n  }\n  vec3 col;\n  if (glow < 0.5) {\n    // Matte: the wall's own unlit model, with a face shade so a box reads as a solid.\n    float shade = 0.72 + 0.28 * vWN.y + 0.1 * vWN.x;\n    col = vColor.rgb * mix(0.35, uWallGain, uNight) * shade * tone;\n    col += uGlow * exp(-max(vWorldY, 0.0) / 6.0) * uNight * (0.55 + 0.45 * shade) * min(tone, 1.0);\n  } else {\n    col = vColor.rgb * kitRung(glow, t) * tone * mix(0.12, 1.0, uNight);\n  }\n  gl_FragColor = vec4(col, 1.0);\n  #include <tonemapping_fragment>\n  #include <colorspace_fragment>\n  #include <fog_fragment>\n}`\n\nconst GLYPH_VERT = /* glsl */ `\nattribute vec4 aColor;\nattribute vec4 aKit;\nvarying vec4 vColor;\nvarying vec3 vKit;\nvarying vec2 vUv;\n#include <fog_pars_vertex>\nvoid main() {\n  vColor = aColor; vKit = aKit.xyz;\n  vec2 cell = vec2(mod(aKit.y, 8.0), floor(aKit.y / 8.0));\n  vUv = vec2(cell.x + uv.x, cell.y + 1.0 - uv.y) / 8.0;\n  vec4 mvPosition = viewMatrix * modelMatrix * instanceMatrix * vec4(position, 1.0);\n  gl_Position = projectionMatrix * mvPosition;\n  #include <fog_vertex>\n}`\n\nconst GLYPH_FRAG = /* glsl */ `\n${PARS}\nuniform sampler2D tAtlas;\nvarying vec4 vColor;\nvarying vec3 vKit;\nvarying vec2 vUv;\n#include <fog_pars_fragment>\nvoid main() {\n  vec3 tx = texture2D(tAtlas, vUv).rgb;\n  float a = vKit.z < 0.5 ? tx.r : (vKit.z < 1.5 ? tx.g : tx.b);\n  // Sharpen the edge when the atlas is magnified. Leave the mip's own coverage when it is not.\n  float texels = length(fwidth(vUv)) * ${ATLAS}.0;\n  float w = clamp(fwidth(a), 0.03, 0.5);\n  a = mix(smoothstep(0.5 - w, 0.5 + w, a), a, clamp(texels - 0.6, 0.0, 1.0));\n  if (a < 0.01) discard;\n  // Glow 0 is paint on a wall (stencil codes). Anything else is a lit letter on its rung.\n  vec3 col = vColor.a < 0.5 ? vColor.rgb * mix(0.35, uWallGain, uNight) + uGlow * uNight * 0.5 : vColor.rgb * kitRung(vColor.a, vKit.x) * mix(0.12, 1.0, uNight);\n  gl_FragColor = vec4(col, a);\n  #include <tonemapping_fragment>\n  #include <colorspace_fragment>\n  #include <fog_fragment>\n}`\n\nconst SPLAT_VERT = /* glsl */ `\nattribute vec4 aColor;\nattribute vec4 aKit;\nuniform float uNight;\nuniform vec2 uStreet;\nvarying vec3 vColor;\nvarying vec2 vUv;\nvarying vec3 vWorld;\nvoid main() {\n  vColor = aColor.rgb * uStreet.x * pow(uStreet.y / uStreet.x, aKit.x) * uNight;\n  vUv = uv;\n  vec4 world = modelMatrix * instanceMatrix * vec4(position, 1.0);\n  vWorld = world.xyz;\n  gl_Position = projectionMatrix * viewMatrix * world;\n}`\n\n// Brightest at the foot of the wall, gone at the far edge. Added to the street, so it fades\n// with the fog range instead of mixing toward the fog color.\nconst SPLAT_FRAG = /* glsl */ `\nvarying vec3 vColor;\nvarying vec2 vUv;\nvarying vec3 vWorld;\n${FOG_FADE}\nvoid main() {\n  float d = length(vec2((vUv.x - 0.5) * 2.0, 1.0 - vUv.y));\n  float a = 1.0 - smoothstep(0.0, 1.0, d);\n  gl_FragColor = vec4(vColor * a * a * hazeFog(vWorld), 1.0);\n}`\n\nfunction glMaterials(): KitMaterialSet {\n  const fog = () => UniformsUtils.merge([UniformsLib.fog])\n  const box = new ShaderMaterial({\n    uniforms: { ...fog(), ...kitUniforms },\n    vertexShader: BOX_VERT,\n    fragmentShader: BOX_FRAG,\n    fog: true,\n  })\n  const glyph = new ShaderMaterial({\n    uniforms: { ...fog(), ...kitUniforms },\n    vertexShader: GLYPH_VERT,\n    fragmentShader: GLYPH_FRAG,\n    fog: true,\n    transparent: true,\n    depthWrite: false,\n  })\n  const splat = new ShaderMaterial({\n    uniforms: { ...fog(), ...kitUniforms },\n    vertexShader: SPLAT_VERT,\n    fragmentShader: SPLAT_FRAG,\n    fog: true,\n    transparent: true,\n    blending: AdditiveBlending,\n    depthWrite: false,\n    // It lies a few centimetres over the street, which is not enough far away.\n    polygonOffset: true,\n    polygonOffsetFactor: -2,\n    polygonOffsetUnits: -4,\n  })\n  return { box, glyph, splat }\n}\n\n// ---------------------------------------------------------------------------------------------\n// The per-scene kit\n\ntype Slot = 'near' | 'small' | 'glyph' | 'splat'\nconst SLOTS: Slot[] = ['near', 'small', 'glyph', 'splat']\n\nexport interface KitMaterialSet {\n  box: Material\n  glyph: Material\n  splat: Material\n}\n\n/** Makes the kit's box, glyph and splat materials. WebGPU passes its node twins. */\nexport type KitMaterials = (atlas: DataTexture) => KitMaterialSet\n\nexport class Kit {\n  private entries = new Map<number, { parts: KitBuilder; world: Matrix4 }>()\n  private meshes: Partial<Record<Slot, InstancedMesh>> = {}\n  private materials: KitMaterialSet\n  private nextId = 1\n  private unskip = new Map<InstancedMesh, () => void>()\n  private queued = false\n  users = 0\n\n  constructor(\n    private scene: Scene,\n    make: KitMaterials | undefined,\n    atlas: DataTexture,\n  ) {\n    kitUniforms.tAtlas.value = atlas\n    this.materials = make ? make(atlas) : glMaterials()\n  }\n\n  add(parts: KitBuilder, world: Matrix4) {\n    const id = this.nextId++\n    this.entries.set(id, { parts, world: world.clone() })\n    this.queue()\n    return id\n  }\n  remove(id: number) {\n    this.entries.delete(id)\n    this.queue()\n  }\n  private queue() {\n    if (this.queued) return\n    this.queued = true\n    queueMicrotask(() => this.flush())\n  }\n\n  /** Rewrite the instance buffers from every registered component. */\n  private flush() {\n    this.queued = false\n    for (const slot of SLOTS) {\n      let count = 0\n      for (const e of this.entries.values()) count += e.parts[slot].length / KIT_STRIDE\n      let mesh = this.meshes[slot]\n      if (!mesh || mesh.instanceMatrix.count < count) {\n        if (mesh) this.drop(mesh)\n        if (count === 0) {\n          delete this.meshes[slot]\n          continue\n        }\n        mesh = this.meshes[slot] = this.make(slot, Math.ceil(count * 1.25) + 16)\n      }\n      const mat = mesh.instanceMatrix.array as Float32Array\n      const color = mesh.geometry.getAttribute('aColor') as InstancedBufferAttribute\n      const kit = mesh.geometry.getAttribute('aKit') as InstancedBufferAttribute\n      let i = 0\n      for (const e of this.entries.values()) {\n        const src = e.parts[slot]\n        for (let o = 0; o < src.length; o += KIT_STRIDE, i++) {\n          m4.fromArray(src, o)\n            .premultiply(e.world)\n            .toArray(mat, i * 16)\n          for (let k = 0; k < 4; k++) {\n            color.array[i * 4 + k] = src[o + 16 + k]\n            kit.array[i * 4 + k] = src[o + 20 + k]\n          }\n        }\n      }\n      mesh.count = count\n      mesh.instanceMatrix.needsUpdate = color.needsUpdate = kit.needsUpdate = true\n    }\n  }\n\n  private make(slot: Slot, capacity: number) {\n    const flat = slot === 'glyph' || slot === 'splat'\n    const geometry = flat ? new PlaneGeometry(1, 1) : new BoxGeometry(1, 1, 1)\n    geometry.setAttribute('aColor', new InstancedBufferAttribute(new Float32Array(capacity * 4), 4))\n    geometry.setAttribute('aKit', new InstancedBufferAttribute(new Float32Array(capacity * 4), 4))\n    const mesh = new InstancedMesh(\n      geometry,\n      flat ? this.materials[slot] : this.materials.box,\n      capacity,\n    )\n    mesh.name = `runek:kit:${slot}`\n    // Instances span the world, so one bound would never cull anything useful.\n    mesh.frustumCulled = false\n    mesh.matrixAutoUpdate = false\n    // Mirrors skip the small parts, and the light on the street they are themselves laid over.\n    if (slot === 'small' || slot === 'splat') this.unskip.set(mesh, skipMirrors(mesh))\n    if (slot === 'glyph') mesh.renderOrder = 2\n    if (slot === 'splat') mesh.renderOrder = 1\n    this.scene.add(mesh)\n    return mesh\n  }\n  private drop(mesh: InstancedMesh) {\n    this.unskip.get(mesh)?.()\n    this.unskip.delete(mesh)\n    this.scene.remove(mesh)\n    mesh.geometry.dispose()\n    mesh.dispose()\n  }\n  dispose() {\n    for (const slot of SLOTS) if (this.meshes[slot]) this.drop(this.meshes[slot])\n    this.meshes = {}\n    this.materials.box.dispose()\n    this.materials.glyph.dispose()\n    this.materials.splat.dispose()\n  }\n}\n\nconst kits = new WeakMap<Scene, Kit>()\n\n/** The scene's kit, made on first use. Pair every call with `releaseKit`. */\nexport function acquireKit(\n  scene: Scene,\n  make: KitMaterials | undefined,\n  fonts?: { display?: string; body?: string },\n) {\n  let kit = kits.get(scene)\n  if (!kit) {\n    kit = new Kit(scene, make, glyphAtlas(fonts))\n    kits.set(scene, kit)\n  }\n  kit.users++\n  return kit\n}\n\nexport function releaseKit(scene: Scene) {\n  const kit = kits.get(scene)\n  if (!kit || --kit.users > 0) return\n  // Wait a tick: a component that re-registers in the same commit keeps the kit alive.\n  queueMicrotask(() => {\n    if (kit.users > 0 || kits.get(scene) !== kit) return\n    kit.dispose()\n    kits.delete(scene)\n  })\n}\n",
      "type": "registry:component"
    },
    {
      "path": "city/kitParts.ts",
      "content": "// The facade kit's parts. Each function adds one prop to a KitBuilder in a wall frame: +X runs\n// along the wall to the viewer's right, +Y is up, +Z points out of the wall. (x, y, z) is where\n// the prop meets the wall. Tower calls these for its street faces, and each also backs a\n// standalone component of the same name.\n\nimport { DETAIL, GLOW, KitBuilder } from './kit'\n\nconst CASES = ['#8a8a84', '#75736c', '#9a9488', '#6b6f70']\nconst DARK = '#141110'\nconst STEEL = '#4a4844'\nconst RUST = '#5a4234'\n\n/** An outdoor AC unit on its bracket. `cage` wraps it in a wire cage. */\nexport function acUnit(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  { seed = 0, cage = false } = {},\n) {\n  const tone = CASES[Math.floor(Math.abs(seed) * 97) % CASES.length]\n  if (cage) {\n    kit.box(true, x, y + 0.36, z + 0.24, 0.98, 0.72, 0.48, RUST, { detail: DETAIL.cage, seed })\n  } else {\n    kit.box(true, x, y + 0.33, z + 0.19, 0.82, 0.58, 0.34, tone, { detail: DETAIL.fan, seed })\n  }\n  kit.box(true, x, y + 0.02, z + 0.2, 0.9, 0.04, 0.4, DARK)\n  // The drain hose.\n  kit.box(true, x + 0.34, y - 0.4, z + 0.03, 0.03, 0.8, 0.03, DARK)\n}\n\n/** A pipe run with collars: up the wall from (x, y, z), or along it when `horizontal`. */\nexport function pipeRun(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  length: number,\n  { horizontal = false, radius = 0.06, color = STEEL } = {},\n) {\n  const t = radius * 2\n  if (horizontal) kit.box(true, x + length / 2, y, z + radius + 0.03, length, t, t, color)\n  else kit.box(true, x, y + length / 2, z + radius + 0.03, t, length, t, color)\n  const collars = Math.max(2, Math.round(length / 2.4))\n  for (let i = 0; i < collars; i++) {\n    const at = ((i + 0.5) * length) / collars\n    if (horizontal) kit.box(true, x + at, y, z + radius + 0.02, 0.07, t + 0.06, t + 0.05, DARK)\n    else kit.box(true, x, y + at, z + radius + 0.02, t + 0.06, 0.07, t + 0.05, DARK)\n  }\n}\n\n/** Height of a cable `t` of the way across (0 to 1): a parabola that drops `sag` at mid span and ends `drop` higher. */\nexport const cableY = (t: number, sag: number, drop = 0) => drop * t - 4 * sag * t * (1 - t)\n\n/** A cable sagging from the wall at (x, y, z) across `span` metres of street. */\nexport function cableSag(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  span: number,\n  { sag = 1.2, drop = 0, segments = 8, color = DARK, thickness = 0.04 } = {},\n) {\n  for (let i = 0; i < segments; i++) {\n    const t0 = i / segments\n    const t1 = (i + 1) / segments\n    const y0 = cableY(t0, sag, drop)\n    const y1 = cableY(t1, sag, drop)\n    const len = span / segments\n    kit.box(\n      true,\n      x,\n      y + (y0 + y1) / 2,\n      z + (t0 + t1) * 0.5 * span,\n      thickness,\n      thickness,\n      len,\n      color,\n      { rise: (y1 - y0) / len },\n    )\n  }\n}\n\n/** A louvred vent under a small hood. */\nexport function vent(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  { width = 0.6, height = 0.45 } = {},\n) {\n  kit.box(true, x, y + height / 2, z + 0.04, width, height, 0.08, STEEL, { detail: DETAIL.slats })\n  kit.box(true, x, y + height + 0.03, z + 0.08, width + 0.08, 0.05, 0.16, DARK)\n}\n\n/** A sloped fabric awning hung at (x, y, z), `width` along the wall, with a valance. */\nexport function awning(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  width: number,\n  { depth = 1.3, drop = 0.45, color = '#5a2a1c', stripes = true } = {},\n) {\n  const detail = stripes ? DETAIL.stripes : DETAIL.none\n  kit.box(false, x, y - drop / 2, z + depth / 2, width, 0.05, depth, color, {\n    detail,\n    rise: -drop / depth,\n  })\n  kit.box(false, x, y - drop - 0.1, z + depth, width, 0.22, 0.03, color, { detail })\n  // The two arms that carry it.\n  for (const side of [-1, 1])\n    kit.box(\n      true,\n      x + side * (width / 2 - 0.05),\n      y - drop / 2 - 0.05,\n      z + depth / 2,\n      0.04,\n      0.04,\n      depth,\n      DARK,\n      { rise: -drop / depth },\n    )\n}\n\n/** A roller shutter in its housing. `open` is the share rolled up, 0 (down) to 1. */\nexport function rollerShutter(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  width: number,\n  height: number,\n  { open = 0, color = '#6e6a62' } = {},\n) {\n  const down = height * (1 - Math.min(1, Math.max(0, open)))\n  if (down > 0.05)\n    kit.box(false, x, y + height - down / 2, z + 0.05, width, down, 0.05, color, {\n      detail: DETAIL.slats,\n    })\n  kit.box(false, x, y + height + 0.1, z + 0.11, width + 0.12, 0.26, 0.22, STEEL)\n  for (const side of [-1, 1])\n    kit.box(\n      true,\n      x + side * (width / 2 + 0.03),\n      y + height / 2,\n      z + 0.05,\n      0.06,\n      height,\n      0.09,\n      STEEL,\n    )\n}\n\n/** The word a blade sign stacks: the longest word of a shop's name that has seven letters or fewer. */\nexport function bladeWord(name: string) {\n  const words = name.toUpperCase().split(' ')\n  let best = ''\n  for (const w of words) if (w.length <= 7 && w.length > best.length) best = w\n  return best || words[0].slice(0, 9)\n}\n\n/** A blade sign: a board standing out from the wall, its letters stacked and lit on both faces. (x, y, z) is the bottom of the board at the wall. */\nexport function bladeSign(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  text: string,\n  { letter = 0.55, color = '#ff6418', gap = 0.3, tube = true } = {},\n) {\n  const word = text.toUpperCase().replace(/ /g, '')\n  const step = letter * 1.28\n  const height = word.length * step + 0.3\n  const depth = letter * 1.15 + 0.3\n  const mid = z + gap + depth / 2\n  kit.box(false, x, y + height / 2, mid, 0.14, height, depth, DARK)\n  const top = y + height - 0.15 - step / 2\n  for (const side of [-1, 1]) {\n    kit.text(word, x + side * 0.085, top, mid, letter, color, {\n      vertical: true,\n      rotY: (side * Math.PI) / 2,\n      t: 0.45,\n    })\n  }\n  if (tube) {\n    for (const edge of [-1, 1])\n      kit.box(\n        false,\n        x,\n        y + height / 2,\n        mid + edge * (depth / 2 + 0.02),\n        0.05,\n        height,\n        0.05,\n        color,\n        { glow: GLOW.tube, t: 0.1 },\n      )\n  }\n  // Two arms back to the wall.\n  for (const at of [0.25, height - 0.25])\n    kit.box(true, x, y + at, z + gap / 2, 0.05, 0.05, gap, STEEL)\n}\n\n/** A vending machine standing against the wall: a matte case and a lit window of goods. The case is solid. */\nexport function vendingMachine(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  { seed = 0, color = '#3a2f45', lamp = '#ffcf9a' } = {},\n) {\n  kit.box(true, x, y + 0.93, z + 0.36, 1.0, 1.86, 0.72, color)\n  kit.solid(x, y + 0.93, z + 0.36, 1.0, 1.86, 0.72)\n  kit.box(false, x - 0.06, y + 1.2, z + 0.73, 0.76, 1.02, 0.03, lamp, {\n    glow: GLOW.glass,\n    t: 0.35,\n    detail: DETAIL.vending,\n    seed,\n  })\n  kit.box(true, x - 0.06, y + 0.38, z + 0.73, 0.6, 0.2, 0.03, DARK)\n  kit.box(true, x + 0.4, y + 1.2, z + 0.73, 0.1, 0.7, 0.03, DARK)\n}\n\n/** A shop's name over its bay: lit letters on a dark board, or bare tube letters. `fit` is the most width it may take. */\nexport function fasciaSign(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  text: string,\n  { letter = 0.5, color = '#ffa64d', fit = 0, tube = false, board = true } = {},\n) {\n  let h = letter\n  const wide = KitBuilder.textWidth(text, h)\n  if (fit > 0 && wide + 0.4 > fit) h *= fit / (wide + 0.4)\n  const width = KitBuilder.textWidth(text, h)\n  if (board)\n    kit.box(false, x, y, z + 0.04, width + h * 0.9, h * 1.75, 0.08, DARK, { detail: DETAIL.panel })\n  kit.text(text, x, y, z + 0.1, h, color, {\n    outline: tube,\n    glow: tube ? GLOW.tube : GLOW.sign,\n    t: tube ? 0.12 : 0.5,\n  })\n  return width + h * 0.9\n}\n\n/** A drum lantern on a wall arm: the corner light of a tenement street. */\nexport function drumLantern(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  { color = '#ffa64d', reach = 0.7 } = {},\n) {\n  const at = z + reach\n  for (const turn of [0, Math.PI / 4]) {\n    kit.box(false, x, y, at, 0.5, 0.78, 0.5, color, { glow: GLOW.sign, t: 0.25, rotY: turn })\n    kit.box(true, x, y + 0.43, at, 0.58, 0.08, 0.58, DARK, { rotY: turn })\n    kit.box(true, x, y - 0.43, at, 0.58, 0.08, 0.58, DARK, { rotY: turn })\n  }\n  kit.box(true, x, y + 0.55, z + reach / 2, 0.05, 0.05, reach, STEEL)\n}\n\n/** Big letters on an open frame, standing on a roof edge. (x, y, z) is the middle of the frame's foot. Returns its width. */\nexport function roofSign(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  text: string,\n  { letter = 1.8, color = '#ff6418', fit = 0 } = {},\n) {\n  let h = letter\n  const wide = KitBuilder.textWidth(text, h, 0.1)\n  if (fit > 0 && wide > fit) h *= fit / wide\n  const width = KitBuilder.textWidth(text, h, 0.1)\n  const base = y + 0.9\n  kit.text(text, x, base + h / 2, z + 0.08, h, color, { t: 0.75, tracking: 0.1 })\n  for (const rail of [0.12, 0.88])\n    kit.box(false, x, base + h * rail, z, width + 0.6, 0.07, 0.07, STEEL)\n  const posts = Math.max(2, Math.round(width / 3))\n  for (let i = 0; i < posts; i++) {\n    const px = x - width / 2 + (width * i) / (posts - 1)\n    kit.box(true, px, y + (0.9 + h) / 2, z - 0.06, 0.1, 0.9 + h, 0.1, STEEL)\n    kit.box(true, px, y + 0.5, z - 0.5, 0.07, 0.07, 0.95, STEEL, { rise: -0.9 })\n  }\n  return width\n}\n\n/** A stencilled code painted on the wall in the body font. */\nexport function stencilCode(\n  kit: KitBuilder,\n  x: number,\n  y: number,\n  z: number,\n  text: string,\n  { letter = 0.3, color = '#a8a092' } = {},\n) {\n  kit.text(text, x, y, z + 0.012, letter, color, { glow: GLOW.matte, body: true, tracking: 0.12 })\n}\n",
      "type": "registry:component"
    },
    {
      "path": "city/useKit.ts",
      "content": "import { useThree } from '@react-three/fiber'\nimport { lazyModule, useNodeRenderer, useWorld } from '@runek/core'\nimport { type DependencyList, useLayoutEffect, useMemo, useRef } from 'react'\nimport type { Group } from 'three'\nimport { useLadder } from './glow'\nimport { acquireKit, KitBuilder, kitUniforms, releaseKit } from './kit'\nimport { applyTowerLight, nightFactor, towerLight } from './towerLight'\n\n// The kit's node (TSL) materials, loaded only under a node renderer.\nconst kitNodes = lazyModule(() => import('../nodes/kit'))\n\n/**\n * Register a component's kit parts with the scene's shared instanced meshes. `build` describes\n * the parts in local space and must be a pure function of `deps`. Attach the returned ref to a\n * group at the component's origin: its world matrix places the parts. `place` is any value that\n * changes when that group moves (the position and rotation props).\n */\nexport function useKit(build: (kit: KitBuilder) => void, deps: DependencyList, place: unknown) {\n  const parts = useMemo(() => {\n    const kit = new KitBuilder()\n    build(kit)\n    return kit\n  }, deps)\n  return useKitParts(parts, place)\n}\n\n/**\n * The same, for a component that built its own `KitBuilder` because it needs more than the\n * instances out of it (Tower reads `solids` to make its colliders). `parts` must be memoized.\n */\nexport function useKitParts(parts: KitBuilder, place: unknown) {\n  const ref = useRef<Group>(null)\n  const scene = useThree((s) => s.scene)\n  const nodes = useNodeRenderer() ? kitNodes() : null\n  const { fonts, time } = useWorld()\n  const ladder = useLadder()\n  const night = Math.round(nightFactor(time.hours) * 10) / 10\n\n  useLayoutEffect(() => applyTowerLight(ladder), [ladder])\n  useLayoutEffect(() => {\n    kitUniforms.uNight.value = night\n    towerLight.night = night\n  }, [night])\n  const placeKey = JSON.stringify(place)\n  useLayoutEffect(() => {\n    const group = ref.current\n    if (!group) return\n    group.updateWorldMatrix(true, false)\n    const kit = acquireKit(scene, nodes?.kitNodeMaterials, fonts)\n    const id = kit.add(parts, group.matrixWorld)\n    return () => {\n      kit.remove(id)\n      releaseKit(scene)\n    }\n  }, [parts, scene, nodes, fonts.display, fonts.body, placeKey])\n  return ref\n}\n",
      "type": "registry:component"
    },
    {
      "path": "city/glow.ts",
      "content": "// How bright each kind of city emitter is, as a ladder of rungs, each the lowest and highest\n// luminance that kind may have, so a sign face is a sign face whatever its hue and a lamp lens\n// always outshines it. The rungs are face values scaled by the world's luminance levels\n// (`useLuminance()`): sign faces by `sign`, tube cores by `tube`, lamp lenses by `lamp`, and lit\n// glass (windows, shopfronts, ad boards, and the light they leave on the pavement) by `screen`.\n// At every level's default of 1 the brightest rungs sit around 1, so they read without bloom; a\n// world with bloom raises `sign`, `tube` and `lamp` to make them bloom.\n//\n// Emissive colors are normalized to unit luminance and then scaled onto a rung, so the hue of a\n// color never changes how bright it reads.\n\nimport {\n  DEFAULT_LUMINANCE,\n  glowLook,\n  type MaterialLook,\n  materialKey,\n  retainMaterial,\n  sharedMaterial,\n  useLuminance,\n  type WorldLuminance,\n} from '@runek/core'\nimport { useMemo } from 'react'\nimport { Color, type Material } from 'three'\n\n/** A rung of the ladder: the lowest and highest luminance that kind of emitter may have. */\nexport type Rung = readonly [number, number]\n\nexport interface Ladder {\n  /** A night sky dome lit from below by a city. Face value. */\n  skyDome: Rung\n  /** A wall with no lamp on it. Face value. */\n  unlitWall: Rung\n  /** Pavement lit by the glass and signs above it. */\n  streetUnderSign: Rung\n  /** A lit room seen through its window from the street. */\n  windowLit: Rung\n  /** Lit shopfront glass, and the white of an ad board. */\n  shopGlass: Rung\n  /** Sign faces and lit letters. */\n  signFace: Rung\n  /** The core of a neon tube. */\n  tubeCore: Rung\n  /** A street lamp's lens seen from below. */\n  lampLens: Rung\n}\n\nconst scale = (r: Rung, k: number): Rung => [r[0] * k, r[1] * k]\n\n/** The rungs at every luminance level's face value (1). */\nexport const FACE_LADDER: Ladder = {\n  skyDome: [0.018, 0.055],\n  unlitWall: [0.02, 0.05],\n  streetUnderSign: [0.1, 0.5],\n  windowLit: [0.15, 0.6],\n  shopGlass: [0.4, 1.2],\n  signFace: [0.6, 1.6],\n  tubeCore: [0.6, 1.7],\n  lampLens: [0.67, 1.5],\n}\n\n/** The ladder for a world's luminance levels. */\nexport function ladderFor(l: WorldLuminance): Ladder {\n  const f = FACE_LADDER\n  return {\n    skyDome: f.skyDome,\n    unlitWall: f.unlitWall,\n    streetUnderSign: scale(f.streetUnderSign, l.screen),\n    windowLit: scale(f.windowLit, l.screen),\n    shopGlass: scale(f.shopGlass, l.screen),\n    signFace: scale(f.signFace, l.sign),\n    tubeCore: scale(f.tubeCore, l.tube),\n    lampLens: scale(f.lampLens, l.lamp),\n  }\n}\n\n/** The ladder at the default levels. */\nexport const DEFAULT_LADDER: Ladder = ladderFor(DEFAULT_LUMINANCE)\n\n/** The world's ladder, from its luminance levels. */\nexport function useLadder(): Ladder {\n  const { screen, sign, tube, lamp, flame } = useLuminance()\n  return useMemo(\n    () => ladderFor({ screen, sign, tube, lamp, flame }),\n    [screen, sign, tube, lamp, flame],\n  )\n}\n\n/** The typical value of a rung: the geometric middle, since luminance is perceived on a log scale. */\nexport function mid(rung: Rung): number {\n  return Math.sqrt(rung[0] * rung[1])\n}\n\n/** A point along a rung, 0 at its bottom and 1 at its top, spaced evenly on a log scale. */\nexport function along(rung: Rung, t: number): number {\n  return rung[0] * (rung[1] / rung[0]) ** t\n}\n\n/** Relative luminance (Rec. 709) of a linear color. */\nexport function luminanceOf(c: Color): number {\n  return 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b\n}\n\n/** `hex` at unit luminance times `luminance`, as a linear (HDR) color. */\nexport function emissiveColor(hex: string, luminance: number): Color {\n  const c = new Color(hex)\n  return c.multiplyScalar(luminance / Math.max(1e-4, luminanceOf(c)))\n}\n\n/** A shared look's material, kept for the life of the page: city emitters come back often. */\nfunction kept(look: MaterialLook): Material {\n  const key = materialKey(look)\n  const material = sharedMaterial(look, key)\n  if (!material.userData.kept) {\n    material.userData.kept = true\n    retainMaterial(key)\n  }\n  return material\n}\n\n/**\n * The shared unlit material for an emitter of color `hex` at `luminance`, through core's\n * `glowLook`, so it batches with every other part of that look. Read-only.\n */\nexport function glowMaterial(hex: string, luminance: number, opacity = 1): Material {\n  return kept(\n    glowLook(\n      emissiveColor(hex, 1),\n      luminance,\n      opacity < 1 ? { transparent: true, opacity, depthWrite: false } : undefined,\n    ),\n  )\n}\n\n/**\n * The shared unlit material for picture content on a lit board: `hex` keeps its own value and\n * is scaled so that white would shine at `white`. Dark backgrounds stay dark, bright text and\n * shapes glow.\n */\nexport function screenMaterial(hex: string, white: number): Material {\n  return kept(glowLook(hex, white))\n}\n",
      "type": "registry:component"
    },
    {
      "path": "city/haze.ts",
      "content": "// Additive light that is not a real light: a lamp's haze cone and the pool it leaves on the\n// street. One shared material per color and strength: a GLSL ShaderMaterial here, and its TSL\n// twin for WebGPURenderer in nodes/haze.ts. Both work on instanced and merged geometry: they read\n// only `uv`, normals and world positions.\n//\n// Additive light must fade into fog rather than mix toward it (mixing would add the fog color\n// wherever the cone is), so they attenuate by the scene's linear fog range themselves.\n\nimport {\n  AdditiveBlending,\n  type Color,\n  DoubleSide,\n  type Material,\n  ShaderMaterial,\n  UniformsLib,\n  UniformsUtils,\n} from 'three'\n\nconst HAZE_VERT = /* glsl */ `\nvarying vec3 vN;\nvarying vec3 vV;\nvarying vec2 vUv;\nvarying vec3 vWorld;\nvoid main() {\n  // Lamps share one instanced mesh for their cones and one for their pools (StreetLamp.tsx), so\n  // each instance brings its own place and turn.\n  #ifdef USE_INSTANCING\n    vec4 world = modelMatrix * instanceMatrix * vec4(position, 1.0);\n    vec3 n = mat3(instanceMatrix) * normal;\n  #else\n    vec4 world = modelMatrix * vec4(position, 1.0);\n    vec3 n = normal;\n  #endif\n  vec4 mv = viewMatrix * world;\n  vN = normalize(normalMatrix * n);\n  vV = normalize(-mv.xyz);\n  vUv = uv;\n  vWorld = world.xyz;\n  gl_Position = projectionMatrix * mv;\n}`\n\n// The scene's linear fog range sets how far additive light carries, whatever fog chunk is in use.\nexport const FOG_FADE = /* glsl */ `\nuniform float fogNear;\nuniform float fogFar;\nfloat hazeFog(vec3 world) {\n  #ifdef USE_FOG\n    return 1.0 - 0.94 * smoothstep(fogNear, fogFar, distance(world, cameraPosition));\n  #else\n    return 1.0;\n  #endif\n}`\n\n// Brightest where the cone is seen side on through its middle, falling to nothing at the top.\nconst CONE_FRAG = /* glsl */ `\nuniform vec3 uColor;\nvarying vec3 vN;\nvarying vec3 vV;\nvarying vec2 vUv;\nvarying vec3 vWorld;\n${FOG_FADE}\nvoid main() {\n  float facing = pow(abs(dot(normalize(vN), normalize(vV))), 1.5);\n  float fall = vUv.y * vUv.y;\n  gl_FragColor = vec4(uColor * facing * fall * hazeFog(vWorld), 1.0);\n}`\n\n// A soft disc on the ground. It doubles in strength with distance, because near lamps usually\n// hold a real light from the pool, which lights the street itself.\nconst POOL_FRAG = /* glsl */ `\nuniform vec3 uColor;\nuniform vec2 uFade;\nvarying vec2 vUv;\nvarying vec3 vWorld;\n${FOG_FADE}\nvoid main() {\n  float r = length(vUv - 0.5) * 2.0;\n  float disc = (1.0 - smoothstep(0.0, 1.0, r));\n  disc *= disc;\n  float far = mix(0.5, 1.0, smoothstep(uFade.x, uFade.y, distance(vWorld, cameraPosition)));\n  gl_FragColor = vec4(uColor * disc * far * hazeFog(vWorld), 1.0);\n}`\n\nconst cache = new Map<string, Material>()\n\nexport function additive<M extends Material>(m: M): M {\n  m.transparent = true\n  m.blending = AdditiveBlending\n  m.depthWrite = false\n  return m\n}\n\n/** The haze cone under a lamp head, in `color` (linear, already scaled to its luminance). */\nexport function coneMaterial(color: Color): Material {\n  const key = `cone:${color.r.toFixed(4)},${color.g.toFixed(4)},${color.b.toFixed(4)}`\n  let m = cache.get(key)\n  if (!m) {\n    m = new ShaderMaterial({\n      vertexShader: HAZE_VERT,\n      fragmentShader: CONE_FRAG,\n      uniforms: UniformsUtils.merge([UniformsLib.fog, { uColor: { value: color.clone() } }]),\n      side: DoubleSide,\n      fog: true,\n    })\n    m.name = `runek:haze:${key}`\n    cache.set(key, additive(m))\n  }\n  return m\n}\n\n/** The pool a lamp leaves on the street, faded in between `near` and `far` meters from the eye. */\nexport function poolMaterial(color: Color, near: number, far: number): Material {\n  const key = `pool:${color.r.toFixed(4)},${color.g.toFixed(4)},${color.b.toFixed(4)}:${near}:${far}`\n  let m = cache.get(key)\n  if (!m) {\n    m = new ShaderMaterial({\n      vertexShader: HAZE_VERT,\n      fragmentShader: POOL_FRAG,\n      uniforms: UniformsUtils.merge([\n        UniformsLib.fog,\n        { uColor: { value: color.clone() }, uFade: { value: [near, far] } },\n      ]),\n      fog: true,\n    })\n    m.polygonOffset = true\n    m.polygonOffsetFactor = -2\n    m.polygonOffsetUnits = -4\n    m.name = `runek:haze:${key}`\n    cache.set(key, additive(m))\n  }\n  return m\n}\n",
      "type": "registry:component"
    },
    {
      "path": "city/towerLight.ts",
      "content": "// What lights a Tower at night, shared by its GLSL material and its TSL port: the lamp colors\n// behind windows and shopfronts (warm LED, sodium, mercury, phosphor violet and green, gas\n// neon), each at unit luminance, and the uniforms that put windows, shop\n// glass, trim, the lowest floors and the light a sign leaves on the street on the world's\n// luminance ladder.\n\nimport { Vector2 } from 'three'\nimport { DEFAULT_LADDER, emissiveColor, type Ladder, mid } from './glow'\n\n/** Lit windows: cumulative share, lamp. Most rooms are warm LED, then sodium, a few mercury, violet and green. */\nexport const WINDOW_LAMPS: [number, string][] = [\n  [0.6, '#ffcf9a'],\n  [0.86, '#ffa64d'],\n  [0.94, '#b8e8c8'],\n  [0.975, '#b967ff'],\n  [1, '#39ff88'],\n]\n\n/** Shopfront bays: cumulative share, lamp. Bays past the last share have their shutters down. */\nexport const SHOP_LAMPS: [number, string][] = [\n  [0.3, '#ffcf9a'],\n  [0.45, '#ffa64d'],\n  [0.52, '#39ff88'],\n  [0.58, '#b967ff'],\n  [0.62, '#ff6418'],\n]\n\n// The facade shader's integer hash (`pcg` and `h21` in towerFacade.ts), bit for bit, so the kit\n// can ask what the shader draws behind a bay's glass.\nfunction pcg(v: number) {\n  const state = (Math.imul(v, 747796405) + 2891336453) >>> 0\n  const word = Math.imul(((state >>> ((state >>> 28) + 4)) ^ state) >>> 0, 277803737) >>> 0\n  return ((word >>> 22) ^ word) >>> 0\n}\nfunction h21(x: number, y: number) {\n  const qx = (Math.floor(x) + 65536) >>> 0\n  const qy = (Math.floor(y) + 65536) >>> 0\n  return pcg((Math.imul(qx, 1664525) + pcg(qy)) >>> 0) / 4294967295\n}\n// The shader works in 32-bit floats: round the same way before a `floor` decides a cell.\nconst f = Math.fround\n\n/**\n * The lamp behind a lit shop bay's glass and where on the shop rung it sits (0 to 1), as the\n * facade shader draws it. `sd` is the tower's seed value, `fseed` the face's, `bay` the bay's\n * place along the face.\n */\nexport function shopLamp(sd: number, fseed: number, bay: number): { color: string; level: number } {\n  const last = SHOP_LAMPS[SHOP_LAMPS.length - 1]\n  const r = h21(bay, f(f(f(sd) * f(13.1)) + f(fseed))) * last[0]\n  return {\n    color: (SHOP_LAMPS.find(([share]) => r < share) ?? last)[1],\n    level: h21(bay + 3, f(f(sd) + f(f(fseed) * 5))),\n  }\n}\n\n/** Trim colors a tower may pick when its `trim` is unset: gas neon, phosphor green and violet, sodium, pump orange. */\nexport const TRIM_NEON = ['#ff6418', '#39ff88', '#b967ff', '#ffa64d', '#ff8a1f']\n\n/** A lamp color at unit luminance, as a GLSL literal. */\nexport function glslLamp(hex: string) {\n  const c = emissiveColor(hex, 1)\n  return `vec3(${c.r.toFixed(4)}, ${c.g.toFixed(4)}, ${c.b.toFixed(4)})`\n}\n\n/** GLSL for a cumulative lamp table: `vec3 name(float r)`, black past the last share. */\nexport function glslLampTable(name: string, table: [number, string][]) {\n  const body = table\n    .map(([share, hex]) => `if (r < ${share.toFixed(3)}) return ${glslLamp(hex)};`)\n    .join('\\n  ')\n  return `vec3 ${name}(float r) {\\n  ${body}\\n  return vec3(0.0);\\n}`\n}\n\n/** The ladder values a tower needs. The wall gain maps a wall color of luminance 0.04 to the bottom of the unlit-wall rung. */\nfunction lightFrom(ladder: Ladder) {\n  return {\n    window: new Vector2(ladder.windowLit[0], ladder.windowLit[1]),\n    shop: new Vector2(ladder.shopGlass[0], ladder.shopGlass[1]),\n    trim: mid(ladder.signFace),\n    sign: new Vector2(ladder.signFace[0], ladder.signFace[1]),\n    tube: new Vector2(ladder.tubeCore[0], ladder.tubeCore[1]),\n    street: new Vector2(ladder.streetUnderSign[0], ladder.streetUnderSign[1]),\n    wallGain: ladder.unlitWall[0] / 0.04,\n    glow: emissiveColor('#ffa64d', ladder.streetUnderSign[0] * 0.3),\n  }\n}\n\n/**\n * The light every tower and kit part is drawn under, one set for the page. The GLSL uniforms\n * below hold its vectors by reference, and the node twins (`nodes/city.ts`) read it each render,\n * so one write relights every tower under either renderer.\n */\nexport const towerLight = { ...lightFrom(DEFAULT_LADDER), night: 1 }\n\n/** Uniforms every tower ShaderMaterial shares by reference. */\nexport const towerUniforms = {\n  uWindow: { value: towerLight.window },\n  uShop: { value: towerLight.shop },\n  uTrim: { value: towerLight.trim },\n  uSign: { value: towerLight.sign },\n  uTube: { value: towerLight.tube },\n  uStreet: { value: towerLight.street },\n  uWallGain: { value: towerLight.wallGain },\n  uGlow: { value: towerLight.glow },\n}\n\n/** Put every tower on `ladder`. Cheap: it writes a handful of shared values. */\nexport function applyTowerLight(ladder: Ladder) {\n  const l = lightFrom(ladder)\n  towerLight.window.copy(l.window)\n  towerLight.shop.copy(l.shop)\n  towerLight.sign.copy(l.sign)\n  towerLight.tube.copy(l.tube)\n  towerLight.street.copy(l.street)\n  towerLight.glow.copy(l.glow)\n  towerLight.trim = towerUniforms.uTrim.value = l.trim\n  towerLight.wallGain = towerUniforms.uWallGain.value = l.wallGain\n}\n\n/** 0 at midday, 1 from late evening to early morning. */\nexport function nightFactor(hours: number) {\n  const fromNoon = Math.abs((((hours % 24) + 24) % 24) - 12) / 12 // 0 noon, 1 midnight\n  return Math.min(1, Math.max(0, (fromNoon - 0.35) / 0.3))\n}\n",
      "type": "registry:component"
    },
    {
      "path": "nodes/kit.ts",
      "content": "// The facade kit's materials as TSL node materials, for WebGPURenderer. Same lighting model as\n// the GLSL in city/kit.ts (matte parts under street light, emitters on their ladder rung, letters cut\n// from the glyph atlas, light splats added to the street). The per-kind surface detail (slats, fan grilles, awning stripes, cage\n// wire, vending rows) is skipped here: parts draw in their flat color.\n\nimport { AdditiveBlending, type DataTexture } from 'three'\nimport {\n  attribute,\n  exp,\n  float,\n  floor,\n  max,\n  mix,\n  mod,\n  normalWorld,\n  positionWorld,\n  pow,\n  select,\n  smoothstep,\n  texture,\n  uv,\n  vec2,\n} from 'three/tsl'\nimport { MeshBasicNodeMaterial, type Node } from 'three/webgpu'\nimport { towerNodeUniforms as U } from './city'\n\nconst rung = (r: Node<'vec2'>, t: Node<'float'>) => r.x.mul(pow(r.y.div(r.x), t))\nconst kitRung = (glow: Node<'float'>, t: Node<'float'>) =>\n  select(\n    glow.lessThan(1.5),\n    rung(U.sign, t),\n    select(glow.lessThan(2.5), rung(U.tube, t), rung(U.shop, t)),\n  )\n\nexport function kitNodeMaterials(atlas: DataTexture) {\n  const color = attribute<'vec4'>('aColor', 'vec4')\n  const kit = attribute<'vec4'>('aKit', 'vec4')\n  const dusk = mix(float(0.12), float(1), U.night)\n\n  const box = new MeshBasicNodeMaterial()\n  const shade = float(0.72).add(normalWorld.y.mul(0.28)).add(normalWorld.x.mul(0.1))\n  const matte = color.rgb\n    .mul(mix(float(0.35), U.wallGain, U.night))\n    .mul(shade)\n    .add(\n      U.glow\n        .mul(exp(max(positionWorld.y, 0).negate().div(6)))\n        .mul(U.night)\n        .mul(shade.mul(0.45).add(0.55)),\n    )\n  box.colorNode = select(\n    color.a.lessThan(0.5),\n    matte,\n    color.rgb.mul(kitRung(color.a, kit.x)).mul(dusk),\n  )\n  box.fog = true\n\n  const glyph = new MeshBasicNodeMaterial()\n  const cell = vec2(mod(kit.y, 8), floor(kit.y.div(8)))\n  const at = vec2(cell.x.add(uv().x), cell.y.add(float(1).sub(uv().y))).div(8)\n  const tx = texture(atlas, at)\n  // Glow 0 is stencil paint: matte under the street light, like the wall it sits on.\n  const paint = color.rgb\n    .mul(mix(float(0.35), U.wallGain, U.night))\n    .add(U.glow.mul(U.night).mul(0.5))\n  glyph.colorNode = select(\n    color.a.lessThan(0.5),\n    paint,\n    color.rgb.mul(kitRung(color.a, kit.x)).mul(dusk),\n  )\n  glyph.opacityNode = select(kit.z.lessThan(0.5), tx.r, select(kit.z.lessThan(1.5), tx.g, tx.b))\n  glyph.transparent = true\n  glyph.depthWrite = false\n  glyph.fog = true\n\n  // Light on the street: a half disc from the foot of the wall, added to what lies under it.\n  const splat = new MeshBasicNodeMaterial()\n  const reach = vec2(uv().x.sub(0.5).mul(2), float(1).sub(uv().y)).length()\n  const disc = float(1).sub(smoothstep(0, 1, reach))\n  splat.colorNode = color.rgb.mul(rung(U.street, kit.x)).mul(U.night).mul(disc.mul(disc))\n  splat.transparent = true\n  splat.blending = AdditiveBlending\n  splat.depthWrite = false\n  splat.fog = false\n  splat.polygonOffset = true\n  splat.polygonOffsetFactor = -2\n  splat.polygonOffsetUnits = -4\n  return { box, glyph, splat }\n}\n",
      "type": "registry:component"
    },
    {
      "path": "nodes/city.ts",
      "content": "// The city's shared light as TSL uniforms, for the tower and kit node materials. They read\n// `towerLight` (city/towerLight.ts) each render, so the light a world sets reaches them without\n// a write of their own.\n\nimport { uniform } from 'three/tsl'\nimport { towerLight as T } from '../city/towerLight'\n\nexport const towerNodeUniforms = {\n  window: uniform(T.window),\n  shop: uniform(T.shop),\n  trim: uniform(T.trim).onRenderUpdate(() => T.trim),\n  sign: uniform(T.sign),\n  tube: uniform(T.tube),\n  street: uniform(T.street),\n  night: uniform(T.night).onRenderUpdate(() => T.night),\n  wallGain: uniform(T.wallGain).onRenderUpdate(() => T.wallGain),\n  glow: uniform(T.glow),\n}\n",
      "type": "registry:component"
    },
    {
      "path": "city/towerFacade.ts",
      "content": "// Tower's facade shader (WebGL). One material draws every wall of every tower from per-vertex\n// data, so towers keep merging in Runek's static batcher.\n//\n// Coordinates are metres on the wall (`aUv`: along the face, and height above the base), never\n// world position, because a merged tower's `position` is already in world space. Every edge is\n// box-filtered over the pixel footprint (`fwidth`), and per-cell randomness fades to its mean\n// once a cell is smaller than a pixel, so windows do not shimmer at distance.\n//\n// Bands (aRect.w): 0 plain trim, 1 street, 2 service, 3 podium, 4 tower, 5 crown, 6 roof.\n\nimport { glslLamp, glslLampTable, SHOP_LAMPS, WINDOW_LAMPS } from './towerLight'\n\nexport const TOWER_VERT = /* glsl */ `\nattribute vec2 aUv;\nattribute vec4 aRect;\nattribute vec4 aCell;\nattribute vec3 aWall;\nattribute vec3 aTrim;\nattribute vec4 aLook;\nvarying vec2 vUv;\nvarying vec3 vRay;\nvarying float vNy;\nflat varying vec4 vRect;\nflat varying vec4 vCell;\nflat varying vec3 vWall;\nflat varying vec3 vTrim;\nflat varying vec4 vLook;\n#include <fog_pars_vertex>\nvoid main() {\n  vUv = aUv; vRect = aRect; vCell = aCell; vWall = aWall; vTrim = aTrim; vLook = aLook;\n  vec4 wp = modelMatrix * vec4(position, 1.0);\n  // The view ray in the wall's own frame: along the face, up, and into the wall.\n  vec3 wn = normalize(mat3(modelMatrix) * normal);\n  vec3 along = normalize(vec3(wn.z, 0.0, -wn.x) + vec3(1e-5, 0.0, 0.0));\n  vec3 view = wp.xyz - cameraPosition;\n  vRay = vec3(dot(view, along), view.y, -dot(view, wn));\n  vNy = normal.y;\n  vec4 mvPosition = viewMatrix * wp;\n  gl_Position = projectionMatrix * mvPosition;\n  #include <fog_vertex>\n}`\n\nexport const TOWER_FRAG = /* glsl */ `\nuniform float uNight;\nuniform vec2 uWindow;\nuniform vec2 uShop;\nuniform float uTrim;\nuniform float uWallGain;\nuniform vec3 uGlow;\nvarying vec2 vUv;\nvarying vec3 vRay;\nvarying float vNy;\nflat varying vec4 vRect;\nflat varying vec4 vCell;\nflat varying vec3 vWall;\nflat varying vec3 vTrim;\nflat varying vec4 vLook;\n#include <fog_pars_fragment>\nuint pcg(uint v) {\n  uint state = v * 747796405u + 2891336453u;\n  uint word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;\n  return (word >> 22u) ^ word;\n}\nfloat h21(vec2 p) {\n  uvec2 q = uvec2(ivec2(floor(p)) + 65536);\n  return float(pcg(q.x * 1664525u + pcg(q.y))) * (1.0 / 4294967295.0);\n}\nfloat pulseInt(float x, float a, float b) { return floor(x) * (b - a) + clamp(fract(x), a, b) - a; }\n// Box-filtered periodic pulse: coverage of [a, b] in each unit cell over a footprint w.\nfloat pulse(float x, float a, float b, float w) {\n  w = max(w, 1e-4);\n  return (pulseInt(x + 0.5 * w, a, b) - pulseInt(x - 0.5 * w, a, b)) / w;\n}\n// Box-filtered single band [a, b].\nfloat band(float x, float a, float b, float w) {\n  return clamp((min(x + 0.5 * w, b) - max(x - 0.5 * w, a)) / max(w, 1e-4), 0.0, 1.0);\n}\n// A point along a ladder rung, spaced evenly on a log scale.\nfloat rung(vec2 r, float t) { return r.x * pow(r.y / r.x, t); }\n${glslLampTable('windowLamp', WINDOW_LAMPS)}\n${glslLampTable('shopLamp', SHOP_LAMPS)}\n\n// Interior mapping, flattened: the ray from the glass meets the back wall, a side wall, the\n// ceiling or the floor of a box room, and each surface is one flat tone of the room's lamp.\n// kind 0 plain room, 1 shelves on the back wall, 2 a shop (stocked shelves over a counter, a back door).\nvec3 room(vec3 ro, vec3 rd, vec3 size, float seed, float kind) {\n  rd.z = max(rd.z, 0.02);\n  rd.xy += vec2(1e-4);\n  vec3 t = (step(0.0, rd) * size - ro) / rd;\n  float tm = min(min(t.x, t.y), t.z);\n  vec3 p = ro + rd * tm;\n  float r1 = fract(seed * 7.31), r2 = fract(seed * 3.17);\n  float tone;\n  if (tm == t.z) {\n    tone = 1.0;\n    if (kind > 1.5) {\n      // A shop: stocked shelves over a counter, and a dark doorway to the back room.\n      vec2 q = vec2(p.x * 3.2, p.y * 2.1);\n      vec2 qc = floor(q), qf = fract(q);\n      float top = 0.35 + 0.55 * h21(qc + vec2(seed * 91.0, 3.0));\n      float stock = step(0.12, qf.y) * step(qf.y, top) * step(0.08, qf.x) * step(0.3, h21(qc + vec2(7.0, seed * 37.0)));\n      float zone = step(size.y * 0.36, p.y) * step(p.y, size.y * 0.9);\n      float door = step(abs(p.x - size.x * (0.2 + 0.6 * r1)), 0.5) * step(p.y, 2.1);\n      tone = mix(tone, 0.55, step(qf.y, 0.12) * zone);\n      tone = mix(tone, mix(0.38, 0.8, h21(qc + vec2(seed * 13.0, 11.0))), stock * zone);\n      tone = mix(tone, 0.3, step(p.y, size.y * 0.3));\n      tone = mix(tone, 0.2, door);\n    } else {\n      float furniture = step(p.y, size.y * (0.24 + 0.2 * r2)) * step(abs(p.x - size.x * (0.25 + 0.5 * r1)), size.x * 0.22);\n      float shelves = step(0.55, fract(p.y * 2.3)) * step(p.y, size.y * 0.85) * step(0.5, kind);\n      tone = mix(tone, 0.62, shelves);\n      tone = mix(tone, 0.2, furniture);\n    }\n  } else if (tm == t.y) {\n    tone = rd.y > 0.0 ? 1.3 : 0.42;\n  } else {\n    // Side walls: a shop's counter and shelf boards run round them.\n    tone = 0.62;\n    float shop = step(1.5, kind);\n    tone = mix(tone, 0.48, shop * step(fract(p.y * 2.1), 0.12) * step(size.y * 0.36, p.y) * step(p.y, size.y * 0.9));\n    tone = mix(tone, 0.34, shop * step(p.y, size.y * 0.3));\n  }\n  return vec3(tone, tm, 0.0);\n}\n\nvoid main() {\n  float kind = vRect.w, faceW = vRect.x, y0 = vRect.y, y1 = vRect.z;\n  float sd = vLook.x, era = vLook.y, fseed = vLook.z, flags = vLook.w;\n  float strips = mod(flags, 2.0), roofline = mod(floor(flags * 0.5), 2.0), fasciaTube = mod(floor(flags * 0.25), 2.0);\n  vec2 m = vUv;\n  vec2 fw = fwidth(m);\n  vec3 wall = vWall * mix(0.35, uWallGain, uNight);\n  vec3 trim = vTrim * uTrim * uNight;\n  vec3 col = wall;\n\n  if (kind > 5.5) {\n    // Roof: darker, patched, with the trim color along its edges after dusk.\n    vec2 ed = min(m, vRect.xy - m);\n    float patchy = mix(0.5, 0.68, h21(floor(m / 2.4) + sd));\n    patchy = mix(0.6, patchy, clamp(1.0 - max(fw.x, fw.y) / 2.4, 0.0, 1.0));\n    col = wall * patchy;\n    col += trim * roofline * (1.0 - band(min(ed.x, ed.y), 0.35, 1e4, max(fw.x, fw.y)));\n  } else if (kind < 0.5) {\n    // Plain trim: slabs, cornices, parapets, rooftop boxes. Shaded by which way the face points.\n    col = wall * (vNy > 0.5 ? 0.75 : (vNy < -0.5 ? 0.4 : 1.0));\n    col += trim * roofline * band(m.y, y1 - 0.4, y1 - 0.12, fw.y) * step(abs(vNy), 0.5);\n    col += uGlow * exp(-max(m.y, 0.0) / 6.0) * uNight * step(abs(vNy), 0.5);\n  } else {\n    float lit = 0.0;\n    vec3 emit = vec3(0.0);\n    // How far a pixel is from the camera in cells decides the level of detail.\n    if (kind < 1.5) {\n      // Street: shop bays between piers under a fascia. vCell = (bay width, 2 bits per bay).\n      float bayW = vCell.x;\n      float sg = m.x / bayW;\n      float bi = floor(sg);\n      float xm = fract(sg) * bayW;\n      float state = mod(floor(vCell.y / exp2(2.0 * bi) + 0.01), 4.0);\n      float r = h21(vec2(bi, sd * 13.1 + fseed));\n      float lod = clamp(fw.x / bayW * 3.0 - 0.5, 0.0, 1.0);\n      float open = band(xm, 0.38, bayW - 0.38, fw.x) * band(m.y, 0.38, 3.3, fw.y);\n      float frame = band(xm, 0.3, bayW - 0.3, fw.x) * band(m.y, 0.3, 3.38, fw.y) - open;\n      float fascia = band(m.y, 3.5, 4.38, fw.y);\n      float plinth = band(m.y, 0.0, 0.3, fw.y);\n      col = mix(col, wall * 0.55, fascia);\n      col = mix(col, wall * 0.7, plinth);\n      col = mix(col, wall * 0.4, frame);\n      vec3 lamp = shopLamp(r * ${SHOP_LAMPS[SHOP_LAMPS.length - 1][0].toFixed(3)}) * rung(uShop, h21(vec2(bi + 3.0, sd + fseed * 5.0))) * mix(0.08, 1.0, uNight);\n      if (state < 0.5) {\n        // Open and lit. Mullions split the glass in three, a door takes one third.\n        float third = bayW - 0.76;\n        float mull = pulse((xm - 0.38) / third * 3.0, 0.0, 0.06, fw.x / third * 3.0) + band(m.y, 2.55, 2.63, fw.y);\n        float counter = band(m.y, 0.38, 1.05, fw.y);\n        float flatTone = (0.62 + 0.38 * smoothstep(0.3, 3.3, m.y)) * mix(1.0, 0.35, counter);\n        vec3 rm = room(vec3(xm - 0.38, m.y - 0.38, 0.0), vRay, vec3(third, 2.92, 3.6), r + fseed, 2.0);\n        float near = 1.0 - smoothstep(0.05, 0.22, max(fw.x, fw.y));\n        float tone = mix(flatTone, rm.x, near);\n        vec3 shop = lamp * tone;\n        shop = mix(shop, wall * 0.35, clamp(mull, 0.0, 1.0));\n        col = mix(col, shop, open);\n        // The fascia tube sits over lit bays only, so the light gathers where the shops are.\n        emit += trim * fasciaTube * band(m.y, 3.42, 3.5, fw.y) * band(xm, 0.2, bayW - 0.2, fw.x);\n      } else if (state < 1.5) {\n        // Shutter down: slats, a housing box, a strip of light under the door.\n        float slat = pulse(m.y / 0.12, 0.0, 0.68, fw.y / 0.12);\n        vec3 shutter = wall * mix(0.9, 1.9, h21(vec2(bi + 11.0, sd))) * mix(0.6, 1.0, slat);\n        shutter = mix(shutter, wall * 0.5, band(m.y, 3.05, 3.3, fw.y));\n        col = mix(col, shutter, open);\n        // Posters pasted across it.\n        vec2 pg = vec2((xm - 0.5) / 0.74, (m.y - 0.9) / 1.05);\n        vec2 pc = floor(pg), pf = fract(pg);\n        float pr = h21(pc + vec2(bi * 7.0 + sd, fseed + 41.0));\n        float on = step(pr, 0.36) * step(0.0, pc.y) * step(pc.y, 1.0) * step(0.0, pg.x) * step(pc.x + 1.0, (bayW - 1.0) / 0.74);\n        float paper = pulse(pg.x, 0.06, 0.94, fw.x / 0.74) * pulse(pg.y, 0.05, 0.95, fw.y / 1.05) * on * (1.0 - lod);\n        vec3 ink = mix(mix(vec3(0.5, 0.42, 0.3), vec3(0.42, 0.2, 0.12), step(0.12, pr)), vec3(0.24, 0.2, 0.34), step(0.25, pr));\n        ink *= mix(1.0, 0.35, step(0.72, pf.y)) * mix(1.0, 0.6, step(pf.y, 0.4) * step(0.5, fract(pf.y * 12.0)));\n        col = mix(col, ink * mix(0.35, uWallGain, uNight) * 1.6, paper * open);\n      } else if (state < 2.5) {\n        // Closed for the night: dark glass holding a little haze, a dim lamp left on at the back.\n        vec3 glass = vec3(0.010, 0.009, 0.008) + vec3(0.02, 0.012, 0.007) * (1.0 - m.y / 3.3);\n        glass += lamp * 0.035 * band(m.y, 2.2, 3.1, fw.y);\n        col = mix(col, glass * mix(8.0, 1.0, uNight), open);\n      } else {\n        // A blank wall with a door, a lit transom over it and a bill or two beside it.\n        float door = band(xm, bayW * 0.5 - 0.62, bayW * 0.5 + 0.62, fw.x);\n        col = mix(col, wall * 0.42, door * band(m.y, 0.0, 2.3, fw.y));\n        emit += lamp * 0.5 * door * band(m.y, 2.38, 2.7, fw.y);\n        float bill = band(xm, 0.6, 1.3, fw.x) * band(m.y, 1.1, 2.05, fw.y) * step(0.4, r) * (1.0 - lod);\n        col = mix(col, vec3(0.5, 0.42, 0.3) * mix(0.35, uWallGain, uNight) * 1.5 * mix(1.0, 0.4, step(1.8, m.y)), bill);\n      }\n    } else if (kind < 2.5) {\n      // Service: louvre panels between joints, a conduit along the bottom.\n      float slat = pulse(m.y / 0.16, 0.0, 0.55, fw.y / 0.16);\n      float panel = pulse(m.x / 2.4, 0.03, 0.97, fw.x / 2.4);\n      col = wall * mix(0.45, 0.8, slat) * mix(0.5, 1.0, panel);\n      col = mix(col, wall * 1.3, band(m.y, y0 + 0.05, y0 + 0.13, fw.y));\n    } else {\n      // Windows. vCell = (cell width, storey height, lit share, style).\n      float cw = vCell.x, ch = vCell.y, litP = vCell.z, style = vCell.w;\n      vec2 g = vec2(m.x / cw, (m.y - y0) / ch);\n      vec2 gw = fw / vec2(cw, ch);\n      vec2 cell = floor(g), f = fract(g);\n      float rows = floor((y1 - y0) / ch + 0.01);\n      float inRows = band(g.y, 0.0, rows, gw.y);\n      float lod = clamp(max(gw.x, gw.y) * 1.6 - 0.5, 0.0, 1.0);\n      float r = h21(cell + vec2(sd * 31.7, fseed * 7.3));\n      float r2 = h21(cell * 1.7 + vec2(sd, fseed + 9.1));\n      vec4 w = style < 0.5 ? vec4(0.2, 0.8, 0.29, 0.76) : (style < 1.5 ? vec4(0.1, 0.9, 0.3, 0.8) : (style < 2.5 ? vec4(0.0, 1.0, 0.3, 0.74) : vec4(0.03, 0.97, 0.05, 0.95)));\n      // The crown reads differently by era: slots on a concrete block, a lit band on a glass slab.\n      if (kind > 4.5 && era < 0.5) w = vec4(0.38, 0.62, 0.12, 0.9);\n      if (kind > 4.5 && era > 1.5 && era < 2.5) { w = vec4(0.02, 0.98, 0.1, 0.92); litP = 1.0; }\n      float mask = pulse(g.x, w.x, w.y, gw.x) * pulse(g.y, w.z, w.w, gw.y) * inRows;\n      float frameMask = pulse(g.x, w.x - 0.035, w.y + 0.035, gw.x) * pulse(g.y, w.z - 0.03, w.w + 0.03, gw.y) * inRows - mask;\n      // Trims by band: a sill under each window row, a course line at each storey, piers at corners.\n      float sill = pulse(g.y, w.z - 0.075, w.z - 0.03, gw.y) * pulse(g.x, w.x - 0.06, w.y + 0.06, gw.x) * inRows;\n      float course = pulse(g.y, 0.0, 0.035, gw.y) * step(kind, 3.5);\n      float fin = pulse(g.x, 0.0, 0.05, gw.x) * step(1.5, style);\n      col = mix(col, wall * 0.62, clamp(frameMask, 0.0, 1.0));\n      col = mix(col, wall * 1.45, sill * step(style, 1.5));\n      col = mix(col, wall * 0.72, course);\n      col = mix(col, wall * 1.35, fin);\n      // Decal slots: one hash per wall cell picks a leak streak, a crack, a sticker or nothing.\n      float d = h21(cell + vec2(77.0 + sd, 13.0 + fseed));\n      float d2 = h21(cell + vec2(5.0 + fseed, 91.0 + sd));\n      float calm = 1.0 - lod;\n      float streakX = (f.x - mix(w.x, w.y, d2)) * cw;\n      float leak = step(d, 0.14) * band(streakX, -0.06 - 0.1 * d2, 0.06 + 0.1 * d2, fw.x) * band(f.y, 0.0, w.z - 0.07, gw.y) * (0.35 + 0.65 * f.y / max(w.z, 0.05));\n      float crackX = (f.x - 0.5 * (w.y + 1.0)) * cw + 0.05 * sin(f.y * 23.0 + d2 * 40.0) + 0.03 * sin(f.y * 61.0);\n      float crack = step(0.14, d) * step(d, 0.2) * band(crackX, -0.012, 0.012, fw.x) * step(style, 1.5);\n      float sticker = step(0.2, d) * step(d, 0.25) * band((f.x - w.y) * cw, 0.08, 0.36, fw.x) * band(f.y * ch, 0.5, 0.95, fw.y) * step(style, 1.5) * step(kind, 3.5);\n      col = mix(col, wall * 0.5, clamp(leak + crack, 0.0, 1.0) * calm * inRows);\n      col = mix(col, mix(vec3(0.5, 0.42, 0.3), vec3(0.24, 0.2, 0.34), step(0.225, d)) * mix(0.35, uWallGain, uNight) * 1.5, sticker * calm * inRows);\n      // Grime under the band's top edge, in streaks.\n      float drip = pulse(m.x / 1.9 + fseed * 0.37, 0.0, 0.16, fw.x / 1.9) * exp(-(y1 - m.y) / 2.2) * 0.45;\n      col *= 1.0 - drip * step(style, 2.5);\n\n      // Glass. Lit rooms sit on the window rung in their lamp's color.\n      float on = step(1.0 - litP, r) * uNight;\n      vec3 lampC = windowLamp(r2) * rung(uWindow, h21(cell + vec2(9.1, sd)));\n      if (kind > 4.5 && era > 1.5 && era < 2.5) lampC = ${glslLamp('#f4f6fb')} * rung(uWindow, 0.9);\n      if (style > 2.5) lampC *= 0.5;\n      vec3 dark = mix(vec3(0.20, 0.24, 0.30), vec3(0.010, 0.009, 0.008) + vec3(0.012, 0.007, 0.004) * (1.0 - f.y), uNight);\n      // Room types: a blind part way down, shelves on the back wall, a screen in a dark room.\n      float blind = step(0.55, r2) * step(f.y, w.w) * step(mix(w.w, w.z, 0.25 + 0.6 * fract(r2 * 7.0)), f.y);\n      float near = (1.0 - smoothstep(0.03, 0.11, max(gw.x, gw.y))) * step(style, 2.5);\n      float tone = mix(0.7, 1.0, smoothstep(w.z, w.w, f.y));\n      if (near > 0.0) {\n        vec3 rm = room(vec3(f.x * cw, f.y * ch, 0.0), vRay, vec3(cw, ch, 3.6), r + r2, step(0.7, fract(r2 * 3.0)));\n        tone = mix(tone, rm.x, near);\n      }\n      tone = mix(tone, 0.55, blind);\n      vec3 glassLit = lampC * tone;\n      float screen = step(0.93, fract(r * 5.3)) * (1.0 - step(1.0 - litP, r)) * band(f.x, mix(w.x, w.y, 0.3), mix(w.x, w.y, 0.62), gw.x) * band(f.y, mix(w.z, w.w, 0.2), mix(w.z, w.w, 0.55), gw.y);\n      vec3 cellGlass = mix(dark, glassLit, on) + ${glslLamp('#b967ff')} * uWindow.x * 0.5 * screen * uNight;\n      // Past a pixel per cell the pattern becomes its own mean.\n      vec3 meanGlass = mix(dark, ${glslLamp('#ffcf9a')} * rung(uWindow, 0.5) * 0.8 * (style > 2.5 ? 0.5 : 1.0), litP * uNight);\n      col = mix(col, mix(cellGlass, meanGlass, lod), mask);\n      // Mullions and a transom split each pane, so a lit window never reads as one flat block.\n      float nx = style < 0.5 ? 2.0 : (style < 1.5 ? 1.0 : (style < 2.5 ? 3.0 : 2.0));\n      float mw = 0.07 * nx / cw;\n      float mull = pulse(g.x * nx + 0.5 * mw, 0.0, mw, gw.x * nx);\n      float ty = mix(w.z, w.w, style < 0.5 ? 0.66 : (style < 2.5 ? 0.3 : 0.5));\n      float transom = band(f.y, ty, ty + 0.06 / ch, gw.y) * inRows;\n      col = mix(col, wall * 0.45, clamp(mull + transom, 0.0, 1.0) * mask * step(kind, 4.5));\n      // Concrete blocks wash their crown with sodium floods.\n      if (kind > 4.5 && era < 0.5) emit += ${glslLamp('#ff9326')} * uWindow.x * 0.6 * uNight * (1.0 - mask) * smoothstep(y1, y0, m.y);\n      emit += trim * roofline * band(m.y, y1 - 0.45, y1 - 0.1, fw.y);\n    }\n    // Band edges: a coping line on top, a shadow line below.\n    col = mix(col, wall * 1.4, band(m.y, y1 - 0.14, y1, fw.y) * step(1.5, kind));\n    emit += trim * 0.85 * strips * band(min(m.x, faceW - m.x), 0.0, 0.22, fw.x) * step(2.5, kind);\n    // Street light (lamps, signs, shop glass) on the lowest floors.\n    col += uGlow * exp(-m.y / 6.0) * uNight;\n    col += emit;\n  }\n  gl_FragColor = vec4(col, 1.0);\n  #include <tonemapping_fragment>\n  #include <colorspace_fragment>\n  #include <fog_fragment>\n}`\n",
      "type": "registry:component"
    },
    {
      "path": "city/towerGrammar.ts",
      "content": "// Tower's shape grammar: a pure function from props and seed to a massing plan (podium, setback,\n// shaft, crown), the facade bands on every face, and the state of every shop bay. The mesh\n// builder and the kit emitter both read the plan, so the shader's bays and the props hung on\n// them always agree.\n\nimport { pick, range, rng } from '@runek/core'\nimport { Color } from 'three'\nimport { emissiveColor } from './glow'\nimport { TRIM_NEON } from './towerLight'\n\nexport type TowerWindows = 'grid' | 'office' | 'ribbon' | 'glass'\nexport type TowerEra = 'concrete' | 'tenement' | 'glass' | 'makeshift'\nexport type TowerFace = '+z' | '+x' | '-z' | '-x'\n\n/** Faces in the order the grammar walks them: each is a quarter turn about Y from the last. */\nexport const FACES: TowerFace[] = ['+z', '+x', '-z', '-x']\nexport const ERAS: TowerEra[] = ['concrete', 'tenement', 'glass', 'makeshift']\nconst STYLES: TowerWindows[] = ['grid', 'office', 'ribbon', 'glass']\n\n/** Storey heights, a street-level shop floor, and the podium and setback a tower is seeded with, in metres. */\nconst STOREY = { residential: 3.1, office: 3.8 }\nconst SHOP_FLOOR = 4.5\nconst PODIUM: [number, number] = [15, 25]\nconst SETBACK: [number, number] = [3, 6]\n\n/** Per window style: cell width, storey height, and the pane's place in its cell (x0, x1, y0, y1 as shares). The facade shader carries the same pane table. */\nexport const WINDOW_CELLS = [\n  { w: 2.4, storey: STOREY.residential, pane: [0.2, 0.8, 0.29, 0.76] },\n  { w: 1.5, storey: STOREY.office, pane: [0.1, 0.9, 0.3, 0.8] },\n  { w: 3.0, storey: 3.4, pane: [0, 1, 0.3, 0.74] },\n  { w: 3.0, storey: STOREY.office, pane: [0.03, 0.97, 0.05, 0.95] },\n] as const\n\n/** Facade band kinds, as the shader numbers them. */\nexport const BAND = {\n  plain: 0,\n  street: 1,\n  service: 2,\n  podium: 3,\n  tower: 4,\n  crown: 5,\n  roof: 6,\n} as const\n/** Shop bay states. */\nexport const BAY = { shop: 0, shutter: 1, dark: 2, door: 3 } as const\n/** The piers between street bays: how far they stand off the wall and how high they reach, in metres. */\nexport const PIER = { proud: 0.3, top: 3.5 } as const\n\nexport interface WindowBand {\n  y0: number\n  y1: number\n  storey: number\n  rows: number\n}\n\nexport interface FacePlan {\n  /** 0 to 3, an index into FACES. */\n  index: number\n  /** Whether this face fronts a street and carries kit props. */\n  front: boolean\n  /** Width at the ground. */\n  width: number\n  bays: number\n  bayW: number\n  /** One BAY state per bay, left to right as seen from the street. */\n  states: number[]\n  /** Bays that anchor a knot of detail: a lit shop with its signs. */\n  knots: number[]\n  seed: number\n}\n\nexport interface TowerPlan {\n  seed: number\n  w: number\n  d: number\n  h: number\n  era: number\n  /** Window style of the shaft, and of the podium under it. */\n  style: number\n  podStyle: number\n  lit: number\n  /** Trim hex, or `none`. */\n  trim: string\n  strips: boolean\n  shopfronts: boolean\n  /** Podium height. Equals `h` when the tower has no shaft. */\n  podium: number\n  hasShaft: boolean\n  /** Setback of the shaft from the podium edge, along X and along Z. */\n  inset: [number, number]\n  streetH: number\n  pod: WindowBand | null\n  shaftBand: WindowBand | null\n  /** Height of the service band at the podium top and at the shaft base. */\n  serviceH: number\n  crownH: number\n  faces: FacePlan[]\n  /** Index of the main street face (the first one listed in `frontage`), or -1. It carries the big sign, the light and the cables. */\n  main: number\n  /** 0 to 1, the per-tower random the shader mixes into its hashes. */\n  sd: number\n}\n\nexport interface TowerPlanInput {\n  seed: number\n  width: number\n  depth: number\n  height: number\n  windows?: TowerWindows\n  lit?: number\n  trim?: string\n  cornerStrips?: boolean\n  shopfronts: boolean\n  era?: TowerEra\n  /** Podium height in metres, for a tower with a shaft. Seeded when unset. */\n  podium?: number\n  frontage: TowerFace[]\n}\n\nfunction fit(y0: number, y1: number, storey: number): WindowBand | null {\n  if (y1 - y0 < 2.6) return null\n  const rows = Math.max(1, Math.round((y1 - y0) / storey))\n  return { y0, y1, storey: (y1 - y0) / rows, rows }\n}\n\n/** The largest setback a side of `size` metres allows while leaving a shaft at least 7 m wide. */\nfunction insetFor(size: number, want: number) {\n  const most = (size - 7) / 2\n  if (most < 1.5) return 0\n  return Math.min(want, most)\n}\n\n/** Every seeded decision about one tower. Pure: the same input always gives the same plan. */\nexport function planTower(p: TowerPlanInput): TowerPlan {\n  const r = rng(p.seed)\n  const seededStyle = pick(r, STYLES)\n  const lit = p.lit ?? range(r, 0.08, 0.3)\n  const trim = p.trim ?? (r() < 0.45 ? pick(r, TRIM_NEON) : 'none')\n  const strips = p.cornerStrips ?? (trim !== 'none' && r() < 0.3)\n  const sd = r()\n  // A seed builds a concrete block, a tenement or a makeshift tower. A glass slab stands out, so\n  // it is only ever asked for.\n  const eraName = p.era ?? pick(r, ['concrete', 'tenement', 'tenement', 'makeshift'] as TowerEra[])\n  const era = ERAS.indexOf(eraName)\n\n  // Each era has its own glazing: punched windows on a concrete block, curtain wall on a glass slab.\n  let styleName = p.windows ?? seededStyle\n  if (!p.windows) {\n    if (eraName === 'glass') styleName = 'glass'\n    else if (eraName === 'concrete' && styleName === 'glass') styleName = 'grid'\n    else if (eraName === 'tenement' && styleName === 'glass') styleName = 'ribbon'\n    else if (eraName === 'makeshift' && styleName === 'glass') styleName = 'office'\n  }\n  const style = STYLES.indexOf(styleName)\n  const podStyle = style === 3 ? 1 : style\n\n  const { width: w, depth: d, height: h } = p\n  const streetH = p.shopfronts ? Math.min(SHOP_FLOOR, h * 0.5) : 0\n  const hasShaft = h >= 34 && Math.min(w, d) >= 10\n  let podium = h\n  let inset: [number, number] = [0, 0]\n  const podiumWant =\n    eraName === 'concrete' ? range(r, 20, PODIUM[1]) : range(r, PODIUM[0], PODIUM[1])\n  const setWant = range(r, SETBACK[0], SETBACK[1])\n  const slab = r()\n  if (hasShaft) {\n    podium =\n      p.podium !== undefined\n        ? Math.min(Math.max(p.podium, 8), h - 12)\n        : Math.min(podiumWant, h * 0.5)\n    // A glass slab is thin one way. Everything else steps back evenly, a concrete block the least.\n    const want = eraName === 'concrete' ? SETBACK[0] : setWant\n    inset = [insetFor(w, want), insetFor(d, want)]\n    if (eraName === 'glass')\n      inset = slab < 0.5 ? [insetFor(w, 6), insetFor(d, 3)] : [insetFor(w, 3), insetFor(d, 6)]\n  }\n\n  const serviceH = podium >= 12 ? 1.4 : 0\n  const parapet = 1.0\n  const pod = fit(streetH, podium - serviceH - parapet, WINDOW_CELLS[podStyle].storey)\n  const crownH = hasShaft ? [5.2, 3.6, 6.4, 3.0][era] : 0\n  const shaftBand = hasShaft\n    ? fit(podium + serviceH, h - crownH - 0.8, WINDOW_CELLS[style].storey)\n    : null\n\n  const faces: FacePlan[] = FACES.map((face, index) => {\n    const width = index % 2 === 0 ? w : d\n    const bays = Math.min(11, Math.max(1, Math.round(width / 5)))\n    const front = p.frontage.includes(face)\n    const seed = r()\n    const states: number[] = []\n    const knots: number[] = []\n    if (front) {\n      // One knot per 10 m of frontage: a lit shop, with the door beside it when there is room.\n      const count = Math.max(1, Math.round(width / 10))\n      for (let b = 0; b < bays; b++) states.push(-1)\n      for (let k = 0; k < count; k++) {\n        const at = Math.min(bays - 1, Math.floor(((k + 0.15 + r() * 0.7) * bays) / count))\n        if (states[at] === -1) {\n          states[at] = BAY.shop\n          knots.push(at)\n        }\n      }\n      const first = knots[0]\n      const door = first + 1 < bays && states[first + 1] === -1 ? first + 1 : first - 1\n      if (bays >= 3 && door >= 0 && states[door] === -1) states[door] = BAY.door\n      for (let b = 0; b < bays; b++) {\n        if (states[b] !== -1) continue\n        const q = r()\n        states[b] = q < 0.22 ? BAY.shop : q < 0.62 ? BAY.shutter : BAY.dark\n      }\n    } else {\n      for (let b = 0; b < bays; b++) {\n        const q = r()\n        states.push(q < 0.4 ? BAY.shop : q < 0.72 ? BAY.shutter : q < 0.9 ? BAY.dark : BAY.door)\n      }\n    }\n    return { index, front, width, bays, bayW: width / bays, states, knots, seed }\n  })\n\n  return {\n    seed: p.seed,\n    w,\n    d,\n    h,\n    era,\n    style,\n    podStyle,\n    lit,\n    trim,\n    strips,\n    shopfronts: p.shopfronts,\n    podium,\n    hasShaft,\n    inset,\n    streetH,\n    pod,\n    shaftBand,\n    serviceH,\n    crownH,\n    faces,\n    main: p.frontage.length ? FACES.indexOf(p.frontage[0]) : -1,\n    sd,\n  }\n}\n\n// ---------------------------------------------------------------------------------------------\n// Mesh\n\n/** The tower mesh's vertex data. Every attribute is a plain float array, so towers merge in the static batcher. */\nexport class FacadeMesh {\n  position: number[] = []\n  normal: number[] = []\n  aUv: number[] = []\n  aRect: number[] = []\n  aCell: number[] = []\n  aWall: number[] = []\n  aTrim: number[] = []\n  aLook: number[] = []\n  index: number[] = []\n\n  /** One quad. Corners run counter-clockwise seen from outside, starting bottom left. */\n  quad(\n    corners: number[][],\n    n: number[],\n    uv: number[][],\n    rect: number[],\n    cell: number[],\n    wall: Color,\n    trim: Color,\n    look: number[],\n  ) {\n    const base = this.position.length / 3\n    for (let i = 0; i < 4; i++) {\n      this.position.push(corners[i][0], corners[i][1], corners[i][2])\n      this.normal.push(n[0], n[1], n[2])\n      this.aUv.push(uv[i][0], uv[i][1])\n      this.aRect.push(rect[0], rect[1], rect[2], rect[3])\n      this.aCell.push(cell[0], cell[1], cell[2], cell[3])\n      this.aWall.push(wall.r, wall.g, wall.b)\n      this.aTrim.push(trim.r, trim.g, trim.b)\n      this.aLook.push(look[0], look[1], look[2], look[3])\n    }\n    this.index.push(base, base + 1, base + 2, base, base + 2, base + 3)\n  }\n}\n\ninterface Band {\n  y0: number\n  y1: number\n  kind: number\n  /** Flags: 1 corner strips, 2 a trim line under the top edge, 4 a tube over lit shop bays. */\n  flags?: number\n  cell?: (face: number, width: number) => number[]\n}\n\nconst NORMALS = [\n  [0, 0, 1],\n  [1, 0, 0],\n  [0, 0, -1],\n  [-1, 0, 0],\n]\nconst ZERO = [0, 0, 0, 0]\nconst BLACK = new Color(0, 0, 0)\n\n/** A point on side `face` of a box centred (cx, cz) sized (w, d): `u` metres along it, `out` metres proud of it. */\nexport function onFace(\n  face: number,\n  cx: number,\n  cz: number,\n  w: number,\n  d: number,\n  u: number,\n  out = 0,\n): [number, number] {\n  if (face === 0) return [cx - w / 2 + u, cz + d / 2 + out]\n  if (face === 1) return [cx + w / 2 + out, cz + d / 2 - u]\n  if (face === 2) return [cx + w / 2 - u, cz - d / 2 - out]\n  return [cx - w / 2 - out, cz - d / 2 + u]\n}\n\n/** Build the tower's merged mesh from its plan. */\nexport function buildTower(plan: TowerPlan, wallHex: string): FacadeMesh {\n  const mesh = new FacadeMesh()\n  const { w, d, h, podium, inset, era, sd } = plan\n  const trim = plan.trim === 'none' ? BLACK : emissiveColor(plan.trim, 1)\n  const wall = new Color(wallHex)\n  // The shaft is a shade apart from its podium. A glass slab is cold and dark.\n  const shaftWall =\n    era === 2\n      ? wall.clone().lerp(new Color('#262b33'), 0.7)\n      : wall.clone().multiplyScalar(era === 0 ? 0.86 : 0.92)\n  const dark = wall.clone().multiplyScalar(0.8)\n  const strips = plan.strips ? 1 : 0\n  const fseed = (face: number) => plan.faces[face].seed\n\n  /** The four walls of a volume, one quad per band per face. */\n  const walls = (cx: number, cz: number, vw: number, vd: number, bands: Band[], color: Color) => {\n    for (let f = 0; f < 4; f++) {\n      const width = f % 2 === 0 ? vw : vd\n      for (const b of bands) {\n        if (b.y1 - b.y0 < 0.01) continue\n        const [ax, az] = onFace(f, cx, cz, vw, vd, 0)\n        const [bx, bz] = onFace(f, cx, cz, vw, vd, width)\n        mesh.quad(\n          [\n            [ax, b.y0, az],\n            [bx, b.y0, bz],\n            [bx, b.y1, bz],\n            [ax, b.y1, az],\n          ],\n          NORMALS[f],\n          [\n            [0, b.y0],\n            [width, b.y0],\n            [width, b.y1],\n            [0, b.y1],\n          ],\n          [width, b.y0, b.y1, b.kind],\n          b.cell ? b.cell(f, width) : ZERO,\n          color,\n          trim,\n          [sd, era, fseed(f), b.flags ?? 0],\n        )\n      }\n    }\n  }\n\n  /** A flat top at height y: a roof, or the plain top of a slab. */\n  const top = (\n    x0: number,\n    x1: number,\n    z0: number,\n    z1: number,\n    y: number,\n    kind: number,\n    color: Color,\n    flags = 0,\n  ) => {\n    const roof = kind === BAND.roof\n    mesh.quad(\n      [\n        [x0, y, z1],\n        [x1, y, z1],\n        [x1, y, z0],\n        [x0, y, z0],\n      ],\n      [0, 1, 0],\n      roof\n        ? [\n            [0, z1 - z0],\n            [x1 - x0, z1 - z0],\n            [x1 - x0, 0],\n            [0, 0],\n          ]\n        : [\n            [0, y],\n            [0, y],\n            [0, y],\n            [0, y],\n          ],\n      roof ? [x1 - x0, z1 - z0, 0, kind] : [x1 - x0, y - 0.1, y, kind],\n      ZERO,\n      color,\n      trim,\n      [sd, era, 0, flags],\n    )\n  }\n\n  /** A plain box: slabs, cornices, piers, balconies, rooftop plant. `skip` names faces to leave out (0 to 3 sides, 4 top, 5 bottom). */\n  const block = (\n    x0: number,\n    x1: number,\n    y0: number,\n    y1: number,\n    z0: number,\n    z1: number,\n    color: Color,\n    skip: number[] = [],\n    flags = 0,\n    roofTop = false,\n  ) => {\n    const cx = (x0 + x1) / 2\n    const cz = (z0 + z1) / 2\n    for (let f = 0; f < 4; f++) {\n      if (skip.includes(f)) continue\n      const width = f % 2 === 0 ? x1 - x0 : z1 - z0\n      const [ax, az] = onFace(f, cx, cz, x1 - x0, z1 - z0, 0)\n      const [bx, bz] = onFace(f, cx, cz, x1 - x0, z1 - z0, width)\n      mesh.quad(\n        [\n          [ax, y0, az],\n          [bx, y0, bz],\n          [bx, y1, bz],\n          [ax, y1, az],\n        ],\n        NORMALS[f],\n        [\n          [0, y0],\n          [width, y0],\n          [width, y1],\n          [0, y1],\n        ],\n        [width, y0, y1, BAND.plain],\n        ZERO,\n        color,\n        trim,\n        [sd, era, 0, flags],\n      )\n    }\n    if (!skip.includes(4)) top(x0, x1, z0, z1, y1, roofTop ? BAND.roof : BAND.plain, color)\n    if (!skip.includes(5)) {\n      mesh.quad(\n        [\n          [x0, y0, z0],\n          [x1, y0, z0],\n          [x1, y0, z1],\n          [x0, y0, z1],\n        ],\n        [0, -1, 0],\n        [\n          [0, y0],\n          [0, y0],\n          [0, y0],\n          [0, y0],\n        ],\n        [x1 - x0, y0, y0 + 0.1, BAND.plain],\n        ZERO,\n        color,\n        trim,\n        [sd, era, 0, 0],\n      )\n    }\n  }\n\n  /** A box set against side `face` of the ground footprint: from u0 to u1 along it, `out` metres proud. */\n  const onWall = (\n    face: number,\n    u0: number,\n    u1: number,\n    y0: number,\n    y1: number,\n    out: number,\n    color: Color,\n    skip: number[] = [],\n  ) => {\n    const [ax, az] = onFace(face, 0, 0, w, d, u0, 0)\n    const [bx, bz] = onFace(face, 0, 0, w, d, u1, out)\n    // Never draw the side that sits against the wall.\n    block(Math.min(ax, bx), Math.max(ax, bx), y0, y1, Math.min(az, bz), Math.max(az, bz), color, [\n      (face + 2) % 4,\n      ...skip,\n    ])\n  }\n\n  const windowCell =\n    (style: number, band: WindowBand, share: number) => (_f: number, width: number) => {\n      const cols = Math.max(1, Math.round(width / WINDOW_CELLS[style].w))\n      return [width / cols, band.storey, share, style]\n    }\n  const streetCell = (f: number) => {\n    const face = plan.faces[f]\n    let bits = 0\n    face.states.forEach((s, i) => {\n      bits += s * 4 ** i\n    })\n    return [face.bayW, bits, 0, 0]\n  }\n\n  // Podium (or the whole building when it has no shaft).\n  const podTop = podium - 1.0\n  const bands: Band[] = []\n  if (plan.streetH > 0)\n    bands.push({ y0: 0, y1: plan.streetH, kind: BAND.street, cell: streetCell, flags: 4 })\n  if (plan.pod) {\n    bands.push({\n      y0: plan.pod.y0,\n      y1: plan.pod.y1,\n      kind: BAND.podium,\n      cell: windowCell(plan.podStyle, plan.pod, plan.lit),\n      flags: plan.hasShaft ? 0 : strips,\n    })\n    if (plan.serviceH > 0) bands.push({ y0: plan.pod.y1, y1: podTop, kind: BAND.service })\n  } else {\n    bands.push({ y0: plan.streetH, y1: podTop, kind: BAND.plain })\n  }\n  bands.push({ y0: podTop, y1: podium, kind: BAND.plain, flags: 2 })\n  walls(0, 0, w, d, bands, wall)\n  top(-w / 2, w / 2, -d / 2, d / 2, podium, BAND.roof, wall, plan.hasShaft ? 0 : 2)\n  // A cornice under the parapet gives the podium a shadow line.\n  if (podium >= 12)\n    block(-w / 2 - 0.25, w / 2 + 0.25, podTop - 0.3, podTop, -d / 2 - 0.25, d / 2 + 0.25, dark)\n\n  const sw = w - inset[0] * 2\n  const sdp = d - inset[1] * 2\n  if (plan.hasShaft && plan.shaftBand) {\n    const sb = plan.shaftBand\n    const crown0 = h - plan.crownH - 0.8\n    walls(\n      0,\n      0,\n      sw,\n      sdp,\n      [\n        { y0: podium, y1: sb.y0, kind: BAND.service },\n        {\n          y0: sb.y0,\n          y1: sb.y1,\n          kind: BAND.tower,\n          cell: windowCell(plan.style, sb, plan.lit),\n          flags: strips,\n        },\n        {\n          y0: crown0,\n          y1: h - 0.8,\n          kind: BAND.crown,\n          cell: (_f, width) => [\n            width / Math.max(1, Math.round(width / (era === 2 ? 3 : 2.2))),\n            plan.crownH,\n            0.55,\n            era === 2 ? 3 : 0,\n          ],\n          flags: strips,\n        },\n        { y0: h - 0.8, y1: h, kind: BAND.plain, flags: 2 },\n      ],\n      shaftWall,\n    )\n    top(-sw / 2, sw / 2, -sdp / 2, sdp / 2, h, BAND.roof, shaftWall, 2)\n    // A slab between shaft and crown. Heavy on a concrete block, a thin fin on a glass slab.\n    const over = [0.6, 0.3, 0.12, 0.2][era]\n    block(\n      -sw / 2 - over,\n      sw / 2 + over,\n      crown0 - 0.35,\n      crown0,\n      -sdp / 2 - over,\n      sdp / 2 + over,\n      dark,\n    )\n  }\n\n  // What stands on the roof, by era.\n  const r = rng(plan.seed * 31 + 7)\n  const roofY = h\n  const rw = plan.hasShaft ? sw : w\n  const rd = plan.hasShaft ? sdp : d\n  if (era === 0 && plan.hasShaft) {\n    // Concrete: a stepped block, the crown stepping in again.\n    block(\n      -rw / 2 + 1.5,\n      rw / 2 - 1.5,\n      roofY,\n      roofY + 3.2,\n      -rd / 2 + 1.5,\n      rd / 2 - 1.5,\n      shaftWall,\n      [5],\n      2,\n      true,\n    )\n  } else if (era === 2) {\n    // Glass: a plant screen and a mast.\n    block(-rw * 0.3, rw * 0.3, roofY, roofY + 2.2, -rd * 0.3, rd * 0.3, shaftWall, [5], 0, true)\n    const mx = range(r, -rw * 0.2, rw * 0.2)\n    block(mx - 0.25, mx + 0.25, roofY + 2.2, roofY + range(r, 11, 20), -0.25, 0.25, dark, [5])\n  } else {\n    // Tenement and makeshift: plant rooms and shacks, off centre.\n    const shacks = era === 3 ? 3 : 1 + Math.floor(r() * 2)\n    for (let i = 0; i < shacks; i++) {\n      const bw = range(r, 2.5, Math.max(3, rw * 0.4))\n      const bd = range(r, 2.5, Math.max(3, rd * 0.4))\n      const bx = range(r, -rw / 2 + bw / 2 + 0.6, rw / 2 - bw / 2 - 0.6)\n      const bz = range(r, -rd / 2 + bd / 2 + 0.6, rd / 2 - bd / 2 - 0.6)\n      block(\n        bx - bw / 2,\n        bx + bw / 2,\n        roofY,\n        roofY + range(r, 2.2, 4.4),\n        bz - bd / 2,\n        bz + bd / 2,\n        i % 2 ? dark : shaftWall,\n        [5],\n        0,\n        true,\n      )\n    }\n  }\n\n  // Street faces get real relief: piers between the bays, a fascia over them, balconies above.\n  for (const face of plan.faces) {\n    if (!face.front || plan.streetH < 4) continue\n    const f = face.index\n    for (let b = 0; b <= face.bays; b++) {\n      const u = b * face.bayW\n      onWall(\n        f,\n        Math.max(0, u - 0.28),\n        Math.min(face.width, u + 0.28),\n        0,\n        PIER.top,\n        PIER.proud,\n        dark,\n        [4, 5],\n      )\n    }\n    onWall(f, 0, face.width, PIER.top, plan.streetH, 0.45, dark)\n    if (era === 1 && plan.pod) {\n      // Tenement: stacked balconies with solid fronts, one run per storey.\n      const rows = Math.min(plan.pod.rows, 6)\n      for (let row = 1; row < rows; row++) {\n        const y = plan.pod.y0 + row * plan.pod.storey\n        const lead = range(r, 0.6, 2.4)\n        const tail = range(r, 0.6, 2.4)\n        if (face.width - lead - tail > 3)\n          onWall(f, lead, face.width - tail, y - 0.12, y + 0.92, 1.0, row % 2 ? wall : dark)\n      }\n    }\n  }\n  return mesh\n}\n",
      "type": "registry:component"
    },
    {
      "path": "city/towerKit.ts",
      "content": "// What Tower hangs on its street faces, at the district's density rules: per 10 m of frontage\n// one shop bay with two to four sign elements, AC units under the windows above it, and a cable\n// crossing every 10 to 15 m. Detail gathers in knots around the lit shops and the door beside\n// them. The bays between stay calm: a shutter, dark glass, a painted code.\n\nimport { pick, range, rng } from '@runek/core'\nimport { GLOW, type KitBuilder } from './kit'\nimport {\n  acUnit,\n  awning,\n  bladeSign,\n  bladeWord,\n  cableSag,\n  cableY,\n  drumLantern,\n  fasciaSign,\n  pipeRun,\n  rollerShutter,\n  roofSign,\n  stencilCode,\n  vendingMachine,\n  vent,\n} from './kitParts'\nimport { BAY, onFace, PIER, type TowerPlan, WINDOW_CELLS } from './towerGrammar'\nimport { shopLamp } from './towerLight'\n\n/** Sign lamps by era. */\nconst ERA_LAMPS = [\n  ['#ff9326', '#ff6418'],\n  ['#ffa64d', '#39ff88', '#b967ff', '#ff6418'],\n  ['#f4f6fb', '#ffcf9a'],\n  ['#b8e8c8', '#7a3cff', '#f6f2ea', '#39ff88'],\n]\nconst AWNINGS = ['#5a2a1c', '#2f3a2c', '#3a2f45', '#4a3a28', '#3d2224']\nconst MACHINES = ['#3a2f45', '#40332a', '#2c3530', '#4a2a22']\n\nconst WHO = [\n  'DOT',\n  'MARA',\n  'TULLY',\n  'VESK',\n  'IONA',\n  'BRAM',\n  'NELL',\n  'PIKE',\n  'OMA',\n  'LUCE',\n  'HARL',\n  'QUILL',\n  'SABLE',\n  'ORRIN',\n  'WREN',\n  'CASS',\n]\nconst WHAT = [\n  'NOODLE',\n  'FIXES',\n  'TEA',\n  'PAWN',\n  'KEYS',\n  'LAMPS',\n  'BUNKS',\n  'SOUP',\n  'TAILOR',\n  'CELLS',\n  'RADIO',\n  'PARTS',\n  'LOCKS',\n  'CUTS',\n  'COILS',\n  'DICE',\n  'BROTH',\n  'TUBES',\n  'SHOES',\n  'SCRAP',\n]\nconst NOTES = [\n  'ALL WINDOWS',\n  'OPEN LATE',\n  'BY THE HOUR',\n  'UPSTAIRS',\n  'NO CREDIT',\n  'BACK ROOM',\n  'ASK INSIDE',\n]\nconst SECTORS = 'LKRSNG'\n/** How far over the ground light on the street is drawn: clear of a pavement's top and of a wet street's deck. */\nconst STREET = 0.045\nconst DIGITS = '01234568'\n\n/** A shop name: proprietor, then offer. */\nexport function shopName(r: () => number) {\n  return `${pick(r, WHO)} ${pick(r, WHAT)}`\n}\n\n/** A painted block code, like `K3-08`. The stencil set has no seven. */\nexport function sectorCode(r: () => number) {\n  const d = () => DIGITS[Math.floor(r() * DIGITS.length)]\n  return `${SECTORS[Math.floor(r() * SECTORS.length)]}${d()}-${d()}${d()}`\n}\n\nexport interface TowerKitOptions {\n  /** The shop name on the tower's main sign. Seeded when unset. */\n  name?: string\n  /** Wall to wall distance across the street, for cable crossings. 0 for none. */\n  cableSpan: number\n  /** The time a glass tower's crown shows, like `21:40`. */\n  clock: string\n  /** How far the ground in front of each face stands above the tower's base (a pavement is a step up from the road), by face. Light on the street lies on it. */\n  street?: readonly number[]\n}\n\n/** The name on a tower's main sign: the one it was given, or one from its seed. */\nconst nameOf = (plan: TowerPlan, name?: string) => name ?? shopName(rng(plan.seed * 13 + 5))\n\n/** A tower's faces with the main one first, so the tower's name lands on it. */\nconst mainFirst = (plan: TowerPlan) =>\n  [...plan.faces].sort((a, b) => Number(b.index === plan.main) - Number(a.index === plan.main))\n\n/**\n * The shop a tower is known by: the name on its main sign, and where that shop's front stands in\n * the tower's local space, at the ground and `out` metres off the wall. It walks the faces the way\n * `towerKit` does, so the two agree on which shop that is. Null when no shop carries the name.\n */\nexport function mainShop(\n  plan: TowerPlan,\n  name?: string,\n  out = 0,\n): { name: string; at: [number, number, number] } | null {\n  if (plan.streetH < 4) return null\n  for (const face of mainFirst(plan)) {\n    if (!face.front) continue\n    const bay = face.knots.find((b) => face.states[b] === BAY.shop)\n    if (bay === undefined) continue\n    const [x, z] = onFace(face.index, 0, 0, plan.w, plan.d, (bay + 0.5) * face.bayW, out)\n    return { name: nameOf(plan, name), at: [x, 0, z] }\n  }\n  return null\n}\n\n/** Add every prop and sign of one tower to `kit`, in the tower's local space. */\nexport function towerKit(kit: KitBuilder, plan: TowerPlan, o: TowerKitOptions) {\n  const { w, d, era } = plan\n  const lamps = ERA_LAMPS[era]\n  const main = plan.trim !== 'none' ? plan.trim : lamps[0]\n  const mainName = nameOf(plan, o.name)\n  let named = false\n\n  for (const face of mainFirst(plan)) {\n    if (!face.front || plan.streetH < 4) continue\n    const r = rng(plan.seed * 17 + face.index * 101 + 3)\n    const [ox, oz] = onFace(face.index, 0, 0, w, d, 0)\n    kit.push(ox, 0, oz, (face.index * Math.PI) / 2)\n    const { bayW, bays, width } = face\n    const proud = 0.45 // the fascia stands this far off the wall\n    const street = (o.street?.[face.index] ?? 0) + STREET\n    // The piers stand 0.3 m off the wall up to the fascia. One slab along the face at that depth,\n    // so a walker slides along the pier line instead of catching on each pier.\n    kit.solid(width / 2, PIER.top / 2, PIER.proud / 2, width, PIER.top, PIER.proud)\n\n    for (let b = 0; b < bays; b++) {\n      const state = face.states[b]\n      const u0 = b * bayW\n      const uc = u0 + bayW / 2\n      const knot = face.knots.includes(b)\n      // What a lit shop's glass leaves on the pavement: its own lamp colour, brighter for a\n      // brighter shop, less with the shutter part way down.\n      const shopLight = (open: number) => {\n        const lamp = shopLamp(plan.sd, face.seed, b)\n        kit.lightSplat(uc, street, PIER.proud, bayW + 1.6, 3.6, lamp.color, {\n          t: (0.3 + 0.5 * lamp.level) * open,\n        })\n      }\n      if (state === BAY.shop && knot) {\n        const name = named ? shopName(r) : mainName\n        const color = named ? pick(r, lamps) : main\n        named = true\n        // The name on the fascia, a tube under it, and the blade sign that carries it down the street.\n        // The board may spill over a calm bay next door, never over another shop's fascia, and\n        // it stays clear of the face ends so two names never collide on a corner.\n        const spill = (n: number) =>\n          n >= 0 && n < bays && face.states[n] !== BAY.shop ? bayW * 0.35 : 0\n        const lo = Math.max(0.7, u0 - spill(b - 1))\n        const hi = Math.min(width - 0.7, u0 + bayW + spill(b + 1))\n        const fit = hi - lo - 0.3\n        const cx = (lo + hi) / 2\n        fasciaSign(kit, cx, 4.0, proud, name, {\n          letter: range(r, 0.45, 0.6),\n          color,\n          fit,\n          tube: era === 1 && r() < 0.35,\n        })\n        kit.box(false, uc, 3.44, proud - 0.04, bayW - 0.7, 0.05, 0.05, color, {\n          glow: GLOW.tube,\n          t: 0.08,\n        })\n        shopLight(1)\n        const bladeU = r() < 0.5 ? u0 + 0.05 : u0 + bayW - 0.05\n        const top = Math.max(8, plan.podium - 1.5)\n        const letter = Math.min(\n          range(r, 0.55, 0.75),\n          (top - 5.2) / (bladeWord(name).length * 1.28 + 0.3),\n        )\n        if (letter > 0.3)\n          bladeSign(kit, Math.min(width - 0.1, Math.max(0.1, bladeU)), 4.9, 0, bladeWord(name), {\n            letter,\n            color,\n            gap: era === 1 ? 1.15 : 0.45,\n          })\n        if (r() < 0.65)\n          awning(kit, uc, range(r, 2.95, 3.2), 0.3, bayW - 0.8, {\n            depth: range(r, 1.1, 1.5),\n            color: pick(r, AWNINGS),\n            stripes: r() < 0.6,\n          })\n        // A small tube notice in the window.\n        kit.text(pick(r, NOTES), uc + range(r, -0.6, 0.6), 2.82, 0.04, 0.17, pick(r, lamps), {\n          outline: false,\n          glow: GLOW.tube,\n          t: 0.02,\n        })\n        // A machine against the calm bay next door.\n        const side =\n          b + 1 < bays && face.states[b + 1] !== BAY.shop\n            ? 1\n            : b > 0 && face.states[b - 1] !== BAY.shop\n              ? -1\n              : 0\n        if (side !== 0 && face.states[b + side] !== BAY.door && r() < 0.7) {\n          vendingMachine(kit, uc + side * (bayW / 2 + 1.0), 0, 0.02, {\n            seed: r(),\n            color: pick(r, MACHINES),\n            lamp: pick(r, ['#ffcf9a', '#b8e8c8', '#ffa64d']),\n          })\n        }\n      } else if (state === BAY.shop) {\n        if (r() < 0.6)\n          fasciaSign(kit, uc, 4.0, proud, shopName(r), {\n            letter: 0.38,\n            color: pick(r, lamps),\n            fit: bayW - 0.6,\n          })\n        let open = 1\n        // Two draws in turn: a shutter part way down, or failing that an awning.\n        const shutter = r() < 0.3\n        if (shutter) {\n          open = range(r, 0.4, 0.7)\n          rollerShutter(kit, uc, 0.38, 0.0, bayW - 0.76, 2.92, { open })\n        } else if (r() < 0.3) awning(kit, uc, 3.1, 0.3, bayW - 0.8, { color: pick(r, AWNINGS) })\n        shopLight(open)\n      } else if (state === BAY.shutter) {\n        kit.box(true, uc, 3.42, 0.1, bayW - 0.7, 0.2, 0.18, '#4a4844')\n        if (r() < 0.45)\n          stencilCode(kit, uc + range(r, -0.5, 0.5), range(r, 1.6, 2.3), 0, sectorCode(r))\n        if (r() < 0.3) vent(kit, u0 + 0.9, 2.7, 0, { width: 0.5, height: 0.36 })\n      } else if (state === BAY.door) {\n        // The service knot: a lamp over the door, its code, a riser and a meter.\n        kit.box(false, uc, 2.86, 0.06, 0.6, 0.07, 0.1, '#ffa64d', { glow: GLOW.tube, t: 0.02 })\n        kit.lightSplat(uc, street, 0.06, 2.4, 1.7, '#ffa64d', { t: 0.25 })\n        stencilCode(kit, uc, 3.12, 0, sectorCode(r))\n        const pipeU = uc - Math.min(1.5, bayW / 2 - 0.55)\n        pipeRun(kit, pipeU, 0.15, 0, 3.3)\n        pipeRun(kit, pipeU, plan.streetH, 0, Math.max(1, plan.podium - 1.0 - plan.streetH))\n        if (era === 3)\n          pipeRun(\n            kit,\n            pipeU + 0.2,\n            plan.streetH + 0.2,\n            0,\n            Math.max(1, plan.podium - 3 - plan.streetH),\n            { radius: 0.04, color: '#5a4234' },\n          )\n        const meterU = uc + Math.min(1.5, bayW / 2 - 0.6)\n        kit.box(true, meterU, 1.45, 0.08, 0.45, 0.6, 0.16, '#6b6f70', { detail: 6 })\n        kit.box(true, meterU, 0.75, 0.06, 0.34, 0.4, 0.12, '#4a4844', { detail: 6 })\n        vent(kit, meterU, 2.5, 0, { width: 0.55, height: 0.4 })\n      }\n    }\n\n    // Tenement: a drum lantern at the lot line.\n    if (era === 1)\n      drumLantern(kit, 0.32, 3.1, 0.3, { color: pick(r, ['#ffa64d', '#ffa64d', '#ff6418']) })\n    // Concrete: the block's number, painted large on its podium.\n    if (era === 0 && plan.pod && plan.pod.rows >= 2) {\n      stencilCode(\n        kit,\n        Math.min(width - 2.5, 3.2),\n        plan.pod.y1 - plan.pod.storey * 0.5,\n        0,\n        sectorCode(r).slice(0, 2),\n        { letter: Math.min(2.2, plan.pod.storey * 0.6), color: '#8a8478' },\n      )\n    }\n\n    // AC units under the windows above each knot, a few strays elsewhere.\n    if (plan.pod) {\n      const cell = WINDOW_CELLS[plan.podStyle]\n      const cols = Math.max(1, Math.round(width / cell.w))\n      const cw = width / cols\n      const rows = Math.min(plan.pod.rows, 5)\n      for (let row = 0; row < rows; row++) {\n        for (let c = 0; c < cols; c++) {\n          const u = (c + 0.5) * cw\n          const overKnot = face.knots.some((k) => u > k * bayW - 0.2 && u < (k + 1) * bayW + 0.2)\n          const chance = (overKnot ? 0.62 : 0.1) + (era === 3 ? 0.15 : 0) - row * 0.06\n          const q = r()\n          const q2 = r()\n          if (q > chance) continue\n          // On a balconied front the unit hangs off the balcony.\n          const balcony = era === 1 && row >= 1 && u > 2.5 && u < width - 2.5\n          const y =\n            plan.pod.y0 +\n            row * plan.pod.storey +\n            (balcony ? 0.05 : Math.max(0.1, cell.pane[2] * plan.pod.storey - 0.68))\n          acUnit(kit, u + (q2 - 0.5) * cw * 0.3, y, balcony ? 1.0 : 0, {\n            seed: q2,\n            cage: era === 3 && q2 < 0.6,\n          })\n        }\n      }\n    }\n\n    // Cable crossings from the main face, one every 10 to 15 m. A tenement street hangs lanterns on some of them.\n    if (o.cableSpan > 0 && face.index === plan.main) {\n      const count = Math.max(1, Math.round(width / 12.5))\n      for (let k = 0; k < count; k++) {\n        const u = ((k + 0.25 + r() * 0.5) * width) / count\n        const y = Math.min(range(r, 6.5, 11), Math.max(5.5, plan.podium - 2))\n        const drop = range(r, -1.2, 1.2)\n        const sag = o.cableSpan * range(r, 0.035, 0.07)\n        cableSag(kit, u, y, 0, o.cableSpan, { sag, drop })\n        const strands = era === 3 ? 2 : r() < 0.4 ? 1 : 0\n        for (let s = 0; s < strands; s++)\n          cableSag(kit, u + range(r, -0.5, 0.5), y + range(r, -0.6, 0.4), 0, o.cableSpan, {\n            sag: sag * range(r, 0.7, 1.5),\n            drop: drop + range(r, -0.5, 0.5),\n            thickness: 0.03,\n          })\n        if (era === 1 && r() < 0.6) {\n          const color = pick(r, lamps)\n          for (const t of [0.3, 0.5, 0.7]) {\n            const ly = y + cableY(t, sag, drop) - 0.34\n            kit.box(false, u, ly, t * o.cableSpan, 0.34, 0.44, 0.34, color, {\n              glow: GLOW.sign,\n              t: 0.18,\n            })\n            kit.box(true, u, ly + 0.25, t * o.cableSpan, 0.4, 0.06, 0.4, '#141110')\n          }\n        }\n      }\n    }\n\n    // One large sign per tower, on its main street face: letters tall enough to read from 100 m.\n    if (face.index === plan.main) {\n      const text = mainName\n      const set = face.index % 2 === 0 ? plan.inset[1] : plan.inset[0]\n      if (era === 1 || era === 3) {\n        if (plan.hasShaft && set >= 2)\n          roofSign(kit, width / 2, plan.podium, -0.5, text, {\n            letter: range(r, 1.6, 2.1),\n            color: main,\n            fit: width - 1.5,\n          })\n        else if (plan.podium >= 12)\n          roofSign(kit, width / 2, plan.podium, -0.4, bladeWord(text), {\n            letter: 1.5,\n            color: main,\n            fit: width - 1.5,\n          })\n      } else if (era === 0 && plan.podium >= 14) {\n        // Concrete: a tall blade on the corner, stencil cut.\n        const word = bladeWord(text)\n        const letter = Math.min(1.6, (plan.podium - 7.5) / (word.length * 1.28 + 0.3))\n        if (letter >= 0.8)\n          bladeSign(kit, width - 0.4, 6.2, 0, word, { letter, color: main, gap: 0.5 })\n      }\n    }\n    kit.pop()\n  }\n\n  // Glass: the crown shows the time on all four sides, white over a line of blue.\n  if (era === 2 && plan.hasShaft) {\n    const sw = w - plan.inset[0] * 2\n    const sdp = d - plan.inset[1] * 2\n    const y = plan.h - 0.8 - plan.crownH / 2\n    for (let f = 0; f < 4; f++) {\n      const fw = f % 2 === 0 ? sw : sdp\n      if (fw < 7) continue\n      const [ox, oz] = onFace(f, 0, 0, sw, sdp, 0)\n      kit.push(ox, 0, oz, (f * Math.PI) / 2)\n      const letter = Math.min(plan.crownH * 0.52, fw / 5)\n      kit.box(false, fw / 2, y, 0.04, letter * 4.4, letter * 1.7, 0.08, '#0c0d10')\n      kit.text(o.clock, fw / 2, y + letter * 0.08, 0.1, letter, '#f4f6fb', {\n        t: 0.6,\n        body: true,\n        tracking: 0.1,\n      })\n      kit.box(false, fw / 2, y - letter * 0.72, 0.1, letter * 3.9, 0.07, 0.05, '#3d5bff', {\n        glow: GLOW.tube,\n        t: 0.05,\n      })\n      kit.pop()\n    }\n  }\n}\n\n/** Where a street-face light sits, in the tower's local space: in front of its first knot. */\nexport function knotLight(plan: TowerPlan): [number, number, number] | null {\n  const face = plan.faces[plan.main]\n  if (!face) return null\n  const knot = face.knots[0] ?? 0\n  const [x, z] = onFace(face.index, 0, 0, plan.w, plan.d, (knot + 0.5) * face.bayW, 1.6)\n  return [x, 3.3, z]\n}\n",
      "type": "registry:component"
    },
    {
      "path": "nodes/tower.ts",
      "content": "// Tower's facade as a TSL node material, for WebGPURenderer (which cannot draw the ShaderMaterial\n// in Tower.tsx). It reads the same per-vertex data and draws the same bands, bay states, window\n// cells, lit shares and trims, so both renderers show the same city. It is a simpler facade:\n// no box filtering of edges, no interior mapping behind glass, no decal slots (posters, stickers,\n// leak streaks, cracks), no blinds or screens in rooms, no mullions, sills, storey courses or\n// grime. Scene fog and tone mapping come from the node system.\n\nimport { shareMaterial } from '@runek/core'\nimport {\n  abs,\n  attribute,\n  dot,\n  exp,\n  Fn,\n  float,\n  floor,\n  fract,\n  If,\n  min,\n  mix,\n  mod,\n  pow,\n  select,\n  sin,\n  smoothstep,\n  step,\n  varying,\n  vec2,\n  vec3,\n  vec4,\n} from 'three/tsl'\nimport { MeshBasicNodeMaterial, type Node } from 'three/webgpu'\nimport { emissiveColor } from '../city/glow'\nimport { SHOP_LAMPS, WINDOW_LAMPS } from '../city/towerLight'\nimport { towerNodeUniforms as U } from './city'\n\n/** GLSL's classic `fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453)`. */\nconst hash21 = (p: Node<'vec2'>) => fract(sin(dot(p, vec2(12.9898, 78.233))).mul(43758.5453))\n\n/** A point along a ladder rung, spaced evenly on a log scale. */\nconst rung = (r: Node<'vec2'>, t: Node<'float'>) => r.x.mul(pow(r.y.div(r.x), t))\n\n/** 1 inside [a, b]. */\nconst inside = (x: Node<'float'>, a: number | Node<'float'>, b: number | Node<'float'>) =>\n  step(a, x).mul(step(x, b))\n\n/** A cumulative lamp table as a select chain, black past the last share. */\nfunction lampTable(r: Node<'float'>, table: [number, string][]) {\n  let out: Node<'vec3'> = vec3(0)\n  for (let i = table.length - 1; i >= 0; i--) {\n    const c = emissiveColor(table[i][1], 1)\n    out = select(r.lessThan(table[i][0]), vec3(c.r, c.g, c.b), out)\n  }\n  return out\n}\n\n/** A per-quad attribute, passed flat so packed values (the bay states) arrive exact. */\nconst flat = <T extends 'vec3' | 'vec4'>(name: string, type: T) => {\n  const v = varying(attribute<T>(name, type)) as unknown as Node<T> & {\n    setInterpolation(kind: string): unknown\n  }\n  v.setInterpolation('flat')\n  return v as Node<T>\n}\n\nconst lampOf = (hex: string) => {\n  const c = emissiveColor(hex, 1)\n  return vec3(c.r, c.g, c.b)\n}\n\nfunction towerColor(night: number) {\n  return Fn(() => {\n    const m = attribute<'vec2'>('aUv', 'vec2')\n    const rect = flat('aRect', 'vec4')\n    const cellData = flat('aCell', 'vec4')\n    const look = flat('aLook', 'vec4')\n    const trimColor = flat('aTrim', 'vec3')\n    const wallColor = flat('aWall', 'vec3')\n    const ny = attribute<'vec3'>('normal', 'vec3').y\n    const n = float(night)\n\n    const kind = rect.w\n    const faceW = rect.x\n    const y0 = rect.y\n    const y1 = rect.z\n    const sd = look.x\n    const era = look.y\n    const fseed = look.z\n    const strips = mod(look.w, 2)\n    const roofline = mod(floor(look.w.mul(0.5)), 2)\n    const fasciaTube = mod(floor(look.w.mul(0.25)), 2)\n    const wall = wallColor.mul(mix(float(0.35), U.wallGain, n))\n    const trim = trimColor.mul(U.trim).mul(n)\n    const col = vec3(wall).toVar()\n    const glow = U.glow.mul(exp(m.y.max(0).negate().div(6))).mul(n)\n    const side = step(abs(ny), 0.5)\n\n    If(kind.greaterThan(5.5), () => {\n      // Roof: darker, with the trim color along its edges after dusk.\n      const ed = min(m, rect.xy.sub(m))\n      col.assign(wall.mul(0.6).add(trim.mul(roofline).mul(step(min(ed.x, ed.y), 0.35))))\n    })\n      .ElseIf(kind.lessThan(0.5), () => {\n        // Plain trim: slabs, cornices, parapets, rooftop boxes.\n        col.assign(\n          wall.mul(\n            select(\n              ny.greaterThan(0.5),\n              float(0.75),\n              select(ny.lessThan(-0.5), float(0.4), float(1)),\n            ),\n          ),\n        )\n        col.addAssign(\n          trim\n            .mul(roofline)\n            .mul(inside(m.y, y1.sub(0.4), y1.sub(0.12)))\n            .mul(side),\n        )\n        col.addAssign(glow.mul(side))\n      })\n      .ElseIf(kind.lessThan(1.5), () => {\n        // Street: shop bays between piers under a fascia.\n        const bayW = cellData.x\n        const bi = floor(m.x.div(bayW))\n        const xm = fract(m.x.div(bayW)).mul(bayW)\n        const state = mod(floor(cellData.y.div(pow(float(4), bi)).add(0.01)), 4)\n        const r = hash21(vec2(bi, sd.mul(13.1).add(fseed)))\n        const open = inside(xm, 0.38, bayW.sub(0.38)).mul(inside(m.y, 0.38, 3.3))\n        col.assign(mix(col, wall.mul(0.55), inside(m.y, 3.5, 4.38)))\n        col.assign(mix(col, wall.mul(0.7), step(m.y, 0.3)))\n        const lamp = lampTable(r.mul(SHOP_LAMPS[SHOP_LAMPS.length - 1][0]), SHOP_LAMPS)\n          .mul(rung(U.shop, hash21(vec2(bi.add(3), sd.add(fseed.mul(5))))))\n          .mul(mix(0.08, 1.0, n))\n        const lit = lamp\n          .mul(float(0.62).add(smoothstep(0.3, 3.3, m.y).mul(0.38)))\n          .mul(mix(1, 0.35, inside(m.y, 0.38, 1.05)))\n        const shutter = wall\n          .mul(mix(0.9, 1.9, hash21(vec2(bi.add(11), sd))))\n          .mul(mix(0.6, 1.0, step(0.32, fract(m.y.div(0.12)))))\n        const dark = vec3(0.01, 0.009, 0.008).add(\n          vec3(0.02, 0.012, 0.007).mul(float(1).sub(m.y.div(3.3))),\n        )\n        const door = inside(xm, bayW.mul(0.5).sub(0.62), bayW.mul(0.5).add(0.62))\n        const blank = mix(wall, wall.mul(0.42), door.mul(step(m.y, 2.3))).add(\n          lamp\n            .mul(0.5)\n            .mul(door)\n            .mul(inside(m.y, 2.38, 2.7)),\n        )\n        const bay = select(\n          state.lessThan(0.5),\n          lit,\n          select(state.lessThan(1.5), shutter, select(state.lessThan(2.5), dark, blank)),\n        )\n        col.assign(mix(col, bay, open))\n        col.addAssign(\n          trim\n            .mul(fasciaTube)\n            .mul(step(state, 0.5))\n            .mul(inside(m.y, 3.42, 3.5))\n            .mul(inside(xm, 0.2, bayW.sub(0.2))),\n        )\n        col.addAssign(glow)\n      })\n      .ElseIf(kind.lessThan(2.5), () => {\n        // Service: louvres.\n        col.assign(wall.mul(mix(0.45, 0.8, step(0.45, fract(m.y.div(0.16))))))\n        col.addAssign(glow)\n      })\n      .Else(() => {\n        // Windows. The cell holds (cell width, storey height, lit share, style).\n        const cw = cellData.x\n        const ch = cellData.y\n        const style = cellData.w\n        const crown = kind.greaterThan(4.5)\n        const raisingCrown = crown.and(era.lessThan(0.5))\n        const indexCrown = crown.and(era.greaterThan(1.5)).and(era.lessThan(2.5))\n        const litP = select(indexCrown, float(1), cellData.z)\n        const g = vec2(m.x.div(cw), m.y.sub(y0).div(ch))\n        const cell = floor(g)\n        const f = fract(g)\n        const rows = floor(y1.sub(y0).div(ch).add(0.01))\n        const r = hash21(cell.add(vec2(sd.mul(31.7), fseed.mul(7.3))))\n        const r2 = hash21(cell.mul(1.7).add(vec2(sd, fseed.add(9.1))))\n        const pane = select(\n          raisingCrown,\n          vec4(0.38, 0.62, 0.12, 0.9),\n          select(\n            indexCrown,\n            vec4(0.02, 0.98, 0.1, 0.92),\n            select(\n              style.lessThan(0.5),\n              vec4(0.2, 0.8, 0.29, 0.76),\n              select(\n                style.lessThan(1.5),\n                vec4(0.1, 0.9, 0.3, 0.8),\n                select(style.lessThan(2.5), vec4(0, 1, 0.3, 0.74), vec4(0.03, 0.97, 0.05, 0.95)),\n              ),\n            ),\n          ),\n        )\n        const mask = inside(f.x, pane.x, pane.y)\n          .mul(inside(f.y, pane.z, pane.w))\n          .mul(step(g.y, rows))\n        const on = step(float(1).sub(litP), r).mul(n)\n        const lamp = select(\n          indexCrown,\n          lampOf('#f4f6fb').mul(rung(U.window, float(0.9))),\n          lampTable(r2, WINDOW_LAMPS).mul(rung(U.window, hash21(cell.add(vec2(9.1, sd))))),\n        )\n          .mul(select(style.greaterThan(2.5), float(0.5), float(1)))\n          .mul(0.85)\n        const dark = mix(\n          vec3(0.2, 0.24, 0.3),\n          vec3(0.01, 0.009, 0.008).add(vec3(0.012, 0.007, 0.004).mul(float(1).sub(f.y))),\n          n,\n        )\n        col.assign(mix(col, mix(dark, lamp, on), mask))\n        col.assign(mix(col, wall.mul(1.4), step(y1.sub(0.14), m.y)))\n        col.addAssign(trim.mul(roofline).mul(inside(m.y, y1.sub(0.45), y1.sub(0.1))))\n        col.addAssign(\n          trim\n            .mul(0.85)\n            .mul(strips)\n            .mul(step(min(m.x, faceW.sub(m.x)), 0.22)),\n        )\n        col.addAssign(glow)\n      })\n    return col\n  })()\n}\n\nconst materials = new Map<number, MeshBasicNodeMaterial>()\n\n/** One node material per (rounded) night level, shared by every tower and marked shared for the\n *  static batcher, as on WebGL. */\nexport function towerNodeMaterial(night: number) {\n  let m = materials.get(night)\n  if (!m) {\n    m = new MeshBasicNodeMaterial()\n    m.colorNode = towerColor(night)\n    m.fog = true\n    m.name = `runek:tower:${night}`\n    materials.set(night, shareMaterial(m))\n  }\n  return m\n}\n",
      "type": "registry:component"
    }
  ]
}
