component

FlyingTraffic

Lanes of hovercars over a street, decks of lanes each way, every car placed by the world clock and `seed` so every viewer sees the same traffic. Three instanced draws however many cars; no colliders.

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

Traffic in the air over a whole street, hundreds of units long.
Tune every prop in the workshop →

Add it

npx @runek/cli add flying-traffic

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

Use it

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

<FlyingTraffic position={[0, 0, 0]} cars={16} levels={[0, 8]} seed={1} />

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

{ "type": "FlyingTraffic", "props": { "position": [0, 0, 0], "cars": 16, "levels": [0, 8], "seed": 1 } }

Props

Prop Type Default Description
position [x, y, z] [0, 40, 0] The middle of the lanes [x, y, z] in units, at the height of the lowest one. Lanes run along local Z.
rotation [x, y, z] [0, 0, 0] Rotation [x, y, z] in radians.
seed number 1 Deals out each car’s lane, speed, paint and where on the lane it starts.
length number 480 How long the lanes are, in units. Cars leave one end and come in at the other, so make it longer than the fog lets anyone see.
cars number 28 How many cars fly.
lanes number 2 Lanes side by side going each way.
spacing number 7 How far apart lanes are, side to side, in units.
levels number[] [0, 9, 20] Heights of the decks of lanes above position, in units.
speed [number, number] [16, 34] Slowest and fastest a car flies, in units a second.

Registry manifest

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

Browse the whole catalog in the gallery →.

Source (2 files)

FlyingTraffic.tsx

import { useFrame } from '@react-three/fiber'
import { Dynamic, rng, skipMirrors, useWorld, type Vec3 } from '@runek/core'
import { useEffect, useMemo, useRef } from 'react'
import {
  AdditiveBlending,
  BoxGeometry,
  type BufferGeometry,
  Color,
  DoubleSide,
  Float32BufferAttribute,
  type Group,
  type InstancedMesh,
  MeshBasicMaterial,
  MeshStandardMaterial,
  Object3D,
  PlaneGeometry,
} from 'three'
import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js'
import { emissiveColor, mid, useLadder } from './city/glow'

export interface FlyingTrafficProps {
  /** The middle of the lanes [x, y, z] in units, at the height of the lowest one. Lanes run along local Z. */
  position?: Vec3
  /** Rotation [x, y, z] in radians. */
  rotation?: Vec3
  /** Deals out each car's lane, speed, paint and where on the lane it starts. */
  seed?: number
  /** How long the lanes are, in units. Cars leave one end and come in at the other, so make it
   *  longer than the fog lets anyone see. */
  length?: number
  /** How many cars fly. */
  cars?: number
  /** Lanes side by side going each way. */
  lanes?: number
  /** How far apart lanes are, side to side, in units. */
  spacing?: number
  /** Heights of the decks of lanes above `position`, in units. */
  levels?: number[]
  /** Slowest and fastest a car flies, in units a second. */
  speed?: [number, number]
}

/** What a car is painted, dark enough to read as a shape against the sky. */
const PAINTS = ['#16141c', '#1d1f22', '#2a120c', '#33363b', '#42464a']
/** The light a car throws down under itself. */
const GLOWS = ['#ffa64d', '#ff6418', '#39ff88', '#b967ff', '#f4f6fb']
const HEAD = '#dfe8ff'
const TAIL = '#ff6418'

interface Car {
  x: number
  y: number
  dir: 1 | -1
  speed: number
  offset: number
  phase: number
}

/** A box with every vertex painted `color` (linear, may be over 1). */
function lamp(
  w: number,
  h: number,
  d: number,
  x: number,
  y: number,
  z: number,
  color: Color,
): BufferGeometry {
  const g = new BoxGeometry(w, h, d).translate(x, y, z)
  const n = g.attributes.position.count
  const paint = new Float32Array(n * 3)
  for (let i = 0; i < n; i++) paint.set([color.r, color.g, color.b], i * 3)
  g.setAttribute('color', new Float32BufferAttribute(paint, 3))
  return g
}

/**
 * Lanes of hovercars over a street: decks of lanes going both ways, every car an instance in
 * three shared meshes (bodies, lamps, and the light under each). Where each car is comes
 * straight from the world clock and `seed`, so every player who shares the clock sees the same
 * traffic (contract §2), and nothing is simulated or sent.
 *
 * Three draws however many cars, left out of the world's mirrors. No colliders: the lanes are
 * meant to fly over anything a body can reach.
 */
export function FlyingTraffic({
  position = [0, 40, 0],
  rotation = [0, 0, 0],
  seed = 1,
  length = 480,
  cars = 28,
  lanes = 2,
  spacing = 7,
  levels = [0, 9, 20],
  speed = [16, 34],
}: FlyingTrafficProps) {
  const { unit, now = Date.now } = useWorld()
  const ladder = useLadder()
  const root = useRef<Group>(null)
  const body = useRef<InstancedMesh>(null)
  const lamps = useRef<InstancedMesh>(null)
  const glow = useRef<InstancedMesh>(null)
  const count = Math.max(0, Math.round(cars))
  const [slow, fast] = speed
  const decks = levels.join(',')

  const fleet = useMemo<Car[]>(() => {
    const r = rng(seed)
    const heights = decks.split(',').map(Number)
    return Array.from({ length: count }, () => {
      const dir = r() < 0.5 ? 1 : -1
      const lane = Math.floor(r() * Math.max(1, lanes))
      return {
        // Each way keeps to its own side, as a road does.
        x: dir * (lane + 0.5) * spacing * unit,
        y: (heights[Math.floor(r() * heights.length)] + (r() - 0.5) * 1.6) * unit,
        dir,
        speed: (slow + r() * (fast - slow)) * unit,
        offset: r() * length * unit,
        phase: r() * Math.PI * 2,
      }
    })
  }, [seed, count, lanes, spacing, decks, slow, fast, length, unit])

  const parts = useMemo(() => {
    const u = unit
    const shell = mergeGeometries([
      new BoxGeometry(2.0 * u, 0.55 * u, 4.4 * u).translate(0, 0.5 * u, 0),
      new BoxGeometry(1.8 * u, 0.3 * u, 0.9 * u).translate(0, 0.42 * u, 2.5 * u),
      new BoxGeometry(1.7 * u, 0.5 * u, 2.0 * u).translate(0, 1.0 * u, -0.3 * u),
    ])
    const head = emissiveColor(HEAD, mid(ladder.lampLens))
    const tail = emissiveColor(TAIL, mid(ladder.signFace))
    const lights = mergeGeometries([
      lamp(0.5 * u, 0.1 * u, 0.06 * u, 0.6 * u, 0.55 * u, 2.96 * u, head),
      lamp(0.5 * u, 0.1 * u, 0.06 * u, -0.6 * u, 0.55 * u, 2.96 * u, head),
      lamp(1.9 * u, 0.08 * u, 0.06 * u, 0, 0.66 * u, -2.22 * u, tail),
    ])
    const under = new PlaneGeometry(1.7 * u, 4.0 * u).rotateX(Math.PI / 2).translate(0, 0.2 * u, 0)
    const paint = new MeshStandardMaterial({ color: '#ffffff', roughness: 0.32, metalness: 0.7 })
    const lit = new MeshBasicMaterial({ vertexColors: true, toneMapped: false })
    const cast = new MeshBasicMaterial({
      color: '#ffffff',
      transparent: true,
      opacity: 0.9,
      blending: AdditiveBlending,
      depthWrite: false,
      side: DoubleSide,
      toneMapped: false,
    })
    return { shell, lights, under, paint, lit, cast }
  }, [unit, ladder.lampLens, ladder.signFace])
  useEffect(
    () => () => {
      for (const part of Object.values(parts)) part.dispose()
    },
    [parts],
  )

  // Paint and underglow are dealt once. Only where the cars are changes from frame to frame.
  useEffect(() => {
    const r = rng(seed + 7919)
    const tint = new Color()
    for (let i = 0; i < count; i++) {
      body.current?.setColorAt(i, tint.set(PAINTS[Math.floor(r() * PAINTS.length)]))
      glow.current?.setColorAt(
        i,
        emissiveColor(GLOWS[Math.floor(r() * GLOWS.length)], ladder.shopGlass[1]),
      )
    }
    for (const mesh of [body.current, glow.current])
      if (mesh?.instanceColor) mesh.instanceColor.needsUpdate = true
  }, [seed, count, ladder.shopGlass, parts])

  const at = useMemo(() => new Object3D(), [])
  useFrame(() => {
    const meshes = [body.current, lamps.current, glow.current]
    if (!meshes[0] || !meshes[1] || !meshes[2]) return
    const seconds = now() / 1000
    const span = length * unit
    for (let i = 0; i < fleet.length; i++) {
      const car = fleet[i]
      const along = (((car.offset + car.speed * seconds) % span) + span) % span
      at.position.set(
        car.x,
        car.y + Math.sin(seconds * 0.7 + car.phase) * 0.25 * unit,
        car.dir * (along - span / 2),
      )
      at.rotation.set(0, car.dir > 0 ? 0 : Math.PI, 0)
      at.updateMatrix()
      for (const mesh of meshes) mesh?.setMatrixAt(i, at.matrix)
    }
    for (const mesh of meshes) if (mesh) mesh.instanceMatrix.needsUpdate = true
  })

  // Cars overhead move every frame: a reflection of them would only trail.
  useEffect(() => skipMirrors(root.current), [count])

  if (count === 0) return null
  return (
    <Dynamic>
      <group ref={root} position={position} rotation={rotation}>
        <instancedMesh ref={body} args={[parts.shell, parts.paint, count]} frustumCulled={false} />
        <instancedMesh ref={lamps} args={[parts.lights, parts.lit, count]} frustumCulled={false} />
        <instancedMesh
          ref={glow}
          args={[parts.under, parts.cast, count]}
          frustumCulled={false}
          renderOrder={2}
        />
      </group>
    </Dynamic>
  )
}

FlyingTraffic.stream = false

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))
}