{
  "name": "neon-sign",
  "title": "NeonSign",
  "type": "registry:component",
  "description": "Words bent out of glass tube on a dark board, at the world's tube luminance level, that flicker: bad tubes buzz and drop out and the whole sign stutters now and then, as a pure function of the world clock and `seed` so every viewer sees the same sign. The tubes are drawn in code from the world's fonts. Decorative: no collider.",
  "dependencies": [
    "@react-three/fiber@^9.6.1",
    "@runek/core@^0.18.0",
    "three@^0.184.0"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "NeonSign.tsx",
      "content": "import { useFrame } from '@react-three/fiber'\nimport {\n  Dynamic,\n  lazyModule,\n  useLight,\n  useMaterial,\n  useNodeRenderer,\n  useWorld,\n  type Vec3,\n} from '@runek/core'\nimport { useEffect, useMemo, useRef, useState } from 'react'\nimport {\n  AdditiveBlending,\n  BoxGeometry,\n  DataTexture,\n  LinearFilter,\n  LinearMipmapLinearFilter,\n  type Material,\n  PlaneGeometry,\n  RGBAFormat,\n  ShaderMaterial,\n  UniformsLib,\n  UniformsUtils,\n} from 'three'\nimport { fontFamily } from './city/fontFace'\nimport { emissiveColor, mid, useLadder } from './city/glow'\nimport { hash2 } from './city/hash'\nimport { FOG_FADE } from './city/haze'\n\n// The node (TSL) material, loaded only under a node renderer.\nconst neonNodes = lazyModule(() => import('./nodes/neon'))\n\nexport interface NeonSignProps {\n  /** The middle of the sign [x, y, z] in units. It faces local +Z. */\n  position?: Vec3\n  /** Rotation [x, y, z] in radians. */\n  rotation?: Vec3\n  /** Picks which letters are the bad ones, and when everything stutters. */\n  seed?: number\n  /** The words, on one line. At most 24 characters are drawn. */\n  text?: string\n  /** Cap height in units. */\n  size?: number\n  /** Tube color, lit at the world's `tube` luminance level. */\n  color?: string\n  /** Which of the world's fonts the tubes are bent to. */\n  variant?: 'display' | 'body'\n  /** A font URL to use instead of a world font. */\n  font?: string\n  /** How badly it flickers, 0 (a new sign) to 1 (one that should be taken down). */\n  flicker?: number\n  /** How many letters have a bad tube of their own. */\n  faults?: number\n  /** Draw the dark board the tubes are mounted on. */\n  board?: boolean\n  /** Ask the world's light pool for a real light, which flickers with the sign. */\n  light?: boolean\n  /** Candela of that light with every tube lit. */\n  intensity?: number\n}\n\n/** The most letters one sign can flicker on their own. */\nconst MAX_LETTERS = 24\n/** Texture height in pixels. The width follows the words. */\nconst TEX_H = 128\n/** A dark tube still shows: glass in front of a wall. */\nconst DARK = 0.04\n\n/**\n * How bright each tube of a sign is at `seconds` on the world clock, 1 lit and near 0 dark,\n * written into `out`. A pure function of its arguments: every player who shares the clock sees\n * the same letters drop out at the same moment.\n *\n * Every tube hums a little. The bad ones (`faults` of them, picked by `seed`) buzz: they drop\n * out in short bursts and sometimes stay dark for a few seconds. Now and then the whole sign\n * stutters, as a transformer does.\n */\nexport function neonLevels(\n  out: Float32Array,\n  letters: number,\n  seed: number,\n  seconds: number,\n  flicker: number,\n  faults: number,\n): Float32Array {\n  const f = Math.min(1, Math.max(0, flicker))\n  // The whole sign: a stutter in one 6 s window out of a few, for under a second.\n  const window = Math.floor(seconds / 6)\n  let all = 1\n  if (f > 0 && hash2(seed * 31 + 7, window) < 0.12 + 0.3 * f) {\n    const into = seconds - window * 6 - hash2(seed, window) * 5\n    if (into > 0 && into < 0.25 + 0.5 * f)\n      all = hash2(seed + 3, Math.floor(seconds * 24)) < 0.5 ? 0.15 : 1\n  }\n  for (let i = 0; i < letters; i++) {\n    // Mains hum: a few percent, out of step from tube to tube.\n    let level = 1 - 0.05 * f * (0.5 + 0.5 * Math.sin(seconds * 37 + i * 1.7))\n    const bad = f > 0 && faults > 0 && hash2(seed * 17 + 1, i) < faults / Math.max(1, letters)\n    if (bad) {\n      // In 3 s spells: lit, buzzing, or out.\n      const spell = Math.floor(seconds / 3)\n      const kind = hash2(seed * 13 + i, spell)\n      if (kind < 0.2 * f) level = DARK\n      else if (kind < 0.2 * f + 0.45)\n        level *= hash2(seed + i * 7, Math.floor(seconds * 18)) < 0.35 + 0.25 * f ? DARK : 1\n    }\n    out[i] = level * all\n  }\n  return out\n}\n\ninterface Drawn {\n  texture: DataTexture\n  /** Width over height of the drawn words, padding included. */\n  aspect: number\n  /** How much of the texture's height a capital takes. */\n  cap: number\n  /** Each letter's left and right edge across the texture, 0 to 1. */\n  edges: Float32Array\n  letters: number\n}\n\n/**\n * The words as bent tubes: R is the tube, G the soft light round it. Drawn in code from a font\n * family the page already has, so no image ships.\n */\nfunction draw(text: string, family: string, weight: number): Drawn | null {\n  if (typeof document === 'undefined') return null\n  const canvas = document.createElement('canvas')\n  // One context for measuring and drawing: the canvas hands back the first one it made.\n  const probe = canvas.getContext('2d', { willReadFrequently: true })\n  if (!probe) return null\n  const word = text.slice(0, MAX_LETTERS)\n  // Size the face so a capital takes 46% of the height, whatever the font.\n  probe.font = `${weight} 100px ${family}`\n  const capAt100 = probe.measureText('H').actualBoundingBoxAscent || 70\n  const px = (100 * TEX_H * 0.46) / capAt100\n  const font = `${weight} ${px}px ${family}`\n  probe.font = font\n  const pad = TEX_H * 0.3\n  const spacing = px * 0.08\n  const advances = [...word].map((ch) => probe.measureText(ch).width + spacing)\n  const wide = advances.reduce((a, b) => a + b, 0)\n  canvas.width = Math.min(4096, Math.ceil(wide + pad * 2))\n  canvas.height = TEX_H\n  const ctx = canvas.getContext('2d', { willReadFrequently: true })\n  if (!ctx) return null\n  const W = canvas.width\n  const baseline = TEX_H * 0.73\n  const pass = (blur: number, line: number) => {\n    ctx.clearRect(0, 0, W, TEX_H)\n    ctx.font = font\n    ctx.textAlign = 'left'\n    ctx.textBaseline = 'alphabetic'\n    ctx.lineJoin = ctx.lineCap = 'round'\n    ctx.strokeStyle = 'white'\n    ctx.lineWidth = line\n    ctx.shadowColor = 'white'\n    ctx.shadowBlur = blur\n    let x = pad\n    for (let i = 0; i < advances.length; i++) {\n      ctx.strokeText(word[i], x, baseline)\n      x += advances[i]\n    }\n    return ctx.getImageData(0, 0, W, TEX_H).data\n  }\n  const tube = pass(0, TEX_H * 0.045)\n  const data = new Uint8Array(W * TEX_H * 4)\n  for (let p = 0; p < W * TEX_H; p++) data[p * 4] = tube[p * 4 + 3]\n  const halo = pass(TEX_H * 0.16, TEX_H * 0.07)\n  for (let p = 0; p < W * TEX_H; p++) {\n    data[p * 4 + 1] = halo[p * 4 + 3]\n    data[p * 4 + 3] = 255\n  }\n  const map = new DataTexture(data, W, TEX_H, RGBAFormat)\n  map.flipY = true\n  map.magFilter = LinearFilter\n  map.minFilter = LinearMipmapLinearFilter\n  map.generateMipmaps = true\n  map.needsUpdate = true\n  const edges = new Float32Array(MAX_LETTERS * 2)\n  let x = pad\n  for (let i = 0; i < advances.length; i++) {\n    edges[i * 2] = (x - spacing / 2) / W\n    x += advances[i]\n    edges[i * 2 + 1] = (x - spacing / 2) / W\n  }\n  return { texture: map, aspect: W / TEX_H, cap: 0.46, edges, letters: advances.length }\n}\n\nconst VERT = /* glsl */ `\nvarying vec2 vUv;\nvarying vec3 vWorld;\nvoid main() {\n  vec4 world = modelMatrix * vec4(position, 1.0);\n  vUv = uv;\n  vWorld = world.xyz;\n  gl_Position = projectionMatrix * viewMatrix * world;\n}`\n\n// Each fragment finds the letter it is in and takes that tube's level. The halo is light in the\n// air, so it is added, and fades with the fog as the lamp cones do.\nconst FRAG = /* glsl */ `\nuniform sampler2D tMap;\nuniform vec3 uCore;\nuniform vec3 uHalo;\nuniform float uLevels[${MAX_LETTERS}];\nuniform float uEdges[${MAX_LETTERS * 2}];\nvarying vec2 vUv;\nvarying vec3 vWorld;\n${FOG_FADE}\nvoid main() {\n  vec2 tx = texture2D(tMap, vUv).rg;\n  float level = 1.0;\n  for (int i = 0; i < ${MAX_LETTERS}; i++) {\n    if (vUv.x >= uEdges[2 * i] && vUv.x < uEdges[2 * i + 1]) level = uLevels[i];\n  }\n  vec3 light = uCore * tx.r * level + uHalo * tx.g * tx.g * level;\n  gl_FragColor = vec4(light * hazeFog(vWorld), 1.0);\n}`\n\n/**\n * A neon sign: words bent out of glass tube on a dark board, lit at the world's `tube` luminance\n * level, that flicker. Some letters have a bad tube and buzz or drop out, and now and then the\n * whole sign stutters. What is lit when is a pure function of the world clock and `seed`\n * (`neonLevels`), so every player sees the same sign. `BladeSign` and `Sign` are the still ones.\n *\n * The tubes are drawn in code, at mount, from the world's declared fonts (contract §4): no image\n * and no font ships with the component. One draw, never batched, since its light changes every\n * frame. No collider. Under `WebGPURenderer` the whole sign flickers as one, since the node\n * material has no per-letter levels.\n */\nexport function NeonSign({\n  position = [0, 0, 0],\n  rotation = [0, 0, 0],\n  seed = 1,\n  text = 'OPEN',\n  size = 0.5,\n  color = '#ff6418',\n  variant = 'display',\n  font,\n  flicker = 0.4,\n  faults = 1,\n  board = true,\n  light = false,\n  intensity = 60,\n}: NeonSignProps) {\n  const { unit, fonts, palette, now = Date.now } = useWorld()\n  const ladder = useLadder()\n  const nodes = useNodeRenderer() ? neonNodes() : null\n  const url = font ?? fonts[variant]\n  const fallback = variant === 'body' ? 'monospace' : 'sans-serif'\n  const weight = variant === 'body' ? 500 : 600\n  // Draw at once in a system face, then again when the world's own font has loaded.\n  const [face, setFace] = useState<string | null>(null)\n  useEffect(() => {\n    let live = true\n    if (url) void fontFamily(url).then((name) => live && setFace(name))\n    return () => {\n      live = false\n    }\n  }, [url])\n  const drawn = useMemo(\n    () => draw(text, face ? `${face}, ${fallback}` : fallback, weight),\n    [text, face, fallback, weight],\n  )\n\n  const core = useMemo(() => emissiveColor(color, mid(ladder.tubeCore)), [color, ladder.tubeCore])\n  const halo = useMemo(() => emissiveColor(color, ladder.signFace[0]), [color, ladder.signFace])\n  const levels = useMemo(() => new Float32Array(MAX_LETTERS).fill(1), [])\n  const setWhole = useRef<((level: number) => void) | null>(null)\n  const material = useMemo<Material | null>(() => {\n    if (!drawn) return null\n    let m: Material\n    setWhole.current = null\n    if (nodes) {\n      const made = nodes.neonNodeMaterial(drawn.texture, core, halo)\n      setWhole.current = made.setLevel\n      m = made.material\n    } else {\n      m = new ShaderMaterial({\n        vertexShader: VERT,\n        fragmentShader: FRAG,\n        uniforms: UniformsUtils.merge([\n          UniformsLib.fog,\n          {\n            tMap: { value: null },\n            uCore: { value: core.clone() },\n            uHalo: { value: halo.clone() },\n            uLevels: { value: null },\n            uEdges: { value: null },\n          },\n        ]),\n        fog: true,\n      })\n      const u = (m as ShaderMaterial).uniforms\n      u.tMap.value = drawn.texture\n      // Flat arrays, set after the merge so the material reads the live ones.\n      u.uLevels.value = levels\n      u.uEdges.value = drawn.edges\n    }\n    m.transparent = true\n    m.depthWrite = false\n    m.blending = AdditiveBlending\n    m.toneMapped = false\n    return m\n  }, [drawn, nodes, core, halo, levels])\n  useEffect(\n    () => () => {\n      material?.dispose()\n      drawn?.texture.dispose()\n    },\n    [material, drawn],\n  )\n\n  const backing = useMaterial({ color: palette.metal, roughness: 0.8 })\n  const emitter = useLight({ color, intensity, distance: 14 * unit, decay: 2 }, light)\n\n  useFrame(() => {\n    if (!drawn) return\n    neonLevels(levels, drawn.letters, seed, now() / 1000, flicker, faults)\n    let sum = 0\n    for (let i = 0; i < drawn.letters; i++) sum += levels[i]\n    const mean = drawn.letters ? sum / drawn.letters : 1\n    setWhole.current?.(mean)\n    emitter.intensity = intensity * mean\n  })\n\n  if (!drawn || !material) return null\n  // The texture's height is the cap height over `cap`, and the plane keeps the texture's shape.\n  const h = (size / drawn.cap) * unit\n  const w = h * drawn.aspect\n  return (\n    <Dynamic>\n      <group position={position} rotation={rotation}>\n        {board && (\n          <mesh\n            position={[0, 0, -0.035 * unit]}\n            material={backing}\n            geometry={boardGeometry(w * 0.94, h * 0.78, 0.05 * unit)}\n          />\n        )}\n        <mesh\n          material={material}\n          geometry={planeGeometry(w, h)}\n          position={[0, 0, 0.02 * unit]}\n          renderOrder={2}\n        />\n        <object3D ref={emitter.ref} position={[0, 0, 0.6 * unit]} />\n      </group>\n    </Dynamic>\n  )\n}\n\nconst planes = new Map<string, PlaneGeometry>()\nfunction planeGeometry(w: number, h: number) {\n  const key = `${w.toFixed(3)}:${h.toFixed(3)}`\n  let g = planes.get(key)\n  if (!g) {\n    g = new PlaneGeometry(w, h)\n    planes.set(key, g)\n  }\n  return g\n}\nconst boards = new Map<string, BoxGeometry>()\nfunction boardGeometry(w: number, h: number, d: number) {\n  const key = `${w.toFixed(3)}:${h.toFixed(3)}:${d.toFixed(3)}`\n  let g = boards.get(key)\n  if (!g) {\n    g = new BoxGeometry(w, h, d)\n    boards.set(key, g)\n  }\n  return g\n}\n",
      "type": "registry:component"
    },
    {
      "path": "city/fontFace.ts",
      "content": "// Font files a component draws its own lettering from (a neon tube, a billboard), loaded once\n// each under a family name of their own. The files are the world's declared fonts (contract §4):\n// nothing here ships a font.\n\nconst families = new Map<string, Promise<string | null>>()\n\n/** Loads a font file and gives back the CSS family name it now has, or null if it would not load. */\nexport function fontFamily(url: string): Promise<string | null> {\n  let asked = families.get(url)\n  if (!asked) {\n    const name = `runek-face-${families.size}`\n    asked =\n      typeof FontFace === 'undefined' || typeof document === 'undefined'\n        ? Promise.resolve(null)\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    families.set(url, asked)\n  }\n  return asked\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/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"
    },
    {
      "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": "nodes/neon.ts",
      "content": "// NeonSign's tubes as a TSL node material, for WebGPURenderer. It has no per-letter levels: the\n// whole sign dims as one, by the mean of its tubes' levels.\n\nimport type { Color, DataTexture } from 'three'\nimport { texture, uniform, uv } from 'three/tsl'\nimport { MeshBasicNodeMaterial } from 'three/webgpu'\n\nexport function neonNodeMaterial(map: DataTexture, core: Color, halo: Color) {\n  const whole = uniform(1)\n  const material = new MeshBasicNodeMaterial()\n  const tx = texture(map, uv())\n  material.colorNode = uniform(core.clone())\n    .mul(tx.r)\n    .add(uniform(halo.clone()).mul(tx.g).mul(tx.g))\n    .mul(whole)\n  material.fog = false\n  /** Set the sign's mean level for this frame. */\n  const setLevel = (level: number) => {\n    whole.value = level\n  }\n  return { material, setLevel }\n}\n",
      "type": "registry:component"
    }
  ]
}
