component
Tower
A procedural city tower from a seeded shape grammar: podium, setback, shaft and crown, with street, service, podium, tower and crown bands drawn by one shared facade shader (shop bays, lit windows with rooms behind them, trims, posters and leaks), so towers batch. Four eras (concrete, tenement, glass, makeshift) set the massing and dressing. Faces listed in `frontage` get relief and the facade kit: shop names, blade and roof signs, awnings, shutters, AC units, pipes, vending machines, cables across the street and light pooled on the pavement. Lit after dusk at the world's luminance levels. Colliders over the footprint and along each street face.
⌖ Explore the library in 3D → · View as Markdown
Add it
npx @runek/cli add tower
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 { Tower } from './runek/Tower'
<Tower position={[0, 0, 0]} height={48} era="tenement" frontage={["+z"]} cableSpan={12} seed={1} />
Or as a node in a world file (worlds as data):
{ "type": "Tower", "props": { "position": [0, 0, 0], "height": 48, "era": "tenement", "frontage": ["+z"], "cableSpan": 12, "seed": 1 } }
Props
| Prop | Type | Default | Description |
|---|---|---|---|
position |
[x, y, z] |
[0, 0, 0] |
Position of the tower’s base centre [x, y, z] in units (1 unit = 1 m, Y-up). |
rotation |
[x, y, z] |
[0, 0, 0] |
Rotation [x, y, z] in radians. Towers stand upright: only the turn about Y is meant to be used. |
seed |
number |
1 |
Seeds the massing, the window pattern, which windows are lit, every prop and sign, and any unset look props. |
width |
number |
16 |
Ground footprint along local X, in units. The podium fills it and the collider matches it. |
depth |
number |
16 |
Ground footprint along local Z, in units. |
height |
number |
60 |
Height to the roof, in units. Rooftop plant and masts stand above it. |
windows |
"glass" | "office" | "grid" | "ribbon" |
Window layout: grid (apartments), office (small dense panes), ribbon (continuous bands) or glass (curtain wall). Seeded by era when unset. |
|
lit |
number |
Share of windows lit at night, 0 to 1. Seeded when unset. | |
trim |
string |
Neon trim along the parapets and crown, and the color of the tower’s main sign, lit at the world’s sign luminance level. "none" for a plain tower. Seeded when unset. |
|
cornerStrips |
boolean |
Also run the trim colour up the corners. | |
shopfronts |
boolean |
true |
Shop bays along the ground floor. |
color |
color |
Wall colour. Defaults to the world palette’s wall. |
|
era |
"glass" | "concrete" | "tenement" | "makeshift" |
Which era built it: concrete (squat, heavy, stencilled), tenement (balconies, sign frames, drum lanterns), glass (a thin glass slab with a clock in its crown) or makeshift (cages, shacks, cable). Seeded among the first, second and last when unset. |
|
podium |
number |
Podium height in units, for a tower tall and wide enough to have a shaft (at least 34 high and 10 across). Seeded between 15 and 25 when unset. | |
frontage |
"+z" | "+x" | "-z" | "-x"[] |
[] |
The faces that front a street: +z, +x, -z, -x in the tower’s own frame. Each gets piers, a fascia, signs and the instanced kit props, and the first one listed carries the tower’s big sign. Empty by default, so a tower costs one merged mesh until it is told where the street is. |
name |
string |
The shop name on the main sign. Seeded when unset. | |
cableSpan |
number |
0 |
Wall to wall distance across the street in units. Above 0, cables sag across it from the first face in frontage. |
light |
boolean |
false |
Ask the world for a real light in front of the main shop. Pooled, so only the ones that matter to the view are lit. |
Registry manifest
registry manifest /r/components/tower.json Self-contained JSON: inlined source plus resolved dependencies, exactly whatrunek add tower fetches.
Browse the whole catalog in the gallery →.
Source (13 files)
Tower.tsx
import { CuboidCollider, RigidBody } from '@react-three/rapier'
import {
lazyModule,
shareMaterial,
useGround,
useLight,
useNodeRenderer,
useWorld,
type Vec3,
} from '@runek/core'
import { useLayoutEffect, useMemo } from 'react'
import {
BufferGeometry,
Float32BufferAttribute,
ShaderMaterial,
UniformsLib,
UniformsUtils,
} from 'three'
import { useLadder } from './city/glow'
import { KitBuilder } from './city/kit'
import { TOWER_FRAG, TOWER_VERT } from './city/towerFacade'
import {
buildTower,
ERAS,
onFace,
planTower,
type TowerEra,
type TowerFace,
type TowerWindows,
} from './city/towerGrammar'
import { knotLight, mainShop, towerKit } from './city/towerKit'
import { applyTowerLight, nightFactor, towerUniforms } from './city/towerLight'
import { useKitParts } from './city/useKit'
export type { TowerEra, TowerFace, TowerWindows } from './city/towerGrammar'
// The facade's node (TSL) material, loaded only under a node renderer.
const towerNodes = lazyModule(() => import('./nodes/tower'))
export interface TowerProps {
/** Position of the tower's base centre [x, y, z] in units (1 unit = 1 m, Y-up). */
position?: Vec3
/** Rotation [x, y, z] in radians. Towers stand upright: only the turn about Y is meant to be used. */
rotation?: Vec3
/** Seeds the massing, the window pattern, which windows are lit, every prop and sign, and any unset look props. */
seed?: number
/** Ground footprint along local X, in units. The podium fills it and the collider matches it. */
width?: number
/** Ground footprint along local Z, in units. */
depth?: number
/** Height to the roof, in units. Rooftop plant and masts stand above it. */
height?: number
/** Window layout: `grid` (apartments), `office` (small dense panes), `ribbon` (continuous bands) or `glass` (curtain wall). Seeded by era when unset. */
windows?: TowerWindows
/** Share of windows lit at night, 0 to 1. Seeded when unset. */
lit?: number
/** Neon trim along the parapets and crown, and the color of the tower's main sign, lit at the world's `sign` luminance level. `"none"` for a plain tower. Seeded when unset. */
trim?: string
/** Also run the trim colour up the corners. */
cornerStrips?: boolean
/** Shop bays along the ground floor. */
shopfronts?: boolean
/** Wall colour. Defaults to the world palette's `wall`. */
color?: string
/** Which era built it: `concrete` (squat, heavy, stencilled), `tenement` (balconies, sign frames, drum lanterns), `glass` (a thin glass slab with a clock in its crown) or `makeshift` (cages, shacks, cable). Seeded among the first, second and last when unset. */
era?: TowerEra
/** Podium height in units, for a tower tall and wide enough to have a shaft (at least 34 high and 10 across). Seeded between 15 and 25 when unset. */
podium?: number
/** The faces that front a street: `+z`, `+x`, `-z`, `-x` in the tower's own frame. Each gets piers, a fascia, signs and the instanced kit props, and the first one listed carries the tower's big sign. Empty by default, so a tower costs one merged mesh until it is told where the street is. */
frontage?: TowerFace[]
/** The shop name on the main sign. Seeded when unset. */
name?: string
/** Wall to wall distance across the street in units. Above 0, cables sag across it from the first face in `frontage`. */
cableSpan?: number
/** Ask the world for a real light in front of the main shop. Pooled, so only the ones that matter to the view are lit. */
light?: boolean
}
/**
* A procedural city tower: a podium, a setback, a shaft and a crown, emitted by a seeded shape
* grammar as one mesh. A shader draws every facade band (street, service, podium, tower, crown)
* from per-vertex data in wall metres, so all towers share one material and the static batcher
* merges them. Faces listed in `frontage` also get real relief and the facade kit: signs, AC
* units, pipes, vents, awnings, shutters, vending machines and cables, all drawn by the world's
* shared instanced meshes. At night every emitter takes its brightness from the world's
* luminance levels (`sign`, `tube`, `screen`). Dark by day. One cuboid collider over the ground footprint, plus one along each street face
* at the pier line and one per vending machine, so nothing a walker can reach stands outside a
* collider. Relief above the piers (fascia, awnings, balconies, cornices) has none.
*/
export function Tower({
position = [0, 0, 0],
rotation = [0, 0, 0],
seed = 1,
width = 16,
depth = 16,
height = 60,
windows,
lit,
trim,
cornerStrips,
shopfronts = true,
color,
era,
podium,
frontage = NO_FRONTAGE,
name,
cableSpan = 0,
light = false,
}: TowerProps) {
const { unit, palette, time } = useWorld()
const w = width * unit
const d = depth * unit
const h = height * unit
const fronts = frontage.join(',')
const plan = useMemo(
() =>
planTower({
seed,
width: w,
depth: d,
height: h,
windows,
lit,
trim,
cornerStrips,
shopfronts,
era,
podium: podium === undefined ? undefined : podium * unit,
frontage: fronts ? (fronts.split(',') as TowerFace[]) : [],
}),
[seed, w, h, d, windows, lit, trim, cornerStrips, shopfronts, era, podium, unit, fronts],
)
const wallHex = color ?? palette.wall
const geometry = useMemo(() => {
const mesh = buildTower(plan, wallHex)
const g = new BufferGeometry()
g.setIndex(mesh.index)
g.setAttribute('position', new Float32BufferAttribute(mesh.position, 3))
g.setAttribute('normal', new Float32BufferAttribute(mesh.normal, 3))
g.setAttribute('aUv', new Float32BufferAttribute(mesh.aUv, 2))
g.setAttribute('aRect', new Float32BufferAttribute(mesh.aRect, 4))
g.setAttribute('aCell', new Float32BufferAttribute(mesh.aCell, 4))
g.setAttribute('aWall', new Float32BufferAttribute(mesh.aWall, 3))
g.setAttribute('aTrim', new Float32BufferAttribute(mesh.aTrim, 3))
g.setAttribute('aLook', new Float32BufferAttribute(mesh.aLook, 4))
g.computeBoundingSphere()
g.computeBoundingBox()
return g
}, [plan, wallHex])
useLayoutEffect(() => () => geometry.dispose(), [geometry])
// WebGPURenderer (either backend) only draws node materials: use the TSL port there.
const nodes = useNodeRenderer() ? towerNodes() : null
const night = Math.round(nightFactor(time.hours) * 10) / 10
const material = nodes ? nodes.towerNodeMaterial(night) : towerMaterial(night)
const ladder = useLadder()
useLayoutEffect(() => applyTowerLight(ladder), [ladder])
// A glass tower's crown shows the world's time, to the last ten minutes.
const clock = plan.era === 2 ? clockText(time.hours) : ''
const span = cableSpan * unit
// Where the street stands in front of each face: a pavement is a step up from the road, and
// the light a shop leaves on the ground has to lie on top of it.
const groundAt = useGround()
const [px, py, pz] = position
const turn = rotation[1]
const street = useMemo(() => {
const cos = Math.cos(turn)
const sin = Math.sin(turn)
return [0, 1, 2, 3]
.map((face) => {
const [x, z] = onFace(face, 0, 0, w, d, (face % 2 === 0 ? w : d) / 2, 1.5 * unit)
const rise = groundAt(px + x * cos + z * sin, pz - x * sin + z * cos) - py
// A floor a storey up is a roof over the street, not the street.
return rise > 0 && rise < 0.6 * unit ? Math.round(rise * 1000) / 1000 : 0
})
.join(',')
}, [groundAt, px, py, pz, turn, w, d, unit])
const parts = useMemo(() => {
const k = new KitBuilder()
towerKit(k, plan, { name, cableSpan: span, clock, street: street.split(',').map(Number) })
return k
}, [plan, name, span, clock, street])
const kit = useKitParts(parts, [position, rotation])
// The kit's solids (the pier line of each street face, vending machines) come out of the same
// seeded run as its instances. The clock redraws the kit every ten minutes: keep the colliders.
const solidKey = JSON.stringify(parts.solids)
const solids = useMemo(() => parts.solids, [solidKey])
const lightAt = useMemo(() => knotLight(plan), [plan])
const lamp = plan.trim !== 'none' ? plan.trim : '#ffa64d'
const emitter = useLight(
{ color: lamp, intensity: 3, distance: 18 * unit, decay: 1.6 },
light && lightAt !== null,
)
return (
<RigidBody type="fixed" colliders={false} position={position} rotation={rotation}>
<mesh geometry={geometry} material={material} receiveShadow />
<group ref={kit} />
{lightAt && <object3D ref={emitter.ref} position={lightAt} />}
<CuboidCollider args={[w / 2, h / 2, d / 2]} position={[0, h / 2, 0]} />
{solids.map((s, i) => (
<CuboidCollider key={i} args={s.half} position={s.position} rotation={[0, s.rotY, 0]} />
))}
</RigidBody>
)
}
Tower.groundSitting = true
const NO_FRONTAGE: TowerFace[] = []
/** What a tower is known by on the street. */
export interface TowerShop {
/** The name on its main sign. */
name: string
/** The era that built it, given or seeded. */
era: TowerEra
/** Where that shop's front stands, at the ground: in the tower's own frame, in units. */
at: Vec3
}
/**
* The shop a tower is known by, worked out from its props alone, for anything that has to say
* what a tower is without drawing it. The props mean what they mean to `Tower`, defaults and
* all. `out` is how far off the wall the point stands, in units. Null for a tower with no shop
* to name: one with no `frontage`, or none with a named shop in it.
*/
export function towerShop(
{
seed = 1,
width = 16,
depth = 16,
height = 60,
windows,
lit,
trim,
cornerStrips,
shopfronts = true,
era,
podium,
frontage = NO_FRONTAGE,
name,
}: TowerProps,
unit = 1,
out = 0,
): TowerShop | null {
const plan = planTower({
seed,
width: width * unit,
depth: depth * unit,
height: height * unit,
windows,
lit,
trim,
cornerStrips,
shopfronts,
era,
podium: podium === undefined ? undefined : podium * unit,
frontage,
})
const shop = mainShop(plan, name, out * unit)
return (
shop && { name: shop.name, era: ERAS[plan.era], at: [shop.at[0] / unit, 0, shop.at[2] / unit] }
)
}
function clockText(hours: number) {
const t = ((hours % 24) + 24) % 24
const hh = Math.floor(t)
const mm = Math.floor(((t - hh) * 60) / 10) * 10
return `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}`
}
const materials = new Map<number, ShaderMaterial>()
/** One shared material per night level. Per-tower looks ride in vertex attributes. */
function towerMaterial(night: number) {
const key = Math.round(night * 10) / 10
let m = materials.get(key)
if (!m) {
m = new ShaderMaterial({
uniforms: {
...UniformsUtils.merge([UniformsLib.fog, { uNight: { value: key } }]),
...towerUniforms,
},
vertexShader: TOWER_VERT,
fragmentShader: TOWER_FRAG,
fog: true,
})
// One material for every tower that draws at this night level: the batcher may merge them.
m.name = `runek:tower:${key}`
materials.set(key, shareMaterial(m))
}
return m
} 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),
} city/towerFacade.ts
// Tower's facade shader (WebGL). One material draws every wall of every tower from per-vertex
// data, so towers keep merging in Runek's static batcher.
//
// Coordinates are metres on the wall (`aUv`: along the face, and height above the base), never
// world position, because a merged tower's `position` is already in world space. Every edge is
// box-filtered over the pixel footprint (`fwidth`), and per-cell randomness fades to its mean
// once a cell is smaller than a pixel, so windows do not shimmer at distance.
//
// Bands (aRect.w): 0 plain trim, 1 street, 2 service, 3 podium, 4 tower, 5 crown, 6 roof.
import { glslLamp, glslLampTable, SHOP_LAMPS, WINDOW_LAMPS } from './towerLight'
export const TOWER_VERT = /* glsl */ `
attribute vec2 aUv;
attribute vec4 aRect;
attribute vec4 aCell;
attribute vec3 aWall;
attribute vec3 aTrim;
attribute vec4 aLook;
varying vec2 vUv;
varying vec3 vRay;
varying float vNy;
flat varying vec4 vRect;
flat varying vec4 vCell;
flat varying vec3 vWall;
flat varying vec3 vTrim;
flat varying vec4 vLook;
#include <fog_pars_vertex>
void main() {
vUv = aUv; vRect = aRect; vCell = aCell; vWall = aWall; vTrim = aTrim; vLook = aLook;
vec4 wp = modelMatrix * vec4(position, 1.0);
// The view ray in the wall's own frame: along the face, up, and into the wall.
vec3 wn = normalize(mat3(modelMatrix) * normal);
vec3 along = normalize(vec3(wn.z, 0.0, -wn.x) + vec3(1e-5, 0.0, 0.0));
vec3 view = wp.xyz - cameraPosition;
vRay = vec3(dot(view, along), view.y, -dot(view, wn));
vNy = normal.y;
vec4 mvPosition = viewMatrix * wp;
gl_Position = projectionMatrix * mvPosition;
#include <fog_vertex>
}`
export const TOWER_FRAG = /* glsl */ `
uniform float uNight;
uniform vec2 uWindow;
uniform vec2 uShop;
uniform float uTrim;
uniform float uWallGain;
uniform vec3 uGlow;
varying vec2 vUv;
varying vec3 vRay;
varying float vNy;
flat varying vec4 vRect;
flat varying vec4 vCell;
flat varying vec3 vWall;
flat varying vec3 vTrim;
flat varying vec4 vLook;
#include <fog_pars_fragment>
uint pcg(uint v) {
uint state = v * 747796405u + 2891336453u;
uint word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;
return (word >> 22u) ^ word;
}
float h21(vec2 p) {
uvec2 q = uvec2(ivec2(floor(p)) + 65536);
return float(pcg(q.x * 1664525u + pcg(q.y))) * (1.0 / 4294967295.0);
}
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;
}
// Box-filtered single band [a, b].
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);
}
// A point along a ladder rung, spaced evenly on a log scale.
float rung(vec2 r, float t) { return r.x * pow(r.y / r.x, t); }
${glslLampTable('windowLamp', WINDOW_LAMPS)}
${glslLampTable('shopLamp', SHOP_LAMPS)}
// Interior mapping, flattened: the ray from the glass meets the back wall, a side wall, the
// ceiling or the floor of a box room, and each surface is one flat tone of the room's lamp.
// kind 0 plain room, 1 shelves on the back wall, 2 a shop (stocked shelves over a counter, a back door).
vec3 room(vec3 ro, vec3 rd, vec3 size, float seed, float kind) {
rd.z = max(rd.z, 0.02);
rd.xy += vec2(1e-4);
vec3 t = (step(0.0, rd) * size - ro) / rd;
float tm = min(min(t.x, t.y), t.z);
vec3 p = ro + rd * tm;
float r1 = fract(seed * 7.31), r2 = fract(seed * 3.17);
float tone;
if (tm == t.z) {
tone = 1.0;
if (kind > 1.5) {
// A shop: stocked shelves over a counter, and a dark doorway to the back room.
vec2 q = vec2(p.x * 3.2, p.y * 2.1);
vec2 qc = floor(q), qf = fract(q);
float top = 0.35 + 0.55 * h21(qc + vec2(seed * 91.0, 3.0));
float stock = step(0.12, qf.y) * step(qf.y, top) * step(0.08, qf.x) * step(0.3, h21(qc + vec2(7.0, seed * 37.0)));
float zone = step(size.y * 0.36, p.y) * step(p.y, size.y * 0.9);
float door = step(abs(p.x - size.x * (0.2 + 0.6 * r1)), 0.5) * step(p.y, 2.1);
tone = mix(tone, 0.55, step(qf.y, 0.12) * zone);
tone = mix(tone, mix(0.38, 0.8, h21(qc + vec2(seed * 13.0, 11.0))), stock * zone);
tone = mix(tone, 0.3, step(p.y, size.y * 0.3));
tone = mix(tone, 0.2, door);
} else {
float furniture = step(p.y, size.y * (0.24 + 0.2 * r2)) * step(abs(p.x - size.x * (0.25 + 0.5 * r1)), size.x * 0.22);
float shelves = step(0.55, fract(p.y * 2.3)) * step(p.y, size.y * 0.85) * step(0.5, kind);
tone = mix(tone, 0.62, shelves);
tone = mix(tone, 0.2, furniture);
}
} else if (tm == t.y) {
tone = rd.y > 0.0 ? 1.3 : 0.42;
} else {
// Side walls: a shop's counter and shelf boards run round them.
tone = 0.62;
float shop = step(1.5, kind);
tone = mix(tone, 0.48, shop * step(fract(p.y * 2.1), 0.12) * step(size.y * 0.36, p.y) * step(p.y, size.y * 0.9));
tone = mix(tone, 0.34, shop * step(p.y, size.y * 0.3));
}
return vec3(tone, tm, 0.0);
}
void main() {
float kind = vRect.w, faceW = vRect.x, y0 = vRect.y, y1 = vRect.z;
float sd = vLook.x, era = vLook.y, fseed = vLook.z, flags = vLook.w;
float strips = mod(flags, 2.0), roofline = mod(floor(flags * 0.5), 2.0), fasciaTube = mod(floor(flags * 0.25), 2.0);
vec2 m = vUv;
vec2 fw = fwidth(m);
vec3 wall = vWall * mix(0.35, uWallGain, uNight);
vec3 trim = vTrim * uTrim * uNight;
vec3 col = wall;
if (kind > 5.5) {
// Roof: darker, patched, with the trim color along its edges after dusk.
vec2 ed = min(m, vRect.xy - m);
float patchy = mix(0.5, 0.68, h21(floor(m / 2.4) + sd));
patchy = mix(0.6, patchy, clamp(1.0 - max(fw.x, fw.y) / 2.4, 0.0, 1.0));
col = wall * patchy;
col += trim * roofline * (1.0 - band(min(ed.x, ed.y), 0.35, 1e4, max(fw.x, fw.y)));
} else if (kind < 0.5) {
// Plain trim: slabs, cornices, parapets, rooftop boxes. Shaded by which way the face points.
col = wall * (vNy > 0.5 ? 0.75 : (vNy < -0.5 ? 0.4 : 1.0));
col += trim * roofline * band(m.y, y1 - 0.4, y1 - 0.12, fw.y) * step(abs(vNy), 0.5);
col += uGlow * exp(-max(m.y, 0.0) / 6.0) * uNight * step(abs(vNy), 0.5);
} else {
float lit = 0.0;
vec3 emit = vec3(0.0);
// How far a pixel is from the camera in cells decides the level of detail.
if (kind < 1.5) {
// Street: shop bays between piers under a fascia. vCell = (bay width, 2 bits per bay).
float bayW = vCell.x;
float sg = m.x / bayW;
float bi = floor(sg);
float xm = fract(sg) * bayW;
float state = mod(floor(vCell.y / exp2(2.0 * bi) + 0.01), 4.0);
float r = h21(vec2(bi, sd * 13.1 + fseed));
float lod = clamp(fw.x / bayW * 3.0 - 0.5, 0.0, 1.0);
float open = band(xm, 0.38, bayW - 0.38, fw.x) * band(m.y, 0.38, 3.3, fw.y);
float frame = band(xm, 0.3, bayW - 0.3, fw.x) * band(m.y, 0.3, 3.38, fw.y) - open;
float fascia = band(m.y, 3.5, 4.38, fw.y);
float plinth = band(m.y, 0.0, 0.3, fw.y);
col = mix(col, wall * 0.55, fascia);
col = mix(col, wall * 0.7, plinth);
col = mix(col, wall * 0.4, frame);
vec3 lamp = shopLamp(r * ${SHOP_LAMPS[SHOP_LAMPS.length - 1][0].toFixed(3)}) * rung(uShop, h21(vec2(bi + 3.0, sd + fseed * 5.0))) * mix(0.08, 1.0, uNight);
if (state < 0.5) {
// Open and lit. Mullions split the glass in three, a door takes one third.
float third = bayW - 0.76;
float mull = pulse((xm - 0.38) / third * 3.0, 0.0, 0.06, fw.x / third * 3.0) + band(m.y, 2.55, 2.63, fw.y);
float counter = band(m.y, 0.38, 1.05, fw.y);
float flatTone = (0.62 + 0.38 * smoothstep(0.3, 3.3, m.y)) * mix(1.0, 0.35, counter);
vec3 rm = room(vec3(xm - 0.38, m.y - 0.38, 0.0), vRay, vec3(third, 2.92, 3.6), r + fseed, 2.0);
float near = 1.0 - smoothstep(0.05, 0.22, max(fw.x, fw.y));
float tone = mix(flatTone, rm.x, near);
vec3 shop = lamp * tone;
shop = mix(shop, wall * 0.35, clamp(mull, 0.0, 1.0));
col = mix(col, shop, open);
// The fascia tube sits over lit bays only, so the light gathers where the shops are.
emit += trim * fasciaTube * band(m.y, 3.42, 3.5, fw.y) * band(xm, 0.2, bayW - 0.2, fw.x);
} else if (state < 1.5) {
// Shutter down: slats, a housing box, a strip of light under the door.
float slat = pulse(m.y / 0.12, 0.0, 0.68, fw.y / 0.12);
vec3 shutter = wall * mix(0.9, 1.9, h21(vec2(bi + 11.0, sd))) * mix(0.6, 1.0, slat);
shutter = mix(shutter, wall * 0.5, band(m.y, 3.05, 3.3, fw.y));
col = mix(col, shutter, open);
// Posters pasted across it.
vec2 pg = vec2((xm - 0.5) / 0.74, (m.y - 0.9) / 1.05);
vec2 pc = floor(pg), pf = fract(pg);
float pr = h21(pc + vec2(bi * 7.0 + sd, fseed + 41.0));
float on = step(pr, 0.36) * step(0.0, pc.y) * step(pc.y, 1.0) * step(0.0, pg.x) * step(pc.x + 1.0, (bayW - 1.0) / 0.74);
float paper = pulse(pg.x, 0.06, 0.94, fw.x / 0.74) * pulse(pg.y, 0.05, 0.95, fw.y / 1.05) * on * (1.0 - lod);
vec3 ink = mix(mix(vec3(0.5, 0.42, 0.3), vec3(0.42, 0.2, 0.12), step(0.12, pr)), vec3(0.24, 0.2, 0.34), step(0.25, pr));
ink *= mix(1.0, 0.35, step(0.72, pf.y)) * mix(1.0, 0.6, step(pf.y, 0.4) * step(0.5, fract(pf.y * 12.0)));
col = mix(col, ink * mix(0.35, uWallGain, uNight) * 1.6, paper * open);
} else if (state < 2.5) {
// Closed for the night: dark glass holding a little haze, a dim lamp left on at the back.
vec3 glass = vec3(0.010, 0.009, 0.008) + vec3(0.02, 0.012, 0.007) * (1.0 - m.y / 3.3);
glass += lamp * 0.035 * band(m.y, 2.2, 3.1, fw.y);
col = mix(col, glass * mix(8.0, 1.0, uNight), open);
} else {
// A blank wall with a door, a lit transom over it and a bill or two beside it.
float door = band(xm, bayW * 0.5 - 0.62, bayW * 0.5 + 0.62, fw.x);
col = mix(col, wall * 0.42, door * band(m.y, 0.0, 2.3, fw.y));
emit += lamp * 0.5 * door * band(m.y, 2.38, 2.7, fw.y);
float bill = band(xm, 0.6, 1.3, fw.x) * band(m.y, 1.1, 2.05, fw.y) * step(0.4, r) * (1.0 - lod);
col = mix(col, vec3(0.5, 0.42, 0.3) * mix(0.35, uWallGain, uNight) * 1.5 * mix(1.0, 0.4, step(1.8, m.y)), bill);
}
} else if (kind < 2.5) {
// Service: louvre panels between joints, a conduit along the bottom.
float slat = pulse(m.y / 0.16, 0.0, 0.55, fw.y / 0.16);
float panel = pulse(m.x / 2.4, 0.03, 0.97, fw.x / 2.4);
col = wall * mix(0.45, 0.8, slat) * mix(0.5, 1.0, panel);
col = mix(col, wall * 1.3, band(m.y, y0 + 0.05, y0 + 0.13, fw.y));
} else {
// Windows. vCell = (cell width, storey height, lit share, style).
float cw = vCell.x, ch = vCell.y, litP = vCell.z, style = vCell.w;
vec2 g = vec2(m.x / cw, (m.y - y0) / ch);
vec2 gw = fw / vec2(cw, ch);
vec2 cell = floor(g), f = fract(g);
float rows = floor((y1 - y0) / ch + 0.01);
float inRows = band(g.y, 0.0, rows, gw.y);
float lod = clamp(max(gw.x, gw.y) * 1.6 - 0.5, 0.0, 1.0);
float r = h21(cell + vec2(sd * 31.7, fseed * 7.3));
float r2 = h21(cell * 1.7 + vec2(sd, fseed + 9.1));
vec4 w = style < 0.5 ? vec4(0.2, 0.8, 0.29, 0.76) : (style < 1.5 ? vec4(0.1, 0.9, 0.3, 0.8) : (style < 2.5 ? vec4(0.0, 1.0, 0.3, 0.74) : vec4(0.03, 0.97, 0.05, 0.95)));
// The crown reads differently by era: slots on a concrete block, a lit band on a glass slab.
if (kind > 4.5 && era < 0.5) w = vec4(0.38, 0.62, 0.12, 0.9);
if (kind > 4.5 && era > 1.5 && era < 2.5) { w = vec4(0.02, 0.98, 0.1, 0.92); litP = 1.0; }
float mask = pulse(g.x, w.x, w.y, gw.x) * pulse(g.y, w.z, w.w, gw.y) * inRows;
float frameMask = pulse(g.x, w.x - 0.035, w.y + 0.035, gw.x) * pulse(g.y, w.z - 0.03, w.w + 0.03, gw.y) * inRows - mask;
// Trims by band: a sill under each window row, a course line at each storey, piers at corners.
float sill = pulse(g.y, w.z - 0.075, w.z - 0.03, gw.y) * pulse(g.x, w.x - 0.06, w.y + 0.06, gw.x) * inRows;
float course = pulse(g.y, 0.0, 0.035, gw.y) * step(kind, 3.5);
float fin = pulse(g.x, 0.0, 0.05, gw.x) * step(1.5, style);
col = mix(col, wall * 0.62, clamp(frameMask, 0.0, 1.0));
col = mix(col, wall * 1.45, sill * step(style, 1.5));
col = mix(col, wall * 0.72, course);
col = mix(col, wall * 1.35, fin);
// Decal slots: one hash per wall cell picks a leak streak, a crack, a sticker or nothing.
float d = h21(cell + vec2(77.0 + sd, 13.0 + fseed));
float d2 = h21(cell + vec2(5.0 + fseed, 91.0 + sd));
float calm = 1.0 - lod;
float streakX = (f.x - mix(w.x, w.y, d2)) * cw;
float leak = step(d, 0.14) * band(streakX, -0.06 - 0.1 * d2, 0.06 + 0.1 * d2, fw.x) * band(f.y, 0.0, w.z - 0.07, gw.y) * (0.35 + 0.65 * f.y / max(w.z, 0.05));
float crackX = (f.x - 0.5 * (w.y + 1.0)) * cw + 0.05 * sin(f.y * 23.0 + d2 * 40.0) + 0.03 * sin(f.y * 61.0);
float crack = step(0.14, d) * step(d, 0.2) * band(crackX, -0.012, 0.012, fw.x) * step(style, 1.5);
float sticker = step(0.2, d) * step(d, 0.25) * band((f.x - w.y) * cw, 0.08, 0.36, fw.x) * band(f.y * ch, 0.5, 0.95, fw.y) * step(style, 1.5) * step(kind, 3.5);
col = mix(col, wall * 0.5, clamp(leak + crack, 0.0, 1.0) * calm * inRows);
col = mix(col, mix(vec3(0.5, 0.42, 0.3), vec3(0.24, 0.2, 0.34), step(0.225, d)) * mix(0.35, uWallGain, uNight) * 1.5, sticker * calm * inRows);
// Grime under the band's top edge, in streaks.
float drip = pulse(m.x / 1.9 + fseed * 0.37, 0.0, 0.16, fw.x / 1.9) * exp(-(y1 - m.y) / 2.2) * 0.45;
col *= 1.0 - drip * step(style, 2.5);
// Glass. Lit rooms sit on the window rung in their lamp's color.
float on = step(1.0 - litP, r) * uNight;
vec3 lampC = windowLamp(r2) * rung(uWindow, h21(cell + vec2(9.1, sd)));
if (kind > 4.5 && era > 1.5 && era < 2.5) lampC = ${glslLamp('#f4f6fb')} * rung(uWindow, 0.9);
if (style > 2.5) lampC *= 0.5;
vec3 dark = mix(vec3(0.20, 0.24, 0.30), vec3(0.010, 0.009, 0.008) + vec3(0.012, 0.007, 0.004) * (1.0 - f.y), uNight);
// Room types: a blind part way down, shelves on the back wall, a screen in a dark room.
float blind = step(0.55, r2) * step(f.y, w.w) * step(mix(w.w, w.z, 0.25 + 0.6 * fract(r2 * 7.0)), f.y);
float near = (1.0 - smoothstep(0.03, 0.11, max(gw.x, gw.y))) * step(style, 2.5);
float tone = mix(0.7, 1.0, smoothstep(w.z, w.w, f.y));
if (near > 0.0) {
vec3 rm = room(vec3(f.x * cw, f.y * ch, 0.0), vRay, vec3(cw, ch, 3.6), r + r2, step(0.7, fract(r2 * 3.0)));
tone = mix(tone, rm.x, near);
}
tone = mix(tone, 0.55, blind);
vec3 glassLit = lampC * tone;
float screen = step(0.93, fract(r * 5.3)) * (1.0 - step(1.0 - litP, r)) * band(f.x, mix(w.x, w.y, 0.3), mix(w.x, w.y, 0.62), gw.x) * band(f.y, mix(w.z, w.w, 0.2), mix(w.z, w.w, 0.55), gw.y);
vec3 cellGlass = mix(dark, glassLit, on) + ${glslLamp('#b967ff')} * uWindow.x * 0.5 * screen * uNight;
// Past a pixel per cell the pattern becomes its own mean.
vec3 meanGlass = mix(dark, ${glslLamp('#ffcf9a')} * rung(uWindow, 0.5) * 0.8 * (style > 2.5 ? 0.5 : 1.0), litP * uNight);
col = mix(col, mix(cellGlass, meanGlass, lod), mask);
// Mullions and a transom split each pane, so a lit window never reads as one flat block.
float nx = style < 0.5 ? 2.0 : (style < 1.5 ? 1.0 : (style < 2.5 ? 3.0 : 2.0));
float mw = 0.07 * nx / cw;
float mull = pulse(g.x * nx + 0.5 * mw, 0.0, mw, gw.x * nx);
float ty = mix(w.z, w.w, style < 0.5 ? 0.66 : (style < 2.5 ? 0.3 : 0.5));
float transom = band(f.y, ty, ty + 0.06 / ch, gw.y) * inRows;
col = mix(col, wall * 0.45, clamp(mull + transom, 0.0, 1.0) * mask * step(kind, 4.5));
// Concrete blocks wash their crown with sodium floods.
if (kind > 4.5 && era < 0.5) emit += ${glslLamp('#ff9326')} * uWindow.x * 0.6 * uNight * (1.0 - mask) * smoothstep(y1, y0, m.y);
emit += trim * roofline * band(m.y, y1 - 0.45, y1 - 0.1, fw.y);
}
// Band edges: a coping line on top, a shadow line below.
col = mix(col, wall * 1.4, band(m.y, y1 - 0.14, y1, fw.y) * step(1.5, kind));
emit += trim * 0.85 * strips * band(min(m.x, faceW - m.x), 0.0, 0.22, fw.x) * step(2.5, kind);
// Street light (lamps, signs, shop glass) on the lowest floors.
col += uGlow * exp(-m.y / 6.0) * uNight;
col += emit;
}
gl_FragColor = vec4(col, 1.0);
#include <tonemapping_fragment>
#include <colorspace_fragment>
#include <fog_fragment>
}` city/towerGrammar.ts
// Tower's shape grammar: a pure function from props and seed to a massing plan (podium, setback,
// shaft, crown), the facade bands on every face, and the state of every shop bay. The mesh
// builder and the kit emitter both read the plan, so the shader's bays and the props hung on
// them always agree.
import { pick, range, rng } from '@runek/core'
import { Color } from 'three'
import { emissiveColor } from './glow'
import { TRIM_NEON } from './towerLight'
export type TowerWindows = 'grid' | 'office' | 'ribbon' | 'glass'
export type TowerEra = 'concrete' | 'tenement' | 'glass' | 'makeshift'
export type TowerFace = '+z' | '+x' | '-z' | '-x'
/** Faces in the order the grammar walks them: each is a quarter turn about Y from the last. */
export const FACES: TowerFace[] = ['+z', '+x', '-z', '-x']
export const ERAS: TowerEra[] = ['concrete', 'tenement', 'glass', 'makeshift']
const STYLES: TowerWindows[] = ['grid', 'office', 'ribbon', 'glass']
/** Storey heights, a street-level shop floor, and the podium and setback a tower is seeded with, in metres. */
const STOREY = { residential: 3.1, office: 3.8 }
const SHOP_FLOOR = 4.5
const PODIUM: [number, number] = [15, 25]
const SETBACK: [number, number] = [3, 6]
/** Per window style: cell width, storey height, and the pane's place in its cell (x0, x1, y0, y1 as shares). The facade shader carries the same pane table. */
export const WINDOW_CELLS = [
{ w: 2.4, storey: STOREY.residential, pane: [0.2, 0.8, 0.29, 0.76] },
{ w: 1.5, storey: STOREY.office, pane: [0.1, 0.9, 0.3, 0.8] },
{ w: 3.0, storey: 3.4, pane: [0, 1, 0.3, 0.74] },
{ w: 3.0, storey: STOREY.office, pane: [0.03, 0.97, 0.05, 0.95] },
] as const
/** Facade band kinds, as the shader numbers them. */
export const BAND = {
plain: 0,
street: 1,
service: 2,
podium: 3,
tower: 4,
crown: 5,
roof: 6,
} as const
/** Shop bay states. */
export const BAY = { shop: 0, shutter: 1, dark: 2, door: 3 } as const
/** The piers between street bays: how far they stand off the wall and how high they reach, in metres. */
export const PIER = { proud: 0.3, top: 3.5 } as const
export interface WindowBand {
y0: number
y1: number
storey: number
rows: number
}
export interface FacePlan {
/** 0 to 3, an index into FACES. */
index: number
/** Whether this face fronts a street and carries kit props. */
front: boolean
/** Width at the ground. */
width: number
bays: number
bayW: number
/** One BAY state per bay, left to right as seen from the street. */
states: number[]
/** Bays that anchor a knot of detail: a lit shop with its signs. */
knots: number[]
seed: number
}
export interface TowerPlan {
seed: number
w: number
d: number
h: number
era: number
/** Window style of the shaft, and of the podium under it. */
style: number
podStyle: number
lit: number
/** Trim hex, or `none`. */
trim: string
strips: boolean
shopfronts: boolean
/** Podium height. Equals `h` when the tower has no shaft. */
podium: number
hasShaft: boolean
/** Setback of the shaft from the podium edge, along X and along Z. */
inset: [number, number]
streetH: number
pod: WindowBand | null
shaftBand: WindowBand | null
/** Height of the service band at the podium top and at the shaft base. */
serviceH: number
crownH: number
faces: FacePlan[]
/** Index of the main street face (the first one listed in `frontage`), or -1. It carries the big sign, the light and the cables. */
main: number
/** 0 to 1, the per-tower random the shader mixes into its hashes. */
sd: number
}
export interface TowerPlanInput {
seed: number
width: number
depth: number
height: number
windows?: TowerWindows
lit?: number
trim?: string
cornerStrips?: boolean
shopfronts: boolean
era?: TowerEra
/** Podium height in metres, for a tower with a shaft. Seeded when unset. */
podium?: number
frontage: TowerFace[]
}
function fit(y0: number, y1: number, storey: number): WindowBand | null {
if (y1 - y0 < 2.6) return null
const rows = Math.max(1, Math.round((y1 - y0) / storey))
return { y0, y1, storey: (y1 - y0) / rows, rows }
}
/** The largest setback a side of `size` metres allows while leaving a shaft at least 7 m wide. */
function insetFor(size: number, want: number) {
const most = (size - 7) / 2
if (most < 1.5) return 0
return Math.min(want, most)
}
/** Every seeded decision about one tower. Pure: the same input always gives the same plan. */
export function planTower(p: TowerPlanInput): TowerPlan {
const r = rng(p.seed)
const seededStyle = pick(r, STYLES)
const lit = p.lit ?? range(r, 0.08, 0.3)
const trim = p.trim ?? (r() < 0.45 ? pick(r, TRIM_NEON) : 'none')
const strips = p.cornerStrips ?? (trim !== 'none' && r() < 0.3)
const sd = r()
// A seed builds a concrete block, a tenement or a makeshift tower. A glass slab stands out, so
// it is only ever asked for.
const eraName = p.era ?? pick(r, ['concrete', 'tenement', 'tenement', 'makeshift'] as TowerEra[])
const era = ERAS.indexOf(eraName)
// Each era has its own glazing: punched windows on a concrete block, curtain wall on a glass slab.
let styleName = p.windows ?? seededStyle
if (!p.windows) {
if (eraName === 'glass') styleName = 'glass'
else if (eraName === 'concrete' && styleName === 'glass') styleName = 'grid'
else if (eraName === 'tenement' && styleName === 'glass') styleName = 'ribbon'
else if (eraName === 'makeshift' && styleName === 'glass') styleName = 'office'
}
const style = STYLES.indexOf(styleName)
const podStyle = style === 3 ? 1 : style
const { width: w, depth: d, height: h } = p
const streetH = p.shopfronts ? Math.min(SHOP_FLOOR, h * 0.5) : 0
const hasShaft = h >= 34 && Math.min(w, d) >= 10
let podium = h
let inset: [number, number] = [0, 0]
const podiumWant =
eraName === 'concrete' ? range(r, 20, PODIUM[1]) : range(r, PODIUM[0], PODIUM[1])
const setWant = range(r, SETBACK[0], SETBACK[1])
const slab = r()
if (hasShaft) {
podium =
p.podium !== undefined
? Math.min(Math.max(p.podium, 8), h - 12)
: Math.min(podiumWant, h * 0.5)
// A glass slab is thin one way. Everything else steps back evenly, a concrete block the least.
const want = eraName === 'concrete' ? SETBACK[0] : setWant
inset = [insetFor(w, want), insetFor(d, want)]
if (eraName === 'glass')
inset = slab < 0.5 ? [insetFor(w, 6), insetFor(d, 3)] : [insetFor(w, 3), insetFor(d, 6)]
}
const serviceH = podium >= 12 ? 1.4 : 0
const parapet = 1.0
const pod = fit(streetH, podium - serviceH - parapet, WINDOW_CELLS[podStyle].storey)
const crownH = hasShaft ? [5.2, 3.6, 6.4, 3.0][era] : 0
const shaftBand = hasShaft
? fit(podium + serviceH, h - crownH - 0.8, WINDOW_CELLS[style].storey)
: null
const faces: FacePlan[] = FACES.map((face, index) => {
const width = index % 2 === 0 ? w : d
const bays = Math.min(11, Math.max(1, Math.round(width / 5)))
const front = p.frontage.includes(face)
const seed = r()
const states: number[] = []
const knots: number[] = []
if (front) {
// One knot per 10 m of frontage: a lit shop, with the door beside it when there is room.
const count = Math.max(1, Math.round(width / 10))
for (let b = 0; b < bays; b++) states.push(-1)
for (let k = 0; k < count; k++) {
const at = Math.min(bays - 1, Math.floor(((k + 0.15 + r() * 0.7) * bays) / count))
if (states[at] === -1) {
states[at] = BAY.shop
knots.push(at)
}
}
const first = knots[0]
const door = first + 1 < bays && states[first + 1] === -1 ? first + 1 : first - 1
if (bays >= 3 && door >= 0 && states[door] === -1) states[door] = BAY.door
for (let b = 0; b < bays; b++) {
if (states[b] !== -1) continue
const q = r()
states[b] = q < 0.22 ? BAY.shop : q < 0.62 ? BAY.shutter : BAY.dark
}
} else {
for (let b = 0; b < bays; b++) {
const q = r()
states.push(q < 0.4 ? BAY.shop : q < 0.72 ? BAY.shutter : q < 0.9 ? BAY.dark : BAY.door)
}
}
return { index, front, width, bays, bayW: width / bays, states, knots, seed }
})
return {
seed: p.seed,
w,
d,
h,
era,
style,
podStyle,
lit,
trim,
strips,
shopfronts: p.shopfronts,
podium,
hasShaft,
inset,
streetH,
pod,
shaftBand,
serviceH,
crownH,
faces,
main: p.frontage.length ? FACES.indexOf(p.frontage[0]) : -1,
sd,
}
}
// ---------------------------------------------------------------------------------------------
// Mesh
/** The tower mesh's vertex data. Every attribute is a plain float array, so towers merge in the static batcher. */
export class FacadeMesh {
position: number[] = []
normal: number[] = []
aUv: number[] = []
aRect: number[] = []
aCell: number[] = []
aWall: number[] = []
aTrim: number[] = []
aLook: number[] = []
index: number[] = []
/** One quad. Corners run counter-clockwise seen from outside, starting bottom left. */
quad(
corners: number[][],
n: number[],
uv: number[][],
rect: number[],
cell: number[],
wall: Color,
trim: Color,
look: number[],
) {
const base = this.position.length / 3
for (let i = 0; i < 4; i++) {
this.position.push(corners[i][0], corners[i][1], corners[i][2])
this.normal.push(n[0], n[1], n[2])
this.aUv.push(uv[i][0], uv[i][1])
this.aRect.push(rect[0], rect[1], rect[2], rect[3])
this.aCell.push(cell[0], cell[1], cell[2], cell[3])
this.aWall.push(wall.r, wall.g, wall.b)
this.aTrim.push(trim.r, trim.g, trim.b)
this.aLook.push(look[0], look[1], look[2], look[3])
}
this.index.push(base, base + 1, base + 2, base, base + 2, base + 3)
}
}
interface Band {
y0: number
y1: number
kind: number
/** Flags: 1 corner strips, 2 a trim line under the top edge, 4 a tube over lit shop bays. */
flags?: number
cell?: (face: number, width: number) => number[]
}
const NORMALS = [
[0, 0, 1],
[1, 0, 0],
[0, 0, -1],
[-1, 0, 0],
]
const ZERO = [0, 0, 0, 0]
const BLACK = new Color(0, 0, 0)
/** A point on side `face` of a box centred (cx, cz) sized (w, d): `u` metres along it, `out` metres proud of it. */
export function onFace(
face: number,
cx: number,
cz: number,
w: number,
d: number,
u: number,
out = 0,
): [number, number] {
if (face === 0) return [cx - w / 2 + u, cz + d / 2 + out]
if (face === 1) return [cx + w / 2 + out, cz + d / 2 - u]
if (face === 2) return [cx + w / 2 - u, cz - d / 2 - out]
return [cx - w / 2 - out, cz - d / 2 + u]
}
/** Build the tower's merged mesh from its plan. */
export function buildTower(plan: TowerPlan, wallHex: string): FacadeMesh {
const mesh = new FacadeMesh()
const { w, d, h, podium, inset, era, sd } = plan
const trim = plan.trim === 'none' ? BLACK : emissiveColor(plan.trim, 1)
const wall = new Color(wallHex)
// The shaft is a shade apart from its podium. A glass slab is cold and dark.
const shaftWall =
era === 2
? wall.clone().lerp(new Color('#262b33'), 0.7)
: wall.clone().multiplyScalar(era === 0 ? 0.86 : 0.92)
const dark = wall.clone().multiplyScalar(0.8)
const strips = plan.strips ? 1 : 0
const fseed = (face: number) => plan.faces[face].seed
/** The four walls of a volume, one quad per band per face. */
const walls = (cx: number, cz: number, vw: number, vd: number, bands: Band[], color: Color) => {
for (let f = 0; f < 4; f++) {
const width = f % 2 === 0 ? vw : vd
for (const b of bands) {
if (b.y1 - b.y0 < 0.01) continue
const [ax, az] = onFace(f, cx, cz, vw, vd, 0)
const [bx, bz] = onFace(f, cx, cz, vw, vd, width)
mesh.quad(
[
[ax, b.y0, az],
[bx, b.y0, bz],
[bx, b.y1, bz],
[ax, b.y1, az],
],
NORMALS[f],
[
[0, b.y0],
[width, b.y0],
[width, b.y1],
[0, b.y1],
],
[width, b.y0, b.y1, b.kind],
b.cell ? b.cell(f, width) : ZERO,
color,
trim,
[sd, era, fseed(f), b.flags ?? 0],
)
}
}
}
/** A flat top at height y: a roof, or the plain top of a slab. */
const top = (
x0: number,
x1: number,
z0: number,
z1: number,
y: number,
kind: number,
color: Color,
flags = 0,
) => {
const roof = kind === BAND.roof
mesh.quad(
[
[x0, y, z1],
[x1, y, z1],
[x1, y, z0],
[x0, y, z0],
],
[0, 1, 0],
roof
? [
[0, z1 - z0],
[x1 - x0, z1 - z0],
[x1 - x0, 0],
[0, 0],
]
: [
[0, y],
[0, y],
[0, y],
[0, y],
],
roof ? [x1 - x0, z1 - z0, 0, kind] : [x1 - x0, y - 0.1, y, kind],
ZERO,
color,
trim,
[sd, era, 0, flags],
)
}
/** A plain box: slabs, cornices, piers, balconies, rooftop plant. `skip` names faces to leave out (0 to 3 sides, 4 top, 5 bottom). */
const block = (
x0: number,
x1: number,
y0: number,
y1: number,
z0: number,
z1: number,
color: Color,
skip: number[] = [],
flags = 0,
roofTop = false,
) => {
const cx = (x0 + x1) / 2
const cz = (z0 + z1) / 2
for (let f = 0; f < 4; f++) {
if (skip.includes(f)) continue
const width = f % 2 === 0 ? x1 - x0 : z1 - z0
const [ax, az] = onFace(f, cx, cz, x1 - x0, z1 - z0, 0)
const [bx, bz] = onFace(f, cx, cz, x1 - x0, z1 - z0, width)
mesh.quad(
[
[ax, y0, az],
[bx, y0, bz],
[bx, y1, bz],
[ax, y1, az],
],
NORMALS[f],
[
[0, y0],
[width, y0],
[width, y1],
[0, y1],
],
[width, y0, y1, BAND.plain],
ZERO,
color,
trim,
[sd, era, 0, flags],
)
}
if (!skip.includes(4)) top(x0, x1, z0, z1, y1, roofTop ? BAND.roof : BAND.plain, color)
if (!skip.includes(5)) {
mesh.quad(
[
[x0, y0, z0],
[x1, y0, z0],
[x1, y0, z1],
[x0, y0, z1],
],
[0, -1, 0],
[
[0, y0],
[0, y0],
[0, y0],
[0, y0],
],
[x1 - x0, y0, y0 + 0.1, BAND.plain],
ZERO,
color,
trim,
[sd, era, 0, 0],
)
}
}
/** A box set against side `face` of the ground footprint: from u0 to u1 along it, `out` metres proud. */
const onWall = (
face: number,
u0: number,
u1: number,
y0: number,
y1: number,
out: number,
color: Color,
skip: number[] = [],
) => {
const [ax, az] = onFace(face, 0, 0, w, d, u0, 0)
const [bx, bz] = onFace(face, 0, 0, w, d, u1, out)
// Never draw the side that sits against the wall.
block(Math.min(ax, bx), Math.max(ax, bx), y0, y1, Math.min(az, bz), Math.max(az, bz), color, [
(face + 2) % 4,
...skip,
])
}
const windowCell =
(style: number, band: WindowBand, share: number) => (_f: number, width: number) => {
const cols = Math.max(1, Math.round(width / WINDOW_CELLS[style].w))
return [width / cols, band.storey, share, style]
}
const streetCell = (f: number) => {
const face = plan.faces[f]
let bits = 0
face.states.forEach((s, i) => {
bits += s * 4 ** i
})
return [face.bayW, bits, 0, 0]
}
// Podium (or the whole building when it has no shaft).
const podTop = podium - 1.0
const bands: Band[] = []
if (plan.streetH > 0)
bands.push({ y0: 0, y1: plan.streetH, kind: BAND.street, cell: streetCell, flags: 4 })
if (plan.pod) {
bands.push({
y0: plan.pod.y0,
y1: plan.pod.y1,
kind: BAND.podium,
cell: windowCell(plan.podStyle, plan.pod, plan.lit),
flags: plan.hasShaft ? 0 : strips,
})
if (plan.serviceH > 0) bands.push({ y0: plan.pod.y1, y1: podTop, kind: BAND.service })
} else {
bands.push({ y0: plan.streetH, y1: podTop, kind: BAND.plain })
}
bands.push({ y0: podTop, y1: podium, kind: BAND.plain, flags: 2 })
walls(0, 0, w, d, bands, wall)
top(-w / 2, w / 2, -d / 2, d / 2, podium, BAND.roof, wall, plan.hasShaft ? 0 : 2)
// A cornice under the parapet gives the podium a shadow line.
if (podium >= 12)
block(-w / 2 - 0.25, w / 2 + 0.25, podTop - 0.3, podTop, -d / 2 - 0.25, d / 2 + 0.25, dark)
const sw = w - inset[0] * 2
const sdp = d - inset[1] * 2
if (plan.hasShaft && plan.shaftBand) {
const sb = plan.shaftBand
const crown0 = h - plan.crownH - 0.8
walls(
0,
0,
sw,
sdp,
[
{ y0: podium, y1: sb.y0, kind: BAND.service },
{
y0: sb.y0,
y1: sb.y1,
kind: BAND.tower,
cell: windowCell(plan.style, sb, plan.lit),
flags: strips,
},
{
y0: crown0,
y1: h - 0.8,
kind: BAND.crown,
cell: (_f, width) => [
width / Math.max(1, Math.round(width / (era === 2 ? 3 : 2.2))),
plan.crownH,
0.55,
era === 2 ? 3 : 0,
],
flags: strips,
},
{ y0: h - 0.8, y1: h, kind: BAND.plain, flags: 2 },
],
shaftWall,
)
top(-sw / 2, sw / 2, -sdp / 2, sdp / 2, h, BAND.roof, shaftWall, 2)
// A slab between shaft and crown. Heavy on a concrete block, a thin fin on a glass slab.
const over = [0.6, 0.3, 0.12, 0.2][era]
block(
-sw / 2 - over,
sw / 2 + over,
crown0 - 0.35,
crown0,
-sdp / 2 - over,
sdp / 2 + over,
dark,
)
}
// What stands on the roof, by era.
const r = rng(plan.seed * 31 + 7)
const roofY = h
const rw = plan.hasShaft ? sw : w
const rd = plan.hasShaft ? sdp : d
if (era === 0 && plan.hasShaft) {
// Concrete: a stepped block, the crown stepping in again.
block(
-rw / 2 + 1.5,
rw / 2 - 1.5,
roofY,
roofY + 3.2,
-rd / 2 + 1.5,
rd / 2 - 1.5,
shaftWall,
[5],
2,
true,
)
} else if (era === 2) {
// Glass: a plant screen and a mast.
block(-rw * 0.3, rw * 0.3, roofY, roofY + 2.2, -rd * 0.3, rd * 0.3, shaftWall, [5], 0, true)
const mx = range(r, -rw * 0.2, rw * 0.2)
block(mx - 0.25, mx + 0.25, roofY + 2.2, roofY + range(r, 11, 20), -0.25, 0.25, dark, [5])
} else {
// Tenement and makeshift: plant rooms and shacks, off centre.
const shacks = era === 3 ? 3 : 1 + Math.floor(r() * 2)
for (let i = 0; i < shacks; i++) {
const bw = range(r, 2.5, Math.max(3, rw * 0.4))
const bd = range(r, 2.5, Math.max(3, rd * 0.4))
const bx = range(r, -rw / 2 + bw / 2 + 0.6, rw / 2 - bw / 2 - 0.6)
const bz = range(r, -rd / 2 + bd / 2 + 0.6, rd / 2 - bd / 2 - 0.6)
block(
bx - bw / 2,
bx + bw / 2,
roofY,
roofY + range(r, 2.2, 4.4),
bz - bd / 2,
bz + bd / 2,
i % 2 ? dark : shaftWall,
[5],
0,
true,
)
}
}
// Street faces get real relief: piers between the bays, a fascia over them, balconies above.
for (const face of plan.faces) {
if (!face.front || plan.streetH < 4) continue
const f = face.index
for (let b = 0; b <= face.bays; b++) {
const u = b * face.bayW
onWall(
f,
Math.max(0, u - 0.28),
Math.min(face.width, u + 0.28),
0,
PIER.top,
PIER.proud,
dark,
[4, 5],
)
}
onWall(f, 0, face.width, PIER.top, plan.streetH, 0.45, dark)
if (era === 1 && plan.pod) {
// Tenement: stacked balconies with solid fronts, one run per storey.
const rows = Math.min(plan.pod.rows, 6)
for (let row = 1; row < rows; row++) {
const y = plan.pod.y0 + row * plan.pod.storey
const lead = range(r, 0.6, 2.4)
const tail = range(r, 0.6, 2.4)
if (face.width - lead - tail > 3)
onWall(f, lead, face.width - tail, y - 0.12, y + 0.92, 1.0, row % 2 ? wall : dark)
}
}
}
return mesh
} city/towerKit.ts
// What Tower hangs on its street faces, at the district's density rules: per 10 m of frontage
// one shop bay with two to four sign elements, AC units under the windows above it, and a cable
// crossing every 10 to 15 m. Detail gathers in knots around the lit shops and the door beside
// them. The bays between stay calm: a shutter, dark glass, a painted code.
import { pick, range, rng } from '@runek/core'
import { GLOW, type KitBuilder } from './kit'
import {
acUnit,
awning,
bladeSign,
bladeWord,
cableSag,
cableY,
drumLantern,
fasciaSign,
pipeRun,
rollerShutter,
roofSign,
stencilCode,
vendingMachine,
vent,
} from './kitParts'
import { BAY, onFace, PIER, type TowerPlan, WINDOW_CELLS } from './towerGrammar'
import { shopLamp } from './towerLight'
/** Sign lamps by era. */
const ERA_LAMPS = [
['#ff9326', '#ff6418'],
['#ffa64d', '#39ff88', '#b967ff', '#ff6418'],
['#f4f6fb', '#ffcf9a'],
['#b8e8c8', '#7a3cff', '#f6f2ea', '#39ff88'],
]
const AWNINGS = ['#5a2a1c', '#2f3a2c', '#3a2f45', '#4a3a28', '#3d2224']
const MACHINES = ['#3a2f45', '#40332a', '#2c3530', '#4a2a22']
const WHO = [
'DOT',
'MARA',
'TULLY',
'VESK',
'IONA',
'BRAM',
'NELL',
'PIKE',
'OMA',
'LUCE',
'HARL',
'QUILL',
'SABLE',
'ORRIN',
'WREN',
'CASS',
]
const WHAT = [
'NOODLE',
'FIXES',
'TEA',
'PAWN',
'KEYS',
'LAMPS',
'BUNKS',
'SOUP',
'TAILOR',
'CELLS',
'RADIO',
'PARTS',
'LOCKS',
'CUTS',
'COILS',
'DICE',
'BROTH',
'TUBES',
'SHOES',
'SCRAP',
]
const NOTES = [
'ALL WINDOWS',
'OPEN LATE',
'BY THE HOUR',
'UPSTAIRS',
'NO CREDIT',
'BACK ROOM',
'ASK INSIDE',
]
const SECTORS = 'LKRSNG'
/** How far over the ground light on the street is drawn: clear of a pavement's top and of a wet street's deck. */
const STREET = 0.045
const DIGITS = '01234568'
/** A shop name: proprietor, then offer. */
export function shopName(r: () => number) {
return `${pick(r, WHO)} ${pick(r, WHAT)}`
}
/** A painted block code, like `K3-08`. The stencil set has no seven. */
export function sectorCode(r: () => number) {
const d = () => DIGITS[Math.floor(r() * DIGITS.length)]
return `${SECTORS[Math.floor(r() * SECTORS.length)]}${d()}-${d()}${d()}`
}
export interface TowerKitOptions {
/** The shop name on the tower's main sign. Seeded when unset. */
name?: string
/** Wall to wall distance across the street, for cable crossings. 0 for none. */
cableSpan: number
/** The time a glass tower's crown shows, like `21:40`. */
clock: string
/** How far the ground in front of each face stands above the tower's base (a pavement is a step up from the road), by face. Light on the street lies on it. */
street?: readonly number[]
}
/** The name on a tower's main sign: the one it was given, or one from its seed. */
const nameOf = (plan: TowerPlan, name?: string) => name ?? shopName(rng(plan.seed * 13 + 5))
/** A tower's faces with the main one first, so the tower's name lands on it. */
const mainFirst = (plan: TowerPlan) =>
[...plan.faces].sort((a, b) => Number(b.index === plan.main) - Number(a.index === plan.main))
/**
* The shop a tower is known by: the name on its main sign, and where that shop's front stands in
* the tower's local space, at the ground and `out` metres off the wall. It walks the faces the way
* `towerKit` does, so the two agree on which shop that is. Null when no shop carries the name.
*/
export function mainShop(
plan: TowerPlan,
name?: string,
out = 0,
): { name: string; at: [number, number, number] } | null {
if (plan.streetH < 4) return null
for (const face of mainFirst(plan)) {
if (!face.front) continue
const bay = face.knots.find((b) => face.states[b] === BAY.shop)
if (bay === undefined) continue
const [x, z] = onFace(face.index, 0, 0, plan.w, plan.d, (bay + 0.5) * face.bayW, out)
return { name: nameOf(plan, name), at: [x, 0, z] }
}
return null
}
/** Add every prop and sign of one tower to `kit`, in the tower's local space. */
export function towerKit(kit: KitBuilder, plan: TowerPlan, o: TowerKitOptions) {
const { w, d, era } = plan
const lamps = ERA_LAMPS[era]
const main = plan.trim !== 'none' ? plan.trim : lamps[0]
const mainName = nameOf(plan, o.name)
let named = false
for (const face of mainFirst(plan)) {
if (!face.front || plan.streetH < 4) continue
const r = rng(plan.seed * 17 + face.index * 101 + 3)
const [ox, oz] = onFace(face.index, 0, 0, w, d, 0)
kit.push(ox, 0, oz, (face.index * Math.PI) / 2)
const { bayW, bays, width } = face
const proud = 0.45 // the fascia stands this far off the wall
const street = (o.street?.[face.index] ?? 0) + STREET
// The piers stand 0.3 m off the wall up to the fascia. One slab along the face at that depth,
// so a walker slides along the pier line instead of catching on each pier.
kit.solid(width / 2, PIER.top / 2, PIER.proud / 2, width, PIER.top, PIER.proud)
for (let b = 0; b < bays; b++) {
const state = face.states[b]
const u0 = b * bayW
const uc = u0 + bayW / 2
const knot = face.knots.includes(b)
// What a lit shop's glass leaves on the pavement: its own lamp colour, brighter for a
// brighter shop, less with the shutter part way down.
const shopLight = (open: number) => {
const lamp = shopLamp(plan.sd, face.seed, b)
kit.lightSplat(uc, street, PIER.proud, bayW + 1.6, 3.6, lamp.color, {
t: (0.3 + 0.5 * lamp.level) * open,
})
}
if (state === BAY.shop && knot) {
const name = named ? shopName(r) : mainName
const color = named ? pick(r, lamps) : main
named = true
// The name on the fascia, a tube under it, and the blade sign that carries it down the street.
// The board may spill over a calm bay next door, never over another shop's fascia, and
// it stays clear of the face ends so two names never collide on a corner.
const spill = (n: number) =>
n >= 0 && n < bays && face.states[n] !== BAY.shop ? bayW * 0.35 : 0
const lo = Math.max(0.7, u0 - spill(b - 1))
const hi = Math.min(width - 0.7, u0 + bayW + spill(b + 1))
const fit = hi - lo - 0.3
const cx = (lo + hi) / 2
fasciaSign(kit, cx, 4.0, proud, name, {
letter: range(r, 0.45, 0.6),
color,
fit,
tube: era === 1 && r() < 0.35,
})
kit.box(false, uc, 3.44, proud - 0.04, bayW - 0.7, 0.05, 0.05, color, {
glow: GLOW.tube,
t: 0.08,
})
shopLight(1)
const bladeU = r() < 0.5 ? u0 + 0.05 : u0 + bayW - 0.05
const top = Math.max(8, plan.podium - 1.5)
const letter = Math.min(
range(r, 0.55, 0.75),
(top - 5.2) / (bladeWord(name).length * 1.28 + 0.3),
)
if (letter > 0.3)
bladeSign(kit, Math.min(width - 0.1, Math.max(0.1, bladeU)), 4.9, 0, bladeWord(name), {
letter,
color,
gap: era === 1 ? 1.15 : 0.45,
})
if (r() < 0.65)
awning(kit, uc, range(r, 2.95, 3.2), 0.3, bayW - 0.8, {
depth: range(r, 1.1, 1.5),
color: pick(r, AWNINGS),
stripes: r() < 0.6,
})
// A small tube notice in the window.
kit.text(pick(r, NOTES), uc + range(r, -0.6, 0.6), 2.82, 0.04, 0.17, pick(r, lamps), {
outline: false,
glow: GLOW.tube,
t: 0.02,
})
// A machine against the calm bay next door.
const side =
b + 1 < bays && face.states[b + 1] !== BAY.shop
? 1
: b > 0 && face.states[b - 1] !== BAY.shop
? -1
: 0
if (side !== 0 && face.states[b + side] !== BAY.door && r() < 0.7) {
vendingMachine(kit, uc + side * (bayW / 2 + 1.0), 0, 0.02, {
seed: r(),
color: pick(r, MACHINES),
lamp: pick(r, ['#ffcf9a', '#b8e8c8', '#ffa64d']),
})
}
} else if (state === BAY.shop) {
if (r() < 0.6)
fasciaSign(kit, uc, 4.0, proud, shopName(r), {
letter: 0.38,
color: pick(r, lamps),
fit: bayW - 0.6,
})
let open = 1
// Two draws in turn: a shutter part way down, or failing that an awning.
const shutter = r() < 0.3
if (shutter) {
open = range(r, 0.4, 0.7)
rollerShutter(kit, uc, 0.38, 0.0, bayW - 0.76, 2.92, { open })
} else if (r() < 0.3) awning(kit, uc, 3.1, 0.3, bayW - 0.8, { color: pick(r, AWNINGS) })
shopLight(open)
} else if (state === BAY.shutter) {
kit.box(true, uc, 3.42, 0.1, bayW - 0.7, 0.2, 0.18, '#4a4844')
if (r() < 0.45)
stencilCode(kit, uc + range(r, -0.5, 0.5), range(r, 1.6, 2.3), 0, sectorCode(r))
if (r() < 0.3) vent(kit, u0 + 0.9, 2.7, 0, { width: 0.5, height: 0.36 })
} else if (state === BAY.door) {
// The service knot: a lamp over the door, its code, a riser and a meter.
kit.box(false, uc, 2.86, 0.06, 0.6, 0.07, 0.1, '#ffa64d', { glow: GLOW.tube, t: 0.02 })
kit.lightSplat(uc, street, 0.06, 2.4, 1.7, '#ffa64d', { t: 0.25 })
stencilCode(kit, uc, 3.12, 0, sectorCode(r))
const pipeU = uc - Math.min(1.5, bayW / 2 - 0.55)
pipeRun(kit, pipeU, 0.15, 0, 3.3)
pipeRun(kit, pipeU, plan.streetH, 0, Math.max(1, plan.podium - 1.0 - plan.streetH))
if (era === 3)
pipeRun(
kit,
pipeU + 0.2,
plan.streetH + 0.2,
0,
Math.max(1, plan.podium - 3 - plan.streetH),
{ radius: 0.04, color: '#5a4234' },
)
const meterU = uc + Math.min(1.5, bayW / 2 - 0.6)
kit.box(true, meterU, 1.45, 0.08, 0.45, 0.6, 0.16, '#6b6f70', { detail: 6 })
kit.box(true, meterU, 0.75, 0.06, 0.34, 0.4, 0.12, '#4a4844', { detail: 6 })
vent(kit, meterU, 2.5, 0, { width: 0.55, height: 0.4 })
}
}
// Tenement: a drum lantern at the lot line.
if (era === 1)
drumLantern(kit, 0.32, 3.1, 0.3, { color: pick(r, ['#ffa64d', '#ffa64d', '#ff6418']) })
// Concrete: the block's number, painted large on its podium.
if (era === 0 && plan.pod && plan.pod.rows >= 2) {
stencilCode(
kit,
Math.min(width - 2.5, 3.2),
plan.pod.y1 - plan.pod.storey * 0.5,
0,
sectorCode(r).slice(0, 2),
{ letter: Math.min(2.2, plan.pod.storey * 0.6), color: '#8a8478' },
)
}
// AC units under the windows above each knot, a few strays elsewhere.
if (plan.pod) {
const cell = WINDOW_CELLS[plan.podStyle]
const cols = Math.max(1, Math.round(width / cell.w))
const cw = width / cols
const rows = Math.min(plan.pod.rows, 5)
for (let row = 0; row < rows; row++) {
for (let c = 0; c < cols; c++) {
const u = (c + 0.5) * cw
const overKnot = face.knots.some((k) => u > k * bayW - 0.2 && u < (k + 1) * bayW + 0.2)
const chance = (overKnot ? 0.62 : 0.1) + (era === 3 ? 0.15 : 0) - row * 0.06
const q = r()
const q2 = r()
if (q > chance) continue
// On a balconied front the unit hangs off the balcony.
const balcony = era === 1 && row >= 1 && u > 2.5 && u < width - 2.5
const y =
plan.pod.y0 +
row * plan.pod.storey +
(balcony ? 0.05 : Math.max(0.1, cell.pane[2] * plan.pod.storey - 0.68))
acUnit(kit, u + (q2 - 0.5) * cw * 0.3, y, balcony ? 1.0 : 0, {
seed: q2,
cage: era === 3 && q2 < 0.6,
})
}
}
}
// Cable crossings from the main face, one every 10 to 15 m. A tenement street hangs lanterns on some of them.
if (o.cableSpan > 0 && face.index === plan.main) {
const count = Math.max(1, Math.round(width / 12.5))
for (let k = 0; k < count; k++) {
const u = ((k + 0.25 + r() * 0.5) * width) / count
const y = Math.min(range(r, 6.5, 11), Math.max(5.5, plan.podium - 2))
const drop = range(r, -1.2, 1.2)
const sag = o.cableSpan * range(r, 0.035, 0.07)
cableSag(kit, u, y, 0, o.cableSpan, { sag, drop })
const strands = era === 3 ? 2 : r() < 0.4 ? 1 : 0
for (let s = 0; s < strands; s++)
cableSag(kit, u + range(r, -0.5, 0.5), y + range(r, -0.6, 0.4), 0, o.cableSpan, {
sag: sag * range(r, 0.7, 1.5),
drop: drop + range(r, -0.5, 0.5),
thickness: 0.03,
})
if (era === 1 && r() < 0.6) {
const color = pick(r, lamps)
for (const t of [0.3, 0.5, 0.7]) {
const ly = y + cableY(t, sag, drop) - 0.34
kit.box(false, u, ly, t * o.cableSpan, 0.34, 0.44, 0.34, color, {
glow: GLOW.sign,
t: 0.18,
})
kit.box(true, u, ly + 0.25, t * o.cableSpan, 0.4, 0.06, 0.4, '#141110')
}
}
}
}
// One large sign per tower, on its main street face: letters tall enough to read from 100 m.
if (face.index === plan.main) {
const text = mainName
const set = face.index % 2 === 0 ? plan.inset[1] : plan.inset[0]
if (era === 1 || era === 3) {
if (plan.hasShaft && set >= 2)
roofSign(kit, width / 2, plan.podium, -0.5, text, {
letter: range(r, 1.6, 2.1),
color: main,
fit: width - 1.5,
})
else if (plan.podium >= 12)
roofSign(kit, width / 2, plan.podium, -0.4, bladeWord(text), {
letter: 1.5,
color: main,
fit: width - 1.5,
})
} else if (era === 0 && plan.podium >= 14) {
// Concrete: a tall blade on the corner, stencil cut.
const word = bladeWord(text)
const letter = Math.min(1.6, (plan.podium - 7.5) / (word.length * 1.28 + 0.3))
if (letter >= 0.8)
bladeSign(kit, width - 0.4, 6.2, 0, word, { letter, color: main, gap: 0.5 })
}
}
kit.pop()
}
// Glass: the crown shows the time on all four sides, white over a line of blue.
if (era === 2 && plan.hasShaft) {
const sw = w - plan.inset[0] * 2
const sdp = d - plan.inset[1] * 2
const y = plan.h - 0.8 - plan.crownH / 2
for (let f = 0; f < 4; f++) {
const fw = f % 2 === 0 ? sw : sdp
if (fw < 7) continue
const [ox, oz] = onFace(f, 0, 0, sw, sdp, 0)
kit.push(ox, 0, oz, (f * Math.PI) / 2)
const letter = Math.min(plan.crownH * 0.52, fw / 5)
kit.box(false, fw / 2, y, 0.04, letter * 4.4, letter * 1.7, 0.08, '#0c0d10')
kit.text(o.clock, fw / 2, y + letter * 0.08, 0.1, letter, '#f4f6fb', {
t: 0.6,
body: true,
tracking: 0.1,
})
kit.box(false, fw / 2, y - letter * 0.72, 0.1, letter * 3.9, 0.07, 0.05, '#3d5bff', {
glow: GLOW.tube,
t: 0.05,
})
kit.pop()
}
}
}
/** Where a street-face light sits, in the tower's local space: in front of its first knot. */
export function knotLight(plan: TowerPlan): [number, number, number] | null {
const face = plan.faces[plan.main]
if (!face) return null
const knot = face.knots[0] ?? 0
const [x, z] = onFace(face.index, 0, 0, plan.w, plan.d, (knot + 0.5) * face.bayW, 1.6)
return [x, 3.3, z]
} nodes/tower.ts
// Tower's facade as a TSL node material, for WebGPURenderer (which cannot draw the ShaderMaterial
// in Tower.tsx). It reads the same per-vertex data and draws the same bands, bay states, window
// cells, lit shares and trims, so both renderers show the same city. It is a simpler facade:
// no box filtering of edges, no interior mapping behind glass, no decal slots (posters, stickers,
// leak streaks, cracks), no blinds or screens in rooms, no mullions, sills, storey courses or
// grime. Scene fog and tone mapping come from the node system.
import { shareMaterial } from '@runek/core'
import {
abs,
attribute,
dot,
exp,
Fn,
float,
floor,
fract,
If,
min,
mix,
mod,
pow,
select,
sin,
smoothstep,
step,
varying,
vec2,
vec3,
vec4,
} from 'three/tsl'
import { MeshBasicNodeMaterial, type Node } from 'three/webgpu'
import { emissiveColor } from '../city/glow'
import { SHOP_LAMPS, WINDOW_LAMPS } from '../city/towerLight'
import { towerNodeUniforms as U } from './city'
/** GLSL's classic `fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453)`. */
const hash21 = (p: Node<'vec2'>) => fract(sin(dot(p, vec2(12.9898, 78.233))).mul(43758.5453))
/** A point along a ladder rung, spaced evenly on a log scale. */
const rung = (r: Node<'vec2'>, t: Node<'float'>) => r.x.mul(pow(r.y.div(r.x), t))
/** 1 inside [a, b]. */
const inside = (x: Node<'float'>, a: number | Node<'float'>, b: number | Node<'float'>) =>
step(a, x).mul(step(x, b))
/** A cumulative lamp table as a select chain, black past the last share. */
function lampTable(r: Node<'float'>, table: [number, string][]) {
let out: Node<'vec3'> = vec3(0)
for (let i = table.length - 1; i >= 0; i--) {
const c = emissiveColor(table[i][1], 1)
out = select(r.lessThan(table[i][0]), vec3(c.r, c.g, c.b), out)
}
return out
}
/** A per-quad attribute, passed flat so packed values (the bay states) arrive exact. */
const flat = <T extends 'vec3' | 'vec4'>(name: string, type: T) => {
const v = varying(attribute<T>(name, type)) as unknown as Node<T> & {
setInterpolation(kind: string): unknown
}
v.setInterpolation('flat')
return v as Node<T>
}
const lampOf = (hex: string) => {
const c = emissiveColor(hex, 1)
return vec3(c.r, c.g, c.b)
}
function towerColor(night: number) {
return Fn(() => {
const m = attribute<'vec2'>('aUv', 'vec2')
const rect = flat('aRect', 'vec4')
const cellData = flat('aCell', 'vec4')
const look = flat('aLook', 'vec4')
const trimColor = flat('aTrim', 'vec3')
const wallColor = flat('aWall', 'vec3')
const ny = attribute<'vec3'>('normal', 'vec3').y
const n = float(night)
const kind = rect.w
const faceW = rect.x
const y0 = rect.y
const y1 = rect.z
const sd = look.x
const era = look.y
const fseed = look.z
const strips = mod(look.w, 2)
const roofline = mod(floor(look.w.mul(0.5)), 2)
const fasciaTube = mod(floor(look.w.mul(0.25)), 2)
const wall = wallColor.mul(mix(float(0.35), U.wallGain, n))
const trim = trimColor.mul(U.trim).mul(n)
const col = vec3(wall).toVar()
const glow = U.glow.mul(exp(m.y.max(0).negate().div(6))).mul(n)
const side = step(abs(ny), 0.5)
If(kind.greaterThan(5.5), () => {
// Roof: darker, with the trim color along its edges after dusk.
const ed = min(m, rect.xy.sub(m))
col.assign(wall.mul(0.6).add(trim.mul(roofline).mul(step(min(ed.x, ed.y), 0.35))))
})
.ElseIf(kind.lessThan(0.5), () => {
// Plain trim: slabs, cornices, parapets, rooftop boxes.
col.assign(
wall.mul(
select(
ny.greaterThan(0.5),
float(0.75),
select(ny.lessThan(-0.5), float(0.4), float(1)),
),
),
)
col.addAssign(
trim
.mul(roofline)
.mul(inside(m.y, y1.sub(0.4), y1.sub(0.12)))
.mul(side),
)
col.addAssign(glow.mul(side))
})
.ElseIf(kind.lessThan(1.5), () => {
// Street: shop bays between piers under a fascia.
const bayW = cellData.x
const bi = floor(m.x.div(bayW))
const xm = fract(m.x.div(bayW)).mul(bayW)
const state = mod(floor(cellData.y.div(pow(float(4), bi)).add(0.01)), 4)
const r = hash21(vec2(bi, sd.mul(13.1).add(fseed)))
const open = inside(xm, 0.38, bayW.sub(0.38)).mul(inside(m.y, 0.38, 3.3))
col.assign(mix(col, wall.mul(0.55), inside(m.y, 3.5, 4.38)))
col.assign(mix(col, wall.mul(0.7), step(m.y, 0.3)))
const lamp = lampTable(r.mul(SHOP_LAMPS[SHOP_LAMPS.length - 1][0]), SHOP_LAMPS)
.mul(rung(U.shop, hash21(vec2(bi.add(3), sd.add(fseed.mul(5))))))
.mul(mix(0.08, 1.0, n))
const lit = lamp
.mul(float(0.62).add(smoothstep(0.3, 3.3, m.y).mul(0.38)))
.mul(mix(1, 0.35, inside(m.y, 0.38, 1.05)))
const shutter = wall
.mul(mix(0.9, 1.9, hash21(vec2(bi.add(11), sd))))
.mul(mix(0.6, 1.0, step(0.32, fract(m.y.div(0.12)))))
const dark = vec3(0.01, 0.009, 0.008).add(
vec3(0.02, 0.012, 0.007).mul(float(1).sub(m.y.div(3.3))),
)
const door = inside(xm, bayW.mul(0.5).sub(0.62), bayW.mul(0.5).add(0.62))
const blank = mix(wall, wall.mul(0.42), door.mul(step(m.y, 2.3))).add(
lamp
.mul(0.5)
.mul(door)
.mul(inside(m.y, 2.38, 2.7)),
)
const bay = select(
state.lessThan(0.5),
lit,
select(state.lessThan(1.5), shutter, select(state.lessThan(2.5), dark, blank)),
)
col.assign(mix(col, bay, open))
col.addAssign(
trim
.mul(fasciaTube)
.mul(step(state, 0.5))
.mul(inside(m.y, 3.42, 3.5))
.mul(inside(xm, 0.2, bayW.sub(0.2))),
)
col.addAssign(glow)
})
.ElseIf(kind.lessThan(2.5), () => {
// Service: louvres.
col.assign(wall.mul(mix(0.45, 0.8, step(0.45, fract(m.y.div(0.16))))))
col.addAssign(glow)
})
.Else(() => {
// Windows. The cell holds (cell width, storey height, lit share, style).
const cw = cellData.x
const ch = cellData.y
const style = cellData.w
const crown = kind.greaterThan(4.5)
const raisingCrown = crown.and(era.lessThan(0.5))
const indexCrown = crown.and(era.greaterThan(1.5)).and(era.lessThan(2.5))
const litP = select(indexCrown, float(1), cellData.z)
const g = vec2(m.x.div(cw), m.y.sub(y0).div(ch))
const cell = floor(g)
const f = fract(g)
const rows = floor(y1.sub(y0).div(ch).add(0.01))
const r = hash21(cell.add(vec2(sd.mul(31.7), fseed.mul(7.3))))
const r2 = hash21(cell.mul(1.7).add(vec2(sd, fseed.add(9.1))))
const pane = select(
raisingCrown,
vec4(0.38, 0.62, 0.12, 0.9),
select(
indexCrown,
vec4(0.02, 0.98, 0.1, 0.92),
select(
style.lessThan(0.5),
vec4(0.2, 0.8, 0.29, 0.76),
select(
style.lessThan(1.5),
vec4(0.1, 0.9, 0.3, 0.8),
select(style.lessThan(2.5), vec4(0, 1, 0.3, 0.74), vec4(0.03, 0.97, 0.05, 0.95)),
),
),
),
)
const mask = inside(f.x, pane.x, pane.y)
.mul(inside(f.y, pane.z, pane.w))
.mul(step(g.y, rows))
const on = step(float(1).sub(litP), r).mul(n)
const lamp = select(
indexCrown,
lampOf('#f4f6fb').mul(rung(U.window, float(0.9))),
lampTable(r2, WINDOW_LAMPS).mul(rung(U.window, hash21(cell.add(vec2(9.1, sd))))),
)
.mul(select(style.greaterThan(2.5), float(0.5), float(1)))
.mul(0.85)
const dark = mix(
vec3(0.2, 0.24, 0.3),
vec3(0.01, 0.009, 0.008).add(vec3(0.012, 0.007, 0.004).mul(float(1).sub(f.y))),
n,
)
col.assign(mix(col, mix(dark, lamp, on), mask))
col.assign(mix(col, wall.mul(1.4), step(y1.sub(0.14), m.y)))
col.addAssign(trim.mul(roofline).mul(inside(m.y, y1.sub(0.45), y1.sub(0.1))))
col.addAssign(
trim
.mul(0.85)
.mul(strips)
.mul(step(min(m.x, faceW.sub(m.x)), 0.22)),
)
col.addAssign(glow)
})
return col
})()
}
const materials = new Map<number, MeshBasicNodeMaterial>()
/** One node material per (rounded) night level, shared by every tower and marked shared for the
* static batcher, as on WebGL. */
export function towerNodeMaterial(night: number) {
let m = materials.get(night)
if (!m) {
m = new MeshBasicNodeMaterial()
m.colorNode = towerColor(night)
m.fog = true
m.name = `runek:tower:${night}`
materials.set(night, shareMaterial(m))
}
return m
}