{
  "name": "glow-sky",
  "title": "GlowSky",
  "type": "registry:component",
  "description": "A night sky that is never black: a dome lit from below by a city, darkest overhead and as bright as the haze at the horizon, with a slow cloud deck catching the district's glow that parts on stars and a moon in its phase. Decorative: no collider.",
  "dependencies": [
    "@react-three/fiber@^9.6.1",
    "@runek/core@^0.18.0",
    "three@^0.184.0"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "GlowSky.tsx",
      "content": "import { useFrame } from '@react-three/fiber'\nimport { lazyModule, useNodeRenderer, useWorld } from '@runek/core'\nimport { useEffect, useMemo } from 'react'\nimport { BackSide, type Color, type Material, ShaderMaterial, SphereGeometry, Vector3 } from 'three'\nimport { along, emissiveColor, useLadder } from './city/glow'\n\n// The dome's node (TSL) material, loaded only under a node renderer.\nconst skyNodes = lazyModule(() => import('./nodes/glowSky'))\n\nexport interface GlowSkyProps {\n  /** Accepted for the component contract. Shifts the cloud pattern. */\n  seed?: number\n  /** Color of the sky overhead. */\n  zenith?: string\n  /** Color at the horizon. Match it to the world's fog so the city fades into the sky. */\n  horizon?: string\n  /** Color of the city glow on the underside of the cloud deck. */\n  glow?: string\n  /** Draw the low cloud deck lit from below. */\n  clouds?: boolean\n  /** Color of the open sky between the clouds. */\n  night?: string\n  /** Color of the clouds themselves, away from the city's glow. Cooler than the haze, so the\n   *  glow on their undersides reads as light on something and not as more haze. */\n  cloud?: string\n  /** Color of the moon and its light on the clouds. */\n  moonColor?: string\n  /** Where the moon hangs: a direction from the viewer, +Y up. */\n  moon?: [number, number, number]\n  /** How the sky is right now. Asked every frame, and eased toward. Unset, the sky stays\n   *  mostly overcast with a full moon behind it. */\n  state?: () => SkyState\n}\n\n/** The part of the sky that changes while you watch. */\nexport interface SkyState {\n  /** How far the clouds have parted, 0 (overcast) to 1 (none left). */\n  clear: number\n  /** The moon's phase as a share of its cycle: 0 new, 0.25 first quarter, 0.5 full, 0.75 last quarter. */\n  phase: number\n}\n\n/**\n * The moon's phase at `ms` (Unix milliseconds), as a share of its cycle from one new moon to\n * the next. Counted from the new moon of 6 January 2000 at the mean length of a lunation, which\n * is within a few hours of the real one: enough for the shape of a moon in the sky.\n */\nexport function moonPhaseAt(ms: number): number {\n  const NEW_MOON = Date.UTC(2000, 0, 6, 18, 14)\n  const LUNATION = 29.530588853 * 86_400_000\n  const cycles = (ms - NEW_MOON) / LUNATION\n  return cycles - Math.floor(cycles)\n}\n\n/** How bright the moon's lit face and the brightest stars are, in scene-linear luminance. */\nconst MOON_LUMINANCE = 2.4\nconst STAR_LUMINANCE = 0.9\n/** The moon's radius as an angle, in radians: about five times the real one, as a night sky is remembered. */\nconst MOON_RADIUS = 0.05\n\n/** Where the sky sits between the darkest and brightest a night sky dome gets: zenith, then\n *  horizon (and haze). A world matches its fog color to the horizon. */\nexport const SKY_ZENITH = 0.15\nexport const SKY_HORIZON = 0.6\n\nconst VERT = /* glsl */ `\nvarying vec3 vDir;\nvoid main() {\n  vDir = normalize(position);\n  vec4 p = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n  gl_Position = p.xyww;\n}`\n\nconst FRAG = /* glsl */ `\nuniform vec3 uZenith;\nuniform vec3 uHorizon;\nuniform vec3 uGlow;\nuniform float uTime;\nuniform float uSeed;\nuniform float uClouds;\nuniform vec3 uNight;\nuniform vec3 uCloud;\nuniform vec3 uMoon;\nuniform vec3 uMoonDir;\nuniform float uMoonRadius;\nuniform float uPhase;\nuniform float uClear;\nuniform float uStar;\nvarying vec3 vDir;\nfloat h(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }\nfloat h3(vec3 p) { return fract(sin(dot(p, vec3(127.1, 311.7, 74.7))) * 43758.5453); }\nfloat n(vec2 p) { vec2 i = floor(p), f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f);\n  return mix(mix(h(i), h(i + vec2(1, 0)), u.x), mix(h(i + vec2(0, 1)), h(i + vec2(1, 1)), u.x), u.y); }\nvoid main() {\n  vec3 d = normalize(vDir);\n  float y = max(d.y, 0.0);\n  float up = pow(smoothstep(0.0, 0.7, y), 0.6);\n  // A cloud deck lit from below by the district. It parts as the sky clears, and never low down,\n  // where the haze closes it.\n  vec2 p = d.xz / max(d.y, 0.05) * 1.4 + vec2(uTime * 0.01 + uSeed, uSeed * 0.37);\n  float cn = n(p) * 0.5 + n(p * 2.3) * 0.27 + n(p * 5.1) * 0.15 + n(p * 11.3) * 0.08;\n  // At 1 no cloud is left at all. A little under it, a few drift through.\n  float from = mix(0.2, 0.92, uClear);\n  // A firm edge, so a cloud is a shape with sky beside it and not a stain.\n  float cl = smoothstep(from, from + 0.12, cn);\n  // How thick the cloud is here: thin at its edge, heavy in its middle.\n  float body = smoothstep(from, from + 0.4, cn);\n  float cover = mix(1.0, max(cl, 1.0 - smoothstep(0.0, 0.16, y)), uClouds);\n\n  // What is behind the clouds: the open night, stars, and the moon in its phase.\n  vec3 open = mix(uHorizon, uNight, up);\n  vec3 sp = d * 150.0;\n  vec3 id = floor(sp);\n  float r = h3(id);\n  float star = step(0.986, r) * smoothstep(0.24, 0.0, length(fract(sp) - 0.5));\n  open += vec3(uStar) * star * (0.25 + 0.75 * fract(r * 71.3)) * (0.75 + 0.25 * sin(uTime * (0.8 + r * 3.0) + r * 40.0));\n\n  float toward = max(dot(d, uMoonDir), 0.0);\n  // 0 at new moon, 1 at full.\n  float lit = 0.5 - 0.5 * cos(uPhase);\n  vec3 mx = normalize(cross(uMoonDir, vec3(0.0, 1.0, 0.0)));\n  vec3 my = cross(mx, uMoonDir);\n  vec2 q = vec2(dot(d, mx), dot(d, my)) / uMoonRadius;\n  float rr = dot(q, q);\n  if (rr < 1.0 && toward > 0.0) {\n    // A ball lit from the side: the sun goes round behind it as the month runs.\n    vec3 face = vec3(q, sqrt(1.0 - rr));\n    float day = smoothstep(-0.04, 0.22, dot(face, vec3(sin(uPhase), 0.0, -cos(uPhase))));\n    float seas = 0.72 + 0.28 * n(q * 2.6 + 9.0);\n    open = mix(open, uMoon * (0.015 + day) * seas, smoothstep(1.0, 0.88, rr));\n  }\n  open += uMoon * lit * (0.1 * pow(toward, 400.0) + 0.012 * pow(toward, 30.0));\n\n  // The clouds: the old dome, the city's glow on their undersides, and the moon behind them.\n  // Their own cool grey, darker where they are thick, sinking into the haze low down. The city\n  // lights their undersides, most near the horizon and most where they are heavy.\n  vec3 cloud = mix(uHorizon, uCloud * mix(1.35, 0.6, body), smoothstep(0.0, 0.3, y));\n  cloud += uGlow * (0.35 + 0.65 * body) * (1.0 - smoothstep(0.0, 0.7, y)) * smoothstep(0.0, 0.04, y) * uClouds;\n  cloud += uMoon * lit * 0.03 * pow(toward, 14.0);\n  // Thin cloud at the edge of a gap catches the moon.\n  cloud += uMoon * lit * 0.05 * pow(toward, 6.0) * cl * (1.0 - cl) * 4.0;\n  gl_FragColor = vec4(mix(open, cloud, cover), 1.0);\n}`\n\n/**\n * A night sky that is never black: a dome lit from below by the city, darkest overhead and as\n * bright as the haze at the horizon, with a slow cloud deck catching the district's glow. The\n * deck parts and closes with `state`: through the gaps are stars and a moon in the phase it is\n * told, which lights the cloud round it. (Under `WebGPURenderer` the deck stays closed, with no\n * stars or moon.) The clouds drift and the stars twinkle on the world's clock. The horizon is\n * meant to match the world's fog color so the two meet without a seam. Drawn behind everything\n * at the far plane, wherever the viewer is. Decorative: no collider.\n */\nexport function GlowSky({\n  seed = 0,\n  zenith = '#10172e',\n  horizon = '#1a2238',\n  glow = '#9ab8ff',\n  clouds = true,\n  night = '#131a3a',\n  cloud = '#3a4052',\n  moonColor = '#f6f2ea',\n  moon = [0.42, 0.62, -0.66],\n  state,\n}: GlowSkyProps) {\n  const ladder = useLadder()\n  const { unit, now = Date.now } = useWorld()\n  const nodes = useNodeRenderer() ? skyNodes() : null\n  const colors = useMemo(\n    () => ({\n      zenith: emissiveColor(zenith, along(ladder.skyDome, SKY_ZENITH)),\n      horizon: emissiveColor(horizon, along(ladder.skyDome, SKY_HORIZON)),\n      glow: emissiveColor(glow, ladder.skyDome[0] * 0.6),\n      night: emissiveColor(night, along(ladder.skyDome, SKY_ZENITH) * 0.6),\n      cloud: emissiveColor(cloud, along(ladder.skyDome, SKY_ZENITH) * 1.5),\n      moon: emissiveColor(moonColor, MOON_LUMINANCE),\n      moonDir: new Vector3(...moon).normalize(),\n    }),\n    [zenith, horizon, glow, night, cloud, moonColor, moon, ladder.skyDome],\n  )\n  const sky = useMemo(\n    () => (nodes ? nodes.nodeSky(colors, seed, clouds) : glslSky(colors, seed, clouds)),\n    [nodes, colors, seed, clouds],\n  )\n  useEffect(() => () => sky.material.dispose(), [sky])\n  useFrame((_, dt) => {\n    // A day's seconds, so the shader's floats keep their precision; the clouds jump once a day.\n    sky.setTime((now() / 1000) % 86_400)\n    if (state) sky.setState?.(state(), Math.min(dt, 0.1))\n  })\n  const geometry = useMemo(() => new SphereGeometry(900 * unit, 32, 16), [unit])\n  useEffect(() => () => geometry.dispose(), [geometry])\n\n  return <mesh material={sky.material} geometry={geometry} renderOrder={-1} frustumCulled={false} />\n}\n\nexport interface SkyColors {\n  zenith: Color\n  horizon: Color\n  glow: Color\n  night: Color\n  cloud: Color\n  moon: Color\n  moonDir: Vector3\n}\n\nexport interface SkyHandle {\n  material: Material\n  setTime: (t: number) => void\n  /** Ease toward `state` over `dt` seconds. */\n  setState?: (state: SkyState, dt: number) => void\n}\n\nfunction glslSky(c: SkyColors, seed: number, clouds: boolean): SkyHandle {\n  const material = new ShaderMaterial({\n    vertexShader: VERT,\n    fragmentShader: FRAG,\n    uniforms: {\n      uZenith: { value: c.zenith },\n      uHorizon: { value: c.horizon },\n      uGlow: { value: c.glow },\n      uTime: { value: 0 },\n      uSeed: { value: (seed % 97) * 3.1 },\n      uClouds: { value: clouds ? 1 : 0 },\n      uNight: { value: c.night },\n      uCloud: { value: c.cloud },\n      uMoon: { value: c.moon },\n      uMoonDir: { value: c.moonDir },\n      uMoonRadius: { value: MOON_RADIUS },\n      uPhase: { value: Math.PI },\n      uClear: { value: 1 },\n      uStar: { value: STAR_LUMINANCE },\n    },\n    side: BackSide,\n    depthWrite: false,\n    fog: false,\n  })\n  material.name = 'glowsky'\n  return {\n    material,\n    setTime: (t) => {\n      material.uniforms.uTime.value = t\n    },\n    setState: (state, dt) => {\n      const u = material.uniforms\n      // Clouds take a minute or so to part. The moon is where the calendar says.\n      u.uClear.value +=\n        (Math.min(1, Math.max(0, state.clear)) - u.uClear.value) * (1 - Math.exp(-dt / 20))\n      u.uPhase.value = state.phase * Math.PI * 2\n    },\n  }\n}\n\nGlowSky.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": "nodes/glowSky.ts",
      "content": "// GlowSky's dome as a TSL node material, for WebGPURenderer: the gradient and the city's glow on\n// a closed cloud deck, without the stars, the moon or the deck parting. The far-plane trick\n// becomes no depth test plus drawing first.\n\nimport { BackSide } from 'three'\nimport {\n  dot,\n  float,\n  floor,\n  fract,\n  max,\n  mix,\n  normalize,\n  positionLocal,\n  pow,\n  sin,\n  smoothstep,\n  uniform,\n  vec2,\n} from 'three/tsl'\nimport { MeshBasicNodeMaterial, type Node } from 'three/webgpu'\nimport type { SkyColors, SkyHandle } from '../GlowSky'\n\nexport function nodeSky(c: SkyColors, seed: number, clouds: boolean): SkyHandle {\n  const time = uniform(0)\n  const hash = (p: Node<'vec2'>) => fract(sin(dot(p, vec2(127.1, 311.7))).mul(43758.5453))\n  const noise = (p: Node<'vec2'>) => {\n    const i = floor(p)\n    const f = fract(p)\n    const u = f.mul(f).mul(float(3).sub(f.mul(2)))\n    return mix(\n      mix(hash(i), hash(i.add(vec2(1, 0))), u.x),\n      mix(hash(i.add(vec2(0, 1))), hash(i.add(vec2(1, 1))), u.x),\n      u.y,\n    )\n  }\n  const d = normalize(positionLocal)\n  const y = max(d.y, 0)\n  let color = mix(uniform(c.horizon), uniform(c.zenith), pow(smoothstep(0, 0.7, y), 0.6))\n  if (clouds) {\n    const s = (seed % 97) * 3.1\n    const p = d.xz\n      .div(max(d.y, 0.05))\n      .mul(1.4)\n      .add(vec2(time.mul(0.01).add(s), s * 0.37))\n    const cl = smoothstep(\n      0.35,\n      0.85,\n      noise(p)\n        .mul(0.6)\n        .add(noise(p.mul(2.3)).mul(0.3))\n        .add(noise(p.mul(5.1)).mul(0.1)),\n    )\n    color = color.add(\n      uniform(c.glow)\n        .mul(cl)\n        .mul(float(1).sub(smoothstep(0, 0.8, y)))\n        .mul(smoothstep(0, 0.04, y)),\n    )\n  }\n  const material = new MeshBasicNodeMaterial()\n  material.colorNode = color\n  material.side = BackSide\n  material.depthWrite = false\n  material.depthTest = false\n  material.fog = false\n  material.name = 'glowsky'\n  return {\n    material,\n    setTime: (t) => {\n      time.value = t\n    },\n  }\n}\n",
      "type": "registry:component"
    }
  ]
}
