{
  "name": "crowd",
  "title": "Crowd",
  "type": "registry:component",
  "description": "People on a street in bulk: hooded figures in long coats walking their lanes there and back, each with one small light at the collar, stepping round the player. Where each walks comes from the world clock and `seed` alone, so every viewer sees the same crowd. Three instanced draws however many walk; no colliders.",
  "dependencies": [
    "@react-three/fiber@^9.6.1",
    "@runek/core@^0.18.0",
    "three@^0.184.0"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "Crowd.tsx",
      "content": "import { useFrame } from '@react-three/fiber'\nimport { Dynamic, rng, skipMirrors, useWorld, type Vec3 } from '@runek/core'\nimport { useEffect, useMemo, useRef } from 'react'\nimport {\n  BoxGeometry,\n  type BufferGeometry,\n  CircleGeometry,\n  Color,\n  CylinderGeometry,\n  Float32BufferAttribute,\n  type Group,\n  type InstancedMesh,\n  LatheGeometry,\n  MeshBasicMaterial,\n  MeshStandardMaterial,\n  Object3D,\n  SphereGeometry,\n  Vector2,\n  Vector3,\n} from 'three'\nimport { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js'\nimport { emissiveColor, useLadder } from './city/glow'\nimport { hash2 } from './city/hash'\n\n/** A path a crowd walks, there and back: a height and the corners it goes through, in units. */\nexport interface CrowdLane {\n  /** The ground along it. */\n  y: number\n  /** Its corners, each [x, z]. */\n  points: [number, number][]\n}\n\nexport interface CrowdProps {\n  /** Where the lanes' origin stands [x, y, z] in units: lanes are in the node's own frame. */\n  position?: Vec3\n  /** Rotation [x, y, z] in radians, turning the lanes with it. */\n  rotation?: Vec3\n  /** Deals out each walker: which lane, where on it, how fast, how tall, what they wear. */\n  seed?: number\n  /** How many walk. */\n  count?: number\n  /** The paths they walk, in the node's frame. A walker keeps to one lane, going to its end and\n   *  back. One 16-unit lane along X by default. */\n  lanes?: CrowdLane[]\n  /** Slowest and fastest a walker goes, in units a second. */\n  speed?: [number, number]\n  /** How far to either side of its lane a walker keeps, in units, so a crowd is not a queue. */\n  spread?: number\n  /** How far round the player a walker steps aside, in units. 0 for none. */\n  berth?: number\n}\n\n/** Coats: dark cloth, as the district wears it. */\nconst COATS = ['#16141c', '#1d1f22', '#2a120c', '#33363b', '#42464a', '#20242a']\n/** The one lit thing each of them carries: a tag at the collar, in a lamp color. */\nconst TAGS = ['#ffa64d', '#ff6418', '#39ff88', '#b967ff', '#f4f6fb', '#dfe8ff']\n\ninterface Walker {\n  lane: number\n  offset: number\n  speed: number\n  aside: number\n  tall: number\n  stride: number\n}\n\ninterface Path {\n  y: number\n  /** Corners in world units, and the length walked by each one. */\n  x: number[]\n  z: number[]\n  at: number[]\n  length: number\n}\n\n/** A box with every vertex painted one shade of grey, for a part the instance color tints. */\nfunction shade<G extends BufferGeometry>(g: G, v: number): G {\n  const n = g.attributes.position.count\n  g.setAttribute('color', new Float32BufferAttribute(new Float32Array(n * 3).fill(v), 3))\n  return g\n}\n\n/**\n * A hooded figure in a long coat, a metre and three quarters tall, standing on the ground at\n * the origin and facing +Z: the coat, the hood, the dark where a face would be, and two sleeves.\n * One mesh. The legs are separate, so they can swing.\n */\nfunction coatGeometry(): BufferGeometry {\n  const profile = [\n    [0.2, 0.34],\n    [0.19, 0.6],\n    [0.165, 0.98],\n    [0.19, 1.3],\n    [0.2, 1.4],\n    [0.1, 1.47],\n    [0.0, 1.48],\n  ].map(([r, y]) => new Vector2(r, y))\n  const coat = shade(new LatheGeometry(profile, 10).scale(1, 1, 0.72), 1)\n  const hood = shade(\n    new SphereGeometry(0.135, 10, 8).scale(1, 1.12, 1.05).translate(0, 1.6, -0.01),\n    0.82,\n  )\n  const face = shade(new CircleGeometry(0.085, 10).translate(0, 1.59, 0.128), 0.04)\n  const sleeve = (side: number) =>\n    shade(new CylinderGeometry(0.05, 0.045, 0.6, 6).translate(side * 0.235, 1.06, 0), 0.9)\n  const parts = [coat, hood, face, sleeve(1), sleeve(-1)].map((g) => g.toNonIndexed())\n  for (const g of parts) g.deleteAttribute('uv')\n  return mergeGeometries(parts)\n}\n\n/**\n * People on the street, in bulk: hooded figures in long coats walking their lanes there and back,\n * each with one small light at the collar. Where each one is comes from the world clock and\n * `seed` alone (contract §2), so every player sees the same crowd and nothing is simulated or\n * sent. They are scenery: no collider, nobody to talk to, and the server knows nothing of them.\n * A walker steps aside for the player rather than walk through them.\n *\n * Three instanced draws however many walk (coats, legs, collar lights), left out of the world's\n * mirrors.\n * Lit like any matte surface, so lamps, signs and fog carry them. Built as a far tier: up close\n * they are a shape in a coat with no face under the hood, and a world that wants a face puts a\n * `Person` there.\n */\nexport function Crowd({\n  position = [0, 0, 0],\n  rotation = [0, 0, 0],\n  seed = 1,\n  count = 24,\n  lanes = DEFAULT_LANES,\n  speed = [0.9, 1.5],\n  spread = 0.9,\n  berth = 1.3,\n}: CrowdProps) {\n  const { unit, player, now = Date.now } = useWorld()\n  const root = useRef<Group>(null)\n  const ladder = useLadder()\n  const coats = useRef<InstancedMesh>(null)\n  const legs = useRef<InstancedMesh>(null)\n  const tags = useRef<InstancedMesh>(null)\n  const total = Math.max(0, Math.round(count))\n  const [slow, fast] = speed\n  const lanesKey = JSON.stringify(lanes)\n\n  const paths = useMemo<Path[]>(() => {\n    const given = JSON.parse(lanesKey) as CrowdLane[]\n    return given\n      .filter((lane) => lane.points.length > 1)\n      .map((lane) => {\n        const x = lane.points.map((p) => p[0] * unit)\n        const z = lane.points.map((p) => p[1] * unit)\n        const at = [0]\n        for (let i = 1; i < x.length; i++)\n          at.push(at[i - 1] + Math.hypot(x[i] - x[i - 1], z[i] - z[i - 1]))\n        return { y: lane.y * unit, x, z, at, length: at[at.length - 1] }\n      })\n      .filter((path) => path.length > 0)\n  }, [lanesKey, unit])\n\n  const walkers = useMemo<Walker[]>(() => {\n    if (!paths.length) return []\n    const r = rng(seed)\n    const whole = paths.reduce((sum, path) => sum + path.length, 0)\n    return Array.from({ length: total }, () => {\n      // Longer lanes carry more of the crowd.\n      let pick = r() * whole\n      let lane = 0\n      while (lane < paths.length - 1 && pick > paths[lane].length) pick -= paths[lane++].length\n      const tall = 0.92 + r() * 0.14\n      return {\n        lane,\n        offset: r() * paths[lane].length * 2,\n        speed: (slow + r() * (fast - slow)) * unit,\n        aside: (r() * 2 - 1) * spread * unit,\n        tall,\n        stride: 1.35 * tall * unit,\n      }\n    })\n  }, [paths, seed, total, slow, fast, spread, unit])\n\n  const made = useMemo(() => {\n    const coat = coatGeometry().scale(unit, unit, unit)\n    // A leg hangs from its top, so it swings about the hip.\n    const leg = shade(\n      new BoxGeometry(0.1 * unit, 0.5 * unit, 0.12 * unit).translate(0, -0.25 * unit, 0),\n      1,\n    )\n    const tag = new BoxGeometry(0.05 * unit, 0.03 * unit, 0.02 * unit)\n    const cloth = new MeshStandardMaterial({\n      color: '#ffffff',\n      vertexColors: true,\n      roughness: 0.92,\n      metalness: 0,\n    })\n    const light = new MeshBasicMaterial({ color: '#ffffff', toneMapped: false })\n    return { coat, leg, tag, cloth, light }\n  }, [unit])\n  useEffect(\n    () => () => {\n      for (const part of Object.values(made)) part.dispose()\n    },\n    [made],\n  )\n\n  // What each one wears is dealt once. Only where they are changes from frame to frame.\n  useEffect(() => {\n    const tint = new Color()\n    for (let i = 0; i < walkers.length; i++) {\n      const coat = tint.set(COATS[Math.floor(hash2(seed + 11, i) * COATS.length)])\n      coats.current?.setColorAt(i, coat)\n      // Trousers and shoes: the coat's cloth, darker.\n      legs.current?.setColorAt(i * 2, tint.multiplyScalar(0.6))\n      legs.current?.setColorAt(i * 2 + 1, tint)\n      tags.current?.setColorAt(\n        i,\n        emissiveColor(TAGS[Math.floor(hash2(seed + 23, i) * TAGS.length)], ladder.signFace[0]),\n      )\n    }\n    for (const mesh of [coats.current, legs.current, tags.current]) {\n      if (!mesh) continue\n      if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true\n    }\n  }, [walkers, seed, ladder.signFace, made])\n\n  const at = useMemo(() => new Object3D(), [])\n  const self = useMemo(() => new Vector3(), [])\n  useFrame(() => {\n    const coat = coats.current\n    const leg = legs.current\n    const tag = tags.current\n    if (!coat || !leg || !tag) return\n    const seconds = now() / 1000\n    const anchor = player?.current\n    // The player in the crowd's own frame, where the lanes are.\n    if (anchor) root.current?.worldToLocal(anchor.getWorldPosition(self))\n    for (let i = 0; i < walkers.length; i++) {\n      const w = walkers[i]\n      const path = paths[w.lane]\n      // There and back: a point that runs the lane's length and returns.\n      const lap =\n        (((w.offset + w.speed * seconds) % (path.length * 2)) + path.length * 2) % (path.length * 2)\n      const back = lap > path.length\n      const along = back ? path.length * 2 - lap : lap\n      let k = 1\n      while (k < path.at.length - 1 && path.at[k] < along) k++\n      const span = path.at[k] - path.at[k - 1] || 1\n      const t = (along - path.at[k - 1]) / span\n      const dx = (path.x[k] - path.x[k - 1]) / span\n      const dz = (path.z[k] - path.z[k - 1]) / span\n      let x = path.x[k - 1] + dx * span * t\n      let z = path.z[k - 1] + dz * span * t\n      // Turn round at an end over the last half metre, not in a blink.\n      const tip = Math.min(along, path.length - along)\n      const turned =\n        tip < 0.5 * unit\n          ? (1 - tip / (0.5 * unit)) * (Math.PI / 2) * (along < path.length / 2 === back ? -1 : 1)\n          : 0\n      const heading = Math.atan2(dx, dz) + (back ? Math.PI : 0) + turned\n      // Keep to one side of the lane, and step round the player.\n      let aside = w.aside\n      if (anchor && berth > 0) {\n        const px = self.x - x\n        const pz = self.z - z\n        const off = px * dz - pz * dx\n        const near = Math.hypot(px, pz)\n        const reach = berth * 2.2 * unit\n        if (\n          near < reach &&\n          Math.abs(self.y - path.y) < 2.5 * unit &&\n          Math.abs(off - aside) < berth * unit\n        ) {\n          const push = (1 - near / reach) * berth * unit\n          aside += off > aside ? -push : push\n        }\n      }\n      x += dz * aside\n      z -= dx * aside\n      const phase = (along / w.stride) * Math.PI * 2\n      const bob = Math.abs(Math.sin(phase)) * 0.025 * w.tall * unit\n\n      at.position.set(x, path.y + bob, z)\n      at.rotation.set(0, heading, 0)\n      at.scale.setScalar(w.tall * unit)\n      at.updateMatrix()\n      coat.setMatrixAt(i, at.matrix)\n\n      const sin = Math.sin(heading)\n      const cos = Math.cos(heading)\n      at.position.set(\n        x + sin * 0.118 * w.tall * unit,\n        path.y + bob + 1.36 * w.tall * unit,\n        z + cos * 0.118 * w.tall * unit,\n      )\n      at.updateMatrix()\n      tag.setMatrixAt(i, at.matrix)\n\n      for (let side = 0; side < 2; side++) {\n        const out = (side ? -0.085 : 0.085) * w.tall * unit\n        at.position.set(x + cos * out, path.y + bob + 0.5 * w.tall * unit, z - sin * out)\n        at.rotation.set(Math.sin(phase + side * Math.PI) * 0.55, heading, 0, 'YXZ')\n        at.updateMatrix()\n        leg.setMatrixAt(i * 2 + side, at.matrix)\n      }\n      at.rotation.order = 'XYZ'\n    }\n    coat.instanceMatrix.needsUpdate = true\n    leg.instanceMatrix.needsUpdate = true\n    tag.instanceMatrix.needsUpdate = true\n  })\n\n  // Walkers move every frame: a reflection of them would only trail.\n  useEffect(() => skipMirrors(root.current), [walkers.length])\n\n  if (!walkers.length) return null\n  return (\n    <Dynamic>\n      <group ref={root} position={position} rotation={rotation}>\n        <instancedMesh\n          ref={coats}\n          args={[made.coat, made.cloth, walkers.length]}\n          frustumCulled={false}\n        />\n        <instancedMesh\n          ref={legs}\n          args={[made.leg, made.cloth, walkers.length * 2]}\n          frustumCulled={false}\n        />\n        <instancedMesh\n          ref={tags}\n          args={[made.tag, made.light, walkers.length]}\n          frustumCulled={false}\n        />\n      </group>\n    </Dynamic>\n  )\n}\n\nconst DEFAULT_LANES: CrowdLane[] = [\n  {\n    y: 0,\n    points: [\n      [-8, 0],\n      [8, 0],\n    ],\n  },\n]\n\nCrowd.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"
    },
    {
      "path": "city/hash.ts",
      "content": "/** A number in [0, 1) from two integers: the same on every machine, with no state. */\nexport function hash2(a: number, b: number): number {\n  let h = Math.imul(a | 0, 0x9e3779b1) ^ Math.imul(b | 0, 0x85ebca6b)\n  h = Math.imul(h ^ (h >>> 15), 0x2c1b3c6d)\n  h = Math.imul(h ^ (h >>> 12), 0x297a2d39)\n  return ((h ^ (h >>> 15)) >>> 0) / 4294967296\n}\n",
      "type": "registry:component"
    }
  ]
}
