{
  "name": "skyline",
  "title": "Skyline",
  "type": "registry:component",
  "description": "A district seen from far off: a band of towers across part of the horizon with a few rooms lit and one landmark (spire, dome or stack) picked out in light, in two draws. Scenery past anywhere a body can reach: no colliders.",
  "dependencies": [
    "@runek/core@^0.18.0",
    "three@^0.184.0"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "Skyline.tsx",
      "content": "import { rng, skipMirrors, useWorld, type Vec3 } from '@runek/core'\nimport { useEffect, useMemo, useRef } from 'react'\nimport {\n  BufferGeometry,\n  Color,\n  DataTexture,\n  DoubleSide,\n  Float32BufferAttribute,\n  type Group,\n  LinearFilter,\n  MeshBasicMaterial,\n  NearestFilter,\n  RepeatWrapping,\n  RGBAFormat,\n  SRGBColorSpace,\n} from 'three'\nimport { emissiveColor, useLadder } from './city/glow'\n\nexport interface SkylineProps {\n  /** Where the skyline is seen from [x, y, z] in units: the middle of the place it rings. */\n  position?: Vec3\n  /** Accepted for the component contract. Turn a skyline with `bearing`. */\n  rotation?: Vec3\n  /** Deals out every tower: where it stands, how tall, how wide, which windows are lit. */\n  seed?: number\n  /** Compass bearing of the middle of the district, in degrees: 0 is +Z, 90 is +X. */\n  bearing?: number\n  /** How many degrees of the horizon it takes up. */\n  spread?: number\n  /** How far off its nearest towers stand, in units. Keep it and `depth` under the camera's far plane. */\n  distance?: number\n  /** How far back the district goes behind that, in units. */\n  depth?: number\n  /** How many towers. */\n  count?: number\n  /** Shortest and tallest tower, in units. */\n  heights?: [number, number]\n  /** What stands over the district: a stepped `spire` with a lit collar, a `dome` in rings, or a squat `stack` with chimneys. */\n  landmark?: 'spire' | 'dome' | 'stack'\n  /** How tall the landmark is, in units. */\n  landmarkHeight?: number\n  /** The color of the landmark's lights. */\n  accent?: string\n  /** Haze color: the world's fog, so the district sinks into the horizon at its foot. */\n  haze?: string\n}\n\n/** The window pattern every skyline shares: a grid of rooms, some of them lit. */\nlet rooms: DataTexture | null = null\nfunction windowTexture(): DataTexture {\n  if (rooms) return rooms\n  const N = 64\n  const r = rng(4242)\n  const lit = [\n    new Color('#ffcf9a'),\n    new Color('#dfe8ff'),\n    new Color('#ffa64d'),\n    new Color('#f4f6fb'),\n  ]\n  const data = new Uint8Array(N * N * 4)\n  for (let i = 0; i < N * N; i++) {\n    const on = r() < 0.11\n    const c = on ? lit[Math.floor(r() * lit.length)] : null\n    // A dark room is a quarter as bright as a lit one, and takes the haze's blue: at this\n    // distance a tower is a shape a little darker than the sky, not a black one.\n    const k = on ? 0.7 + 0.3 * r() : 0.25\n    // Lit rooms are washed out by the air between: half their color, half white.\n    const tone = (v: number | undefined, dark: number) => (v === undefined ? dark : 0.5 + 0.5 * v)\n    data.set(\n      [\n        Math.round(255 * k * tone(c?.r, 0.62)),\n        Math.round(255 * k * tone(c?.g, 0.74)),\n        Math.round(255 * k * tone(c?.b, 1)),\n        255,\n      ],\n      i * 4,\n    )\n  }\n  rooms = new DataTexture(data, N, N, RGBAFormat)\n  rooms.colorSpace = SRGBColorSpace\n  rooms.wrapS = rooms.wrapT = RepeatWrapping\n  rooms.magFilter = NearestFilter\n  rooms.minFilter = LinearFilter\n  rooms.needsUpdate = true\n  return rooms\n}\n\n/** One room of the window pattern is this wide and this tall, in units. */\nconst ROOM = { wide: 5, tall: 4.5 }\n\ninterface Mass {\n  positions: number[]\n  uvs: number[]\n  colors: number[]\n}\n\n/**\n * A box standing on the ground at (x, z), turned to `yaw`, from `y0` up to `y1`: four walls and\n * a roof. Walls are lit from the foot by haze, so `foot` and `head` tint them from bottom to top.\n */\nfunction tower(\n  m: Mass,\n  x: number,\n  z: number,\n  yaw: number,\n  w: number,\n  d: number,\n  y0: number,\n  y1: number,\n  foot: Color,\n  head: Color,\n  shift: number,\n) {\n  const c = Math.cos(yaw)\n  const s = Math.sin(yaw)\n  const corner = (lx: number, lz: number): [number, number] => [\n    x + lx * c + lz * s,\n    z - lx * s + lz * c,\n  ]\n  const ring = [\n    corner(-w / 2, -d / 2),\n    corner(w / 2, -d / 2),\n    corner(w / 2, d / 2),\n    corner(-w / 2, d / 2),\n  ]\n  const lengths = [w, d, w, d]\n  let along = shift\n  for (let i = 0; i < 4; i++) {\n    const a = ring[i]\n    const b = ring[(i + 1) % 4]\n    const u0 = along / ROOM.wide / 64\n    along += lengths[i]\n    const u1 = along / ROOM.wide / 64\n    const v0 = (y0 / ROOM.tall + shift) / 64\n    const v1 = (y1 / ROOM.tall + shift) / 64\n    // Two triangles, wound to face outward.\n    m.positions.push(\n      a[0],\n      y0,\n      a[1],\n      a[0],\n      y1,\n      a[1],\n      b[0],\n      y1,\n      b[1],\n      a[0],\n      y0,\n      a[1],\n      b[0],\n      y1,\n      b[1],\n      b[0],\n      y0,\n      b[1],\n    )\n    m.uvs.push(u0, v0, u0, v1, u1, v1, u0, v0, u1, v1, u1, v0)\n    for (const tint of [foot, head, head, foot, head, foot]) m.colors.push(tint.r, tint.g, tint.b)\n  }\n  // The roof: dark, one texel of the pattern, whatever it holds.\n  const [p0, p1, p2, p3] = ring\n  m.positions.push(\n    p0[0],\n    y1,\n    p0[1],\n    p2[0],\n    y1,\n    p2[1],\n    p1[0],\n    y1,\n    p1[1],\n    p0[0],\n    y1,\n    p0[1],\n    p3[0],\n    y1,\n    p3[1],\n    p2[0],\n    y1,\n    p2[1],\n  )\n  for (let k = 0; k < 6; k++) {\n    m.uvs.push(0.004, 0.004)\n    m.colors.push(head.r * 0.5, head.g * 0.5, head.b * 0.5)\n  }\n}\n\n/**\n * A district seen from far off: towers standing in the haze across the water, with a few rooms\n * lit and one landmark over them. It is scenery only, out past anywhere a body can reach, and\n * it is what tells a small world that it is part of a city.\n *\n * Two draws: every tower in one merged mesh, and the landmark's lights in another. Neither takes\n * the scene's fog, since fog would hide them outright. Each tower is tinted toward `haze` at its\n * foot instead, and its dark rooms sit just under the brightness of a night sky's horizon, so it\n * reads as a silhouette with windows. Both are left out of the world's mirrors. No colliders.\n * Plain `MeshBasicMaterial`s, so it draws the same under `WebGPURenderer`.\n */\nexport function Skyline({\n  position = [0, 0, 0],\n  seed = 1,\n  bearing = 180,\n  spread = 70,\n  distance = 620,\n  depth = 180,\n  count = 60,\n  heights = [50, 170],\n  landmark,\n  landmarkHeight = 380,\n  accent = '#3d5bff',\n  haze = '#1a2238',\n}: SkylineProps) {\n  const { unit } = useWorld()\n  const ladder = useLadder()\n\n  const built = useMemo(() => {\n    const r = rng(seed)\n    const body: Mass = { positions: [], uvs: [], colors: [] }\n    const glow: number[] = []\n    const mid = (bearing * Math.PI) / 180\n    const half = ((spread / 2) * Math.PI) / 180\n    const white = new Color(1, 1, 1)\n    // Haze lifts and blues the foot of every tower toward the horizon's own color.\n    const tint = new Color(haze)\n    const peak = Math.max(tint.r, tint.g, tint.b, 1e-3)\n    const foot = tint.clone().multiplyScalar(1.5 / peak)\n    for (let i = 0; i < count; i++) {\n      const a = mid + (r() * 2 - 1) * half\n      const far = distance + r() * depth\n      // Tall in the middle of the district, low at its edges.\n      const centred = 1 - Math.abs(a - mid) / Math.max(half, 1e-3)\n      const h = heights[0] + (heights[1] - heights[0]) * r() ** 1.6 * (0.45 + 0.55 * centred)\n      const w = 20 + r() * 26\n      const d = 20 + r() * 26\n      tower(\n        body,\n        Math.sin(a) * far,\n        Math.cos(a) * far,\n        a + (r() - 0.5) * 0.5,\n        w,\n        d,\n        -6,\n        h,\n        foot,\n        white,\n        r() * 64,\n      )\n      // A stepped head on some.\n      if (r() < 0.35)\n        tower(\n          body,\n          Math.sin(a) * far,\n          Math.cos(a) * far,\n          a,\n          w * 0.55,\n          d * 0.55,\n          h,\n          h * 1.18,\n          white,\n          white,\n          r() * 64,\n        )\n    }\n    if (landmark) {\n      const far = distance + depth * 0.5\n      const x = Math.sin(mid) * far\n      const z = Math.cos(mid) * far\n      const H = landmarkHeight\n      // A bar of light: a thin box, `wide` round the landmark, at height `y`.\n      const band = (y: number, wide: number, tall: number) => {\n        const m: Mass = { positions: [], uvs: [], colors: [] }\n        tower(m, x, z, mid, wide, wide, y, y + tall, white, white, 0)\n        glow.push(...m.positions)\n      }\n      if (landmark === 'spire') {\n        // The Regulator: three steps to a point, a lit collar where a clock would be, a lamp on top.\n        tower(body, x, z, mid, 64, 64, -6, H * 0.45, foot, white, 3)\n        tower(body, x, z, mid, 44, 44, H * 0.45, H * 0.78, white, white, 9)\n        tower(body, x, z, mid, 22, 22, H * 0.78, H * 0.96, white, white, 17)\n        tower(body, x, z, mid, 5, 5, H * 0.96, H * 1.12, white, white, 0)\n        band(H * 0.8, 50, 4)\n        band(H * 0.455, 68, 2.5)\n        band(H * 1.12, 7, 6)\n      } else if (landmark === 'dome') {\n        // The Orrery: rings stepping in to a crown, each edged in light.\n        const steps = 7\n        for (let k = 0; k < steps; k++) {\n          const t0 = k / steps\n          const t1 = (k + 1) / steps\n          const wide = 150 * Math.cos((t0 * Math.PI) / 2) + 14\n          tower(\n            body,\n            x,\n            z,\n            mid + k * 0.2,\n            wide,\n            wide,\n            k === 0 ? -6 : H * Math.sin((t0 * Math.PI) / 2),\n            H * Math.sin((t1 * Math.PI) / 2),\n            k === 0 ? foot : white,\n            white,\n            k * 7,\n          )\n          if (k % 2 === 1) band(H * Math.sin((t1 * Math.PI) / 2), wide + 4, 1.8)\n        }\n      } else {\n        // Pump One: a squat hall and three chimneys with lit tips.\n        tower(body, x, z, mid, 170, 90, -6, H * 0.4, foot, white, 5)\n        for (const off of [-52, 0, 52]) {\n          const cx = x + Math.cos(mid) * off\n          const cz = z - Math.sin(mid) * off\n          tower(body, cx, cz, mid, 16, 16, H * 0.4, H, white, white, off)\n          const m: Mass = { positions: [], uvs: [], colors: [] }\n          tower(m, cx, cz, mid, 19, 19, H, H + 3, white, white, 0)\n          glow.push(...m.positions)\n        }\n      }\n    }\n    const scale = (list: number[]) =>\n      new Float32BufferAttribute(\n        list.map((v) => v * unit),\n        3,\n      )\n    const towers = new BufferGeometry()\n    towers.setAttribute('position', scale(body.positions))\n    towers.setAttribute('uv', new Float32BufferAttribute(body.uvs, 2))\n    towers.setAttribute('color', new Float32BufferAttribute(body.colors, 3))\n    const lights = new BufferGeometry()\n    lights.setAttribute('position', scale(glow))\n    return { towers, lights: glow.length ? lights : null }\n  }, [seed, bearing, spread, distance, depth, count, heights, landmark, landmarkHeight, haze, unit])\n\n  const materials = useMemo(() => {\n    // A dark room lands at about two thirds of the horizon's glow, so a tower is a shape just\n    // darker than the sky behind it, and a lit one at the foot of the window rung.\n    const walls = new MeshBasicMaterial({\n      map: windowTexture(),\n      vertexColors: true,\n      fog: false,\n      toneMapped: false,\n      side: DoubleSide,\n    })\n    walls.color.setScalar((ladder.skyDome[1] * 0.68) / 0.25)\n    const lit = new MeshBasicMaterial({\n      color: emissiveColor(accent, ladder.signFace[0]),\n      fog: false,\n      toneMapped: false,\n      side: DoubleSide,\n    })\n    return { walls, lit }\n  }, [ladder.windowLit, ladder.signFace, accent])\n  useEffect(\n    () => () => {\n      built.towers.dispose()\n      built.lights?.dispose()\n    },\n    [built],\n  )\n  useEffect(\n    () => () => {\n      materials.walls.dispose()\n      materials.lit.dispose()\n    },\n    [materials],\n  )\n\n  // Too far off to reflect, and two big draws a reflection would only repeat.\n  const root = useRef<Group>(null)\n  useEffect(() => skipMirrors(root.current), [])\n\n  return (\n    <group ref={root} position={position}>\n      <mesh geometry={built.towers} material={materials.walls} frustumCulled={false} />\n      {built.lights && (\n        <mesh geometry={built.lights} material={materials.lit} frustumCulled={false} />\n      )}\n    </group>\n  )\n}\n\nSkyline.stream = false\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"
    }
  ]
}
