component

CableSag

A cable sagging across a street between two anchors: a parabola cut into straight pieces. Drawn by the world's shared facade-kit meshes. Decorative: no collider.

⌖ Explore the library in 3D → · View as Markdown

Tune every prop in the workshop →

Add it

npx @runek/cli add cable-sag

Pulls @react-three/fiber@^9.6.1, @runek/core@^0.18.0, three@^0.184.0.

Use it

import { CableSag } from './runek/CableSag'

<CableSag position={[0, 0, 0]} span={12} sag={0.8} />

Or as a node in a world file (worlds as data):

{ "type": "CableSag", "props": { "position": [0, 0, 0], "span": 12, "sag": 0.8 } }

Props

Prop Type Default Description
position [x, y, z] [0, 0, 0] The near anchor [x, y, z] in units. The cable crosses along local +Z.
rotation [x, y, z] [0, 0, 0] Rotation [x, y, z] in radians. Turn about Y to aim it across the street.
seed number Accepted for the component contract. This component has no seeded variation.
span number 27 Distance to the far anchor, in units.
sag number 1.4 How far the middle hangs below the straight line, in units.
drop number 0 How much higher (or lower, when negative) the far anchor sits, in units.
segments number 8 Straight pieces the curve is cut into.
thickness number 0.04 Cable thickness, in units.
color color "#141110" Cable color.

Registry manifest

registry manifest /r/components/cable-sag.json Self-contained JSON: inlined source plus resolved dependencies, exactly what runek add cable-sag fetches.

Browse the whole catalog in the gallery →.

Source (9 files)

CableSag.tsx

import { useWorld, type Vec3 } from '@runek/core'
import { cableSag } from './city/kitParts'
import { useKit } from './city/useKit'

export interface CableSagProps {
  /** The near anchor [x, y, z] in units. The cable crosses along local +Z. */
  position?: Vec3
  /** Rotation [x, y, z] in radians. Turn about Y to aim it across the street. */
  rotation?: Vec3
  /** Accepted for the component contract. This component has no seeded variation. */
  seed?: number
  /** Distance to the far anchor, in units. */
  span?: number
  /** How far the middle hangs below the straight line, in units. */
  sag?: number
  /** How much higher (or lower, when negative) the far anchor sits, in units. */
  drop?: number
  /** Straight pieces the curve is cut into. */
  segments?: number
  /** Cable thickness, in units. */
  thickness?: number
  /** Cable color. */
  color?: string
}

/**
 * A cable sagging across a street between two anchors: a parabola cut into straight pieces.
 * Drawn by the world's shared kit meshes and left out of the world's mirrors. No collider.
 */
export function CableSag({
  position = [0, 0, 0],
  rotation = [0, 0, 0],
  span = 27,
  sag = 1.4,
  drop = 0,
  segments = 8,
  thickness = 0.04,
  color = '#141110',
}: CableSagProps) {
  const { unit } = useWorld()
  const ref = useKit(
    (kit) =>
      cableSag(kit, 0, 0, 0, span, {
        sag: sag,
        drop: drop,
        segments: Math.max(2, Math.round(segments)),
        thickness: thickness,
        color,
      }),
    [span, sag, drop, segments, thickness, color],
    [position, rotation, unit],
  )
  return <group ref={ref} position={position} rotation={rotation} scale={unit} />
}

city/kit.ts

// The facade kit's shared draw: every AC unit, pipe, cable, vent, awning, shutter, sign and
// vending machine in a world is an instance in one of three InstancedMeshes, so a street full of
// props costs three draws however many towers it has. A fourth holds the light those signs leave
// on the ground.
//
// `near` holds the parts worth reflecting in the wet street (signs, tubes, awnings, shutters).
// `small` holds the rest and is left out of the world's mirrors (`skipMirrors`).
// `glyph` holds sign letters, cut from an atlas drawn in code at load from the world's fonts.
// `splat` holds soft additive pools on the street in front of lit signs and door lamps. They are
// not real lights: a shop's glow reads on the pavement without spending one of the world's few.
//
// Components describe their parts in local space with a KitBuilder (a pure function of props and
// seed) and hand them to `useKit`, which registers them in world space with the scene's Kit.

import { skipMirrors } from '@runek/core'
import {
  AdditiveBlending,
  BoxGeometry,
  Color,
  DataTexture,
  InstancedBufferAttribute,
  InstancedMesh,
  LinearFilter,
  LinearMipmapLinearFilter,
  type Material,
  Matrix4,
  PlaneGeometry,
  RGBAFormat,
  type Scene,
  ShaderMaterial,
  UniformsLib,
  UniformsUtils,
  Vector3,
} from 'three'
import { emissiveColor } from './glow'
import { FOG_FADE } from './haze'
import { towerUniforms } from './towerLight'

/** Floats per box or glyph instance: a 4x4 matrix, then two vec4s. */
export const KIT_STRIDE = 24
/** How a part is lit: matte under street light, or an emitter on a ladder rung. */
export const GLOW = { matte: 0, sign: 1, tube: 2, glass: 3 } as const
/** Surface detail drawn by the box shader from the face's size in metres. */
export const DETAIL = {
  none: 0,
  slats: 1,
  fan: 2,
  vending: 3,
  stripes: 4,
  cage: 5,
  panel: 6,
} as const

const GLYPHS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-.:'&/!?#"
const ADVANCE: Record<string, number> = {
  I: 0.42,
  '1': 0.55,
  '.': 0.34,
  ':': 0.34,
  "'": 0.3,
  '!': 0.4,
  ' ': 0.45,
  M: 0.95,
  W: 1.0,
  '-': 0.6,
  '+': 0.7,
}
/** Advance of one glyph, in letter heights. */
export const glyphAdvance = (ch: string) => ADVANCE[ch] ?? 0.8
/** A glyph's quad side, in letter heights (the cap height fills half a cell). */
const GLYPH_QUAD = 2

const m4 = new Matrix4()
const m4b = new Matrix4()
const v3 = new Vector3()

/** A box that stops a walker, in the component's local space. Upright, turned about Y only. */
export interface KitSolid {
  /** Centre [x, y, z]. */
  position: [number, number, number]
  /** Half extents along the box's own X, Y and Z. */
  half: [number, number, number]
  /** Turn about Y, in radians. */
  rotY: number
}

/** Collects a component's kit parts in its local space. */
export class KitBuilder {
  near: number[] = []
  small: number[] = []
  glyph: number[] = []
  splat: number[] = []
  /** What a walker should bump into. The kit meshes do not read it: the component that owns the builder makes the colliders. */
  solids: KitSolid[] = []
  private frame = new Matrix4()
  private stack: Matrix4[] = []

  /** Enter a local frame at (x, y, z) turned `rotY` about Y. Parts added until `pop` sit in it. */
  push(x: number, y: number, z: number, rotY = 0) {
    this.stack.push(this.frame.clone())
    this.frame.multiply(m4.makeRotationY(rotY).setPosition(x, y, z))
    return this
  }
  pop() {
    this.frame.copy(this.stack.pop() ?? new Matrix4())
    return this
  }

  /**
   * Mark a box centred at (x, y, z) of size (sx, sy, sz) in the current frame as solid. It draws
   * nothing. Parts record their own (a vending machine's case), so a component that places them
   * gets colliders that follow the same seeded layout as the instances.
   */
  solid(x: number, y: number, z: number, sx: number, sy: number, sz: number) {
    const e = this.frame.elements
    v3.set(x, y, z).applyMatrix4(this.frame)
    this.solids.push({
      position: [v3.x, v3.y, v3.z],
      half: [sx / 2, sy / 2, sz / 2],
      rotY: Math.atan2(e[8], e[0]),
    })
    return this
  }

  private write(
    out: number[],
    local: Matrix4,
    color: string,
    glow: number,
    a: number,
    b: number,
    c: number,
    d: number,
  ) {
    m4b.multiplyMatrices(this.frame, local)
    const col = glow === GLOW.matte ? new Color(color) : emissiveColor(color, 1)
    out.push(...m4b.elements, col.r, col.g, col.b, glow, a, b, c, d)
  }

  /**
   * A box centred at (x, y, z) of size (sx, sy, sz). `glow` picks matte or a ladder rung, `t` the
   * place along that rung (0 to 1), `detail` a surface pattern. `shear` leans the box: its top
   * moves that far along local Z per metre of height (an awning's slope). `rise` lifts its far
   * end: that many metres of height per metre of local Z (a cable's slope).
   */
  box(
    small: boolean,
    x: number,
    y: number,
    z: number,
    sx: number,
    sy: number,
    sz: number,
    color: string,
    {
      glow = GLOW.matte as number,
      t = 0.5,
      detail = DETAIL.none as number,
      seed = 0,
      rotY = 0,
      shear = 0,
      rise = 0,
    } = {},
  ) {
    m4.makeRotationY(rotY).setPosition(x, y, z)
    const s = new Matrix4().makeScale(sx, sy, sz)
    if (shear) s.elements[6] = shear * sy // local Z gains shear per unit of local Y
    if (rise) s.elements[9] = rise * sz // local Y gains rise per unit of local Z
    m4.multiply(s)
    this.write(small ? this.small : this.near, m4, color, glow, t, detail, seed, 0)
    return this
  }

  /**
   * Light left on the ground: a soft half disc lying flat at height y, its straight edge centred
   * on (x, z) and running along local X for `sx`, reaching `sz` out along local +Z (away from
   * the wall the light comes from). `t` is its place on the street-under-sign rung.
   */
  lightSplat(
    x: number,
    y: number,
    z: number,
    sx: number,
    sz: number,
    color: string,
    { t = 0.5 } = {},
  ) {
    // A unit plane laid flat: its top edge (uv.y = 1) ends up on the -Z side, at the wall.
    m4.makeRotationX(-Math.PI / 2)
      .scale(v3.set(sx, sz, 1))
      .setPosition(x, y, z + sz / 2)
    this.write(this.splat, m4, color, GLOW.sign, t, 0, 0, 0)
    return this
  }

  /** Width of `text` set at letter height `h`. */
  static textWidth(text: string, h: number, tracking = 0.06) {
    let w = 0
    for (const ch of text) w += (glyphAdvance(ch) + tracking) * h
    return w - tracking * h
  }

  /**
   * A line of text centred on (x, y, z), facing local +Z after `rotY`, letters `h` tall.
   * `outline` draws bent-tube letters, `body` uses the world's body font (stencil codes).
   * `vertical` stacks the letters downward from y.
   */
  text(
    text: string,
    x: number,
    y: number,
    z: number,
    h: number,
    color: string,
    {
      glow = GLOW.sign as number,
      t = 0.5,
      rotY = 0,
      outline = false,
      body = false,
      vertical = false,
      tracking = 0.06,
    } = {},
  ) {
    const q = h * GLYPH_QUAD
    const channel = body ? 2 : outline ? 1 : 0
    const width = vertical ? 0 : KitBuilder.textWidth(text, h, tracking)
    let cursor = -width / 2
    let row = 0
    for (const ch of text.toUpperCase()) {
      const adv = glyphAdvance(ch) * h
      const index = GLYPHS.indexOf(ch)
      if (index >= 0) {
        const lx = vertical ? 0 : cursor + adv / 2
        const ly = vertical ? -row * h * 1.28 : 0
        m4.makeRotationY(rotY)
        m4.multiply(new Matrix4().makeTranslation(lx, ly, 0)).multiply(
          new Matrix4().makeScale(q, q, 1),
        )
        m4.elements[12] += x
        m4.elements[13] += y
        m4.elements[14] += z
        this.write(this.glyph, m4, color, glow, t, index, channel, 0)
      }
      cursor += adv + tracking * h
      if (ch !== ' ' || vertical) row++
    }
    return this
  }
}

// ---------------------------------------------------------------------------------------------
// Glyph atlas

const ATLAS = 1024
const CELL = ATLAS / 8
const atlasData = new Uint8Array(ATLAS * ATLAS * 4)
let atlasTexture: DataTexture | null = null
const fontsAsked = new Set<string>()

function drawAtlas(display: string, body: string) {
  const canvas = document.createElement('canvas')
  canvas.width = canvas.height = ATLAS
  const ctx = canvas.getContext('2d', { willReadFrequently: true })
  if (!ctx) return
  const pass = (family: string, weight: number, stroke: boolean, channel: number) => {
    ctx.clearRect(0, 0, ATLAS, ATLAS)
    ctx.fillStyle = ctx.strokeStyle = 'white'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'alphabetic'
    ctx.lineJoin = ctx.lineCap = 'round'
    // Size the font so a capital is exactly half a cell tall, whatever the face.
    ctx.font = `${weight} 100px ${family}`
    const cap = ctx.measureText('H').actualBoundingBoxAscent || 70
    const px = (100 * CELL * 0.5) / cap
    ctx.font = `${weight} ${px}px ${family}`
    ctx.lineWidth = CELL * 0.05
    for (let i = 0; i < GLYPHS.length; i++) {
      const cx = (i % 8) * CELL + CELL / 2
      const cy = Math.floor(i / 8) * CELL + CELL * 0.75
      if (stroke) ctx.strokeText(GLYPHS[i], cx, cy)
      else ctx.fillText(GLYPHS[i], cx, cy)
    }
    const img = ctx.getImageData(0, 0, ATLAS, ATLAS).data
    for (let p = 0; p < ATLAS * ATLAS; p++) atlasData[p * 4 + channel] = img[p * 4 + 3]
  }
  pass(display, 600, false, 0)
  pass(display, 600, true, 1)
  pass(body, 500, false, 2)
  for (let p = 0; p < ATLAS * ATLAS; p++) atlasData[p * 4 + 3] = 255
  if (atlasTexture) atlasTexture.needsUpdate = true
}

/** The sign glyph atlas: R display fill, G display outline, B body fill. Redrawn when the world's fonts arrive. */
export function glyphAtlas(fonts?: { display?: string; body?: string }) {
  const families = { display: 'sans-serif', body: 'monospace' }
  if (!atlasTexture) {
    atlasTexture = new DataTexture(atlasData, ATLAS, ATLAS, RGBAFormat)
    atlasTexture.magFilter = LinearFilter
    atlasTexture.minFilter = LinearMipmapLinearFilter
    atlasTexture.generateMipmaps = true
    if (typeof document !== 'undefined') drawAtlas(families.display, families.body)
    atlasTexture.needsUpdate = true
  }
  if (typeof document === 'undefined' || typeof FontFace === 'undefined') return atlasTexture
  const key = `${fonts?.display}|${fonts?.body}`
  if (fonts && !fontsAsked.has(key)) {
    fontsAsked.add(key)
    const load = (name: string, url?: string) =>
      url
        ? new FontFace(name, `url(${url})`).load().then(
            (f) => {
              ;(document.fonts as unknown as { add(face: FontFace): void }).add(f)
              return `"${name}"`
            },
            () => null,
          )
        : Promise.resolve(null)
    void Promise.all([
      load('runek-kit-display', fonts.display),
      load('runek-kit-body', fonts.body),
    ]).then(([d, b]) => {
      if (d || b)
        drawAtlas(d ? `${d}, sans-serif` : families.display, b ? `${b}, monospace` : families.body)
    })
  }
  return atlasTexture
}

// ---------------------------------------------------------------------------------------------
// Materials (WebGL). The WebGPU twins live in kitNode.ts.

/** Uniforms the kit shares with every tower, plus its own night level. */
export const kitUniforms = {
  ...towerUniforms,
  uNight: { value: 1 },
  tAtlas: { value: null as DataTexture | null },
}

const PARS = /* glsl */ `
uniform float uNight;
uniform float uWallGain;
uniform vec3 uGlow;
uniform vec2 uSign;
uniform vec2 uTube;
uniform vec2 uShop;
float rung(vec2 r, float t) { return r.x * pow(r.y / r.x, t); }
float kitRung(float glow, float t) { return glow < 1.5 ? rung(uSign, t) : (glow < 2.5 ? rung(uTube, t) : rung(uShop, t)); }
`

const BOX_VERT = /* glsl */ `
attribute vec4 aColor;
attribute vec4 aKit;
varying vec4 vColor;
varying vec4 vKit;
varying vec2 vUvM;
varying vec2 vFace;
varying vec3 vLN;
varying vec3 vWN;
varying float vWorldY;
#include <fog_pars_vertex>
void main() {
  vColor = aColor; vKit = aKit; vLN = normal;
  mat4 im = instanceMatrix;
  vec3 s = vec3(length(im[0].xyz), length(im[1].xyz), length(im[2].xyz));
  vec3 an = abs(normal);
  vFace = an.x > 0.5 ? s.zy : (an.y > 0.5 ? s.xz : s.xy);
  vUvM = uv * vFace;
  vWN = normalize(mat3(modelMatrix) * mat3(im) * normal);
  vec4 wp = modelMatrix * im * vec4(position, 1.0);
  vWorldY = wp.y;
  vec4 mvPosition = viewMatrix * wp;
  gl_Position = projectionMatrix * mvPosition;
  #include <fog_vertex>
}`

const BOX_FRAG = /* glsl */ `
${PARS}
varying vec4 vColor;
varying vec4 vKit;
varying vec2 vUvM;
varying vec2 vFace;
varying vec3 vLN;
varying vec3 vWN;
varying float vWorldY;
#include <fog_pars_fragment>
float pulseInt(float x, float a, float b) { return floor(x) * (b - a) + clamp(fract(x), a, b) - a; }
// Box-filtered periodic pulse: coverage of [a, b] in each unit cell over a footprint w.
float pulse(float x, float a, float b, float w) {
  w = max(w, 1e-4);
  return (pulseInt(x + 0.5 * w, a, b) - pulseInt(x - 0.5 * w, a, b)) / w;
}
float band(float x, float a, float b, float w) {
  return clamp((min(x + 0.5 * w, b) - max(x - 0.5 * w, a)) / max(w, 1e-4), 0.0, 1.0);
}
void main() {
  float glow = vColor.a, t = vKit.x, detail = vKit.y, sd = vKit.z;
  vec2 m = vUvM, fw = fwidth(vUvM);
  float side = 1.0 - step(0.5, abs(vLN.y));
  float front = step(0.5, vLN.z);
  float tone = 1.0;
  if (detail > 0.5 && detail < 1.5) {
    tone = mix(0.55, 1.0, pulse(m.y / 0.11, 0.0, 0.7, fw.y / 0.11)) * side + (1.0 - side);
  } else if (detail < 2.5 && detail > 1.5) {
    // An outdoor unit: a fan ring behind fins on the front, a seam round the case.
    vec2 c = (m - vec2(vFace.x * 0.38, vFace.y * 0.5)) / (vFace.y * 0.4);
    float disc = 1.0 - smoothstep(0.92, 1.0, length(c));
    float fins = pulse(m.y / 0.045, 0.0, 0.5, fw.y / 0.045);
    tone = mix(1.0, mix(0.25, 0.6, fins) * (0.6 + 0.4 * smoothstep(0.15, 0.3, length(c))), disc * front);
    tone *= mix(1.0, 0.7, (1.0 - front) * side * band(m.y, vFace.y - 0.05, vFace.y, fw.y));
  } else if (detail < 3.5 && detail > 2.5) {
    // A vending window: rows of lit goods.
    tone = mix(0.2, 1.0, pulse(m.y / 0.26, 0.12, 1.0, fw.y / 0.26) * pulse(m.x / 0.13, 0.2, 1.0, fw.x / 0.13));
  } else if (detail < 4.5 && detail > 3.5) {
    tone = mix(0.55, 1.0, pulse(m.x / 0.7, 0.0, 0.5, fw.x / 0.7));
  } else if (detail < 5.5 && detail > 4.5) {
    float wire = 1.0 - pulse(m.x / 0.09, 0.0, 0.8, fw.x / 0.09) * pulse(m.y / 0.09, 0.0, 0.8, fw.y / 0.09);
    tone = mix(0.35, 1.3, wire);
  } else if (detail > 5.5) {
    float rim = 1.0 - band(m.x, 0.05, vFace.x - 0.05, fw.x) * band(m.y, 0.05, vFace.y - 0.05, fw.y);
    tone = mix(1.0, 2.2, rim * (1.0 - step(0.5, abs(vLN.x))));
  }
  vec3 col;
  if (glow < 0.5) {
    // Matte: the wall's own unlit model, with a face shade so a box reads as a solid.
    float shade = 0.72 + 0.28 * vWN.y + 0.1 * vWN.x;
    col = vColor.rgb * mix(0.35, uWallGain, uNight) * shade * tone;
    col += uGlow * exp(-max(vWorldY, 0.0) / 6.0) * uNight * (0.55 + 0.45 * shade) * min(tone, 1.0);
  } else {
    col = vColor.rgb * kitRung(glow, t) * tone * mix(0.12, 1.0, uNight);
  }
  gl_FragColor = vec4(col, 1.0);
  #include <tonemapping_fragment>
  #include <colorspace_fragment>
  #include <fog_fragment>
}`

const GLYPH_VERT = /* glsl */ `
attribute vec4 aColor;
attribute vec4 aKit;
varying vec4 vColor;
varying vec3 vKit;
varying vec2 vUv;
#include <fog_pars_vertex>
void main() {
  vColor = aColor; vKit = aKit.xyz;
  vec2 cell = vec2(mod(aKit.y, 8.0), floor(aKit.y / 8.0));
  vUv = vec2(cell.x + uv.x, cell.y + 1.0 - uv.y) / 8.0;
  vec4 mvPosition = viewMatrix * modelMatrix * instanceMatrix * vec4(position, 1.0);
  gl_Position = projectionMatrix * mvPosition;
  #include <fog_vertex>
}`

const GLYPH_FRAG = /* glsl */ `
${PARS}
uniform sampler2D tAtlas;
varying vec4 vColor;
varying vec3 vKit;
varying vec2 vUv;
#include <fog_pars_fragment>
void main() {
  vec3 tx = texture2D(tAtlas, vUv).rgb;
  float a = vKit.z < 0.5 ? tx.r : (vKit.z < 1.5 ? tx.g : tx.b);
  // Sharpen the edge when the atlas is magnified. Leave the mip's own coverage when it is not.
  float texels = length(fwidth(vUv)) * ${ATLAS}.0;
  float w = clamp(fwidth(a), 0.03, 0.5);
  a = mix(smoothstep(0.5 - w, 0.5 + w, a), a, clamp(texels - 0.6, 0.0, 1.0));
  if (a < 0.01) discard;
  // Glow 0 is paint on a wall (stencil codes). Anything else is a lit letter on its rung.
  vec3 col = vColor.a < 0.5 ? vColor.rgb * mix(0.35, uWallGain, uNight) + uGlow * uNight * 0.5 : vColor.rgb * kitRung(vColor.a, vKit.x) * mix(0.12, 1.0, uNight);
  gl_FragColor = vec4(col, a);
  #include <tonemapping_fragment>
  #include <colorspace_fragment>
  #include <fog_fragment>
}`

const SPLAT_VERT = /* glsl */ `
attribute vec4 aColor;
attribute vec4 aKit;
uniform float uNight;
uniform vec2 uStreet;
varying vec3 vColor;
varying vec2 vUv;
varying vec3 vWorld;
void main() {
  vColor = aColor.rgb * uStreet.x * pow(uStreet.y / uStreet.x, aKit.x) * uNight;
  vUv = uv;
  vec4 world = modelMatrix * instanceMatrix * vec4(position, 1.0);
  vWorld = world.xyz;
  gl_Position = projectionMatrix * viewMatrix * world;
}`

// Brightest at the foot of the wall, gone at the far edge. Added to the street, so it fades
// with the fog range instead of mixing toward the fog color.
const SPLAT_FRAG = /* glsl */ `
varying vec3 vColor;
varying vec2 vUv;
varying vec3 vWorld;
${FOG_FADE}
void main() {
  float d = length(vec2((vUv.x - 0.5) * 2.0, 1.0 - vUv.y));
  float a = 1.0 - smoothstep(0.0, 1.0, d);
  gl_FragColor = vec4(vColor * a * a * hazeFog(vWorld), 1.0);
}`

function glMaterials(): KitMaterialSet {
  const fog = () => UniformsUtils.merge([UniformsLib.fog])
  const box = new ShaderMaterial({
    uniforms: { ...fog(), ...kitUniforms },
    vertexShader: BOX_VERT,
    fragmentShader: BOX_FRAG,
    fog: true,
  })
  const glyph = new ShaderMaterial({
    uniforms: { ...fog(), ...kitUniforms },
    vertexShader: GLYPH_VERT,
    fragmentShader: GLYPH_FRAG,
    fog: true,
    transparent: true,
    depthWrite: false,
  })
  const splat = new ShaderMaterial({
    uniforms: { ...fog(), ...kitUniforms },
    vertexShader: SPLAT_VERT,
    fragmentShader: SPLAT_FRAG,
    fog: true,
    transparent: true,
    blending: AdditiveBlending,
    depthWrite: false,
    // It lies a few centimetres over the street, which is not enough far away.
    polygonOffset: true,
    polygonOffsetFactor: -2,
    polygonOffsetUnits: -4,
  })
  return { box, glyph, splat }
}

// ---------------------------------------------------------------------------------------------
// The per-scene kit

type Slot = 'near' | 'small' | 'glyph' | 'splat'
const SLOTS: Slot[] = ['near', 'small', 'glyph', 'splat']

export interface KitMaterialSet {
  box: Material
  glyph: Material
  splat: Material
}

/** Makes the kit's box, glyph and splat materials. WebGPU passes its node twins. */
export type KitMaterials = (atlas: DataTexture) => KitMaterialSet

export class Kit {
  private entries = new Map<number, { parts: KitBuilder; world: Matrix4 }>()
  private meshes: Partial<Record<Slot, InstancedMesh>> = {}
  private materials: KitMaterialSet
  private nextId = 1
  private unskip = new Map<InstancedMesh, () => void>()
  private queued = false
  users = 0

  constructor(
    private scene: Scene,
    make: KitMaterials | undefined,
    atlas: DataTexture,
  ) {
    kitUniforms.tAtlas.value = atlas
    this.materials = make ? make(atlas) : glMaterials()
  }

  add(parts: KitBuilder, world: Matrix4) {
    const id = this.nextId++
    this.entries.set(id, { parts, world: world.clone() })
    this.queue()
    return id
  }
  remove(id: number) {
    this.entries.delete(id)
    this.queue()
  }
  private queue() {
    if (this.queued) return
    this.queued = true
    queueMicrotask(() => this.flush())
  }

  /** Rewrite the instance buffers from every registered component. */
  private flush() {
    this.queued = false
    for (const slot of SLOTS) {
      let count = 0
      for (const e of this.entries.values()) count += e.parts[slot].length / KIT_STRIDE
      let mesh = this.meshes[slot]
      if (!mesh || mesh.instanceMatrix.count < count) {
        if (mesh) this.drop(mesh)
        if (count === 0) {
          delete this.meshes[slot]
          continue
        }
        mesh = this.meshes[slot] = this.make(slot, Math.ceil(count * 1.25) + 16)
      }
      const mat = mesh.instanceMatrix.array as Float32Array
      const color = mesh.geometry.getAttribute('aColor') as InstancedBufferAttribute
      const kit = mesh.geometry.getAttribute('aKit') as InstancedBufferAttribute
      let i = 0
      for (const e of this.entries.values()) {
        const src = e.parts[slot]
        for (let o = 0; o < src.length; o += KIT_STRIDE, i++) {
          m4.fromArray(src, o)
            .premultiply(e.world)
            .toArray(mat, i * 16)
          for (let k = 0; k < 4; k++) {
            color.array[i * 4 + k] = src[o + 16 + k]
            kit.array[i * 4 + k] = src[o + 20 + k]
          }
        }
      }
      mesh.count = count
      mesh.instanceMatrix.needsUpdate = color.needsUpdate = kit.needsUpdate = true
    }
  }

  private make(slot: Slot, capacity: number) {
    const flat = slot === 'glyph' || slot === 'splat'
    const geometry = flat ? new PlaneGeometry(1, 1) : new BoxGeometry(1, 1, 1)
    geometry.setAttribute('aColor', new InstancedBufferAttribute(new Float32Array(capacity * 4), 4))
    geometry.setAttribute('aKit', new InstancedBufferAttribute(new Float32Array(capacity * 4), 4))
    const mesh = new InstancedMesh(
      geometry,
      flat ? this.materials[slot] : this.materials.box,
      capacity,
    )
    mesh.name = `runek:kit:${slot}`
    // Instances span the world, so one bound would never cull anything useful.
    mesh.frustumCulled = false
    mesh.matrixAutoUpdate = false
    // Mirrors skip the small parts, and the light on the street they are themselves laid over.
    if (slot === 'small' || slot === 'splat') this.unskip.set(mesh, skipMirrors(mesh))
    if (slot === 'glyph') mesh.renderOrder = 2
    if (slot === 'splat') mesh.renderOrder = 1
    this.scene.add(mesh)
    return mesh
  }
  private drop(mesh: InstancedMesh) {
    this.unskip.get(mesh)?.()
    this.unskip.delete(mesh)
    this.scene.remove(mesh)
    mesh.geometry.dispose()
    mesh.dispose()
  }
  dispose() {
    for (const slot of SLOTS) if (this.meshes[slot]) this.drop(this.meshes[slot])
    this.meshes = {}
    this.materials.box.dispose()
    this.materials.glyph.dispose()
    this.materials.splat.dispose()
  }
}

const kits = new WeakMap<Scene, Kit>()

/** The scene's kit, made on first use. Pair every call with `releaseKit`. */
export function acquireKit(
  scene: Scene,
  make: KitMaterials | undefined,
  fonts?: { display?: string; body?: string },
) {
  let kit = kits.get(scene)
  if (!kit) {
    kit = new Kit(scene, make, glyphAtlas(fonts))
    kits.set(scene, kit)
  }
  kit.users++
  return kit
}

export function releaseKit(scene: Scene) {
  const kit = kits.get(scene)
  if (!kit || --kit.users > 0) return
  // Wait a tick: a component that re-registers in the same commit keeps the kit alive.
  queueMicrotask(() => {
    if (kit.users > 0 || kits.get(scene) !== kit) return
    kit.dispose()
    kits.delete(scene)
  })
}

city/kitParts.ts

// The facade kit's parts. Each function adds one prop to a KitBuilder in a wall frame: +X runs
// along the wall to the viewer's right, +Y is up, +Z points out of the wall. (x, y, z) is where
// the prop meets the wall. Tower calls these for its street faces, and each also backs a
// standalone component of the same name.

import { DETAIL, GLOW, KitBuilder } from './kit'

const CASES = ['#8a8a84', '#75736c', '#9a9488', '#6b6f70']
const DARK = '#141110'
const STEEL = '#4a4844'
const RUST = '#5a4234'

/** An outdoor AC unit on its bracket. `cage` wraps it in a wire cage. */
export function acUnit(
  kit: KitBuilder,
  x: number,
  y: number,
  z: number,
  { seed = 0, cage = false } = {},
) {
  const tone = CASES[Math.floor(Math.abs(seed) * 97) % CASES.length]
  if (cage) {
    kit.box(true, x, y + 0.36, z + 0.24, 0.98, 0.72, 0.48, RUST, { detail: DETAIL.cage, seed })
  } else {
    kit.box(true, x, y + 0.33, z + 0.19, 0.82, 0.58, 0.34, tone, { detail: DETAIL.fan, seed })
  }
  kit.box(true, x, y + 0.02, z + 0.2, 0.9, 0.04, 0.4, DARK)
  // The drain hose.
  kit.box(true, x + 0.34, y - 0.4, z + 0.03, 0.03, 0.8, 0.03, DARK)
}

/** A pipe run with collars: up the wall from (x, y, z), or along it when `horizontal`. */
export function pipeRun(
  kit: KitBuilder,
  x: number,
  y: number,
  z: number,
  length: number,
  { horizontal = false, radius = 0.06, color = STEEL } = {},
) {
  const t = radius * 2
  if (horizontal) kit.box(true, x + length / 2, y, z + radius + 0.03, length, t, t, color)
  else kit.box(true, x, y + length / 2, z + radius + 0.03, t, length, t, color)
  const collars = Math.max(2, Math.round(length / 2.4))
  for (let i = 0; i < collars; i++) {
    const at = ((i + 0.5) * length) / collars
    if (horizontal) kit.box(true, x + at, y, z + radius + 0.02, 0.07, t + 0.06, t + 0.05, DARK)
    else kit.box(true, x, y + at, z + radius + 0.02, t + 0.06, 0.07, t + 0.05, DARK)
  }
}

/** Height of a cable `t` of the way across (0 to 1): a parabola that drops `sag` at mid span and ends `drop` higher. */
export const cableY = (t: number, sag: number, drop = 0) => drop * t - 4 * sag * t * (1 - t)

/** A cable sagging from the wall at (x, y, z) across `span` metres of street. */
export function cableSag(
  kit: KitBuilder,
  x: number,
  y: number,
  z: number,
  span: number,
  { sag = 1.2, drop = 0, segments = 8, color = DARK, thickness = 0.04 } = {},
) {
  for (let i = 0; i < segments; i++) {
    const t0 = i / segments
    const t1 = (i + 1) / segments
    const y0 = cableY(t0, sag, drop)
    const y1 = cableY(t1, sag, drop)
    const len = span / segments
    kit.box(
      true,
      x,
      y + (y0 + y1) / 2,
      z + (t0 + t1) * 0.5 * span,
      thickness,
      thickness,
      len,
      color,
      { rise: (y1 - y0) / len },
    )
  }
}

/** A louvred vent under a small hood. */
export function vent(
  kit: KitBuilder,
  x: number,
  y: number,
  z: number,
  { width = 0.6, height = 0.45 } = {},
) {
  kit.box(true, x, y + height / 2, z + 0.04, width, height, 0.08, STEEL, { detail: DETAIL.slats })
  kit.box(true, x, y + height + 0.03, z + 0.08, width + 0.08, 0.05, 0.16, DARK)
}

/** A sloped fabric awning hung at (x, y, z), `width` along the wall, with a valance. */
export function awning(
  kit: KitBuilder,
  x: number,
  y: number,
  z: number,
  width: number,
  { depth = 1.3, drop = 0.45, color = '#5a2a1c', stripes = true } = {},
) {
  const detail = stripes ? DETAIL.stripes : DETAIL.none
  kit.box(false, x, y - drop / 2, z + depth / 2, width, 0.05, depth, color, {
    detail,
    rise: -drop / depth,
  })
  kit.box(false, x, y - drop - 0.1, z + depth, width, 0.22, 0.03, color, { detail })
  // The two arms that carry it.
  for (const side of [-1, 1])
    kit.box(
      true,
      x + side * (width / 2 - 0.05),
      y - drop / 2 - 0.05,
      z + depth / 2,
      0.04,
      0.04,
      depth,
      DARK,
      { rise: -drop / depth },
    )
}

/** A roller shutter in its housing. `open` is the share rolled up, 0 (down) to 1. */
export function rollerShutter(
  kit: KitBuilder,
  x: number,
  y: number,
  z: number,
  width: number,
  height: number,
  { open = 0, color = '#6e6a62' } = {},
) {
  const down = height * (1 - Math.min(1, Math.max(0, open)))
  if (down > 0.05)
    kit.box(false, x, y + height - down / 2, z + 0.05, width, down, 0.05, color, {
      detail: DETAIL.slats,
    })
  kit.box(false, x, y + height + 0.1, z + 0.11, width + 0.12, 0.26, 0.22, STEEL)
  for (const side of [-1, 1])
    kit.box(
      true,
      x + side * (width / 2 + 0.03),
      y + height / 2,
      z + 0.05,
      0.06,
      height,
      0.09,
      STEEL,
    )
}

/** The word a blade sign stacks: the longest word of a shop's name that has seven letters or fewer. */
export function bladeWord(name: string) {
  const words = name.toUpperCase().split(' ')
  let best = ''
  for (const w of words) if (w.length <= 7 && w.length > best.length) best = w
  return best || words[0].slice(0, 9)
}

/** A blade sign: a board standing out from the wall, its letters stacked and lit on both faces. (x, y, z) is the bottom of the board at the wall. */
export function bladeSign(
  kit: KitBuilder,
  x: number,
  y: number,
  z: number,
  text: string,
  { letter = 0.55, color = '#ff6418', gap = 0.3, tube = true } = {},
) {
  const word = text.toUpperCase().replace(/ /g, '')
  const step = letter * 1.28
  const height = word.length * step + 0.3
  const depth = letter * 1.15 + 0.3
  const mid = z + gap + depth / 2
  kit.box(false, x, y + height / 2, mid, 0.14, height, depth, DARK)
  const top = y + height - 0.15 - step / 2
  for (const side of [-1, 1]) {
    kit.text(word, x + side * 0.085, top, mid, letter, color, {
      vertical: true,
      rotY: (side * Math.PI) / 2,
      t: 0.45,
    })
  }
  if (tube) {
    for (const edge of [-1, 1])
      kit.box(
        false,
        x,
        y + height / 2,
        mid + edge * (depth / 2 + 0.02),
        0.05,
        height,
        0.05,
        color,
        { glow: GLOW.tube, t: 0.1 },
      )
  }
  // Two arms back to the wall.
  for (const at of [0.25, height - 0.25])
    kit.box(true, x, y + at, z + gap / 2, 0.05, 0.05, gap, STEEL)
}

/** A vending machine standing against the wall: a matte case and a lit window of goods. The case is solid. */
export function vendingMachine(
  kit: KitBuilder,
  x: number,
  y: number,
  z: number,
  { seed = 0, color = '#3a2f45', lamp = '#ffcf9a' } = {},
) {
  kit.box(true, x, y + 0.93, z + 0.36, 1.0, 1.86, 0.72, color)
  kit.solid(x, y + 0.93, z + 0.36, 1.0, 1.86, 0.72)
  kit.box(false, x - 0.06, y + 1.2, z + 0.73, 0.76, 1.02, 0.03, lamp, {
    glow: GLOW.glass,
    t: 0.35,
    detail: DETAIL.vending,
    seed,
  })
  kit.box(true, x - 0.06, y + 0.38, z + 0.73, 0.6, 0.2, 0.03, DARK)
  kit.box(true, x + 0.4, y + 1.2, z + 0.73, 0.1, 0.7, 0.03, DARK)
}

/** A shop's name over its bay: lit letters on a dark board, or bare tube letters. `fit` is the most width it may take. */
export function fasciaSign(
  kit: KitBuilder,
  x: number,
  y: number,
  z: number,
  text: string,
  { letter = 0.5, color = '#ffa64d', fit = 0, tube = false, board = true } = {},
) {
  let h = letter
  const wide = KitBuilder.textWidth(text, h)
  if (fit > 0 && wide + 0.4 > fit) h *= fit / (wide + 0.4)
  const width = KitBuilder.textWidth(text, h)
  if (board)
    kit.box(false, x, y, z + 0.04, width + h * 0.9, h * 1.75, 0.08, DARK, { detail: DETAIL.panel })
  kit.text(text, x, y, z + 0.1, h, color, {
    outline: tube,
    glow: tube ? GLOW.tube : GLOW.sign,
    t: tube ? 0.12 : 0.5,
  })
  return width + h * 0.9
}

/** A drum lantern on a wall arm: the corner light of a tenement street. */
export function drumLantern(
  kit: KitBuilder,
  x: number,
  y: number,
  z: number,
  { color = '#ffa64d', reach = 0.7 } = {},
) {
  const at = z + reach
  for (const turn of [0, Math.PI / 4]) {
    kit.box(false, x, y, at, 0.5, 0.78, 0.5, color, { glow: GLOW.sign, t: 0.25, rotY: turn })
    kit.box(true, x, y + 0.43, at, 0.58, 0.08, 0.58, DARK, { rotY: turn })
    kit.box(true, x, y - 0.43, at, 0.58, 0.08, 0.58, DARK, { rotY: turn })
  }
  kit.box(true, x, y + 0.55, z + reach / 2, 0.05, 0.05, reach, STEEL)
}

/** Big letters on an open frame, standing on a roof edge. (x, y, z) is the middle of the frame's foot. Returns its width. */
export function roofSign(
  kit: KitBuilder,
  x: number,
  y: number,
  z: number,
  text: string,
  { letter = 1.8, color = '#ff6418', fit = 0 } = {},
) {
  let h = letter
  const wide = KitBuilder.textWidth(text, h, 0.1)
  if (fit > 0 && wide > fit) h *= fit / wide
  const width = KitBuilder.textWidth(text, h, 0.1)
  const base = y + 0.9
  kit.text(text, x, base + h / 2, z + 0.08, h, color, { t: 0.75, tracking: 0.1 })
  for (const rail of [0.12, 0.88])
    kit.box(false, x, base + h * rail, z, width + 0.6, 0.07, 0.07, STEEL)
  const posts = Math.max(2, Math.round(width / 3))
  for (let i = 0; i < posts; i++) {
    const px = x - width / 2 + (width * i) / (posts - 1)
    kit.box(true, px, y + (0.9 + h) / 2, z - 0.06, 0.1, 0.9 + h, 0.1, STEEL)
    kit.box(true, px, y + 0.5, z - 0.5, 0.07, 0.07, 0.95, STEEL, { rise: -0.9 })
  }
  return width
}

/** A stencilled code painted on the wall in the body font. */
export function stencilCode(
  kit: KitBuilder,
  x: number,
  y: number,
  z: number,
  text: string,
  { letter = 0.3, color = '#a8a092' } = {},
) {
  kit.text(text, x, y, z + 0.012, letter, color, { glow: GLOW.matte, body: true, tracking: 0.12 })
}

city/useKit.ts

import { useThree } from '@react-three/fiber'
import { lazyModule, useNodeRenderer, useWorld } from '@runek/core'
import { type DependencyList, useLayoutEffect, useMemo, useRef } from 'react'
import type { Group } from 'three'
import { useLadder } from './glow'
import { acquireKit, KitBuilder, kitUniforms, releaseKit } from './kit'
import { applyTowerLight, nightFactor, towerLight } from './towerLight'

// The kit's node (TSL) materials, loaded only under a node renderer.
const kitNodes = lazyModule(() => import('../nodes/kit'))

/**
 * Register a component's kit parts with the scene's shared instanced meshes. `build` describes
 * the parts in local space and must be a pure function of `deps`. Attach the returned ref to a
 * group at the component's origin: its world matrix places the parts. `place` is any value that
 * changes when that group moves (the position and rotation props).
 */
export function useKit(build: (kit: KitBuilder) => void, deps: DependencyList, place: unknown) {
  const parts = useMemo(() => {
    const kit = new KitBuilder()
    build(kit)
    return kit
  }, deps)
  return useKitParts(parts, place)
}

/**
 * The same, for a component that built its own `KitBuilder` because it needs more than the
 * instances out of it (Tower reads `solids` to make its colliders). `parts` must be memoized.
 */
export function useKitParts(parts: KitBuilder, place: unknown) {
  const ref = useRef<Group>(null)
  const scene = useThree((s) => s.scene)
  const nodes = useNodeRenderer() ? kitNodes() : null
  const { fonts, time } = useWorld()
  const ladder = useLadder()
  const night = Math.round(nightFactor(time.hours) * 10) / 10

  useLayoutEffect(() => applyTowerLight(ladder), [ladder])
  useLayoutEffect(() => {
    kitUniforms.uNight.value = night
    towerLight.night = night
  }, [night])
  const placeKey = JSON.stringify(place)
  useLayoutEffect(() => {
    const group = ref.current
    if (!group) return
    group.updateWorldMatrix(true, false)
    const kit = acquireKit(scene, nodes?.kitNodeMaterials, fonts)
    const id = kit.add(parts, group.matrixWorld)
    return () => {
      kit.remove(id)
      releaseKit(scene)
    }
  }, [parts, scene, nodes, fonts.display, fonts.body, placeKey])
  return ref
}

city/glow.ts

// How bright each kind of city emitter is, as a ladder of rungs, each the lowest and highest
// luminance that kind may have, so a sign face is a sign face whatever its hue and a lamp lens
// always outshines it. The rungs are face values scaled by the world's luminance levels
// (`useLuminance()`): sign faces by `sign`, tube cores by `tube`, lamp lenses by `lamp`, and lit
// glass (windows, shopfronts, ad boards, and the light they leave on the pavement) by `screen`.
// At every level's default of 1 the brightest rungs sit around 1, so they read without bloom; a
// world with bloom raises `sign`, `tube` and `lamp` to make them bloom.
//
// Emissive colors are normalized to unit luminance and then scaled onto a rung, so the hue of a
// color never changes how bright it reads.

import {
  DEFAULT_LUMINANCE,
  glowLook,
  type MaterialLook,
  materialKey,
  retainMaterial,
  sharedMaterial,
  useLuminance,
  type WorldLuminance,
} from '@runek/core'
import { useMemo } from 'react'
import { Color, type Material } from 'three'

/** A rung of the ladder: the lowest and highest luminance that kind of emitter may have. */
export type Rung = readonly [number, number]

export interface Ladder {
  /** A night sky dome lit from below by a city. Face value. */
  skyDome: Rung
  /** A wall with no lamp on it. Face value. */
  unlitWall: Rung
  /** Pavement lit by the glass and signs above it. */
  streetUnderSign: Rung
  /** A lit room seen through its window from the street. */
  windowLit: Rung
  /** Lit shopfront glass, and the white of an ad board. */
  shopGlass: Rung
  /** Sign faces and lit letters. */
  signFace: Rung
  /** The core of a neon tube. */
  tubeCore: Rung
  /** A street lamp's lens seen from below. */
  lampLens: Rung
}

const scale = (r: Rung, k: number): Rung => [r[0] * k, r[1] * k]

/** The rungs at every luminance level's face value (1). */
export const FACE_LADDER: Ladder = {
  skyDome: [0.018, 0.055],
  unlitWall: [0.02, 0.05],
  streetUnderSign: [0.1, 0.5],
  windowLit: [0.15, 0.6],
  shopGlass: [0.4, 1.2],
  signFace: [0.6, 1.6],
  tubeCore: [0.6, 1.7],
  lampLens: [0.67, 1.5],
}

/** The ladder for a world's luminance levels. */
export function ladderFor(l: WorldLuminance): Ladder {
  const f = FACE_LADDER
  return {
    skyDome: f.skyDome,
    unlitWall: f.unlitWall,
    streetUnderSign: scale(f.streetUnderSign, l.screen),
    windowLit: scale(f.windowLit, l.screen),
    shopGlass: scale(f.shopGlass, l.screen),
    signFace: scale(f.signFace, l.sign),
    tubeCore: scale(f.tubeCore, l.tube),
    lampLens: scale(f.lampLens, l.lamp),
  }
}

/** The ladder at the default levels. */
export const DEFAULT_LADDER: Ladder = ladderFor(DEFAULT_LUMINANCE)

/** The world's ladder, from its luminance levels. */
export function useLadder(): Ladder {
  const { screen, sign, tube, lamp, flame } = useLuminance()
  return useMemo(
    () => ladderFor({ screen, sign, tube, lamp, flame }),
    [screen, sign, tube, lamp, flame],
  )
}

/** The typical value of a rung: the geometric middle, since luminance is perceived on a log scale. */
export function mid(rung: Rung): number {
  return Math.sqrt(rung[0] * rung[1])
}

/** A point along a rung, 0 at its bottom and 1 at its top, spaced evenly on a log scale. */
export function along(rung: Rung, t: number): number {
  return rung[0] * (rung[1] / rung[0]) ** t
}

/** Relative luminance (Rec. 709) of a linear color. */
export function luminanceOf(c: Color): number {
  return 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b
}

/** `hex` at unit luminance times `luminance`, as a linear (HDR) color. */
export function emissiveColor(hex: string, luminance: number): Color {
  const c = new Color(hex)
  return c.multiplyScalar(luminance / Math.max(1e-4, luminanceOf(c)))
}

/** A shared look's material, kept for the life of the page: city emitters come back often. */
function kept(look: MaterialLook): Material {
  const key = materialKey(look)
  const material = sharedMaterial(look, key)
  if (!material.userData.kept) {
    material.userData.kept = true
    retainMaterial(key)
  }
  return material
}

/**
 * The shared unlit material for an emitter of color `hex` at `luminance`, through core's
 * `glowLook`, so it batches with every other part of that look. Read-only.
 */
export function glowMaterial(hex: string, luminance: number, opacity = 1): Material {
  return kept(
    glowLook(
      emissiveColor(hex, 1),
      luminance,
      opacity < 1 ? { transparent: true, opacity, depthWrite: false } : undefined,
    ),
  )
}

/**
 * The shared unlit material for picture content on a lit board: `hex` keeps its own value and
 * is scaled so that white would shine at `white`. Dark backgrounds stay dark, bright text and
 * shapes glow.
 */
export function screenMaterial(hex: string, white: number): Material {
  return kept(glowLook(hex, white))
}

city/haze.ts

// Additive light that is not a real light: a lamp's haze cone and the pool it leaves on the
// street. One shared material per color and strength: a GLSL ShaderMaterial here, and its TSL
// twin for WebGPURenderer in nodes/haze.ts. Both work on instanced and merged geometry: they read
// only `uv`, normals and world positions.
//
// Additive light must fade into fog rather than mix toward it (mixing would add the fog color
// wherever the cone is), so they attenuate by the scene's linear fog range themselves.

import {
  AdditiveBlending,
  type Color,
  DoubleSide,
  type Material,
  ShaderMaterial,
  UniformsLib,
  UniformsUtils,
} from 'three'

const HAZE_VERT = /* glsl */ `
varying vec3 vN;
varying vec3 vV;
varying vec2 vUv;
varying vec3 vWorld;
void main() {
  // Lamps share one instanced mesh for their cones and one for their pools (StreetLamp.tsx), so
  // each instance brings its own place and turn.
  #ifdef USE_INSTANCING
    vec4 world = modelMatrix * instanceMatrix * vec4(position, 1.0);
    vec3 n = mat3(instanceMatrix) * normal;
  #else
    vec4 world = modelMatrix * vec4(position, 1.0);
    vec3 n = normal;
  #endif
  vec4 mv = viewMatrix * world;
  vN = normalize(normalMatrix * n);
  vV = normalize(-mv.xyz);
  vUv = uv;
  vWorld = world.xyz;
  gl_Position = projectionMatrix * mv;
}`

// The scene's linear fog range sets how far additive light carries, whatever fog chunk is in use.
export const FOG_FADE = /* glsl */ `
uniform float fogNear;
uniform float fogFar;
float hazeFog(vec3 world) {
  #ifdef USE_FOG
    return 1.0 - 0.94 * smoothstep(fogNear, fogFar, distance(world, cameraPosition));
  #else
    return 1.0;
  #endif
}`

// Brightest where the cone is seen side on through its middle, falling to nothing at the top.
const CONE_FRAG = /* glsl */ `
uniform vec3 uColor;
varying vec3 vN;
varying vec3 vV;
varying vec2 vUv;
varying vec3 vWorld;
${FOG_FADE}
void main() {
  float facing = pow(abs(dot(normalize(vN), normalize(vV))), 1.5);
  float fall = vUv.y * vUv.y;
  gl_FragColor = vec4(uColor * facing * fall * hazeFog(vWorld), 1.0);
}`

// A soft disc on the ground. It doubles in strength with distance, because near lamps usually
// hold a real light from the pool, which lights the street itself.
const POOL_FRAG = /* glsl */ `
uniform vec3 uColor;
uniform vec2 uFade;
varying vec2 vUv;
varying vec3 vWorld;
${FOG_FADE}
void main() {
  float r = length(vUv - 0.5) * 2.0;
  float disc = (1.0 - smoothstep(0.0, 1.0, r));
  disc *= disc;
  float far = mix(0.5, 1.0, smoothstep(uFade.x, uFade.y, distance(vWorld, cameraPosition)));
  gl_FragColor = vec4(uColor * disc * far * hazeFog(vWorld), 1.0);
}`

const cache = new Map<string, Material>()

export function additive<M extends Material>(m: M): M {
  m.transparent = true
  m.blending = AdditiveBlending
  m.depthWrite = false
  return m
}

/** The haze cone under a lamp head, in `color` (linear, already scaled to its luminance). */
export function coneMaterial(color: Color): Material {
  const key = `cone:${color.r.toFixed(4)},${color.g.toFixed(4)},${color.b.toFixed(4)}`
  let m = cache.get(key)
  if (!m) {
    m = new ShaderMaterial({
      vertexShader: HAZE_VERT,
      fragmentShader: CONE_FRAG,
      uniforms: UniformsUtils.merge([UniformsLib.fog, { uColor: { value: color.clone() } }]),
      side: DoubleSide,
      fog: true,
    })
    m.name = `runek:haze:${key}`
    cache.set(key, additive(m))
  }
  return m
}

/** The pool a lamp leaves on the street, faded in between `near` and `far` meters from the eye. */
export function poolMaterial(color: Color, near: number, far: number): Material {
  const key = `pool:${color.r.toFixed(4)},${color.g.toFixed(4)},${color.b.toFixed(4)}:${near}:${far}`
  let m = cache.get(key)
  if (!m) {
    m = new ShaderMaterial({
      vertexShader: HAZE_VERT,
      fragmentShader: POOL_FRAG,
      uniforms: UniformsUtils.merge([
        UniformsLib.fog,
        { uColor: { value: color.clone() }, uFade: { value: [near, far] } },
      ]),
      fog: true,
    })
    m.polygonOffset = true
    m.polygonOffsetFactor = -2
    m.polygonOffsetUnits = -4
    m.name = `runek:haze:${key}`
    cache.set(key, additive(m))
  }
  return m
}

city/towerLight.ts

// What lights a Tower at night, shared by its GLSL material and its TSL port: the lamp colors
// behind windows and shopfronts (warm LED, sodium, mercury, phosphor violet and green, gas
// neon), each at unit luminance, and the uniforms that put windows, shop
// glass, trim, the lowest floors and the light a sign leaves on the street on the world's
// luminance ladder.

import { Vector2 } from 'three'
import { DEFAULT_LADDER, emissiveColor, type Ladder, mid } from './glow'

/** Lit windows: cumulative share, lamp. Most rooms are warm LED, then sodium, a few mercury, violet and green. */
export const WINDOW_LAMPS: [number, string][] = [
  [0.6, '#ffcf9a'],
  [0.86, '#ffa64d'],
  [0.94, '#b8e8c8'],
  [0.975, '#b967ff'],
  [1, '#39ff88'],
]

/** Shopfront bays: cumulative share, lamp. Bays past the last share have their shutters down. */
export const SHOP_LAMPS: [number, string][] = [
  [0.3, '#ffcf9a'],
  [0.45, '#ffa64d'],
  [0.52, '#39ff88'],
  [0.58, '#b967ff'],
  [0.62, '#ff6418'],
]

// The facade shader's integer hash (`pcg` and `h21` in towerFacade.ts), bit for bit, so the kit
// can ask what the shader draws behind a bay's glass.
function pcg(v: number) {
  const state = (Math.imul(v, 747796405) + 2891336453) >>> 0
  const word = Math.imul(((state >>> ((state >>> 28) + 4)) ^ state) >>> 0, 277803737) >>> 0
  return ((word >>> 22) ^ word) >>> 0
}
function h21(x: number, y: number) {
  const qx = (Math.floor(x) + 65536) >>> 0
  const qy = (Math.floor(y) + 65536) >>> 0
  return pcg((Math.imul(qx, 1664525) + pcg(qy)) >>> 0) / 4294967295
}
// The shader works in 32-bit floats: round the same way before a `floor` decides a cell.
const f = Math.fround

/**
 * The lamp behind a lit shop bay's glass and where on the shop rung it sits (0 to 1), as the
 * facade shader draws it. `sd` is the tower's seed value, `fseed` the face's, `bay` the bay's
 * place along the face.
 */
export function shopLamp(sd: number, fseed: number, bay: number): { color: string; level: number } {
  const last = SHOP_LAMPS[SHOP_LAMPS.length - 1]
  const r = h21(bay, f(f(f(sd) * f(13.1)) + f(fseed))) * last[0]
  return {
    color: (SHOP_LAMPS.find(([share]) => r < share) ?? last)[1],
    level: h21(bay + 3, f(f(sd) + f(f(fseed) * 5))),
  }
}

/** Trim colors a tower may pick when its `trim` is unset: gas neon, phosphor green and violet, sodium, pump orange. */
export const TRIM_NEON = ['#ff6418', '#39ff88', '#b967ff', '#ffa64d', '#ff8a1f']

/** A lamp color at unit luminance, as a GLSL literal. */
export function glslLamp(hex: string) {
  const c = emissiveColor(hex, 1)
  return `vec3(${c.r.toFixed(4)}, ${c.g.toFixed(4)}, ${c.b.toFixed(4)})`
}

/** GLSL for a cumulative lamp table: `vec3 name(float r)`, black past the last share. */
export function glslLampTable(name: string, table: [number, string][]) {
  const body = table
    .map(([share, hex]) => `if (r < ${share.toFixed(3)}) return ${glslLamp(hex)};`)
    .join('\n  ')
  return `vec3 ${name}(float r) {\n  ${body}\n  return vec3(0.0);\n}`
}

/** The ladder values a tower needs. The wall gain maps a wall color of luminance 0.04 to the bottom of the unlit-wall rung. */
function lightFrom(ladder: Ladder) {
  return {
    window: new Vector2(ladder.windowLit[0], ladder.windowLit[1]),
    shop: new Vector2(ladder.shopGlass[0], ladder.shopGlass[1]),
    trim: mid(ladder.signFace),
    sign: new Vector2(ladder.signFace[0], ladder.signFace[1]),
    tube: new Vector2(ladder.tubeCore[0], ladder.tubeCore[1]),
    street: new Vector2(ladder.streetUnderSign[0], ladder.streetUnderSign[1]),
    wallGain: ladder.unlitWall[0] / 0.04,
    glow: emissiveColor('#ffa64d', ladder.streetUnderSign[0] * 0.3),
  }
}

/**
 * The light every tower and kit part is drawn under, one set for the page. The GLSL uniforms
 * below hold its vectors by reference, and the node twins (`nodes/city.ts`) read it each render,
 * so one write relights every tower under either renderer.
 */
export const towerLight = { ...lightFrom(DEFAULT_LADDER), night: 1 }

/** Uniforms every tower ShaderMaterial shares by reference. */
export const towerUniforms = {
  uWindow: { value: towerLight.window },
  uShop: { value: towerLight.shop },
  uTrim: { value: towerLight.trim },
  uSign: { value: towerLight.sign },
  uTube: { value: towerLight.tube },
  uStreet: { value: towerLight.street },
  uWallGain: { value: towerLight.wallGain },
  uGlow: { value: towerLight.glow },
}

/** Put every tower on `ladder`. Cheap: it writes a handful of shared values. */
export function applyTowerLight(ladder: Ladder) {
  const l = lightFrom(ladder)
  towerLight.window.copy(l.window)
  towerLight.shop.copy(l.shop)
  towerLight.sign.copy(l.sign)
  towerLight.tube.copy(l.tube)
  towerLight.street.copy(l.street)
  towerLight.glow.copy(l.glow)
  towerLight.trim = towerUniforms.uTrim.value = l.trim
  towerLight.wallGain = towerUniforms.uWallGain.value = l.wallGain
}

/** 0 at midday, 1 from late evening to early morning. */
export function nightFactor(hours: number) {
  const fromNoon = Math.abs((((hours % 24) + 24) % 24) - 12) / 12 // 0 noon, 1 midnight
  return Math.min(1, Math.max(0, (fromNoon - 0.35) / 0.3))
}

nodes/kit.ts

// The facade kit's materials as TSL node materials, for WebGPURenderer. Same lighting model as
// the GLSL in city/kit.ts (matte parts under street light, emitters on their ladder rung, letters cut
// from the glyph atlas, light splats added to the street). The per-kind surface detail (slats, fan grilles, awning stripes, cage
// wire, vending rows) is skipped here: parts draw in their flat color.

import { AdditiveBlending, type DataTexture } from 'three'
import {
  attribute,
  exp,
  float,
  floor,
  max,
  mix,
  mod,
  normalWorld,
  positionWorld,
  pow,
  select,
  smoothstep,
  texture,
  uv,
  vec2,
} from 'three/tsl'
import { MeshBasicNodeMaterial, type Node } from 'three/webgpu'
import { towerNodeUniforms as U } from './city'

const rung = (r: Node<'vec2'>, t: Node<'float'>) => r.x.mul(pow(r.y.div(r.x), t))
const kitRung = (glow: Node<'float'>, t: Node<'float'>) =>
  select(
    glow.lessThan(1.5),
    rung(U.sign, t),
    select(glow.lessThan(2.5), rung(U.tube, t), rung(U.shop, t)),
  )

export function kitNodeMaterials(atlas: DataTexture) {
  const color = attribute<'vec4'>('aColor', 'vec4')
  const kit = attribute<'vec4'>('aKit', 'vec4')
  const dusk = mix(float(0.12), float(1), U.night)

  const box = new MeshBasicNodeMaterial()
  const shade = float(0.72).add(normalWorld.y.mul(0.28)).add(normalWorld.x.mul(0.1))
  const matte = color.rgb
    .mul(mix(float(0.35), U.wallGain, U.night))
    .mul(shade)
    .add(
      U.glow
        .mul(exp(max(positionWorld.y, 0).negate().div(6)))
        .mul(U.night)
        .mul(shade.mul(0.45).add(0.55)),
    )
  box.colorNode = select(
    color.a.lessThan(0.5),
    matte,
    color.rgb.mul(kitRung(color.a, kit.x)).mul(dusk),
  )
  box.fog = true

  const glyph = new MeshBasicNodeMaterial()
  const cell = vec2(mod(kit.y, 8), floor(kit.y.div(8)))
  const at = vec2(cell.x.add(uv().x), cell.y.add(float(1).sub(uv().y))).div(8)
  const tx = texture(atlas, at)
  // Glow 0 is stencil paint: matte under the street light, like the wall it sits on.
  const paint = color.rgb
    .mul(mix(float(0.35), U.wallGain, U.night))
    .add(U.glow.mul(U.night).mul(0.5))
  glyph.colorNode = select(
    color.a.lessThan(0.5),
    paint,
    color.rgb.mul(kitRung(color.a, kit.x)).mul(dusk),
  )
  glyph.opacityNode = select(kit.z.lessThan(0.5), tx.r, select(kit.z.lessThan(1.5), tx.g, tx.b))
  glyph.transparent = true
  glyph.depthWrite = false
  glyph.fog = true

  // Light on the street: a half disc from the foot of the wall, added to what lies under it.
  const splat = new MeshBasicNodeMaterial()
  const reach = vec2(uv().x.sub(0.5).mul(2), float(1).sub(uv().y)).length()
  const disc = float(1).sub(smoothstep(0, 1, reach))
  splat.colorNode = color.rgb.mul(rung(U.street, kit.x)).mul(U.night).mul(disc.mul(disc))
  splat.transparent = true
  splat.blending = AdditiveBlending
  splat.depthWrite = false
  splat.fog = false
  splat.polygonOffset = true
  splat.polygonOffsetFactor = -2
  splat.polygonOffsetUnits = -4
  return { box, glyph, splat }
}

nodes/city.ts

// The city's shared light as TSL uniforms, for the tower and kit node materials. They read
// `towerLight` (city/towerLight.ts) each render, so the light a world sets reaches them without
// a write of their own.

import { uniform } from 'three/tsl'
import { towerLight as T } from '../city/towerLight'

export const towerNodeUniforms = {
  window: uniform(T.window),
  shop: uniform(T.shop),
  trim: uniform(T.trim).onRenderUpdate(() => T.trim),
  sign: uniform(T.sign),
  tube: uniform(T.tube),
  street: uniform(T.street),
  night: uniform(T.night).onRenderUpdate(() => T.night),
  wallGain: uniform(T.wallGain).onRenderUpdate(() => T.wallGain),
  glow: uniform(T.glow),
}