component

Hologram

A plaza centrepiece: a pedestal, a beam of light with scan lines climbing it, and in it a wire cage turning round three rings that keep time (once a minute, once an hour, once every `round` seconds) off the world clock. The pedestal has a cylinder collider.

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

Tune every prop in the workshop →

Add it

npx @runek/cli add hologram

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

Use it

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

<Hologram position={[0, 0, 0]} color="#39ff88" round={600} />

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

{ "type": "Hologram", "props": { "position": [0, 0, 0], "color": "#39ff88", "round": 600 } }

Props

Prop Type Default Description
position [x, y, z] [0, 0, 0] The middle of the pedestal’s foot [x, y, z] in units.
rotation [x, y, z] [0, 0, 0] Rotation [x, y, z] in radians.
seed number Accepted for the component contract. Every hologram keeps the same time.
radius number 1.6 Radius of the pedestal, in units.
height number 6.5 How high the middle of the figure hangs over the pedestal’s foot, in units.
size number 2.2 Radius of the figure, in units.
color color "#3d5bff" The beam and the figure’s cage, lit at the world’s sign and tube levels.
accent color "#f4f6fb" The rings that keep time.
round number 1440 Seconds the slow ring takes to go round once: a district’s power round, say.
light boolean true Ask the world’s light pool for a real light at the figure.

Registry manifest

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

Browse the whole catalog in the gallery →.

Source (3 files)

Hologram.tsx

import { useFrame } from '@react-three/fiber'
import { CylinderCollider, RigidBody } from '@react-three/rapier'
import {
  Dynamic,
  lazyModule,
  skipMirrors,
  useLight,
  useMaterial,
  useNodeRenderer,
  useWorld,
  type Vec3,
} from '@runek/core'
import { useEffect, useMemo, useRef } from 'react'
import {
  AdditiveBlending,
  CylinderGeometry,
  DoubleSide,
  EdgesGeometry,
  type Group,
  IcosahedronGeometry,
  LineBasicMaterial,
  type Material,
  ShaderMaterial,
  TorusGeometry,
} from 'three'
import { emissiveColor, glowMaterial, mid, useLadder } from './city/glow'

// The beam's node (TSL) material, loaded only under a node renderer.
const hologramNodes = lazyModule(() => import('./nodes/hologram'))

export interface HologramProps {
  /** The middle of the pedestal's foot [x, y, z] in units. */
  position?: Vec3
  /** Rotation [x, y, z] in radians. */
  rotation?: Vec3
  /** Accepted for the component contract. Every hologram keeps the same time. */
  seed?: number
  /** Radius of the pedestal, in units. */
  radius?: number
  /** How high the middle of the figure hangs over the pedestal's foot, in units. */
  height?: number
  /** Radius of the figure, in units. */
  size?: number
  /** The beam and the figure's cage, lit at the world's `sign` and `tube` levels. */
  color?: string
  /** The rings that keep time. */
  accent?: string
  /** Seconds the slow ring takes to go round once: a district's power round, say. */
  round?: number
  /** Ask the world's light pool for a real light at the figure. */
  light?: boolean
}

const BEAM_VERT = /* glsl */ `
varying vec2 vUv;
void main() {
  vUv = uv;
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}`

// Scan lines climbing a cone of light that thins toward the top.
const BEAM_FRAG = /* glsl */ `
uniform vec3 uColor;
uniform float uTime;
varying vec2 vUv;
void main() {
  float lines = 0.6 + 0.4 * step(0.5, fract(vUv.y * 40.0 - uTime * 2.0));
  gl_FragColor = vec4(uColor * (1.0 - vUv.y) * lines, 1.0);
}`

/**
 * A hologram on a pedestal: a beam of light up from a ring, and in it a cage that turns slowly
 * round three rings that keep time. The fast ring goes round once a minute, the middle one once
 * an hour and the slow one once every `round` seconds, all read off the world clock, so it is a
 * clock anyone in the city can check and every player sees it at the same angle.
 *
 * The pedestal is lit, solid and has a collider. The light parts are unlit, at the world's
 * luminance levels, left out of the world's mirrors, and drawn inside a `<Dynamic>`. Under
 * `WebGPURenderer` the beam has no scan lines.
 */
export function Hologram({
  position = [0, 0, 0],
  rotation = [0, 0, 0],
  radius = 1.6,
  height = 6.5,
  size = 2.2,
  color = '#3d5bff',
  accent = '#f4f6fb',
  round = 1440,
  light = true,
}: HologramProps) {
  const { unit, palette, now = Date.now } = useWorld()
  const ladder = useLadder()
  const nodes = useNodeRenderer() ? hologramNodes() : null
  const r = radius * unit
  const s = size * unit
  const base = 0.5 * unit
  const beamH = (height + size * 0.6) * unit - base

  const metal = useMaterial({ color: palette.metal, roughness: 0.35, metalness: 0.7 })
  const rim = glowMaterial(color, mid(ladder.tubeCore))
  const ringMinute = glowMaterial(accent, ladder.signFace[1])
  const ringHour = glowMaterial(accent, mid(ladder.signFace))
  const ringRound = glowMaterial(color, ladder.signFace[1])
  const time = useMemo(() => ({ value: 0 }), [])
  const made = useMemo(() => {
    const tone = emissiveColor(color, ladder.shopGlass[0])
    let beam: Material
    if (nodes) {
      beam = nodes.beamNodeMaterial(tone)
    } else {
      beam = new ShaderMaterial({
        vertexShader: BEAM_VERT,
        fragmentShader: BEAM_FRAG,
        uniforms: { uColor: { value: tone.clone() }, uTime: time },
      })
    }
    beam.transparent = true
    beam.blending = AdditiveBlending
    beam.depthWrite = false
    beam.side = DoubleSide
    const cage = new LineBasicMaterial({
      color: emissiveColor(color, ladder.signFace[0]),
      toneMapped: false,
    })
    const core = new LineBasicMaterial({
      color: emissiveColor(accent, mid(ladder.signFace)),
      toneMapped: false,
    })
    return {
      beam,
      cage,
      core,
      pedestal: new CylinderGeometry(r, r * 1.15, base, 40),
      rim: new TorusGeometry(r * 1.02, 0.03 * unit, 8, 64),
      cone: new CylinderGeometry(r * 0.62, r * 0.94, beamH, 40, 1, true),
      shell: new EdgesGeometry(new IcosahedronGeometry(s, 1)),
      heart: new EdgesGeometry(new IcosahedronGeometry(s * 0.4, 0)),
      ring: [1.5, 1.26, 1.02].map((k) => new TorusGeometry(s * k, 0.022 * unit, 6, 120)),
    }
  }, [nodes, color, accent, ladder.shopGlass, ladder.signFace, time, r, s, base, beamH, unit])
  useEffect(
    () => () => {
      for (const part of [
        made.beam,
        made.cage,
        made.core,
        made.pedestal,
        made.rim,
        made.cone,
        made.shell,
        made.heart,
        ...made.ring,
      ]) {
        part.dispose()
      }
    },
    [made],
  )

  const figure = useRef<Group>(null)
  const cage = useRef<Group>(null)
  const core = useRef<Group>(null)
  const minute = useRef<Group>(null)
  const hour = useRef<Group>(null)
  const slow = useRef<Group>(null)
  // It turns: hidden from mirrors, so a reflection never shows it a frame behind.
  useEffect(() => skipMirrors(figure.current), [])
  const emitter = useLight({ color, intensity: 220, distance: 22 * unit, decay: 2 }, light)

  useFrame(() => {
    const seconds = now() / 1000
    time.value = seconds % 1000
    const turn = Math.PI * 2
    if (cage.current) cage.current.rotation.set(seconds * 0.05, seconds * 0.11, 0)
    if (core.current) core.current.rotation.set(seconds * -0.3, seconds * 0.45, 0)
    // Three rings, each tilted its own way and turning about the upright at its own rate.
    if (minute.current) minute.current.rotation.y = ((seconds % 60) / 60) * turn
    if (hour.current) hour.current.rotation.y = ((seconds % 3600) / 3600) * turn
    if (slow.current) slow.current.rotation.y = ((seconds % round) / round) * turn
  })

  return (
    <group position={position} rotation={rotation}>
      <RigidBody type="fixed" colliders={false}>
        <CylinderCollider args={[base / 2, r]} position={[0, base / 2, 0]} />
      </RigidBody>
      <mesh
        position={[0, base / 2, 0]}
        material={metal}
        geometry={made.pedestal}
        castShadow
        receiveShadow
      />
      <Dynamic>
        <group ref={figure}>
          <mesh
            position={[0, base + 0.02 * unit, 0]}
            rotation={[Math.PI / 2, 0, 0]}
            material={rim}
            geometry={made.rim}
          />
          <mesh
            position={[0, base + beamH / 2, 0]}
            material={made.beam}
            geometry={made.cone}
            renderOrder={2}
          />
          <group position={[0, height * unit, 0]}>
            <group ref={cage}>
              <lineSegments geometry={made.shell} material={made.cage} />
            </group>
            <group ref={core}>
              <lineSegments geometry={made.heart} material={made.core} />
            </group>
            <group ref={minute}>
              <mesh
                rotation={[Math.PI / 2 - 0.5, 0, 0]}
                material={ringMinute}
                geometry={made.ring[2]}
              />
            </group>
            <group ref={hour}>
              <mesh
                rotation={[Math.PI / 2 + 0.35, 0, 0.6]}
                material={ringHour}
                geometry={made.ring[1]}
              />
            </group>
            <group ref={slow}>
              <mesh
                rotation={[Math.PI / 2 + 0.12, 0, -0.3]}
                material={ringRound}
                geometry={made.ring[0]}
              />
            </group>
            <object3D ref={emitter.ref} />
          </group>
        </group>
      </Dynamic>
    </group>
  )
}

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

nodes/hologram.ts

// Hologram's beam as a TSL node material, for WebGPURenderer: the cone of light thinning toward
// the top, without the scan lines the GLSL draws.

import type { Color } from 'three'
import { float, uniform, uv } from 'three/tsl'
import { MeshBasicNodeMaterial } from 'three/webgpu'

export function beamNodeMaterial(tone: Color) {
  const material = new MeshBasicNodeMaterial()
  material.colorNode = uniform(tone.clone()).mul(float(1).sub(uv().y))
  material.fog = false
  return material
}