component

Ship

A big three-masted sailing ship you can board and walk through: a plank up from the dock, the waist, the quarterdeck with its wheel, the forecastle with its bell and bowsprit, a gun deck with a cannon at every port and hammocks slung forward, a cargo hold, and the captain's cabin under the stern windows. Lanterns light the decks below. Seeded planking, sails, gunport lids and cargo; moored and steady.

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

Tune every prop in the workshop →

Add it

npx @runek/cli add ship

Pulls barrel, bed, chair, crate, flag, staircase, table, @react-three/rapier@^2.2.0, @runek/core@^0.18.0, three@^0.184.0.

Use it

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

<Ship position={[0, 0, 0]} sails="set" guns={8} gangway="starboard" seed={1} />

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

{ "type": "Ship", "props": { "position": [0, 0, 0], "sails": "set", "guns": 8, "gangway": "starboard", "seed": 1 } }

Props

Prop Type Default Description
length number 36 Hull length from stern to stem, in units (30 to 60). Deck heights, stairs and doors keep human scale; the length spreads the layout.
beam number 10 Hull breadth at its widest, in units (8 to 16).
masts number 3 3 for fore, main and mizzen; 2 drops the mizzen; 1 keeps only the main.
sails "none" | "set" | "furled" "set" Sails set and drawing, furled on their yards, or bare spars.
guns number 8 Cannons a side on the gun deck (0 for none); the waist carries a few more.
gangway "none" | "starboard" | "port" "starboard" Which side the boarding plank runs out from, or none.
gangwayDrop number 3.8 How far below the main deck the plank’s shore end sits, in units: a dock deck’s height under the main deck (which stands 4.8 above the waterline).
furnish boolean true Fit out the cabin, crew quarters, mess and hold with furniture and cargo.
lanterns boolean true Hang lit lanterns below decks and on the stern.
flag boolean true Fly a flag from the main truck.
collider boolean true The hull, decks and fittings are solid (board it and walk the decks). Off, they are a bare visual; the stairs and furniture it is fitted out with keep their own colliders.
hullColor color Topsides colour; defaults to the world palette’s woodDark.
bandColor color "#a8742c" The painted band along the gunports.
deckColor color Deck planking; defaults to the palette’s floor.
sailColor color "#e9e0c8"
flagColor color "#1b1b1b"
position [x, y, z] [0, 0, 0] Position [x, y, z] in units (1 unit = 1 m, Y-up).
rotation [x, y, z] [0, 0, 0] Euler rotation [x, y, z] in radians.
seed number 1 Seed for the deterministic variation: same seed, same result.

Registry manifest

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

Browse the whole catalog in the gallery →.

Source (10 files)

Ship.tsx

import {
  ConvexHullCollider,
  CuboidCollider,
  CylinderCollider,
  RigidBody,
  TrimeshCollider,
} from '@react-three/rapier'
import { useMaterials, useWorld, type WorldComponentProps } from '@runek/core'
import { useEffect, useMemo } from 'react'
import { BoxGeometry, Color, DoubleSide, Euler, Matrix4, Quaternion, Vector3 } from 'three'
import { Flag } from './Flag'
import { buildBulkhead, buildDeck, bulkheads, deckBeams, deckHulls, shipDecks } from './ship/decks'
import { Furnishing, Stairs } from './ship/Furnishing'
import {
  cabinTable,
  cargoLayout,
  furnishLayout,
  gunLayout,
  hammockLayout,
  lanternLayout,
} from './ship/fittings'
import { buildHull, gangwayGap, hullCollider } from './ship/hull'
import { MeshBuilder, type V3 } from './ship/mesh'
import {
  Anchors,
  Bell,
  CannonColliders,
  Cannons,
  Capstan,
  Gangway,
  GangwayColliders,
  gangwayPlan,
  Hammocks,
  Instanced,
  Lantern,
  type Mats,
  Ports,
  Rudder,
  Wheel,
  WheelColliders,
} from './ship/parts'
import { Rig } from './ship/Rig'
import { rigLayout, type SailPlan } from './ship/rigging'
import {
  gangwayReach,
  innerBreadth,
  LEVEL,
  type ShipLayout,
  SKIN,
  shipLayout,
  shipShape,
  shipSurface,
  sternZ,
} from './surfaces/ship'

export interface ShipProps extends WorldComponentProps {
  /** Hull length from stern to stem, in units (30 to 60). Deck heights, stairs and doors keep
   *  human scale; the length spreads the layout. */
  length?: number
  /** Hull breadth at its widest, in units (8 to 16). */
  beam?: number
  /** 3 for fore, main and mizzen; 2 drops the mizzen; 1 keeps only the main. */
  masts?: number
  /** Sails set and drawing, furled on their yards, or bare spars. */
  sails?: SailPlan
  /** Cannons a side on the gun deck (0 for none); the waist carries a few more. */
  guns?: number
  /** Which side the boarding plank runs out from, or none. */
  gangway?: 'starboard' | 'port' | 'none'
  /** How far below the main deck the plank's shore end sits, in units: a dock deck's height
   *  under the main deck (which stands 4.8 above the waterline). */
  gangwayDrop?: number
  /** Fit out the cabin, crew quarters, mess and hold with furniture and cargo. */
  furnish?: boolean
  /** Hang lit lanterns below decks and on the stern. */
  lanterns?: boolean
  /** Fly a flag from the main truck. */
  flag?: boolean
  /** The hull, decks and fittings are solid (board it and walk the decks). Off, they are a bare
   *  visual; the stairs and furniture it is fitted out with keep their own colliders. */
  collider?: boolean
  /** Topsides colour; defaults to the world palette's `woodDark`. */
  hullColor?: string
  /** The painted band along the gunports. */
  bandColor?: string
  /** Deck planking; defaults to the palette's `floor`. */
  deckColor?: string
  sailColor?: string
  flagColor?: string
}

const compose = (p: V3, r: V3 = [0, 0, 0], s: V3 = [1, 1, 1]) =>
  new Matrix4().compose(
    new Vector3(...p),
    new Quaternion().setFromEuler(new Euler(...r)),
    new Vector3(...s),
  )

interface Rail {
  key: string
  y: number
  x0: number
  z0: number
  x1: number
  z1: number
}

/** Rails round each hatch (open at the stair's head) and along each castle's break. */
function rails(lay: ShipLayout): Rail[] {
  const { main, gun, quarter, fore } = LEVEL
  const out: Rail[] = []
  const hatch = (key: string, y: number, h: ShipLayout['hatchA'], end: number) => {
    const w = h.w / 2 + 0.05
    out.push({ key: `${key}p`, y, x0: w, z0: h.z0, x1: w, z1: h.z1 })
    out.push({ key: `${key}s`, y, x0: -w, z0: h.z0, x1: -w, z1: h.z1 })
    out.push({ key: `${key}e`, y, x0: -w, z0: end, x1: w, z1: end })
  }
  hatch('a', main, lay.hatchA, lay.hatchA.z1)
  hatch('b', gun, lay.hatchB, lay.hatchB.z0)
  const qx = Math.abs(lay.quarterStairs[0].x) - lay.quarterStairs[0].w / 2 - 0.05
  out.push({ key: 'q', y: quarter, x0: -qx, z0: lay.zQ - 0.05, x1: qx, z1: lay.zQ - 0.05 })
  const fx = Math.abs(lay.foreStairs[0].x) - lay.foreStairs[0].w / 2 - 0.05
  out.push({ key: 'f', y: fore, x0: -fx, z0: lay.zF + 0.05, x1: fx, z1: lay.zF + 0.05 })
  return out
}

/**
 * A big three-masted sailing ship you can board and walk through. A plank runs up from the dock
 * to the waist; hatches drop to the gun deck (a cannon at every port, hammocks slung forward, a
 * mess table) and on down to the cargo hold. Stairs climb to the quarterdeck (the wheel) and
 * the forecastle (the bell, the bowsprit), and doors at each break open into the captain's
 * cabin under the stern windows and the crew quarters in the bow. Lanterns light the decks
 * below. The hull is lofted from one shape that the decks, the colliders and the deck surface
 * all share; the seed varies the planking, the sails, the open gunport lids and the cargo.
 * Moored and steady: the origin is the waterline at midships, the bow at +Z.
 */
export function Ship({
  position = [0, 0, 0],
  rotation = [0, 0, 0],
  seed = 1,
  length = 36,
  beam = 10,
  masts = 3,
  sails = 'set',
  guns = 8,
  gangway = 'starboard',
  gangwayDrop = 3.8,
  furnish = true,
  lanterns = true,
  flag = true,
  collider = true,
  hullColor,
  bandColor = '#a8742c',
  deckColor,
  sailColor = '#e9e0c8',
  flagColor = '#1b1b1b',
}: ShipProps) {
  const { unit: U, palette } = useWorld()
  const hullC = hullColor ?? palette.woodDark
  const deckC = deckColor ?? palette.floor
  const m = useMaterials({
    painted: {
      color: '#ffffff',
      vertexColors: true,
      flatShading: true,
      roughness: 0.85,
      side: DoubleSide,
    },
    wood: { slot: 'wood', color: palette.wood, roughness: 0.8 },
    dark: { slot: 'wood', color: '#2b211a', roughness: 0.8 },
    spar: { slot: 'wood', color: palette.woodDark, roughness: 0.75 },
    iron: { slot: 'metal.painted', color: '#2a2a2d', metalness: 0.55, roughness: 0.45 },
    port: { color: '#15110e', roughness: 1 },
    lid: { color: hullC, roughness: 0.85 },
    canvas: { slot: 'fabric', color: '#d6cbad', roughness: 1, side: DoubleSide },
    sail: { slot: 'fabric', color: sailColor, roughness: 0.95, side: DoubleSide },
    glass: { color: '#ffd28a', emissive: '#ffae45', emissiveIntensity: 1.4, roughness: 0.3 },
    window: { color: '#26323a', emissive: '#d49a52', emissiveIntensity: 0.3, roughness: 0.15 },
    brass: { slot: 'metal.bare', color: '#b08d3c', metalness: 0.7, roughness: 0.35 },
    rope: { color: '#4a3b2a', roughness: 1 },
  })
  const mats: Mats = m

  const shape = useMemo(() => shipShape(length, beam), [length, beam])
  const side = gangway === 'port' ? 1 : -1
  const lay = useMemo(() => shipLayout(shape, side), [shape, side])
  const open = gangway !== 'none'
  const gap = useMemo(() => gangwayGap(lay, open), [lay, open])
  const rig = useMemo(() => rigLayout(lay, masts), [lay, masts])
  const mastZ = useMemo(() => {
    const z = (k: string) => rig.masts.find((mt) => mt.key === k)?.z ?? null
    return { main: lay.masts.main, fore: z('fore'), mizzen: z('mizzen') }
  }, [rig, lay])

  const hull = useMemo(() => {
    const colors = {
      hull: new Color(hullC),
      band: new Color(bandColor),
      bottom: new Color('#3b2a21'),
      trim: new Color(hullC).multiplyScalar(0.5),
      inner: new Color(palette.wood),
    }
    const { outer, inner, trim } = buildHull(lay, colors, gap, seed)
    const b = new MeshBuilder()
    for (const part of [outer, inner, trim]) b.append(part)
    const top = new Color(deckC)
    const under = new Color(palette.wood).multiplyScalar(0.8)
    const decks = shipDecks(lay)
    decks.forEach((d, i) => {
      buildDeck(b, shape, d, top, under, seed + 10 + i)
    })
    for (const h of bulkheads(lay)) buildBulkhead(b, h, colors.inner, seed + 20)
    return { geometry: b.geometry(), decks }
  }, [lay, shape, gap, seed, hullC, bandColor, deckC, palette.wood])
  useEffect(() => () => hull.geometry.dispose(), [hull])

  const solid = useMemo(() => {
    if (!collider) return null
    return {
      walls: hullCollider(lay, gap),
      decks: hull.decks.flatMap((d) => deckHulls(shape, d)),
    }
  }, [collider, lay, gap, hull, shape])

  const beams = useMemo(
    () =>
      hull.decks.slice(1).flatMap((d) => {
        const { y, beams: bs } = deckBeams(shape, d)
        return bs.map((b) => compose([0, y, b.z], [0, 0, 0], [b.w, 1, 1]))
      }),
    [hull, shape],
  )

  const windows = useMemo(() => {
    const y = LEVEL.main + 1.25
    const z = sternZ(shape, y) + SKIN / 2
    const tilt = Math.atan((sternZ(shape, y + 0.1) - sternZ(shape, y - 0.1)) / 0.2)
    const span = innerBreadth(shape, z, y) * 1.6
    const panes = Array.from({ length: 5 }, (_, i) =>
      compose([((i - 2) * span) / 5, y, z], [tilt, 0, 0]),
    )
    return {
      pane: new BoxGeometry(0.62, 0.78, SKIN + 0.08),
      bar: new BoxGeometry(0.66, 0.05, SKIN + 0.12),
      panes,
    }
  }, [shape])
  const beamBox = useMemo(() => new BoxGeometry(1, 0.22, 0.2), [])

  const guns_ = useMemo(() => gunLayout(lay, guns, gap, seed), [lay, guns, gap, seed])
  const hammocks = useMemo(
    () => (furnish ? hammockLayout(lay, mastZ.fore, seed) : []),
    [furnish, lay, mastZ, seed],
  )
  const pieces = useMemo(() => (furnish ? furnishLayout(lay, mastZ) : []), [furnish, lay, mastZ])
  const cargo = useMemo(() => (furnish ? cargoLayout(lay, seed) : []), [furnish, lay, seed])
  const tableZ = cabinTable(lay, mastZ.mizzen)
  const lamps = useMemo(() => lanternLayout(lay, tableZ), [lay, tableZ])
  const plan = useMemo(
    () => gangwayPlan(shape, lay.gangway.z, side, gangwayDrop, gangwayReach(gangwayDrop)),
    [shape, lay, side, gangwayDrop],
  )
  const railList = useMemo(() => rails(lay), [lay])
  const wheelZ = mastZ.mizzen !== null ? mastZ.mizzen + 1.7 : lay.zQ - 2.2
  const capstanZ = mastZ.main - 3
  const bellZ = lay.zF + 0.7
  const main = rig.masts.find((mt) => mt.key === 'main') ?? rig.masts[0]

  const visual = (
    <>
      <mesh geometry={hull.geometry} material={m.painted} castShadow receiveShadow />
      <Instanced geometry={beamBox} material={m.dark} matrices={beams} />
      <Instanced geometry={windows.pane} material={m.window} matrices={windows.panes} />
      <Instanced geometry={windows.bar} material={m.dark} matrices={windows.panes} />
      {railList.map((r) => (
        <RailMesh key={r.key} rail={r} m={mats} />
      ))}
      <Rig
        lay={lay}
        rig={rig}
        sails={sails}
        seed={seed}
        spar={m.spar}
        sail={m.sail}
        rope="#2a2118"
      />
      <Cannons guns={guns_} m={mats} />
      <Ports guns={guns_} shape={shape} m={mats} />
      {hammocks.length > 0 && <Hammocks items={hammocks} m={mats} />}
      <Wheel z={wheelZ} m={mats} />
      <Capstan z={capstanZ} m={mats} />
      <Bell z={bellZ} m={mats} />
      <Anchors shape={shape} m={mats} />
      <Rudder shape={shape} m={mats} />
      {open && <Gangway plan={plan} m={mats} />}
      {lanterns &&
        lamps.map((l) => (
          <Lantern key={l.position.join()} position={l.position} stern={l.stern} m={mats} />
        ))}
    </>
  )

  const at = (p: V3): V3 => [p[0] * U, p[1] * U, p[2] * U]

  return (
    <group position={position} rotation={rotation}>
      <group scale={U}>
        {solid ? (
          <RigidBody type="fixed" colliders={false}>
            <TrimeshCollider args={solid.walls} />
            {solid.decks.map((pts, i) => (
              <ConvexHullCollider key={i} args={[pts]} />
            ))}
            {bulkheads(lay).flatMap((h) => {
              const w = Math.min(h.w0, h.w1) + 0.1
              const d = 0.6
              const half = (w - d) / 2
              return [-1, 1].map((s) => (
                <CuboidCollider
                  key={`${h.z}:${s}`}
                  args={[half, (h.y1 - h.y0) / 2, 0.05]}
                  position={[s * (d + half), (h.y0 + h.y1) / 2, h.z]}
                />
              ))
            })}
            {railList.map((r) => {
              const len = Math.hypot(r.x1 - r.x0, r.z1 - r.z0)
              return (
                <CuboidCollider
                  key={r.key}
                  args={[r.x0 === r.x1 ? 0.04 : len / 2, 0.5, r.x0 === r.x1 ? len / 2 : 0.04]}
                  position={[(r.x0 + r.x1) / 2, r.y + 0.5, (r.z0 + r.z1) / 2]}
                />
              )
            })}
            {rig.masts.map((mt) => {
              const top = mt.key === 'main' ? LEVEL.main + 3 : LEVEL.quarter + 3
              return (
                <CylinderCollider
                  key={mt.key}
                  args={[(top - LEVEL.hold) / 2, mt.r]}
                  position={[0, (top + LEVEL.hold) / 2, mt.z]}
                />
              )
            })}
            <CylinderCollider args={[0.55, 0.58]} position={[0, LEVEL.main + 0.55, capstanZ]} />
            <CuboidCollider args={[0.45, 0.75, 0.1]} position={[0, LEVEL.fore + 0.75, bellZ]} />
            <WheelColliders z={wheelZ} />
            <CannonColliders guns={guns_} />
            {open && <GangwayColliders plan={plan} />}
            {visual}
          </RigidBody>
        ) : (
          visual
        )}
      </group>
      <Stairs lay={lay} unit={U} color={deckC} />
      {furnish && <Furnishing pieces={pieces} cargo={cargo} unit={U} seed={seed} />}
      {flag && (
        <Flag
          position={at([0, main.truck + 0.1, main.z])}
          rotation={[0, Math.PI / 2, 0]}
          poleHeight={2.2}
          fly={3.2}
          drop={2}
          color={flagColor}
          seed={seed}
        />
      )}
    </group>
  )
}

Ship.surface = shipSurface

function RailMesh({ rail, m }: { rail: Rail; m: Mats }) {
  const len = Math.hypot(rail.x1 - rail.x0, rail.z1 - rail.z0)
  const along = rail.x0 === rail.x1 ? Math.PI / 2 : 0
  const cx = (rail.x0 + rail.x1) / 2
  const cz = (rail.z0 + rail.z1) / 2
  const posts = Math.max(2, Math.round(len / 0.9) + 1)
  return (
    <group position={[cx, rail.y, cz]} rotation={[0, along, 0]}>
      <mesh material={m.dark} position={[0, 1, 0]} castShadow>
        <boxGeometry args={[len + 0.08, 0.08, 0.1]} />
      </mesh>
      <mesh material={m.dark} position={[0, 0.5, 0]}>
        <boxGeometry args={[len, 0.05, 0.05]} />
      </mesh>
      {Array.from({ length: posts }, (_, i) => (
        <mesh key={i} material={m.dark} position={[-len / 2 + (len * i) / (posts - 1), 0.5, 0]}>
          <boxGeometry args={[0.07, 1, 0.07]} />
        </mesh>
      ))}
    </group>
  )
}

ship/Furnishing.tsx

import { sub, type Vec3 } from '@runek/core'
import { Barrel } from '../Barrel'
import { Bed } from '../Bed'
import { Chair } from '../Chair'
import { Crate } from '../Crate'
import { Staircase } from '../Staircase'
import { CASTLE_STAIR, LEVEL, type ShipLayout, STAIR, STEPS } from '../surfaces/ship'
import { Table } from '../Table'
import type { Cargo, Piece } from './fittings'
import type { V3 } from './mesh'

/** The flights between levels, as the catalog's own `Staircase`, placed in world units. */
export function Stairs({ lay, unit, color }: { lay: ShipLayout; unit: number; color: string }) {
  const at = (p: V3): Vec3 => [p[0] * unit, p[1] * unit, p[2] * unit]
  const { gun, hold, main, quarter, fore } = LEVEL
  const flights: {
    key: string
    at: V3
    turn: boolean
    rise: number
    run: number
    width: number
    steps: number
  }[] = [
    {
      key: 'a',
      at: [0, gun, lay.hatchA.z0 + STAIR.run],
      turn: true,
      rise: main - gun,
      run: STAIR.run,
      width: STAIR.width,
      steps: STEPS.main,
    },
    {
      key: 'b',
      at: [0, hold, lay.hatchB.z1 - STAIR.run],
      turn: false,
      rise: gun - hold,
      run: STAIR.run,
      width: STAIR.width,
      steps: STEPS.main,
    },
    ...lay.quarterStairs.map((b, i) => ({
      key: `q${i}`,
      at: [b.x, main, b.z1] as V3,
      turn: true,
      rise: quarter - main,
      run: CASTLE_STAIR.quarterRun,
      width: b.w,
      steps: STEPS.quarter,
    })),
    ...lay.foreStairs.map((b, i) => ({
      key: `f${i}`,
      at: [b.x, main, b.z0] as V3,
      turn: false,
      rise: fore - main,
      run: CASTLE_STAIR.foreRun,
      width: b.w,
      steps: STEPS.fore,
    })),
  ]
  return flights.map((f) => (
    <Staircase
      key={f.key}
      position={at(f.at)}
      rotation={[0, f.turn ? Math.PI : 0, 0]}
      form="floating"
      steps={f.steps}
      totalHeight={f.rise}
      width={f.width}
      depth={f.run}
      color={color}
    />
  ))
}

/** The cabins, mess, crew quarters and cargo, furnished from the catalog. */
export function Furnishing({
  pieces,
  cargo,
  unit,
  seed,
}: {
  pieces: Piece[]
  cargo: Cargo[]
  unit: number
  seed: number
}) {
  const at = (p: V3): Vec3 => [p[0] * unit, p[1] * unit, p[2] * unit]
  return (
    <>
      {pieces.map((p, i) => {
        const key = `${p.type}-${i}`
        const s = sub(seed, i)
        switch (p.type) {
          case 'Table':
            return (
              <Table
                key={key}
                position={at(p.position)}
                rotation={p.rotation}
                width={p.width}
                depth={p.depth}
                height={p.height}
                seed={s}
              />
            )
          case 'Chair':
            return <Chair key={key} position={at(p.position)} rotation={p.rotation} seed={s} />
          case 'Bed':
            return <Bed key={key} position={at(p.position)} rotation={p.rotation} seed={s} />
          case 'Crate':
            return (
              <Crate
                key={key}
                position={at(p.position)}
                rotation={p.rotation}
                size={p.size}
                seed={s}
              />
            )
          case 'Barrel':
            return <Barrel key={key} position={at(p.position)} seed={s} />
        }
        return null
      })}
      {cargo.map((c, i) => {
        const key = `cargo-${c.seed}`
        const s = sub(seed, 100 + i)
        if (c.kind === 'barrel') return <Barrel key={key} position={at(c.position)} seed={s} />
        const top: V3 = [c.position[0], c.position[1] + 0.8, c.position[2]]
        return (
          <group key={key}>
            <Crate position={at(c.position)} seed={s} />
            {c.stacked && (
              <Crate position={at(top)} size={0.7} rotation={[0, 0.3, 0]} seed={s + 1} />
            )}
          </group>
        )
      })}
    </>
  )
}

ship/Rig.tsx

import { useEffect, useMemo } from 'react'
import {
  BufferAttribute,
  BufferGeometry,
  LineBasicMaterial,
  type Material,
  Quaternion,
  Vector3,
} from 'three'
import { LEVEL, type ShipLayout } from '../surfaces/ship'
import type { V3 } from './mesh'
import { buildRigging, buildSails, type Rig as RigPlan, type SailPlan } from './rigging'

const UP = new Vector3(0, 1, 0)

/** A round spar between two points, tapering from `r0` to `r1`. */
function Spar({
  from,
  to,
  r0,
  r1,
  material,
}: {
  from: V3
  to: V3
  r0: number
  r1: number
  material: Material
}) {
  const { position, quaternion, length } = useMemo(() => {
    const a = new Vector3(...from)
    const b = new Vector3(...to)
    const dir = b.clone().sub(a)
    return {
      position: a.add(b).multiplyScalar(0.5),
      quaternion: new Quaternion().setFromUnitVectors(UP, dir.clone().normalize()),
      length: dir.length(),
    }
  }, [from, to])
  return (
    <mesh material={material} position={position} quaternion={quaternion} castShadow>
      <cylinderGeometry args={[r1, r0, length, 8]} />
    </mesh>
  )
}

export function Rig({
  lay,
  rig,
  sails,
  seed,
  spar,
  sail,
  rope,
}: {
  lay: ShipLayout
  rig: RigPlan
  sails: SailPlan
  seed: number
  spar: Material
  sail: Material
  rope: string
}) {
  const cloth = useMemo(() => (sails === 'set' ? buildSails(rig, seed) : null), [rig, sails, seed])
  const lines = useMemo(() => {
    const g = new BufferGeometry()
    g.setAttribute('position', new BufferAttribute(buildRigging(lay, rig), 3))
    return g
  }, [lay, rig])
  const lineMaterial = useMemo(() => new LineBasicMaterial({ color: rope }), [rope])
  useEffect(() => () => cloth?.dispose(), [cloth])
  useEffect(() => () => lines.dispose(), [lines])
  useEffect(() => () => lineMaterial.dispose(), [lineMaterial])
  const { base, tip } = rig.bowsprit
  const sp = rig.spanker
  return (
    <>
      {rig.masts.map((m) => {
        const k = m.r / 0.45
        return (
          <group key={m.key}>
            <Spar
              from={[0, LEVEL.hold, m.z]}
              to={[0, m.top + 0.8, m.z]}
              r0={m.r}
              r1={m.r * 0.78}
              material={spar}
            />
            <Spar
              from={[0, m.top - 0.6, m.z]}
              to={[0, m.cross + 0.7, m.z]}
              r0={m.r * 0.55}
              r1={m.r * 0.42}
              material={spar}
            />
            <Spar
              from={[0, m.cross - 0.6, m.z]}
              to={[0, m.truck, m.z]}
              r0={m.r * 0.34}
              r1={m.r * 0.2}
              material={spar}
            />
            <mesh material={spar} position={[0, m.top, m.z - 0.1]} castShadow>
              <boxGeometry args={[m.topHalf * 2, 0.14, 1.7 * k]} />
            </mesh>
            <mesh material={spar} position={[0, m.cross, m.z]}>
              <boxGeometry args={[1.5 * k, 0.1, 0.9 * k]} />
            </mesh>
            <mesh material={spar} position={[0, m.truck + 0.08, m.z]}>
              <cylinderGeometry args={[0.14 * k, 0.14 * k, 0.16, 10]} />
            </mesh>
            {m.yards.map((yd) => (
              <group key={yd.y} position={[0, yd.y, m.z + m.r + 0.1]}>
                <mesh material={spar} rotation={[0, 0, Math.PI / 2]} castShadow>
                  <cylinderGeometry args={[0.1 * k, 0.17 * k, yd.half * 2, 8]} />
                </mesh>
                {sails === 'furled' && yd.sail && (
                  <mesh
                    material={sail}
                    position={[0, 0.12, 0.22]}
                    rotation={[0, 0, Math.PI / 2]}
                    castShadow
                  >
                    <cylinderGeometry args={[0.22 * k, 0.22 * k, yd.half * 1.84, 8]} />
                  </mesh>
                )}
              </group>
            ))}
          </group>
        )
      })}
      <Spar from={base} to={tip} r0={0.24} r1={0.1} material={spar} />
      {sp && (
        <>
          <Spar from={sp.jaw} to={sp.peak} r0={0.12} r1={0.08} material={spar} />
          <Spar from={sp.tack} to={sp.clew} r0={0.14} r1={0.1} material={spar} />
        </>
      )}
      {cloth && <mesh geometry={cloth} material={sail} castShadow receiveShadow />}
      <lineSegments geometry={lines} material={lineMaterial} />
    </>
  )
}

ship/decks.ts

import type { Color } from 'three'
import {
  type Box,
  DECK,
  DOOR,
  deckSpan,
  innerBreadth,
  LEVEL,
  type ShipLayout,
  type ShipShape,
} from '../surfaces/ship'
import { hash01, type MeshBuilder } from './mesh'

export interface DeckSpec {
  y: number
  z0: number
  z1: number
  hole?: Box
  /** Ends that stand open to the waist, so their edge shows. */
  open?: { aft?: boolean; fore?: boolean }
}

interface Piece {
  z0: number
  z1: number
  /** 0 spans the hull; ±1 is the strip beside a hatch on that side. */
  side: 0 | 1 | -1
  hw: number
}

const PLANK = 0.26
const BUTT = 3.6

/** A deck as convex pieces: the whole width, or, around a hatch, aft, fore and two strips. */
function pieces(d: DeckSpec): Piece[] {
  const h = d.hole
  if (!h) return [{ z0: d.z0, z1: d.z1, side: 0, hw: 0 }]
  return [
    { z0: d.z0, z1: h.z0, side: 0, hw: 0 },
    { z0: h.z1, z1: d.z1, side: 0, hw: 0 },
    { z0: h.z0, z1: h.z1, side: 1, hw: h.w / 2 },
    { z0: h.z0, z1: h.z1, side: -1, hw: h.w / 2 },
  ]
}

const samples = (z0: number, z1: number, step: number) => {
  const n = Math.max(1, Math.ceil((z1 - z0) / step))
  return Array.from({ length: n + 1 }, (_, i) => z0 + ((z1 - z0) * i) / n)
}

function limits(s: ShipShape, y: number, p: Piece, z: number): [number, number] {
  const w = innerBreadth(s, z, y)
  if (p.side === 0) return [-w, w]
  const edge = Math.max(w, p.hw)
  return p.side > 0 ? [p.hw, edge] : [-edge, -p.hw]
}

const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v))

/** Planked top (a seeded shade per plank length, butts staggered), plain underside, and the
 *  edges that show round a hatch or an open castle end. */
export function buildDeck(
  b: MeshBuilder,
  s: ShipShape,
  d: DeckSpec,
  top: Color,
  under: Color,
  seed: number,
) {
  const { y } = d
  const yb = y - DECK
  for (const p of pieces(d)) {
    if (p.z1 - p.z0 < 0.01) continue
    const zs = samples(p.z0, p.z1, 0.8)
    const lims = zs.map((z) => limits(s, y, p, z))
    const lo = Math.min(...lims.map((l) => l[0]))
    const hi = Math.max(...lims.map((l) => l[1]))
    for (let k = Math.floor(lo / PLANK); k < Math.ceil(hi / PLANK); k++) {
      const xa = k * PLANK
      const xb = xa + PLANK
      const stagger = hash01(k, 7, seed) * BUTT
      for (let i = 0; i < zs.length - 1; i++) {
        const [la, ha] = lims[i]
        const [lb, hb] = lims[i + 1]
        const a0 = clamp(xa, la, ha)
        const a1 = clamp(xb, la, ha)
        const b0 = clamp(xa, lb, hb)
        const b1 = clamp(xb, lb, hb)
        if (a1 - a0 < 1e-4 && b1 - b0 < 1e-4) continue
        const seg = Math.floor(((zs[i] + zs[i + 1]) / 2 + stagger) / BUTT)
        const shade = top.clone().multiplyScalar(0.86 + 0.22 * hash01(k, seg, seed))
        b.quad(
          [a0, y, zs[i]],
          [a1, y, zs[i]],
          [b1, y, zs[i + 1]],
          [b0, y, zs[i + 1]],
          [0, 1, 0],
          shade,
        )
      }
    }
    for (let i = 0; i < zs.length - 1; i++) {
      const [la, ha] = lims[i]
      const [lb, hb] = lims[i + 1]
      b.quad(
        [la, yb, zs[i]],
        [ha, yb, zs[i]],
        [hb, yb, zs[i + 1]],
        [lb, yb, zs[i + 1]],
        [0, -1, 0],
        under,
      )
    }
  }
  const edge = (x0: number, z0: number, x1: number, z1: number, hint: [number, number, number]) =>
    b.quad([x0, yb, z0], [x1, yb, z1], [x1, y, z1], [x0, y, z0], hint, under)
  const h = d.hole
  if (h) {
    const w = h.w / 2
    edge(-w, h.z0, w, h.z0, [0, 0, 1])
    edge(-w, h.z1, w, h.z1, [0, 0, -1])
    edge(w, h.z0, w, h.z1, [-1, 0, 0])
    edge(-w, h.z0, -w, h.z1, [1, 0, 0])
  }
  const w0 = innerBreadth(s, d.z0, y)
  const w1 = innerBreadth(s, d.z1, y)
  if (d.open?.aft) edge(-w0, d.z0, w0, d.z0, [0, 0, -1])
  if (d.open?.fore) edge(-w1, d.z1, w1, d.z1, [0, 0, 1])
}

/** Each deck piece's corner points, for a convex-hull collider. */
export function deckHulls(s: ShipShape, d: DeckSpec): Float32Array[] {
  const out: Float32Array[] = []
  for (const p of pieces(d)) {
    if (p.z1 - p.z0 < 0.05) continue
    const pts: number[] = []
    for (const z of samples(p.z0, p.z1, 1.5)) {
      const [l, h] = limits(s, d.y, p, z)
      if (h - l < 0.05) continue
      pts.push(l, d.y, z, h, d.y, z, l, d.y - DECK, z, h, d.y - DECK, z)
    }
    if (pts.length >= 24) out.push(new Float32Array(pts))
  }
  return out
}

/** Beams under a deck, across the hull, clear of the hatch the stair climbs through. */
export function deckBeams(s: ShipShape, d: DeckSpec, spacing = 1.25) {
  const out: { z: number; w: number }[] = []
  const y = d.y - DECK - 0.11
  for (let z = d.z0 + 0.6; z < d.z1 - 0.3; z += spacing) {
    if (d.hole && z > d.hole.z0 - 0.2 && z < d.hole.z1 + 0.2) continue
    const w = 2 * innerBreadth(s, z, y)
    if (w > 0.6) out.push({ z, w })
  }
  return { y, beams: out }
}

/** The ship's five floors: hold, gun deck, main deck (under the castles too), quarterdeck and
 *  forecastle. */
export function shipDecks(lay: ShipLayout): DeckSpec[] {
  const s = lay.shape
  const span = (y: number) => deckSpan(s, y)
  const { hold, gun, main, quarter, fore } = LEVEL
  return [
    { y: hold, z0: span(hold)[0], z1: span(hold)[1] },
    { y: gun, z0: span(gun)[0], z1: span(gun)[1], hole: lay.hatchB },
    { y: main, z0: span(main)[0], z1: span(main)[1], hole: lay.hatchA },
    { y: quarter, z0: span(quarter)[0], z1: lay.zQ, open: { fore: true } },
    { y: fore, z0: lay.zF, z1: span(fore)[1], open: { aft: true } },
  ]
}

export interface Bulkhead {
  z: number
  y0: number
  y1: number
  /** Inner hull half-width at the bulkhead's foot and head. */
  w0: number
  w1: number
}

/** The two castle breaks: a wall from the main deck up to the castle deck, a door in its
 *  middle. */
export function bulkheads(lay: ShipLayout): Bulkhead[] {
  const s = lay.shape
  const { main } = LEVEL
  return [
    { z: lay.zQ, y1: LEVEL.quarter - DECK },
    { z: lay.zF, y1: LEVEL.fore - DECK },
  ].map(({ z, y1 }) => ({
    z,
    y0: main,
    y1,
    w0: innerBreadth(s, z, main),
    w1: innerBreadth(s, z, y1),
  }))
}

const BOARD = 0.3
const WALL = 0.05

/** Vertical boards both faces of a bulkhead, with the doorway left open and its jambs faced. */
export function buildBulkhead(b: MeshBuilder, h: Bulkhead, color: Color, seed: number) {
  const door = DOOR.width / 2
  const wMax = Math.max(h.w0, h.w1)
  for (let k = Math.floor(-wMax / BOARD); k < Math.ceil(wMax / BOARD); k++) {
    let x0 = k * BOARD
    let x1 = x0 + BOARD
    if (x1 > -door && x0 < door) {
      if (x0 < -door) x1 = -door
      else if (x1 > door) x0 = door
      else continue
    }
    const shade = color.clone().multiplyScalar(0.88 + 0.2 * hash01(k, 31, seed))
    const lo = (x: number) => clamp(x, -h.w0, h.w0)
    const hi = (x: number) => clamp(x, -h.w1, h.w1)
    if (lo(x1) - lo(x0) < 1e-4 && hi(x1) - hi(x0) < 1e-4) continue
    for (const f of [-1, 1]) {
      const z = h.z + f * WALL
      b.quad(
        [lo(x0), h.y0, z],
        [lo(x1), h.y0, z],
        [hi(x1), h.y1, z],
        [hi(x0), h.y1, z],
        [0, 0, f],
        shade,
      )
    }
  }
  for (const x of [-door, door]) {
    b.quad(
      [x, h.y0, h.z - WALL],
      [x, h.y0, h.z + WALL],
      [x, h.y1, h.z + WALL],
      [x, h.y1, h.z - WALL],
      [-Math.sign(x), 0, 0],
      color,
    )
  }
}

ship/fittings.ts

import {
  DECK,
  deckSpan,
  halfBreadth,
  innerBreadth,
  LEVEL,
  railY,
  type ShipLayout,
  sternZ,
} from '../surfaces/ship'
import type { Gap } from './hull'
import { hash01, type V3 } from './mesh'

export interface Gun {
  side: 1 | -1
  x: number
  y: number
  z: number
  /** Height of the port's centre on the hull. */
  portY: number
  open: boolean
}

const GUN_PITCH = 1.7

function row(z0: number, z1: number, n: number): number[] {
  const fit = Math.min(n, Math.floor((z1 - z0) / GUN_PITCH) + 1)
  if (fit <= 0) return []
  if (fit === 1) return [(z0 + z1) / 2]
  return Array.from({ length: fit }, (_, i) => z0 + ((z1 - z0) * i) / (fit - 1))
}

/** Cannons run out at a port each: `count` a side on the gun deck, fewer along the waist, none
 *  in the gangway's way. Which lids stand open is seeded. */
export function gunLayout(lay: ShipLayout, count: number, gap: Gap | null, seed: number): Gun[] {
  if (count <= 0) return []
  const s = lay.shape
  const { gun, main } = LEVEL
  const [za, zb] = deckSpan(s, gun)
  const out: Gun[] = []
  const place = (
    zs: number[],
    y: number,
    portY: number,
    skip?: (side: number, z: number) => boolean,
  ) => {
    for (const side of [1, -1] as const)
      for (const z of zs) {
        if (skip?.(side, z)) continue
        const x = side * (innerBreadth(s, z, y + 0.6) - 0.95)
        out.push({ side, x, y, z, portY, open: hash01(Math.round(z * 10), side, seed) < 0.75 })
      }
  }
  place(row(za + 3.2, zb - 4.5, Math.round(count)), gun, gun + 0.75)
  const waist = Math.max(2, Math.round(count * 0.4))
  const zw = row(lay.quarterStairs[0].z1 + 0.9, lay.foreStairs[0].z0 - 0.9, waist)
  place(
    zw,
    main,
    main + 0.6,
    (side, z) => !!gap && side === gap.side && Math.abs(z - lay.gangway.z) < 1.4,
  )
  return out
}

export interface Hammock {
  x: number
  y: number
  z: number
  sag: number
  tint: number
}

/** Hammocks slung fore and aft in rows: the gun deck's berth forward of the main hatch, and
 *  the crew quarters under the forecastle. Clear of the guns, the foremast, and head height. */
export function hammockLayout(lay: ShipLayout, foremast: number | null, seed: number): Hammock[] {
  const s = lay.shape
  const out: Hammock[] = []
  const zones = [
    { y: LEVEL.gun, z0: lay.hatchA.z1 + 1.1, z1: deckSpan(s, LEVEL.gun)[1] - 1.6, margin: 2.1 },
    { y: LEVEL.main, z0: lay.zF + 1.2, z1: deckSpan(s, LEVEL.main)[1] - 1.2, margin: 0.9 },
  ]
  let n = 0
  for (const zone of zones) {
    for (let z = zone.z0; z <= zone.z1; z += 2.2) {
      const reach = innerBreadth(s, z, zone.y + 1.95) - zone.margin
      for (let x = -Math.floor(reach / 0.85) * 0.85; x <= reach; x += 0.85) {
        if (foremast !== null && Math.abs(x) < 0.8 && Math.abs(z - foremast) < 1.4) continue
        n++
        out.push({
          x,
          y: zone.y + 1.95,
          z,
          sag: 0.85 + 0.3 * hash01(n, 1, seed),
          tint: 0.85 + 0.2 * hash01(n, 2, seed),
        })
      }
    }
  }
  return out
}

export interface Cargo {
  kind: 'crate' | 'barrel'
  position: V3
  stacked: boolean
  seed: number
}

const MAX_CARGO = 28

/** Cargo stowed along both sides of the hold, leaving a centre aisle to the stair. */
export function cargoLayout(lay: ShipLayout, seed: number): Cargo[] {
  const s = lay.shape
  const y = LEVEL.hold
  const [za, zb] = deckSpan(s, y)
  const slots: (Cargo & { order: number })[] = []
  let n = 0
  for (const side of [1, -1] as const)
    for (let z = za + 1.4; z < zb - 2.2; z += 1.6)
      for (const col of [0, 1]) {
        n++
        const x = side * (innerBreadth(s, z, y + 0.6) - 0.65 - col * 1.0)
        if (Math.abs(x) < 1.4) continue
        const r = hash01(n, 11, seed)
        if (r < 0.3) continue
        const kind = r < 0.68 ? 'crate' : 'barrel'
        slots.push({
          kind,
          position: [x, y, z],
          stacked: kind === 'crate' && hash01(n, 12, seed) < 0.4,
          seed: n,
          order: hash01(n, 13, seed),
        })
      }
  return slots
    .sort((a, b) => a.order - b.order)
    .slice(0, MAX_CARGO)
    .map(({ order: _, ...c }) => c)
}

export interface Lamp {
  position: V3
  /** A big stern lantern on the taffrail rather than one hung from a beam. */
  stern?: boolean
}

/** Lanterns: two in the hold, two on the gun deck, one in each cabin, two at the stern. */
export function lanternLayout(lay: ShipLayout, tableZ: number): Lamp[] {
  const s = lay.shape
  const L = s.length
  const { gun, main, quarter, fore } = LEVEL
  const hang = (deck: number) => deck - DECK - 0.55
  const [, gunBow] = deckSpan(s, gun)
  const [, mainBow] = deckSpan(s, main)
  const yr = railY(s, sternZ(s, quarter + 1))
  const zs = sternZ(s, yr) + 0.35
  const xs = halfBreadth(s, zs, yr) - 0.55
  return [
    { position: [0, hang(gun), -0.22 * L] },
    { position: [0, hang(gun), 0.2 * L] },
    { position: [0, hang(main), (lay.hatchA.z1 + gunBow) / 2] },
    { position: [0, hang(main), lay.hatchB.z0 - 1] },
    { position: [0, hang(quarter), tableZ] },
    { position: [0, hang(fore), (lay.zF + mainBow) / 2] },
    { position: [xs, yr, zs], stern: true },
    { position: [-xs, yr, zs], stern: true },
  ]
}

export type Piece =
  | { type: 'Table'; position: V3; rotation?: V3; width: number; depth: number; height: number }
  | { type: 'Chair'; position: V3; rotation: V3 }
  | { type: 'Bed'; position: V3; rotation?: V3 }
  | { type: 'Crate'; position: V3; size: number; rotation?: V3 }
  | { type: 'Barrel'; position: V3 }

/** Where the captain's table goes: aft of the mizzen, clear of the transom. */
export function cabinTable(lay: ShipLayout, mizzen: number | null): number {
  const aft = deckSpan(lay.shape, LEVEL.main)[0]
  if (mizzen === null) return (aft + lay.zQ) / 2 - 0.5
  const z = mizzen - 2.5
  return z - 1.6 > aft + 0.4 ? z : (aft + mizzen) / 2
}

/** The furniture each room is fitted with: the captain's cabin, the gun deck's mess, the crew
 *  quarters, and a little deck cargo. The hold's cargo comes from `cargoLayout`. */
export function furnishLayout(
  lay: ShipLayout,
  masts: { main: number; fore: number | null; mizzen: number | null },
): Piece[] {
  const s = lay.shape
  const { gun, main } = LEVEL
  const out: Piece[] = []
  const t = cabinTable(lay, masts.mizzen)
  out.push({ type: 'Table', position: [0, main, t], width: 1.2, depth: 2.4, height: 0.76 })
  for (const dz of [-0.55, 0.55]) {
    out.push({ type: 'Chair', position: [0.95, main, t + dz], rotation: [0, -Math.PI / 2, 0] })
    out.push({ type: 'Chair', position: [-0.95, main, t + dz], rotation: [0, Math.PI / 2, 0] })
  }
  out.push({ type: 'Chair', position: [0, main, t - 1.55], rotation: [0, 0, 0] })
  const zb = lay.zQ - 1.5
  const wb = innerBreadth(s, zb, main + 0.5)
  out.push({ type: 'Bed', position: [wb - 0.8, main, zb] })
  out.push({ type: 'Crate', position: [wb - 0.6, main, zb - 1.5], size: 0.55 })
  out.push({
    type: 'Table',
    position: [-(wb - 0.55), main, zb],
    rotation: [0, Math.PI / 2, 0],
    width: 1.3,
    depth: 0.7,
    height: 0.8,
  })
  out.push({ type: 'Chair', position: [-(wb - 1.25), main, zb], rotation: [0, -Math.PI / 2, 0] })

  const depth = 2.2
  let mess = lay.hatchB.z0 - 1.4 - depth / 2
  if (masts.mizzen !== null && Math.abs(mess - masts.mizzen) < depth / 2 + 0.7)
    mess = masts.mizzen - 0.8 - depth / 2
  out.push({ type: 'Table', position: [0, gun, mess], width: 0.9, depth, height: 0.72 })
  for (const sx of [-1, 1])
    for (const dz of [-0.55, 0.55])
      out.push({ type: 'Crate', position: [sx * 0.8, gun, mess + dz], size: 0.42 })
  for (const sx of [-1, 1]) {
    const x = sx * (innerBreadth(s, masts.main, gun + 0.5) - 2.7)
    out.push({ type: 'Barrel', position: [x, gun, masts.main] })
  }

  for (const sx of [-1, 1])
    for (const k of [0, 1]) {
      const z = lay.zF + 1 + k * 1.3
      out.push({
        type: 'Crate',
        position: [sx * (innerBreadth(s, z, main + 0.3) - 0.45), main, z],
        size: 0.5,
      })
    }
  out.push({
    type: 'Barrel',
    position: [innerBreadth(s, lay.zF + 3.6, main + 0.5) - 0.6, main, lay.zF + 3.6],
  })

  if (masts.fore !== null)
    for (const sx of [-1, 1])
      out.push({ type: 'Barrel', position: [sx * 1, main, masts.fore - 1.1] })
  out.push({ type: 'Crate', position: [1.3, main, masts.main - 1.3], size: 0.8 })
  out.push({
    type: 'Crate',
    position: [1.3, main + 0.8, masts.main - 1.3],
    size: 0.6,
    rotation: [0, 0.4, 0],
  })
  return out
}

ship/hull.ts

import type { Color } from 'three'
import {
  bowZ,
  DECK,
  GANGWAY,
  halfBreadth,
  innerBreadth,
  LEVEL,
  railY,
  type ShipLayout,
  type ShipShape,
  SKIN,
  sternZ,
  TOP,
} from '../surfaces/ship'
import { hash01, MeshBuilder, type V3 } from './mesh'

export interface HullColors {
  hull: Color
  band: Color
  bottom: Color
  trim: Color
  inner: Color
}

type Height = number | ((z: number) => number)

interface Band {
  y0: Height
  y1: Height
  rows: number
  color?: Color
  /** Above the main deck, where the gangway opening is cut. */
  upper?: boolean
}

interface Skin {
  breadth: (z: number, y: number) => number
  ends: (y: number) => [number, number]
  /** Which way the face looks on the port (+x) side. */
  outward: 1 | -1
}

const at = (h: Height, z: number) => (typeof h === 'number' ? h : h(z))

/** Stations along the hull, cosine-spaced so the ends get detail, plus exact marks. */
export function stations(s: ShipShape, n: number, marks: number[]): number[] {
  const z0 = sternZ(s, TOP)
  const z1 = bowZ(s, TOP)
  const out: number[] = []
  for (let i = 0; i < n; i++)
    out.push(z0 + ((1 - Math.cos((Math.PI * i) / (n - 1))) / 2) * (z1 - z0))
  for (const m of marks) if (m > z0 && m < z1) out.push(m)
  out.sort((a, b) => a - b)
  return out.filter((z, i) => i === 0 || z - out[i - 1] > 0.05)
}

export interface Gap {
  side: 1 | -1
  z0: number
  z1: number
}

export function gangwayGap(lay: ShipLayout, open: boolean): Gap | null {
  if (!open) return null
  const half = GANGWAY.gap / 2
  return { side: lay.gangway.side, z0: lay.gangway.z - half, z1: lay.gangway.z + half }
}

function inGap(gap: Gap | null, side: number, za: number, zb: number) {
  return !!gap && side === gap.side && (za + zb) / 2 > gap.z0 && (za + zb) / 2 < gap.z1
}

function skin(
  b: MeshBuilder,
  zs: number[],
  sk: Skin,
  bands: Band[],
  gap: Gap | null,
  seed: number,
  shade = true,
) {
  const point = (side: number, z: number, y: number): [V3, number] => {
    const [lo, hi] = sk.ends(y)
    const zc = Math.min(hi, Math.max(lo, z))
    return [[side * sk.breadth(zc, y), y, zc], zc]
  }
  bands.forEach((band, bi) => {
    for (let r = 0; r < band.rows; r++) {
      for (const side of [1, -1]) {
        const tint = shade ? 0.93 + 0.12 * hash01(bi * 16 + r, side, seed) : 1
        const color = band.color?.clone().multiplyScalar(tint)
        for (let i = 0; i < zs.length - 1; i++) {
          const za = zs[i]
          const zb = zs[i + 1]
          if (band.upper && inGap(gap, side, za, zb)) continue
          const y = (z: number, k: number) => {
            const y0 = at(band.y0, z)
            return y0 + ((at(band.y1, z) - y0) * k) / band.rows
          }
          const [A, cA] = point(side, za, y(za, r))
          const [B, cB] = point(side, zb, y(zb, r))
          const [C, cC] = point(side, zb, y(zb, r + 1))
          const [D, cD] = point(side, za, y(za, r + 1))
          if (cA === cB && cC === cD) continue
          b.quad(A, B, C, D, [side * sk.outward, 0, 0], color)
        }
      }
    }
  })
}

/** A flat face across the stern (or the stem), port to starboard, through the band rows. */
function across(
  b: MeshBuilder,
  bands: Band[],
  zAt: (y: number) => number,
  breadth: (z: number, y: number) => number,
  hint: V3,
  zRef: number,
) {
  for (const band of bands) {
    const y0 = at(band.y0, zRef)
    const y1 = at(band.y1, zRef)
    for (let r = 0; r < band.rows; r++) {
      const ya = y0 + ((y1 - y0) * r) / band.rows
      const yb = y0 + ((y1 - y0) * (r + 1)) / band.rows
      const za = zAt(ya)
      const zb = zAt(yb)
      const xa = breadth(za, ya)
      const xb = breadth(zb, yb)
      b.quad([-xa, ya, za], [xa, ya, za], [xb, yb, zb], [-xb, yb, zb], hint, band.color)
    }
  }
}

export interface HullGeometry {
  outer: MeshBuilder
  inner: MeshBuilder
  trim: MeshBuilder
}

/** The hull's painted outer skin, its planked inner skin, and the rail cap that joins them. */
export function buildHull(
  lay: ShipLayout,
  colors: HullColors,
  gap: Gap | null,
  seed: number,
): HullGeometry {
  const s = lay.shape
  const rail = (z: number) => railY(s, z)
  const cap = (z: number) => rail(z) - 0.12
  const zs = stations(s, 72, [
    ...(gap ? [gap.z0, gap.z1] : []),
    lay.zQ,
    lay.zQ + 1.5,
    lay.zF - 1.5,
    lay.zF,
  ])
  const { keel, gun, main, hold } = LEVEL
  const outerBands: Band[] = [
    { y0: keel, y1: 0.3, rows: 4, color: colors.bottom },
    { y0: 0.3, y1: gun + 0.3, rows: 3, color: colors.hull },
    { y0: gun + 0.3, y1: gun + 1.25, rows: 1, color: colors.band },
    { y0: gun + 1.25, y1: main, rows: 2, color: colors.hull },
    { y0: main, y1: cap, rows: 3, color: colors.hull, upper: true },
    { y0: cap, y1: rail, rows: 1, color: colors.trim, upper: true },
  ]
  const innerBands: Band[] = [
    { y0: hold - DECK, y1: gun, rows: 2, color: colors.inner },
    { y0: gun, y1: main, rows: 2, color: colors.inner },
    { y0: main, y1: rail, rows: 3, color: colors.inner, upper: true },
  ]
  const outerSkin: Skin = {
    breadth: (z, y) => halfBreadth(s, z, y),
    ends: (y) => [sternZ(s, y), bowZ(s, y)],
    outward: 1,
  }
  const innerSkin: Skin = {
    breadth: (z, y) => innerBreadth(s, z, y),
    ends: (y) => [sternZ(s, y) + SKIN, bowZ(s, y)],
    outward: -1,
  }

  const outer = new MeshBuilder()
  skin(outer, zs, outerSkin, outerBands, gap, seed)
  const zStern = sternZ(s, TOP)
  const zBow = bowZ(s, TOP)
  const hb = (z: number, y: number) => halfBreadth(s, z, y)
  across(outer, outerBands, (y) => sternZ(s, y), hb, [0, 0, -1], zStern)
  across(outer, outerBands, (y) => bowZ(s, y), hb, [0, 0, 1], zBow)
  for (let i = 0; i < zs.length - 1; i++) {
    const [lo, hi] = outerSkin.ends(keel)
    const za = Math.min(hi, Math.max(lo, zs[i]))
    const zb = Math.min(hi, Math.max(lo, zs[i + 1]))
    if (za === zb) continue
    const xa = hb(za, keel)
    const xb = hb(zb, keel)
    outer.quad(
      [-xa, keel, za],
      [xa, keel, za],
      [xb, keel, zb],
      [-xb, keel, zb],
      [0, -1, 0],
      colors.bottom,
    )
  }

  const inner = new MeshBuilder()
  skin(inner, zs, innerSkin, innerBands, gap, seed + 1)
  const ib = (z: number, y: number) => innerBreadth(s, z, y)
  across(inner, innerBands, (y) => sternZ(s, y) + SKIN, ib, [0, 0, 1], zStern)

  const trim = new MeshBuilder()
  for (const side of [1, -1]) {
    for (let i = 0; i < zs.length - 1; i++) {
      const za = zs[i]
      const zb = zs[i + 1]
      const open = inGap(gap, side, za, zb)
      const ya = open ? main : rail(za)
      const yb = open ? main : rail(zb)
      const [lo, hi] = outerSkin.ends(ya)
      if (zb <= lo || za >= hi) continue
      const ca = Math.max(lo, za)
      const cb = Math.min(hi, zb)
      trim.quad(
        [side * hb(ca, ya), ya, ca],
        [side * hb(cb, yb), yb, cb],
        [side * ib(cb, yb), yb, cb],
        [side * ib(ca, ya), ya, ca],
        [0, 1, 0],
        colors.trim,
      )
    }
  }
  if (gap) {
    for (const z of [gap.z0, gap.z1]) {
      const y = rail(z)
      const o = gap.side * hb(z, main)
      const n = gap.side * ib(z, main)
      trim.quad(
        [o, main, z],
        [n, main, z],
        [n, y, z],
        [o, y, z],
        [0, 0, z === gap.z0 ? 1 : -1],
        colors.trim,
      )
    }
  }
  const yr = rail(zStern)
  const zo = sternZ(s, yr)
  const zi = zo + SKIN
  const xo = hb(zo, yr)
  const xi = ib(zi, yr)
  trim.quad([-xo, yr, zo], [xo, yr, zo], [xi, yr, zi], [-xi, yr, zi], [0, 1, 0], colors.trim)

  return { outer, inner, trim }
}

/** The walls the avatar walks along: the skin's mid-surface from the hold floor to the rail,
 *  and the transom, as one trimesh. */
export function hullCollider(lay: ShipLayout, gap: Gap | null): [Float32Array, Uint32Array] {
  const s = lay.shape
  const rail = (z: number) => railY(s, z)
  const zs = stations(s, 40, [...(gap ? [gap.z0, gap.z1] : []), lay.zQ, lay.zF])
  const mid: Skin = {
    breadth: (z, y) => halfBreadth(s, z, y) - SKIN / 2,
    ends: (y) => [sternZ(s, y) + SKIN / 2, bowZ(s, y)],
    outward: 1,
  }
  const { hold, gun, main } = LEVEL
  const bands: Band[] = [
    { y0: hold - DECK, y1: gun, rows: 1 },
    { y0: gun, y1: main, rows: 1 },
    { y0: main, y1: rail, rows: 1, upper: true },
  ]
  const b = new MeshBuilder()
  skin(b, zs, mid, bands, gap, 0, false)
  across(b, bands, (y) => sternZ(s, y) + SKIN / 2, mid.breadth, [0, 0, 1], sternZ(s, TOP))
  return b.trimesh()
}

/** Where a fitting sits flush on the outer skin at (z, y): its position and the turn (Euler
 *  order `YZX`) that points its local +x out of the hull and +y up the topsides. */
export function onHull(s: ShipShape, side: 1 | -1, z: number, y: number, proud = 0) {
  const d = 0.05
  const dz = (halfBreadth(s, z + d, y) - halfBreadth(s, z - d, y)) / (2 * d)
  const dy = (halfBreadth(s, z, y + d) - halfBreadth(s, z, y - d)) / (2 * d)
  const position: V3 = [side * (halfBreadth(s, z, y) + proud), y, z]
  const yaw = side > 0 ? Math.atan(dz) : Math.PI - Math.atan(dz)
  const rotation: V3 = [0, yaw, -Math.atan(dy)]
  return { position, rotation }
}

ship/mesh.ts

import { BufferAttribute, BufferGeometry, type Color } from 'three'

export type V3 = [number, number, number]

/** Collects flat-shaded, vertex-coloured triangles. `quad` takes a hint the face should point
 *  along and winds it to match, so callers never reason about winding. */
export class MeshBuilder {
  readonly pos: number[] = []
  readonly col: number[] = []

  tri(a: V3, b: V3, c: V3, color?: Color) {
    const ux = b[0] - a[0]
    const uy = b[1] - a[1]
    const uz = b[2] - a[2]
    const vx = c[0] - a[0]
    const vy = c[1] - a[1]
    const vz = c[2] - a[2]
    const nx = uy * vz - uz * vy
    const ny = uz * vx - ux * vz
    const nz = ux * vy - uy * vx
    // Clamped hull rows meet at the stem and stern; their slivers would only trouble the collider.
    if (nx * nx + ny * ny + nz * nz < 1e-10) return
    this.pos.push(...a, ...b, ...c)
    if (color) for (let i = 0; i < 3; i++) this.col.push(color.r, color.g, color.b)
  }

  quad(a: V3, b: V3, c: V3, d: V3, hint: V3, color?: Color) {
    // The diagonals' cross product stays true when the quad has collapsed to a triangle.
    const ux = c[0] - a[0]
    const uy = c[1] - a[1]
    const uz = c[2] - a[2]
    const vx = d[0] - b[0]
    const vy = d[1] - b[1]
    const vz = d[2] - b[2]
    const n =
      (uy * vz - uz * vy) * hint[0] + (uz * vx - ux * vz) * hint[1] + (ux * vy - uy * vx) * hint[2]
    if (n >= 0) {
      this.tri(a, b, c, color)
      this.tri(a, c, d, color)
    } else {
      this.tri(a, c, b, color)
      this.tri(a, d, c, color)
    }
  }

  append(other: MeshBuilder) {
    for (const v of other.pos) this.pos.push(v)
    for (const v of other.col) this.col.push(v)
  }

  get empty() {
    return this.pos.length === 0
  }

  geometry(): BufferGeometry {
    const g = new BufferGeometry()
    g.setAttribute('position', new BufferAttribute(new Float32Array(this.pos), 3))
    if (this.col.length) g.setAttribute('color', new BufferAttribute(new Float32Array(this.col), 3))
    g.computeVertexNormals()
    return g
  }

  /** The same triangles as a trimesh collider's vertices and indices. */
  trimesh(): [Float32Array, Uint32Array] {
    const vertices = new Float32Array(this.pos)
    const indices = new Uint32Array(vertices.length / 3)
    for (let i = 0; i < indices.length; i++) indices[i] = i
    return [vertices, indices]
  }
}

/** A cheap stable hash of two integers and a seed, in [0, 1). */
export function hash01(a: number, b: number, seed: number): number {
  let h =
    Math.imul(a | 0, 0x27d4eb2d) ^ Math.imul(b | 0, 0x165667b1) ^ Math.imul(seed | 0, 0x9e3779b1)
  h = Math.imul(h ^ (h >>> 15), 0x85ebca6b)
  h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35)
  return ((h ^ (h >>> 16)) >>> 0) / 4294967296
}

ship/parts.tsx

import { CuboidCollider, CylinderCollider } from '@react-three/rapier'
import { useLight } from '@runek/core'
import { useEffect, useLayoutEffect, useMemo, useRef } from 'react'
import {
  BoxGeometry,
  type BufferGeometry,
  Color,
  CylinderGeometry,
  Euler,
  type InstancedMesh,
  type Material,
  Matrix4,
  PlaneGeometry,
  Quaternion,
  Vector3,
} from 'three'
import { bowZ, GANGWAY, halfBreadth, LEVEL, type ShipShape, sternZ } from '../surfaces/ship'
import type { Gun, Hammock } from './fittings'
import { onHull } from './hull'
import type { V3 } from './mesh'

export type Mats = Record<
  'wood' | 'dark' | 'iron' | 'port' | 'lid' | 'canvas' | 'glass' | 'brass' | 'rope',
  Material
>

const matrix = (position: V3, rotation: V3 = [0, 0, 0], scale: V3 = [1, 1, 1], order = 'XYZ') =>
  new Matrix4().compose(
    new Vector3(...position),
    new Quaternion().setFromEuler(new Euler(...rotation, order as 'XYZ')),
    new Vector3(...scale),
  )

/** One instanced draw for many copies of a part. */
export function Instanced({
  geometry,
  material,
  matrices,
  colors,
  castShadow = false,
}: {
  geometry: BufferGeometry
  material: Material
  matrices: Matrix4[]
  colors?: Color[]
  castShadow?: boolean
}) {
  const ref = useRef<InstancedMesh>(null)
  useLayoutEffect(() => {
    const mesh = ref.current
    if (!mesh) return
    matrices.forEach((m, i) => {
      mesh.setMatrixAt(i, m)
      if (colors) mesh.setColorAt(i, colors[i])
    })
    mesh.instanceMatrix.needsUpdate = true
    if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true
    mesh.computeBoundingSphere()
  }, [matrices, colors])
  useEffect(() => () => geometry.dispose(), [geometry])
  if (!matrices.length) return null
  return (
    <instancedMesh
      key={matrices.length}
      ref={ref}
      args={[geometry, material, matrices.length]}
      castShadow={castShadow}
      receiveShadow
    />
  )
}

const BARREL = matrix([0.15, 0.62, 0], [0, 0, -Math.PI / 2])
const CARRIAGE = matrix([-0.15, 0.34, 0])
const WHEELS = [-1, 1].flatMap((a) =>
  [-1, 1].map((b) => matrix([-0.15 + a * 0.42, 0.17, b * 0.42], [Math.PI / 2, 0, 0])),
)

/** Cannons on their carriages, run out to the ports. */
export function Cannons({ guns, m }: { guns: Gun[]; m: Mats }) {
  const parts = useMemo(() => {
    const bases = guns.map((g) => matrix([g.x, g.y, g.z], [0, g.side > 0 ? 0 : Math.PI, 0]))
    return {
      barrel: new CylinderGeometry(0.12, 0.2, 2, 12),
      carriage: new BoxGeometry(1.3, 0.36, 0.78),
      wheel: new CylinderGeometry(0.17, 0.17, 0.1, 10),
      barrels: bases.map((b) => b.clone().multiply(BARREL)),
      carriages: bases.map((b) => b.clone().multiply(CARRIAGE)),
      wheels: bases.flatMap((b) => WHEELS.map((w) => b.clone().multiply(w))),
    }
  }, [guns])
  return (
    <>
      <Instanced geometry={parts.barrel} material={m.iron} matrices={parts.barrels} castShadow />
      <Instanced
        geometry={parts.carriage}
        material={m.wood}
        matrices={parts.carriages}
        castShadow
      />
      <Instanced geometry={parts.wheel} material={m.dark} matrices={parts.wheels} />
    </>
  )
}

/** One cuboid per gun: the gun line is something you walk round, not through. */
export function CannonColliders({ guns }: { guns: Gun[] }) {
  return guns.map((g) => (
    <CuboidCollider
      key={`${g.side}:${g.y}:${g.z.toFixed(2)}`}
      args={[0.95, 0.45, 0.42]}
      position={[g.x, g.y + 0.45, g.z]}
    />
  ))
}

const LID_SHUT = matrix([0.05, 0, 0])
const LID_OPEN = matrix([0.03, 0.33, 0])
  .multiply(matrix([0, 0, 0], [0, 0, 1.15]))
  .multiply(matrix([0.03, -0.33, 0]))

/** A dark recess and a lid for each gun's port, flush on the hull. */
export function Ports({ guns, shape, m }: { guns: Gun[]; shape: ShipShape; m: Mats }) {
  const parts = useMemo(() => {
    const frames = guns.map((g) => {
      const size = g.y === LEVEL.gun ? 1 : 0.8
      const { position, rotation } = onHull(shape, g.side, g.z, g.portY, 0.01)
      return { base: matrix(position, rotation, [1, size, size], 'YZX'), open: g.open }
    })
    return {
      port: new BoxGeometry(0.08, 0.62, 0.62),
      lid: new BoxGeometry(0.06, 0.66, 0.66),
      ports: frames.map((f) => f.base),
      lids: frames.map((f) => f.base.clone().multiply(f.open ? LID_OPEN : LID_SHUT)),
    }
  }, [guns, shape])
  return (
    <>
      <Instanced geometry={parts.port} material={m.port} matrices={parts.ports} />
      <Instanced geometry={parts.lid} material={m.lid} matrices={parts.lids} />
    </>
  )
}

/** Canvas hammocks slung under the beams, each sagging and weathered a little differently. */
export function Hammocks({ items, m }: { items: Hammock[]; m: Mats }) {
  const parts = useMemo(() => {
    const g = new PlaneGeometry(0.8, 1.9, 6, 8)
    g.rotateX(-Math.PI / 2)
    const p = g.attributes.position
    for (let i = 0; i < p.count; i++) {
      const u = p.getX(i) / 0.4
      const v = p.getZ(i) / 0.95
      p.setY(i, -0.2 * (1 - u * u) * (1 - v ** 6))
    }
    g.computeVertexNormals()
    const base = new Color(1, 1, 1)
    return {
      geometry: g,
      matrices: items.map((h) => matrix([h.x, h.y, h.z], [0, 0, 0], [1, h.sag, 1])),
      colors: items.map((h) => base.clone().multiplyScalar(h.tint)),
    }
  }, [items])
  return (
    <Instanced
      geometry={parts.geometry}
      material={m.canvas}
      matrices={parts.matrices}
      colors={parts.colors}
    />
  )
}

/** A hanging lantern, or a big stern lantern on the taffrail. Lit through the light pool. */
export function Lantern({
  position,
  stern = false,
  m,
}: {
  position: V3
  stern?: boolean
  m: Mats
}) {
  const glow = useLight({
    color: '#ffb766',
    intensity: stern ? 14 : 7,
    distance: stern ? 14 : 9,
    decay: 2,
  })
  const k = stern ? 2.2 : 1
  return (
    <group position={position} scale={k}>
      {!stern && (
        <mesh material={m.iron} position={[0, 0.36, 0]}>
          <cylinderGeometry args={[0.012, 0.012, 0.32, 4]} />
        </mesh>
      )}
      {stern && (
        <mesh material={m.iron} position={[0, -0.32, 0]}>
          <cylinderGeometry args={[0.03, 0.05, 0.28, 6]} />
        </mesh>
      )}
      <mesh material={m.glass}>
        <cylinderGeometry args={[0.11, 0.09, 0.3, 6]} />
      </mesh>
      <mesh material={m.iron} position={[0, 0.19, 0]}>
        <coneGeometry args={[0.15, 0.12, 6]} />
      </mesh>
      <mesh material={m.iron} position={[0, -0.17, 0]}>
        <cylinderGeometry args={[0.12, 0.1, 0.04, 6]} />
      </mesh>
      <object3D ref={glow.ref} />
    </group>
  )
}

/** The ship's wheel on its pedestal, with the binnacle forward of it. */
export function Wheel({ z, m }: { z: number; m: Mats }) {
  const y = LEVEL.quarter
  return (
    <group position={[0, y, z]}>
      {[-1, 1].map((s) => (
        <mesh key={s} material={m.wood} position={[s * 0.32, 0.62, 0]} castShadow>
          <boxGeometry args={[0.12, 1.25, 0.18]} />
        </mesh>
      ))}
      <mesh material={m.wood} position={[0, 1.15, 0]} castShadow>
        <boxGeometry args={[0.76, 0.26, 0.3]} />
      </mesh>
      <group position={[0, 1.15, 0.22]}>
        <mesh material={m.dark} castShadow>
          <torusGeometry args={[0.62, 0.035, 6, 28]} />
        </mesh>
        <mesh material={m.dark} rotation={[Math.PI / 2, 0, 0]}>
          <cylinderGeometry args={[0.11, 0.11, 0.14, 10]} />
        </mesh>
        {[0, 1, 2, 3].map((k) => (
          <mesh key={k} material={m.dark} rotation={[0, 0, (k * Math.PI) / 4]}>
            <boxGeometry args={[0.04, 1.62, 0.04]} />
          </mesh>
        ))}
      </group>
      <group position={[0, 0, 1.1]}>
        <mesh material={m.wood} position={[0, 0.5, 0]} castShadow>
          <cylinderGeometry args={[0.22, 0.28, 1, 8]} />
        </mesh>
        <mesh material={m.brass} position={[0, 1, 0]}>
          <sphereGeometry args={[0.2, 12, 6, 0, Math.PI * 2, 0, Math.PI / 2]} />
        </mesh>
      </group>
    </group>
  )
}

export function WheelColliders({ z }: { z: number }) {
  const y = LEVEL.quarter
  return (
    <>
      <CuboidCollider args={[0.45, 0.9, 0.3]} position={[0, y + 0.9, z + 0.05]} />
      <CylinderCollider args={[0.55, 0.28]} position={[0, y + 0.55, z + 1.1]} />
    </>
  )
}

/** The capstan: a waisted drum with whelps under a round drumhead. */
export function Capstan({ z, m }: { z: number; m: Mats }) {
  return (
    <group position={[0, LEVEL.main, z]}>
      <mesh material={m.wood} position={[0, 0.45, 0]} castShadow>
        <cylinderGeometry args={[0.4, 0.46, 0.9, 12]} />
      </mesh>
      {Array.from({ length: 8 }, (_, k) => {
        const a = (k / 8) * Math.PI * 2
        return (
          <mesh
            key={a}
            material={m.dark}
            position={[Math.sin(a) * 0.44, 0.45, Math.cos(a) * 0.44]}
            rotation={[0, a, 0]}
          >
            <boxGeometry args={[0.08, 0.82, 0.1]} />
          </mesh>
        )
      })}
      <mesh material={m.wood} position={[0, 0.98, 0]} castShadow>
        <cylinderGeometry args={[0.58, 0.58, 0.16, 16]} />
      </mesh>
    </group>
  )
}

/** The ship's bell in a small belfry at the forecastle's break. */
export function Bell({ z, m }: { z: number; m: Mats }) {
  return (
    <group position={[0, LEVEL.fore, z]}>
      {[-1, 1].map((s) => (
        <mesh key={s} material={m.wood} position={[s * 0.36, 0.7, 0]} castShadow>
          <boxGeometry args={[0.1, 1.4, 0.12]} />
        </mesh>
      ))}
      <mesh material={m.wood} position={[0, 1.42, 0]} castShadow>
        <boxGeometry args={[0.86, 0.12, 0.16]} />
      </mesh>
      <mesh material={m.brass} position={[0, 1.15, 0]} castShadow>
        <cylinderGeometry args={[0.08, 0.17, 0.3, 14, 1, true]} />
      </mesh>
    </group>
  )
}

/** The rudder, hung on the raked sternpost from below the keel line to the counter. */
export function Rudder({ shape, m }: { shape: ShipShape; m: Mats }) {
  const y0 = LEVEL.keel + 0.3
  const y1 = LEVEL.gun + 0.6
  const z0 = sternZ(shape, y0)
  const z1 = sternZ(shape, y1)
  const rake = Math.atan2(z0 - z1, y1 - y0)
  const chord = 1.3
  return (
    <mesh
      material={m.dark}
      position={[0, (y0 + y1) / 2, (z0 + z1) / 2 - chord / 2]}
      rotation={[-rake, 0, 0]}
      castShadow
    >
      <boxGeometry args={[0.28, Math.hypot(y1 - y0, z1 - z0), chord]} />
    </mesh>
  )
}

/** A stocked anchor hanging from its cathead on each bow. */
export function Anchors({ shape, m }: { shape: ShipShape; m: Mats }) {
  const y = LEVEL.fore + 0.6
  const z = bowZ(shape, y) - 4
  return [1, -1].map((side) => {
    const x = side * (halfBreadth(shape, z, y) + 0.45)
    const hx = side * (halfBreadth(shape, z, y - 2) + 0.5)
    return (
      <group key={side}>
        <mesh material={m.wood} position={[x + side * 0.1, y, z]} castShadow>
          <boxGeometry args={[1.1, 0.26, 0.26]} />
        </mesh>
        <group position={[hx, y - 1.5, z]} rotation={[0, 0, side * 0.08]}>
          <mesh material={m.iron} castShadow>
            <cylinderGeometry args={[0.06, 0.07, 2.6, 6]} />
          </mesh>
          <mesh material={m.wood} position={[0, 1.15, 0]} castShadow>
            <boxGeometry args={[0.14, 0.14, 1.9]} />
          </mesh>
          {[-1, 1].map((a) => (
            <mesh
              key={a}
              material={m.iron}
              position={[0, -1.05, a * 0.42]}
              rotation={[a * -0.75, 0, 0]}
              castShadow
            >
              <boxGeometry args={[0.1, 0.8, 0.12]} />
            </mesh>
          ))}
        </group>
      </group>
    )
  })
}

export interface GangwayPlan {
  side: 1 | -1
  z: number
  /** Outer hull at the main deck, where the plank meets the ship. */
  x: number
  reach: number
  drop: number
}

export function gangwayPlan(
  shape: ShipShape,
  z: number,
  side: 1 | -1,
  drop: number,
  reach: number,
) {
  return { side, z, x: side * halfBreadth(shape, z, LEVEL.main), reach, drop }
}

/** A cleated plank from the gangway opening down to the shore, with rope rails on stanchions. */
export function Gangway({ plan, m }: { plan: GangwayPlan; m: Mats }) {
  const { reach, drop } = plan
  const len = Math.hypot(reach, drop)
  const tilt = Math.atan2(drop, reach)
  const w = GANGWAY.width
  const parts = useMemo(() => {
    const cleat = new BoxGeometry(0.05, 0.04, w * 0.9)
    const cleats: Matrix4[] = []
    for (let d = 0.3; d < len - 0.2; d += 0.4) cleats.push(matrix([d, 0.02, 0]))
    const post = new CylinderGeometry(0.03, 0.03, 1, 5)
    const posts: Matrix4[] = []
    const n = Math.max(2, Math.round(len / 1.5) + 1)
    for (let i = 0; i < n; i++)
      for (const s of [-1, 1]) posts.push(matrix([(len * i) / (n - 1), 0.5, s * (w / 2 - 0.03)]))
    return { cleat, cleats, post, posts }
  }, [len, w])
  return (
    <group position={[plan.x, LEVEL.main, plan.z]} rotation={[0, plan.side > 0 ? 0 : Math.PI, 0]}>
      <group rotation={[0, 0, -tilt]}>
        <mesh material={m.wood} position={[len / 2, -0.05, 0]} castShadow receiveShadow>
          <boxGeometry args={[len, 0.1, w]} />
        </mesh>
        <Instanced geometry={parts.cleat} material={m.dark} matrices={parts.cleats} />
        <Instanced geometry={parts.post} material={m.wood} matrices={parts.posts} />
        {[-1, 1].map((s) => (
          <mesh
            key={s}
            material={m.rope}
            position={[len / 2, 0.98, s * (w / 2 - 0.03)]}
            rotation={[0, 0, Math.PI / 2]}
          >
            <cylinderGeometry args={[0.018, 0.018, len, 4]} />
          </mesh>
        ))}
      </group>
    </group>
  )
}

/** The plank, its rails, and a sill bridging the hull's thickness to the deck. */
export function GangwayColliders({ plan }: { plan: GangwayPlan }) {
  const { reach, drop } = plan
  const len = Math.hypot(reach, drop)
  const tilt = Math.atan2(drop, reach)
  const w = GANGWAY.width
  return (
    <group position={[plan.x, LEVEL.main, plan.z]} rotation={[0, plan.side > 0 ? 0 : Math.PI, 0]}>
      <CuboidCollider args={[0.3, 0.075, w / 2]} position={[-0.25, -0.075, 0]} />
      <group rotation={[0, 0, -tilt]}>
        <CuboidCollider args={[len / 2, 0.05, w / 2]} position={[len / 2, -0.05, 0]} />
        {[-1, 1].map((s) => (
          <CuboidCollider
            key={s}
            args={[len / 2, 0.5, 0.03]}
            position={[len / 2, 0.5, s * (w / 2 + 0.03)]}
          />
        ))}
      </group>
    </group>
  )
}

ship/rigging.ts

import { BufferAttribute, BufferGeometry } from 'three'
import { bowZ, halfBreadth, LEVEL, railY, type ShipLayout, sternZ } from '../surfaces/ship'
import { hash01, type V3 } from './mesh'

export type SailPlan = 'set' | 'furled' | 'none'

export interface Yard {
  y: number
  /** Half the yard's span. */
  half: number
  /** Carries a square sail hanging to the yard below (or the course's foot). */
  sail: boolean
}

export interface Mast {
  key: 'fore' | 'main' | 'mizzen'
  z: number
  /** Radius at the deck. */
  r: number
  top: number
  cross: number
  truck: number
  /** Half the top platform's width. */
  topHalf: number
  yards: Yard[]
}

export interface Bowsprit {
  base: V3
  tip: V3
  length: number
  angle: number
}

export interface Spanker {
  jaw: V3
  peak: V3
  tack: V3
  clew: V3
}

export interface Rig {
  masts: Mast[]
  bowsprit: Bowsprit
  spanker: Spanker | null
}

const SCALE = { fore: 0.86, main: 1, mizzen: 0.66 }

/** Which masts stand for a count: three-masted, then the mizzen goes, then the fore. */
const STEP: Record<number, Mast['key'][]> = {
  1: ['main'],
  2: ['fore', 'main'],
  3: ['fore', 'main', 'mizzen'],
}

export function rigLayout(lay: ShipLayout, count: number): Rig {
  const s = lay.shape
  const L = s.length
  const H = 0.85 * L
  const { main } = LEVEL
  const masts = STEP[Math.min(3, Math.max(1, Math.round(count)))].map((key): Mast => {
    const k = SCALE[key]
    const h = H * k
    const mizzen = key === 'mizzen'
    return {
      key,
      z: lay.masts[key],
      r: 0.45 * k,
      top: main + 0.42 * h,
      cross: main + 0.74 * h,
      truck: main + h,
      topHalf: 1.3 * k,
      yards: [
        // The mizzen's lowest yard (the crossjack) sets no sail: the spanker fills that space.
        { y: main + 0.36 * h, half: 0.25 * L * k, sail: !mizzen },
        { y: main + 0.62 * h, half: 0.19 * L * k, sail: true },
        { y: main + 0.86 * h, half: 0.13 * L * k, sail: true },
      ],
    }
  })
  const zb = bowZ(s, LEVEL.fore)
  const angle = 0.36
  const length = 0.26 * L
  const base: V3 = [0, LEVEL.fore + 0.5, zb - 2.2]
  const tip: V3 = [0, base[1] + Math.sin(angle) * length, base[2] + Math.cos(angle) * length]
  const miz = masts.find((m) => m.key === 'mizzen')
  let spanker: Spanker | null = null
  if (miz) {
    const jaw: V3 = [0, miz.top - 0.6, miz.z - miz.r]
    const gaff = 0.17 * L
    const peak: V3 = [0, jaw[1] + gaff * 0.5, jaw[2] - gaff * 0.87]
    const boomY = LEVEL.quarter + 2.3
    const tack: V3 = [0, boomY, miz.z - miz.r]
    const clew: V3 = [0, boomY, Math.max(miz.z - 0.24 * L, sternZ(s, boomY) - 1.6)]
    spanker = { jaw, peak, tack, clew }
  }
  return { masts, bowsprit: { base, tip, length, angle }, spanker }
}

/** Indexed, smooth-shaded cloth. */
class Cloth {
  readonly pos: number[] = []
  readonly idx: number[] = []

  grid(nu: number, nv: number, at: (u: number, v: number) => V3) {
    const start = this.pos.length / 3
    for (let j = 0; j <= nv; j++) for (let i = 0; i <= nu; i++) this.pos.push(...at(i / nu, j / nv))
    const row = nu + 1
    for (let j = 0; j < nv; j++)
      for (let i = 0; i < nu; i++) {
        const a = start + j * row + i
        this.idx.push(a, a + 1, a + row, a + 1, a + row + 1, a + row)
      }
  }

  /** A triangle subdivided n times, its belly deepest at the centroid. */
  triangle(n: number, a: V3, b: V3, c: V3, belly: V3) {
    const start = this.pos.length / 3
    const index: number[][] = []
    for (let i = 0; i <= n; i++) {
      index.push([])
      for (let j = 0; j <= n - i; j++) {
        const la = 1 - (i + j) / n
        const lb = i / n
        const lc = j / n
        const f = 27 * la * lb * lc
        index[i].push(this.pos.length / 3 - start)
        this.pos.push(
          la * a[0] + lb * b[0] + lc * c[0] + belly[0] * f,
          la * a[1] + lb * b[1] + lc * c[1] + belly[1] * f,
          la * a[2] + lb * b[2] + lc * c[2] + belly[2] * f,
        )
      }
    }
    for (let i = 0; i < n; i++)
      for (let j = 0; j < n - i; j++) {
        const p = start + index[i][j]
        const q = start + index[i + 1][j]
        const r = start + index[i][j + 1]
        this.idx.push(p, q, r)
        if (j < n - i - 1) this.idx.push(q, start + index[i + 1][j + 1], r)
      }
  }

  geometry() {
    const g = new BufferGeometry()
    g.setAttribute('position', new BufferAttribute(new Float32Array(this.pos), 3))
    g.setIndex(this.idx)
    g.computeVertexNormals()
    return g
  }
}

/** Where each square sail hangs: from its yard down to the yard below, the course to a foot
 *  clear of a castle deck's heads. */
export function squareSails(rig: Rig) {
  const out: { z: number; yt: number; yb: number; top: number; bottom: number }[] = []
  for (const m of rig.masts) {
    m.yards.forEach((yd, i) => {
      if (!yd.sail) return
      const below = m.yards[i - 1]
      out.push({
        z: m.z + m.r + 0.25,
        yt: yd.y,
        yb: below ? below.y + 0.3 : LEVEL.main + 4.2,
        top: yd.half * 0.96,
        bottom: below ? below.half * 0.94 : yd.half * 1.02,
      })
    })
  }
  return out
}

/** Every set sail as one geometry: square sails bellied forward, the spanker and the jibs
 *  bellied to port. The seed varies each sail's belly. */
export function buildSails(rig: Rig, seed: number): BufferGeometry {
  const cloth = new Cloth()
  squareSails(rig).forEach((sq, i) => {
    const belly = (0.55 + 0.4 * hash01(i, 3, seed)) * (sq.top / 9)
    cloth.grid(10, 6, (u, v) => {
      const x = -1 + 2 * u
      const half = sq.bottom + (sq.top - sq.bottom) * v
      const roach = (1 - v) * 0.35 * Math.sin(Math.PI * u)
      const y = sq.yb + (sq.yt - sq.yb) * v + roach
      const bag = Math.sin(Math.PI * u) ** 0.8 * Math.sin(Math.PI * (1 - v) * 0.85)
      return [x * half, y, sq.z + belly * bag]
    })
  })
  const sp = rig.spanker
  if (sp) {
    const belly = 0.6 + 0.3 * hash01(40, 3, seed)
    cloth.grid(6, 6, (u, v) => {
      const lerp = (a: V3, b: V3, t: number): V3 => [
        a[0] + (b[0] - a[0]) * t,
        a[1] + (b[1] - a[1]) * t,
        a[2] + (b[2] - a[2]) * t,
      ]
      const foot = lerp(sp.tack, sp.clew, u)
      const head = lerp(sp.jaw, sp.peak, u)
      const p = lerp(foot, head, v)
      p[0] += belly * Math.sin(Math.PI * u) * Math.sin(Math.PI * v)
      return p
    })
  }
  const fore = rig.masts.find((m) => m.key === 'fore') ?? rig.masts[0]
  const { tip, base } = rig.bowsprit
  const stay = (from: V3, to: V3, t: number): V3 => [
    from[0] + (to[0] - from[0]) * t,
    from[1] + (to[1] - from[1]) * t,
    from[2] + (to[2] - from[2]) * t,
  ]
  const head: V3 = [0, fore.cross, fore.z]
  const mid: V3 = stay(base, tip, 0.45)
  const inner: V3 = [0, fore.top, fore.z]
  const jibs: [V3, V3][] = [
    [stay(tip, head, 0.06), stay(tip, head, 0.6)],
    [stay(mid, inner, 0.06), stay(mid, inner, 0.62)],
  ]
  jibs.forEach(([tack, peak], i) => {
    const clew: V3 = [0, tack[1] - 0.4 - i * 0.6, tack[2] - 0.62 * (tack[2] - peak[2])]
    const belly = 0.45 + 0.3 * hash01(50 + i, 3, seed)
    cloth.triangle(6, tack, peak, clew, [belly, 0, 0])
  })
  return cloth.geometry()
}

/** Shrouds with ratlines, stays, backstays, lifts and braces: one line-segment list. */
export function buildRigging(lay: ShipLayout, rig: Rig): Float32Array {
  const s = lay.shape
  const seg: number[] = []
  const line = (a: V3, b: V3) => seg.push(...a, ...b)
  const lerp = (a: V3, b: V3, t: number): V3 => [
    a[0] + (b[0] - a[0]) * t,
    a[1] + (b[1] - a[1]) * t,
    a[2] + (b[2] - a[2]) * t,
  ]
  const channel = (side: number, z: number): V3 => {
    const zc = Math.max(sternZ(s, LEVEL.quarter) + 1, z)
    const y = railY(s, zc) - 0.15
    return [side * (halfBreadth(s, zc, y) + 0.35), y, zc]
  }
  for (const m of rig.masts) {
    const n = m.key === 'mizzen' ? 4 : 6
    for (const side of [1, -1]) {
      const head: V3 = [side * m.topHalf * 0.9, m.top, m.z]
      const feet = Array.from({ length: n }, (_, k) => channel(side, m.z - 2.6 + k * 0.8))
      for (const f of feet) line(head, f)
      const low = Math.max(...feet.map((f) => f[1])) + 0.5
      for (let y = low; y < m.top - 0.8; y += 0.42) {
        const pts = feet.map((f) => lerp(f, head, (y - f[1]) / (head[1] - f[1])))
        for (let k = 0; k < pts.length - 1; k++) line(pts[k], pts[k + 1])
      }
      for (let k = -1; k <= 1; k++)
        line([side * 0.35, m.cross, m.z], [side * m.topHalf, m.top, m.z + k * 0.5])
      for (const dz of [5.4, 6.6]) line([side * 0.3, m.cross, m.z], channel(side, m.z - dz))
      for (const yd of m.yards) {
        const end: V3 = [side * yd.half, yd.y, m.z + m.r]
        line([0, yd.y + 2.2, m.z], end)
        line(end, channel(side, m.z - 7.5))
      }
    }
  }
  const by = Object.fromEntries(rig.masts.map((m) => [m.key, m])) as Partial<
    Record<Mast['key'], Mast>
  >
  const { tip, base } = rig.bowsprit
  const first = by.fore ?? by.main
  if (first) {
    line([0, first.top, first.z], lerp(base, tip, 0.45))
    line([0, first.cross, first.z], tip)
    line([0, first.truck - 0.5, first.z], tip)
  }
  if (by.main && by.fore) {
    line([0, by.main.top, by.main.z], [0, LEVEL.main + 1, by.fore.z - 0.6])
    line([0, by.main.cross, by.main.z], [0, by.fore.top, by.fore.z])
  }
  if (by.mizzen && by.main) {
    line([0, by.mizzen.top, by.mizzen.z], [0, LEVEL.main + 3.5, by.main.z])
    line([0, by.mizzen.cross, by.mizzen.z], [0, by.main.top, by.main.z])
  }
  line(tip, [0, 1.2, bowZ(s, 1.2)])
  return new Float32Array(seg)
}

surfaces/ship.ts

import type { SurfaceDef } from '@runek/core'

// The ship's shape and layout, in metres with the origin on the waterline at midships and the
// bow at +z. Pure, so the mesh, the colliders and `runek check-world` all read one hull.

/** Floor heights of each level above the waterline. */
export const LEVEL = { keel: -3.6, hold: 0.4, gun: 2.6, main: 4.8, fore: 7, quarter: 7 }
export const DECK = 0.15
export const SKIN = 0.2
export const BULWARK = 1.05
/** Each hatch's opening; its stair runs the length of it, 0.2 short at the foot. */
export const HATCH = { width: 1.5, length: 5 }
export const STAIR = { width: 1.2, run: 4.8 }
export const CASTLE_STAIR = { width: 1.1, quarterRun: 4.4, foreRun: 4.4 }
export const DOOR = { width: 1.2, height: 2 }
export const GANGWAY = { width: 1.2, gap: 1.6, slope: 0.38 }

export const TOP = LEVEL.quarter + BULWARK
const STEM = 0.15

const clamp01 = (v: number) => Math.min(1, Math.max(0, v))
const smooth = (v: number) => {
  const t = clamp01(v)
  return t * t * (3 - 2 * t)
}

export interface ShipShape {
  length: number
  beam: number
}

export function shipShape(length = 36, beam = 10): ShipShape {
  return {
    length: Math.min(60, Math.max(30, length)),
    beam: Math.min(16, Math.max(8, beam)),
  }
}

const heightFrac = (y: number) => clamp01((y - LEVEL.keel) / (TOP - LEVEL.keel))

/** Where the stem is at height y: raked forward toward the rail. */
export const bowZ = (s: ShipShape, y: number) => (s.length / 2) * (0.8 + 0.2 * heightFrac(y) ** 0.8)

/** Where the stern is at height y: the transom overhangs above the waterline. */
export const sternZ = (s: ShipShape, y: number) =>
  -(s.length / 2) * (0.86 + 0.14 * smooth(heightFrac(y)))

/** Half the outer hull's breadth at (z, y): full midships, a fine entry at the bow, a wide
 *  transom aft above the waterline narrowing to the sternpost below it, a little tumblehome. */
export function halfBreadth(s: ShipShape, z: number, y: number): number {
  const zb = bowZ(s, y)
  const zs = sternZ(s, y)
  if (z > zb || z < zs) return 0
  let plan: number
  let fine: number
  if (z >= 0) {
    const u = z / zb
    plan = 1 - u ** 2.3
    fine = u ** 1.5
  } else {
    const a = z / zs
    const transom = 0.62 * smooth((y + 1.2) / 4.2)
    plan = transom + (1 - transom) * (1 - a ** 2.6) ** 0.6
    fine = a * a * 0.6
  }
  let section: number
  if (y < 0) {
    const q = clamp01((y - LEVEL.keel) / -LEVEL.keel)
    const full = 1 - (1 - q) ** 2.6
    section = full + (q ** 0.9 - full) * fine
  } else {
    section = 1 - 0.1 * clamp01(y / TOP) ** 1.6
  }
  return Math.max((s.beam / 2) * plan * section, STEM)
}

export const innerBreadth = (s: ShipShape, z: number, y: number) =>
  Math.max(0, halfBreadth(s, z, y) - SKIN)

/** The z span a deck at height y covers: from inside the transom to where the bow gets too
 *  narrow to stand in. */
export function deckSpan(s: ShipShape, y: number): [number, number] {
  const aft = sternZ(s, y) + SKIN
  let lo = 0
  let hi = bowZ(s, y)
  for (let i = 0; i < 30; i++) {
    const mid = (lo + hi) / 2
    if (innerBreadth(s, mid, y) > 0.05) lo = mid
    else hi = mid
  }
  return [aft, lo]
}

const ease = (v: number) => smooth(v)

/** Top of the bulwark at z: a castle's rail over the quarterdeck and forecastle, the waist's
 *  rail between, eased up over 1.5 m outside each castle. */
export function railY(s: ShipShape, z: number): number {
  const { zQ, zF } = breaks(s)
  const q = (LEVEL.quarter - LEVEL.main) * ease((zQ + 1.5 - z) / 1.5)
  const f = (LEVEL.fore - LEVEL.main) * ease((z - (zF - 1.5)) / 1.5)
  return LEVEL.main + BULWARK + q + f
}

/** The quarterdeck (aft of zQ) and forecastle (fore of zF) breaks. */
export function breaks(s: ShipShape) {
  const h = s.length / 2
  return { zQ: -h + 0.3 * s.length, zF: h - 0.2 * s.length }
}

export interface Box {
  z0: number
  z1: number
  x: number
  w: number
}

export interface ShipLayout {
  shape: ShipShape
  zQ: number
  zF: number
  masts: { fore: number; main: number; mizzen: number }
  /** Main deck to gun deck: the stair rises aft, its head at `z0`. */
  hatchA: Box
  /** Gun deck to hold: the stair rises forward, its head at `z1`. */
  hatchB: Box
  /** Waist to quarterdeck, port and starboard: rising aft, head at zQ. */
  quarterStairs: Box[]
  /** Waist to forecastle: rising forward, head at zF. */
  foreStairs: Box[]
  gangway: { z: number; side: 1 | -1 }
}

/** Every place the ship's levels, masts, hatches and stairs go, from length and beam. */
export function shipLayout(s: ShipShape, gangwaySide: 1 | -1 = -1): ShipLayout {
  const h = s.length / 2
  const { zQ, zF } = breaks(s)
  const masts = { fore: 0.52 * h, main: -0.05 * h, mizzen: -0.62 * h }
  const a0 = masts.main + 2.1
  const hatchA = { z0: a0, z1: a0 + HATCH.length, x: 0, w: HATCH.width }
  const b1 = masts.main - 1.5
  const hatchB = { z0: b1 - HATCH.length, z1: b1, x: 0, w: HATCH.width }
  const w = CASTLE_STAIR.width
  const qz1 = zQ + CASTLE_STAIR.quarterRun
  const qx = Math.min(innerBreadth(s, zQ, LEVEL.quarter), innerBreadth(s, qz1, LEVEL.main)) - 0.7
  const fz0 = zF - CASTLE_STAIR.foreRun
  const fx = Math.min(innerBreadth(s, zF, LEVEL.fore), innerBreadth(s, zF, LEVEL.main)) - 0.7
  return {
    shape: s,
    zQ,
    zF,
    masts,
    hatchA,
    hatchB,
    quarterStairs: [-1, 1].map((side) => ({ z0: zQ, z1: qz1, x: side * qx, w })),
    foreStairs: [-1, 1].map((side) => ({ z0: fz0, z1: zF, x: side * fx, w })),
    gangway: { z: (qz1 + fz0) / 2, side: gangwaySide },
  }
}

/** The gangplank's horizontal reach for a given drop to the shore end. */
export const gangwayReach = (drop: number) => Math.max(2, drop / GANGWAY.slope)

/** Tread top of a `Staircase` flight (floating form) at distance `d` from its foot. */
function treadAt(d: number, run: number, rise: number, steps: number): number | null {
  if (d < 0 || d > run) return null
  const i = Math.min(steps - 1, Math.floor((d / run) * steps))
  return (rise / steps) * (i + 1)
}

export const STEPS = { main: 12, quarter: 12, fore: 12 }

const inBox = (b: Box, x: number, z: number) =>
  z >= b.z0 && z <= b.z1 && Math.abs(x - b.x) <= b.w / 2

interface ShipSurfaceProps {
  length?: number
  beam?: number
  gangway?: 'port' | 'starboard' | 'none'
  gangwayDrop?: number
  collider?: boolean
}

/** The ship's weather decks: the waist, the quarterdeck and forecastle, their stairs, and the
 *  gangplank, the highest walkable top at a point. Below-deck floors are covered. */
export const shipSurface: SurfaceDef = {
  kind: 'deck',
  build(props, { unit }) {
    const p = props as ShipSurfaceProps
    if (p.collider === false) return () => null
    const s = shipShape(p.length, p.beam)
    const side = p.gangway === 'port' ? 1 : -1
    const lay = shipLayout(s, side)
    const drop = p.gangwayDrop ?? 3.8
    const reach = gangwayReach(drop)
    const [, bowMain] = deckSpan(s, LEVEL.main)
    const [aftQ] = deckSpan(s, LEVEL.quarter)
    const [, bowF] = deckSpan(s, LEVEL.fore)
    return (ux, uz) => {
      const x = ux / unit
      const z = uz / unit
      const at = (y: number) => y * unit
      if (p.gangway !== 'none') {
        const out = side * x - halfBreadth(s, lay.gangway.z, LEVEL.main)
        if (Math.abs(z - lay.gangway.z) <= GANGWAY.width / 2 && out >= 0 && out <= reach)
          return at(LEVEL.main - (out / reach) * drop)
      }
      for (const b of lay.quarterStairs) {
        if (!inBox(b, x, z)) continue
        const t = treadAt(
          b.z1 - z,
          CASTLE_STAIR.quarterRun,
          LEVEL.quarter - LEVEL.main,
          STEPS.quarter,
        )
        if (t !== null) return at(LEVEL.main + t)
      }
      for (const b of lay.foreStairs) {
        if (!inBox(b, x, z)) continue
        const t = treadAt(z - b.z0, CASTLE_STAIR.foreRun, LEVEL.fore - LEVEL.main, STEPS.fore)
        if (t !== null) return at(LEVEL.main + t)
      }
      if (z <= lay.zQ) {
        if (z < aftQ || Math.abs(x) > innerBreadth(s, z, LEVEL.quarter)) return null
        return at(LEVEL.quarter)
      }
      if (z >= lay.zF) {
        if (z > bowF || Math.abs(x) > innerBreadth(s, z, LEVEL.fore)) return null
        return at(LEVEL.fore)
      }
      if (z > bowMain || Math.abs(x) > innerBreadth(s, z, LEVEL.main)) return null
      if (inBox(lay.hatchA, x, z)) {
        const t = treadAt(
          lay.hatchA.z0 + STAIR.run - z,
          STAIR.run,
          LEVEL.main - LEVEL.gun,
          STEPS.main,
        )
        return at(LEVEL.gun + (t ?? 0))
      }
      return at(LEVEL.main)
    }
  },
}