{
  "name": "wet-street",
  "title": "WetStreet",
  "type": "registry:component",
  "description": "A rain-soaked asphalt street with kerbs: puddles from world-space noise and in the gutters, darkened glossy asphalt, lane, edge and centre paint, zebras at crossings, and reflections from the world's shared mirror, full in standing water and faint on damp asphalt. A mounted `Rain` rings the puddles and dries and soaks the street with its weather. Decorative: no collider.",
  "dependencies": [
    "@runek/core@^0.18.0",
    "three@^0.184.0"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "WetStreet.tsx",
      "content": "import {\n  type MirrorSurface,\n  useMaterial,\n  useMirrorMaterial,\n  useNodeRenderer,\n  useWorld,\n  type WorldComponentProps,\n} from '@runek/core'\nimport { useMemo } from 'react'\nimport {\n  BoxGeometry,\n  BufferGeometry,\n  Color,\n  Float32BufferAttribute,\n  type WebGLProgramParametersWithUniforms,\n} from 'three'\nimport { RAIN_PERIOD, rainUniforms } from './city/weather'\n\n/** Where a cross street meets this one: its centre along this street, and its width, in units. */\nexport interface StreetCrossing {\n  at: number\n  width: number\n}\n\nexport interface WetStreetProps extends WorldComponentProps {\n  /** Length along local Z, in units. */\n  length?: number\n  /** Width along local X, kerb to kerb, in units. */\n  width?: number\n  /** Asphalt color; defaults to the palette's `stone`. */\n  color?: string\n  /** Kerb color; defaults to the palette's `floor` (the pavement). */\n  kerbColor?: string\n  /** How wet the street is when the weather has soaked it, 0 (dry) to 1 (soaked). */\n  wetness?: number\n  /** How much of the street stands in puddles then, 0 to 1. */\n  puddles?: number\n  /** Paint lane and edge lines, and a zebra at each crossing. */\n  markings?: boolean\n  /** Lane, edge and zebra paint. */\n  paint?: string\n  /** The centre line. */\n  centrePaint?: string\n  /** Cross streets: no kerbs, lines or gutters inside them, a zebra either side. At most four. */\n  crossings?: StreetCrossing[]\n}\n\n/** Most crossings one street can hold. */\nconst MAX_CROSSINGS = 4\n\n/**\n * A wet asphalt street with kerbs, laid in the XZ plane just above the ground, straight along\n * local Z: a `Road` that reads as rain-soaked. Puddles collect from a world-space noise field\n * and in the gutters, wet asphalt darkens and turns glossy (Lagarde's porosity model), paint\n * stays drier, and the deck reflects the street through the world's shared mirror for its\n * height: fully in standing water, faintly on damp asphalt. While a `Rain` is mounted, drops ring\n * the puddles, more of them the harder it rains, and the weather it follows dries the street and\n * its puddles out and soaks them again. Streets that cross should share a `seed`: their puddles\n * then match where they overlap. Decorative, like `Road`: it owns no collider.\n *\n * The puddles, paint and rain rings are `WebGLRenderer` only. Under `WebGPURenderer` the deck is\n * damp asphalt with an even, faint reflection.\n */\nexport function WetStreet({\n  position = [0, 0, 0],\n  rotation = [0, 0, 0],\n  seed = 0,\n  length = 12,\n  width = 7,\n  color,\n  kerbColor,\n  wetness = 0.85,\n  puddles = 0.5,\n  markings = true,\n  paint = '#ece6da',\n  centrePaint = '#c98a3e',\n  crossings = NO_CROSSINGS,\n}: WetStreetProps) {\n  const { unit, palette } = useWorld()\n  const node = useNodeRenderer()\n  const L = length * unit\n  const W = width * unit\n  const kerbW = 0.18 * unit\n  const kerbH = 0.12 * unit\n  const kerb = useMaterial({ slot: 'concrete', color: kerbColor ?? palette.floor, roughness: 0.85 })\n  const cutKey = JSON.stringify(crossings)\n  const cuts = useMemo(\n    () =>\n      crossings\n        .slice(0, MAX_CROSSINGS)\n        .map((c) => ({ at: c.at * unit, half: (c.width * unit) / 2 })),\n    [cutKey, unit],\n  )\n  const deck = useMemo(() => deckGeometry(W, L), [W, L])\n  const kerbs = useMemo(() => kerbSegments(L, cuts), [L, cuts])\n  const surface = useMemo(\n    () =>\n      streetSurface({ wetness, puddles, markings, paint, centrePaint, seed, half: W / 2, cuts }),\n    [wetness, puddles, markings, paint, centrePaint, seed, W, cuts],\n  )\n  // Under WebGPU there is no wet layer to darken the asphalt, so the look does it, as `Road` does.\n  const asphalt = color ?? palette.stone\n  const deckColor = useMemo(\n    () =>\n      node ? `#${new Color(asphalt).multiplyScalar(1 - 0.45 * wetness).getHexString()}` : asphalt,\n    [node, asphalt, wetness],\n  )\n  const deckMaterial = useMirrorMaterial(\n    { slot: 'asphalt', color: deckColor, roughness: node ? 1 - 0.7 * wetness : 0.85, metalness: 0 },\n    node ? 0.25 * wetness : 1,\n    surface,\n  )\n\n  const edge = W / 2 - kerbW / 2\n  return (\n    <group position={[position[0], position[1] + 0.03 * unit, position[2]]} rotation={rotation}>\n      <mesh geometry={deck} material={deckMaterial} receiveShadow />\n      {[edge, -edge].map((x) =>\n        kerbs.map(([z, len]) => (\n          <mesh\n            key={`${x}:${z}`}\n            material={kerb}\n            position={[x, kerbH / 2, z]}\n            geometry={kerbGeometry(kerbW, kerbH, len)}\n            receiveShadow\n          />\n        )),\n      )}\n    </group>\n  )\n}\n\nconst NO_CROSSINGS: StreetCrossing[] = []\n\n/** A flat deck with street coordinates (across, along) in meters, which survive batching. */\nfunction deckGeometry(w: number, l: number) {\n  const g = new BufferGeometry()\n  const x = w / 2\n  const z = l / 2\n  g.setAttribute(\n    'position',\n    new Float32BufferAttribute([-x, 0, z, x, 0, z, x, 0, -z, -x, 0, -z], 3),\n  )\n  g.setAttribute('normal', new Float32BufferAttribute([0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0], 3))\n  g.setAttribute('uv', new Float32BufferAttribute([0, 0, 1, 0, 1, 1, 0, 1], 2))\n  g.setAttribute('aStreet', new Float32BufferAttribute([-x, z, x, z, x, -z, -x, -z], 2))\n  g.setIndex([0, 1, 2, 0, 2, 3])\n  return g\n}\n\n/** Kerb runs as [centre z, length], broken where cross streets come in. */\nfunction kerbSegments(l: number, cuts: { at: number; half: number }[]): [number, number][] {\n  const gaps = cuts.map((c) => [c.at - c.half, c.at + c.half] as const).sort((a, b) => a[0] - b[0])\n  const out: [number, number][] = []\n  let from = -l / 2\n  for (const [a, b] of gaps) {\n    if (a > from + 0.01) out.push([(from + Math.min(a, l / 2)) / 2, Math.min(a, l / 2) - from])\n    from = Math.max(from, b)\n  }\n  if (l / 2 > from + 0.01) out.push([(from + l / 2) / 2, l / 2 - from])\n  return out\n}\n\nconst kerbCache = new Map<string, BoxGeometry>()\nfunction kerbGeometry(w: number, h: number, l: number) {\n  const key = `${w}:${h}:${l.toFixed(3)}`\n  let g = kerbCache.get(key)\n  if (!g) {\n    g = new BoxGeometry(w, h, l)\n    kerbCache.set(key, g)\n  }\n  return g\n}\n\ninterface StreetLook {\n  wetness: number\n  puddles: number\n  markings: boolean\n  paint: string\n  centrePaint: string\n  seed: number\n  half: number\n  cuts: { at: number; half: number }[]\n}\n\n/** The street's own shader edits over the mirror material, and how strongly each pixel reflects:\n *  standing water fully, damp asphalt faintly. One program for every street. */\nfunction streetSurface(look: StreetLook): MirrorSurface {\n  const v3 = (hex: string) => new Color(hex)\n  const cuts = Array.from({ length: MAX_CROSSINGS }, (_, i) => look.cuts[i] ?? { at: 1e6, half: 0 })\n  const uniforms = {\n    uWet: { value: look.wetness },\n    uPuddles: { value: look.puddles },\n    uSeed: { value: [((look.seed * 17.31) % 97) + 11.7, ((look.seed * 7.13) % 89) + 3.1] },\n    uHalf: { value: look.half },\n    uCuts: { value: cuts.flatMap((c) => [c.at, c.half]) },\n    uMarkings: { value: look.markings ? 1 : 0 },\n    uPaint: { value: v3(look.paint) },\n    uCentre: { value: v3(look.centrePaint) },\n  }\n  return {\n    key: 'wetstreet',\n    strength: 'streetPuddle + ( 1.0 - streetPuddle ) * streetWet * streetGloss * 0.35',\n    compile(shader: WebGLProgramParametersWithUniforms) {\n      Object.assign(shader.uniforms, uniforms, rainUniforms)\n      shader.vertexShader = shader.vertexShader\n        .replace('#include <common>', `#include <common>\\n${VERT_PARS}`)\n        .replace('#include <project_vertex>', `#include <project_vertex>\\n${VERT_MAIN}`)\n      shader.fragmentShader = shader.fragmentShader\n        .replace('#include <common>', `#include <common>\\n${FRAG_PARS}`)\n        .replace('#include <map_fragment>', `#include <map_fragment>\\n${ALBEDO}`)\n        .replace(\n          '#include <roughnessmap_fragment>',\n          `#include <roughnessmap_fragment>\\n${ROUGHNESS}`,\n        )\n        .replace('#include <normal_fragment_maps>', `#include <normal_fragment_maps>\\n${RIPPLES}`)\n        .replace(\n          '#include <lights_fragment_maps>',\n          '#include <lights_fragment_maps>\\nradiance *= streetGloss;',\n        )\n        .replace(\n          '#include <lights_fragment_end>',\n          '#include <lights_fragment_end>\\nreflectedLight.directSpecular *= streetGloss;',\n        )\n    },\n  }\n}\n\nconst VERT_PARS = /* glsl */ `\nattribute vec2 aStreet;\nvarying vec2 vStreet;\nvarying vec3 vStreetWorld;\n`\nconst VERT_MAIN = /* glsl */ `\nvStreet = aStreet;\nvStreetWorld = ( modelMatrix * vec4( transformed, 1.0 ) ).xyz;\n`\n\nconst FRAG_PARS = /* glsl */ `\nvarying vec2 vStreet;\nvarying vec3 vStreetWorld;\nuniform float uMarkings;\nuniform vec3 uPaint;\nuniform vec3 uCentre;\nuniform float uWet;\nuniform float uPuddles;\nuniform vec2 uSeed;\nuniform float uHalf;\nuniform vec2 uCuts[${MAX_CROSSINGS}];\nfloat streetHash( vec2 p ) { return fract( sin( dot( p, vec2( 127.1, 311.7 ) ) ) * 43758.5453 ); }\nfloat streetNoise( vec2 p ) {\n  vec2 i = floor( p ), f = fract( p );\n  vec2 u = f * f * ( 3.0 - 2.0 * f );\n  return mix( mix( streetHash( i ), streetHash( i + vec2( 1.0, 0.0 ) ), u.x ), mix( streetHash( i + vec2( 0.0, 1.0 ) ), streetHash( i + vec2( 1.0, 1.0 ) ), u.x ), u.y );\n}\n// Coverage of [a, b] over a pixel footprint w: a box-filtered band, so lines never shimmer.\nfloat streetBand( 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}\nfloat streetPulseInt( float x, float a, float b ) { return floor( x ) * ( b - a ) + clamp( fract( x ), a, b ) - a; }\nfloat streetPulse( float x, float a, float b, float w ) {\n  w = max( w, 1e-4 );\n  return ( streetPulseInt( x + 0.5 * w, a, b ) - streetPulseInt( x - 0.5 * w, a, b ) ) / w;\n}\nuniform float uRainTime;\nuniform float uRain;\nuniform float uWetness;\n// The slope a raindrop's ring gives the water: one drop at a time in each cell of a grid, at a\n// new spot in the cell each time. Rates in eighths keep every cell in step with the rain clock's wrap.\n// The harder it rains, the more of the cells take a drop: about one in twelve in a drizzle, over half in heavy rain.\nvec2 streetRipple( vec2 p, float cell, float shift ) {\n  vec2 q = p / cell + shift;\n  vec2 id = floor( q );\n  vec2 f = q - id;\n  float rate = 0.875 + floor( streetHash( id + shift ) * 5.0 ) * 0.125;\n  float t = uRainTime * rate + floor( streetHash( id + 41.7 ) * 17.0 );\n  float turn = mod( floor( t ), rate * ${RAIN_PERIOD.toFixed(1)} );\n  float life = fract( t );\n  vec2 c = 0.3 + 0.4 * vec2( streetHash( id + turn * 0.37 + 3.1 ), streetHash( id + turn * 0.71 + 7.9 ) );\n  float fires = step( 1.0 - 0.55 * uRain, streetHash( id + turn * 1.31 + 1.7 ) );\n  vec2 d = f - c;\n  float dist = length( d ) + 1e-4;\n  float x = ( dist - 0.3 * life ) * 14.0;\n  float fade = 1.0 - life;\n  return ( d / dist ) * ( -2.0 * x * exp( -x * x ) ) * fade * fade * fires;\n}\n`\n\n// Paint first (it decides where water stands), then puddles and wetness.\nconst ALBEDO = /* glsl */ `\nfloat streetPaint = 0.0;\nfloat streetInCross = 0.0;\nfloat streetZebra = 0.0;\nfloat streetZebraZone = 0.0;\n{\n  vec2 sp = vStreet;\n  vec2 sfw = fwidth( sp );\n  for ( int i = 0; i < ${MAX_CROSSINGS}; i++ ) {\n    vec2 c = uCuts[i];\n    streetInCross = max( streetInCross, streetBand( sp.y, c.x - c.y, c.x + c.y, sfw.y ) );\n    float near = streetBand( abs( sp.y - c.x ), c.y + 1.0, c.y + 4.5, sfw.y );\n    streetZebraZone = max( streetZebraZone, near );\n    streetZebra = max( streetZebra, near * streetPulse( sp.x / 1.0, 0.0, 0.5, sfw.x ) * step( abs( sp.x ), uHalf - 0.6 ) );\n  }\n  if ( uMarkings > 0.5 ) {\n    float ax = abs( sp.x );\n    float edgeLine = streetBand( ax, uHalf - 0.5, uHalf - 0.38, sfw.x );\n    float lane = uHalf >= 6.0 ? streetBand( ax, uHalf * 0.5 - 0.06, uHalf * 0.5 + 0.06, sfw.x ) * streetPulse( sp.y / 9.0, 0.0, 0.33, sfw.y / 9.0 ) : 0.0;\n    float centre = streetBand( ax, 0.08, 0.2, sfw.x );\n    float open = 1.0 - streetInCross;\n    float lanes = open * ( 1.0 - streetZebraZone );\n    float bone = max( edgeLine * open + lane * lanes, streetZebra );\n    diffuseColor.rgb = mix( diffuseColor.rgb, uPaint * 0.55, bone );\n    diffuseColor.rgb = mix( diffuseColor.rgb, uCentre * 0.55, centre * lanes );\n    streetPaint = max( bone, centre * lanes );\n  }\n}\nvec2 streetW = vStreetWorld.xz + uSeed;\nfloat streetBig = streetNoise( streetW / 7.0 ) * 0.6 + streetNoise( streetW / 3.1 ) * 0.3 + streetNoise( streetW / 1.3 ) * 0.1;\nfloat streetFine = streetNoise( streetW / 1.7 + 17.0 );\n// Camber: water runs to the gutters, except inside a crossing where there are none.\nfloat streetGutter = smoothstep( uHalf - 1.4, uHalf - 0.2, abs( vStreet.x ) ) * ( 1.0 - streetInCross );\nfloat streetLevel = streetBig + streetGutter * 0.22;\n// The weather fills the street and dries it again. Standing water goes first, drawing back to\n// the low spots and the gutters, and the damp in the asphalt goes after it.\nfloat streetStand = smoothstep( 0.1, 0.6, uWetness );\nfloat streetEdge = 0.74 - uPuddles * 0.2 + ( 1.0 - streetStand ) * 0.3;\nfloat streetPuddle = smoothstep( streetEdge, streetEdge + 0.03, streetLevel ) * ( 1.0 - streetPaint * 0.8 ) * smoothstep( 0.0, 0.15, streetStand );\nfloat streetWet = clamp( uWet * uWetness * mix( 0.35, 1.0, smoothstep( 0.3, 0.68, streetFine ) ), 0.0, 1.0 );\n// Wet asphalt is full of grain and tyre polish, so outside the puddles it gives back only part\n// of what a mirror (or a lamp) would, in patches. Standing water reflects fully.\nfloat streetGloss = mix( mix( 0.2, 0.5, streetFine ), 1.0, streetPuddle );\n// Wet porous asphalt darkens (Lagarde), standing water darkens it further.\ndiffuseColor.rgb *= mix( 1.0, mix( 1.0, 0.25, 0.5 ), streetWet );\ndiffuseColor.rgb *= mix( 1.0, 0.55, streetPuddle );\n`\n\n// Rain rings on standing water. They fade out where a pixel is wider than a ring, so far\n// puddles hold still and never shimmer.\nconst RIPPLES = /* glsl */ `\nvec2 streetRfw = fwidth( vStreetWorld.xz );\nfloat streetRings = ( 1.0 - smoothstep( 0.03, 0.1, max( streetRfw.x, streetRfw.y ) ) ) * smoothstep( 0.0, 0.08, uRain ) * streetPuddle;\nif ( streetRings > 0.0 ) {\n  vec2 slope = streetRipple( vStreetWorld.xz, 0.7, 0.0 ) + streetRipple( vStreetWorld.xz, 1.1, 13.7 );\n  normal = normalize( normal + ( viewMatrix * vec4( -slope.x, 0.0, -slope.y, 0.0 ) ).xyz * streetRings * 0.4 );\n}\n`\n\nconst ROUGHNESS = /* glsl */ `\nroughnessFactor = mix( roughnessFactor, 0.06, streetWet * 0.6 );\nroughnessFactor = mix( roughnessFactor, 0.4, streetPaint * ( 1.0 - streetPuddle ) );\nroughnessFactor = mix( roughnessFactor, 0.025, streetPuddle );\n`\n",
      "type": "registry:component"
    },
    {
      "path": "city/weather.ts",
      "content": "// The weather: what falls, how hard the wind blows and how wet the ground is, as a pure function\n// of a clock. Hand `weatherAt` the same Unix time on two machines and both get the same weather,\n// so players who share a clock share the sky with nothing sent between them.\n//\n// Also here, the uniforms `Rain` and `WetStreet` share. `Rain` drives them from the weather it is\n// given and the street only listens.\n//\n// No three.js, React or Runek in this file, so a HUD can import it without pulling in the 3D code.\n\nexport type WeatherKind = 'dry' | 'windy' | 'drizzle' | 'light-rain' | 'heavy-rain' | 'snow'\n\ninterface WeatherRow {\n  /** How likely a spell is to be this kind, against the other rows. Any positive numbers. */\n  odds: number\n  /** A spell lasts between these, in minutes. Keep the shorter one well above `WEATHER_TIMING.blend`. */\n  minutes: readonly [number, number]\n  /** How hard it rains, 0 to 1: how many streaks fall, how fast and how long they are, how loud it is. */\n  rain: number\n  /** How hard it snows, 0 to 1. */\n  snow: number\n  /** The steady wind is somewhere between these, in units a second. Each spell picks its own speed and heading. */\n  wind: readonly [number, number]\n  /** How far gusts swing the wind around that speed: 0.4 is 40% either way. */\n  gust: number\n  /** How wet the ground ends up if the spell lasts, 0 (dry) to 1 (soaked). */\n  wet: number\n}\n\n/**\n * The tuning table: one row for each kind of weather. Change the mix of weather here.\n *\n * `odds` are relative (these add up to 100, so they read as percentages of spells, not of time:\n * a kind with long spells fills more of the night than its odds say). The same kind never comes\n * twice in a row.\n */\nexport const WEATHER: Record<WeatherKind, WeatherRow> = {\n  dry: { odds: 28, minutes: [5, 12], rain: 0, snow: 0, wind: [0.4, 1.6], gust: 0.3, wet: 0 },\n  windy: { odds: 14, minutes: [3, 7], rain: 0, snow: 0, wind: [7, 11], gust: 0.45, wet: 0 },\n  drizzle: {\n    odds: 16,\n    minutes: [4, 9],\n    rain: 0.15,\n    snow: 0,\n    wind: [0.5, 2.5],\n    gust: 0.3,\n    wet: 0.6,\n  },\n  'light-rain': {\n    odds: 20,\n    minutes: [4, 10],\n    rain: 0.45,\n    snow: 0,\n    wind: [1, 3.5],\n    gust: 0.35,\n    wet: 0.85,\n  },\n  'heavy-rain': { odds: 12, minutes: [3, 6], rain: 1, snow: 0, wind: [3, 7], gust: 0.5, wet: 1 },\n  snow: { odds: 10, minutes: [5, 10], rain: 0, snow: 0.85, wind: [0.5, 2.5], gust: 0.3, wet: 0.5 },\n}\n\n/** The clocks behind the table, in seconds unless they say otherwise. */\nexport const WEATHER_TIMING = {\n  /** One spell eases into the next over this long, so nothing pops. */\n  blend: 45,\n  /** Heavy rain soaks dry ground in about this long. Lighter weather takes longer. */\n  soak: 40,\n  /** Wet ground loses about two thirds of its water in this long once the rain stops. */\n  dry: 480,\n  /** The same in a wind, which dries a street faster. */\n  dryWindy: 200,\n  /** How far back the ground remembers, in minutes. Several times `dry`, or wetness steps. */\n  memoryMinutes: 40,\n  /** The schedule is dealt in blocks this long, in minutes. A spell never runs across two blocks. */\n  blockMinutes: 120,\n  /** Changes every spell at once: a different night of weather for the same clock. */\n  seed: 2047,\n}\n\nexport const WEATHER_KINDS = Object.keys(WEATHER) as WeatherKind[]\n\nexport interface WeatherState {\n  /** The kind of weather this is. Halfway through a change it becomes the new one. */\n  kind: WeatherKind\n  /** How hard it rains now, 0 to 1. */\n  rain: number\n  /** How hard it snows now, 0 to 1. */\n  snow: number\n  /** The wind now, gusts and all, in units a second along x and z. */\n  wind: { x: number; z: number }\n  /** The length of `wind`. */\n  speed: number\n  /** How wet the ground is, 0 to 1. It lags the rain: streets stay wet for a while after it stops. */\n  wetness: number\n}\n\n/** A state to hand to `weatherAt` as `out`, so a caller that asks every frame makes no garbage. */\nexport function makeWeather(): WeatherState {\n  return { kind: 'dry', rain: 0, snow: 0, wind: { x: 0, z: 0 }, speed: 0, wetness: 0 }\n}\n\n/** Short names `?weather=` also takes. */\nconst ALIASES: Record<string, WeatherKind> = {\n  clear: 'dry',\n  wind: 'windy',\n  light: 'light-rain',\n  rain: 'light-rain',\n  heavy: 'heavy-rain',\n  storm: 'heavy-rain',\n}\n\n/** The kind a word names, or null when it names none. */\nexport function parseWeatherKind(word: string | null | undefined): WeatherKind | null {\n  if (!word) return null\n  const w = word.trim().toLowerCase()\n  if (w in WEATHER) return w as WeatherKind\n  return ALIASES[w] ?? null\n}\n\n// The schedule --------------------------------------------------------------------------------\n\ninterface Spell {\n  kind: WeatherKind\n  /** Unix ms. */\n  start: number\n  end: number\n  rain: number\n  snow: number\n  /** The steady wind, before gusts. */\n  wx: number\n  wz: number\n  gust: number\n  wet: number\n  /** Seconds for the ground to take this spell's water up, and to let it go. */\n  soak: number\n  dry: number\n}\n\nconst BLOCK_MS = WEATHER_TIMING.blockMinutes * 60_000\nconst BLEND_MS = WEATHER_TIMING.blend * 1000\nconst MEMORY_MS = WEATHER_TIMING.memoryMinutes * 60_000\n/** A block never ends on a spell shorter than this: the one before runs on to the end instead. */\nconst SHORTEST_MS = Math.max(\n  2 * BLEND_MS,\n  Math.min(...WEATHER_KINDS.map((k) => WEATHER[k].minutes[0])) * 60_000,\n)\n\n/** A small seeded generator, so the same block deals the same spells on every machine. */\nfunction seeded(seed: number): () => number {\n  let a = seed >>> 0\n  return () => {\n    a = (a + 0x6d2b79f5) >>> 0\n    let t = a\n    t = Math.imul(t ^ (t >>> 15), t | 1)\n    t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n  }\n}\n\nfunction pick(r: () => number, not: WeatherKind | null): WeatherKind {\n  let total = 0\n  for (const k of WEATHER_KINDS) if (k !== not) total += WEATHER[k].odds\n  let at = r() * total\n  let last = WEATHER_KINDS[0]\n  for (const k of WEATHER_KINDS) {\n    if (k === not) continue\n    last = k\n    at -= WEATHER[k].odds\n    if (at < 0) return k\n  }\n  return last\n}\n\nconst blocks = new Map<number, Spell[]>()\n\n/** The spells of one block, end to end. Dealt from the block's number alone, so any block can be asked for on its own. */\nfunction spellsOf(block: number): Spell[] {\n  const known = blocks.get(block)\n  if (known) return known\n  const r = seeded(Math.imul(block, 0x9e3779b1) ^ WEATHER_TIMING.seed)\n  const from = block * BLOCK_MS\n  const spells: Spell[] = []\n  let t = 0\n  let prev: WeatherKind | null = null\n  while (t < BLOCK_MS) {\n    const kind = pick(r, prev)\n    const row = WEATHER[kind]\n    let length = (row.minutes[0] + r() * (row.minutes[1] - row.minutes[0])) * 60_000\n    if (BLOCK_MS - (t + length) < SHORTEST_MS) length = BLOCK_MS - t\n    const heading = r() * Math.PI * 2\n    const speed = row.wind[0] + r() * (row.wind[1] - row.wind[0])\n    // No two spells of a kind are quite alike: each falls a little harder or softer than the table says.\n    const strength = 0.85 + r() * 0.3\n    const rain = Math.min(1, row.rain * strength)\n    const snow = Math.min(1, row.snow * strength)\n    spells.push({\n      kind,\n      start: from + t,\n      end: from + t + length,\n      rain,\n      snow,\n      wx: Math.cos(heading) * speed,\n      wz: Math.sin(heading) * speed,\n      gust: row.gust,\n      wet: row.wet,\n      soak: WEATHER_TIMING.soak / (0.25 + 0.75 * Math.max(rain, snow * 0.3)),\n      dry: kind === 'windy' ? WEATHER_TIMING.dryWindy : WEATHER_TIMING.dry,\n    })\n    t += length\n    prev = kind\n  }\n  if (blocks.size > 6) blocks.clear()\n  blocks.set(block, spells)\n  return spells\n}\n\n// The state at one moment ---------------------------------------------------------------------\n\nconst clamp01 = (v: number) => Math.min(1, Math.max(0, v))\nconst smooth = (v: number) => {\n  const x = clamp01(v)\n  return x * x * (3 - 2 * x)\n}\nconst mix = (a: number, b: number, k: number) => a + (b - a) * k\n/** What falls eases out in the first part of a change and in over the last, so rain is nearly gone before snow starts. */\nconst fall = (from: number, to: number, x: number) =>\n  mix(from, to, to < from ? smooth(x / 0.6) : smooth((x - 0.4) / 0.6))\n\nconst TURN = Math.PI * 2\n\n/** Lay gusts over a steady wind. Slow sums of sines of the clock, so every player feels the same gust. */\nfunction blow(out: WeatherState, wx: number, wz: number, gust: number, unixMs: number) {\n  const t = unixMs / 1000\n  const swell =\n    0.5 * Math.sin((t * TURN) / 23.1) +\n    0.3 * Math.sin((t * TURN) / 9.7 + 1.3) +\n    0.2 * Math.sin((t * TURN) / 4.3 + 4.1)\n  const veer = 0.6 * gust * Math.sin((t * TURN) / 37 + 2.2)\n  const scale = Math.max(0.15, 1 + gust * swell)\n  const cos = Math.cos(veer) * scale\n  const sin = Math.sin(veer) * scale\n  out.wind.x = wx * cos - wz * sin\n  out.wind.z = wx * sin + wz * cos\n  out.speed = Math.hypot(out.wind.x, out.wind.z)\n}\n\n/** Carry the ground's wetness through the spells of one block that fall inside its memory. -1 means nothing yet. */\nfunction soakThrough(spells: Spell[], since: number, now: number, wet: number): number {\n  for (const s of spells) {\n    if (s.end <= since || s.start > now) continue\n    if (wet < 0) wet = s.wet\n    const seconds = (Math.min(s.end, now) - Math.max(s.start, since)) / 1000\n    wet = s.wet + (wet - s.wet) * Math.exp(-seconds / (s.wet > wet ? s.soak : s.dry))\n  }\n  return wet\n}\n\n/**\n * The weather at a moment, from the clock alone. `unixMs` is Unix time in milliseconds: hand it\n * the clock the players share. Pure: the same time always gives the same weather, whenever and\n * wherever it is asked. Pass `out` to have it filled in place.\n */\nexport function weatherAt(unixMs: number, out: WeatherState = makeWeather()): WeatherState {\n  const block = Math.floor(unixMs / BLOCK_MS)\n  const today = spellsOf(block)\n  const before = spellsOf(block - 1)\n  let i = today.length - 1\n  while (i > 0 && today[i].start > unixMs) i--\n  const cur = today[i]\n  const prev = i > 0 ? today[i - 1] : before[before.length - 1]\n  const x = clamp01((unixMs - cur.start) / BLEND_MS)\n  const k = smooth(x)\n  out.kind = x < 0.5 ? prev.kind : cur.kind\n  out.rain = fall(prev.rain, cur.rain, x)\n  out.snow = fall(prev.snow, cur.snow, x)\n  blow(out, mix(prev.wx, cur.wx, k), mix(prev.wz, cur.wz, k), mix(prev.gust, cur.gust, k), unixMs)\n  const since = unixMs - MEMORY_MS\n  out.wetness = clamp01(soakThrough(today, since, unixMs, soakThrough(before, since, unixMs, -1)))\n  return out\n}\n\n/**\n * One kind of weather that never changes, as if its spell had always been: for `?weather=`, tests\n * and screenshots. The wind still gusts with the clock.\n */\nexport function steadyWeather(\n  kind: WeatherKind,\n  unixMs: number,\n  out: WeatherState = makeWeather(),\n): WeatherState {\n  const row = WEATHER[kind]\n  const speed = (row.wind[0] + row.wind[1]) / 2\n  out.kind = kind\n  out.rain = row.rain\n  out.snow = row.snow\n  blow(out, speed * 0.894, speed * 0.447, row.gust, unixMs)\n  out.wetness = row.wet\n  return out\n}\n\n// What `Rain` and `WetStreet` share -----------------------------------------------------------\n\n/**\n * The rain clock wraps to 0 after this many seconds. Every speed and rate that reads the clock\n * is picked so its motion repeats exactly at the wrap, and nothing jumps.\n */\nexport const RAIN_PERIOD = 160\n\n/**\n * Read by the streaks, splashes and flakes in `Rain` and by every `WetStreet`. With no `Rain`\n * mounted they stay as they are here: no rings, and streets as wet as their own props say.\n */\nexport const rainUniforms = {\n  /** Seconds of weather so far, wrapped at `RAIN_PERIOD`. */\n  uRainTime: { value: 0 },\n  /** How hard rain rings the puddles, 0 (still water) to 1 (heavy rain). */\n  uRain: { value: 0 },\n  /** How wet the weather has left the ground, 0 to 1. It scales each street's own `wetness` and `puddles`. */\n  uWetness: { value: 1 },\n}\n",
      "type": "registry:component"
    }
  ]
}
