@adatechnology/game-destruction-three 0.26.4 → 0.26.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../game-terrain/src/catalog.ts","../../game-terrain/src/random.ts","../../game-terrain/src/cracks.ts","../../game-terrain/src/debris.ts","../../game-terrain/src/ground-loss.ts","../../game-terrain/src/height-patch.ts","../../game-terrain/src/marks.ts","../../game-terrain/src/terrain.ts","../../game-terrain/src/impl.ts","../../game-terrain/src/types.ts","../../game-terrain/src/footprints.ts","../../game-terrain/src/buoyancy.ts","../src/engine-ground-collision.ts","../src/engine-ground-step.ts","../src/engine-ground-ring.ts","../src/engine-ground-reach.ts","../src/engine-ground-solid.ts","../src/engine-ground.ts","../src/engine-ground-job.ts","../src/engine-ground-port.ts","../src/ground-worker.ts"],"sourcesContent":["import type { TerrainBlow, TerrainMaterial, TerrainProfile } from './types'\n\n// Specific energies are what the marks of real blows imply: a 500 J pistol round leaves about 120 cm³ in soil and 3 cm³ in concrete, an 800 kJ grenade a 1.3 m crater in soil and a 25 cm spall on a slab.\n// Cracks run about a metre from a grenade on a slab and half that on asphalt; a contact charge breaks a reinforced slab right through at about 1 kg of TNT (4.2 MJ) for 12 cm,\n// the thickness cubed (the breaching rule of thumb), leaving a hole about one and a half thicknesses wide with the bars across it.\n// Rolling resistance (C_rr) of each ground, for a round thing rolling on it. Tyre tables (Engineering ToolBox \"Rolling Resistance\", after Gillespie, Fundamentals of Vehicle\n// Dynamics, 1992; Wong, Theory of Ground Vehicles): concrete and new asphalt 0.010-0.015, small new cobbles 0.010-0.015, large worn cobbles 0.03, solid sand, loose gravel and\n// medium hard soil 0.04-0.08, loose sand 0.2-0.4. Grass: a mown golf green 0.07-0.13 (Penner, The physics of putting, Can. J. Phys. 80, 2002), a lawn is longer and slower.\n// A tyre spreads its load; a small rigid roller (a rod, a casing) sinks deeper for its size, so on soft ground the high end of each range is taken. Mud is taken as loose sand\n// (the wheel sinks), dry clay and laterite as medium hard soil at its low end, loose snow (0.3 m, a foot sinks 8 cm) an estimate between packed snow (~0.03) and sand.\n// The rough hard floors keep the 0.015 the kit has always used; a smooth one (glazed tile 0.008, a hardwood floor 0.01) holds a small roller back less, so a bottle rolls farther on it.\n// Rolling damping (1/s, `rollingDamping`): the share of its spin a roller loses per second on top of C_rr, from what drags more the faster it rolls (grass blades, ploughed sand\n// and mud, crunched gravel and snow). Rough hard floors lose 0.3 a second (grit, joints, the floor's own give), glazed tile and hardwood about a third of that; grass 1.5, so a can rolling onto a lawn stops within a metre\n// or two, as one does; loose sand and mud the most. Estimates from the stop distances of a ball or a can on each ground, not a table: no standard publishes them.\nexport const TERRAIN_MATERIALS: readonly TerrainMaterial[] = [\n {\n id: 'turf',\n rolling: 0.15,\n rollingDamping: 1.5,\n dig: { effort: 1.3 },\n debris: 'clods',\n rimShare: 0.25,\n reposeDegrees: 55,\n color: [0.09, 0.2, 0.04],\n pattern: 'grass',\n hits: {\n ballistic: { specificEnergy: 3e6, aspect: 0.6 },\n blunt: { specificEnergy: 2e6, aspect: 0.2, thresholdJoules: 60 },\n slash: { specificEnergy: 3e5, aspect: 0.5 },\n explosive: { specificEnergy: 3e6, aspect: 0.45 },\n },\n fire: { maxScorch: 1, scorchPerSecond: 0.45, flammable: true },\n },\n {\n id: 'soil',\n rolling: 0.08,\n rollingDamping: 0.6,\n dig: { effort: 1 },\n debris: 'clods',\n rimShare: 0.35,\n reposeDegrees: 40,\n color: [0.2, 0.12, 0.06],\n pattern: 'soil',\n hits: {\n ballistic: { specificEnergy: 4e6, aspect: 0.6 },\n blunt: { specificEnergy: 2e6, aspect: 0.2, thresholdJoules: 60 },\n slash: { specificEnergy: 3e5, aspect: 0.5 },\n explosive: { specificEnergy: 4e6, aspect: 0.45 },\n },\n fire: { maxScorch: 0.6, scorchPerSecond: 0.15 },\n },\n {\n id: 'sand',\n rolling: 0.3,\n rollingDamping: 2.0,\n dig: { effort: 0.8 },\n debris: 'dust',\n rimShare: 0.5,\n reposeDegrees: 33,\n color: [0.62, 0.5, 0.3],\n pattern: 'sand',\n hits: {\n ballistic: { specificEnergy: 2.5e6, aspect: 0.5 },\n blunt: { specificEnergy: 1e6, aspect: 0.2, thresholdJoules: 30 },\n slash: { specificEnergy: 1.5e5, aspect: 0.5 },\n explosive: { specificEnergy: 3e6, aspect: 0.35 },\n },\n fire: { maxScorch: 0.2, scorchPerSecond: 0.05 },\n },\n {\n id: 'gravel',\n rolling: 0.08,\n rollingDamping: 1.0,\n dig: { effort: 1.6 },\n debris: 'chips',\n rimShare: 0.15,\n reposeDegrees: 38,\n color: [0.27, 0.25, 0.22],\n pattern: 'gravel',\n hits: {\n ballistic: { specificEnergy: 8e6, aspect: 0.4 },\n blunt: { specificEnergy: 8e6, aspect: 0.2, thresholdJoules: 200 },\n slash: { specificEnergy: 3e7, aspect: 0.3, thresholdJoules: 400 },\n explosive: { specificEnergy: 1e7, aspect: 0.35 },\n },\n fire: { maxScorch: 0.3, scorchPerSecond: 0.06 },\n scatters: true,\n },\n {\n id: 'asphalt',\n rolling: 0.015,\n rollingDamping: 0.35,\n debris: 'chips',\n color: [0.05, 0.05, 0.055],\n pattern: 'asphalt',\n crack: { reach: 0.6, width: 0.008, thresholdJoules: 800 },\n hits: {\n ballistic: { specificEnergy: 3e7, aspect: 0.2, minRadius: 0.03 },\n blunt: { specificEnergy: 1e8, aspect: 0.1, thresholdJoules: 400 },\n slash: { specificEnergy: 3e8, aspect: 0.2, thresholdJoules: 400 },\n explosive: { specificEnergy: 2e8, aspect: 0.12 },\n },\n fire: { maxScorch: 0.85, scorchPerSecond: 0.1, burnsAway: 0.00005 },\n },\n {\n id: 'concrete',\n rolling: 0.015,\n rollingDamping: 0.3,\n debris: 'chips',\n color: [0.33, 0.33, 0.31],\n pattern: 'concrete',\n crack: { reach: 1, width: 0.006, thresholdJoules: 300 },\n breach: { joulesPerCubedThickness: 2.4e9, radiusOverThickness: 1.5 },\n hits: {\n ballistic: { specificEnergy: 1.5e8, aspect: 0.14, minRadius: 0.018 },\n blunt: { specificEnergy: 3e8, aspect: 0.08, thresholdJoules: 800 },\n slash: { specificEnergy: 1e9, aspect: 0.2, thresholdJoules: 800 },\n explosive: { specificEnergy: 2.7e9, aspect: 0.12 },\n },\n fire: { maxScorch: 0.45, scorchPerSecond: 0.08 },\n },\n {\n id: 'mortar',\n rollingDamping: 0.3,\n debris: 'chips',\n color: [0.42, 0.4, 0.36],\n pattern: 'plain',\n hits: {\n ballistic: { specificEnergy: 4e7, aspect: 0.2 },\n blunt: { specificEnergy: 8e7, aspect: 0.1, thresholdJoules: 300 },\n slash: { specificEnergy: 3e8, aspect: 0.2, thresholdJoules: 300 },\n explosive: { specificEnergy: 8e8, aspect: 0.14 },\n },\n fire: { maxScorch: 0.45, scorchPerSecond: 0.08 },\n },\n {\n id: 'ceramic',\n rolling: 0.008,\n rollingDamping: 0.1,\n debris: 'shards',\n color: [0.72, 0.7, 0.66],\n pattern: 'tile',\n crack: { reach: 0.5, width: 0.002, thresholdJoules: 40 },\n hits: {\n ballistic: { specificEnergy: 8e6, aspect: 0.1, minRadius: 0.05 },\n blunt: { specificEnergy: 1e7, aspect: 0.08, thresholdJoules: 80, minRadius: 0.06 },\n slash: { specificEnergy: 2e8, aspect: 0.1, thresholdJoules: 200, minRadius: 0.03 },\n explosive: { specificEnergy: 1e8, aspect: 0.03, minRadius: 0.12 },\n },\n fire: { maxScorch: 0.5, scorchPerSecond: 0.08 },\n },\n {\n id: 'wood_hard',\n rolling: 0.01,\n rollingDamping: 0.12,\n debris: 'splinters',\n color: [0.3, 0.16, 0.07],\n pattern: 'planks',\n hits: {\n ballistic: { specificEnergy: 2.5e7, aspect: 0.35, minRadius: 0.012 },\n blunt: { specificEnergy: 8e7, aspect: 0.1, thresholdJoules: 120 },\n slash: { specificEnergy: 1.5e7, aspect: 0.4, thresholdJoules: 15 },\n explosive: { specificEnergy: 2e8, aspect: 0.1, minRadius: 0.1 },\n },\n fire: { maxScorch: 1, scorchPerSecond: 0.2, burnsAway: 0.0012, flammable: true },\n },\n {\n id: 'stone',\n rolling: 0.015,\n rollingDamping: 0.3,\n debris: 'chips',\n color: [0.23, 0.22, 0.2],\n pattern: 'stone',\n crack: { reach: 0.5, width: 0.004, thresholdJoules: 1000 },\n hits: {\n ballistic: { specificEnergy: 2.5e8, aspect: 0.12, minRadius: 0.015 },\n blunt: { specificEnergy: 5e8, aspect: 0.08, thresholdJoules: 1500 },\n slash: { specificEnergy: 2e9, aspect: 0.2, thresholdJoules: 1500 },\n explosive: { specificEnergy: 4e9, aspect: 0.14 },\n },\n fire: { maxScorch: 0.4, scorchPerSecond: 0.06 },\n },\n {\n id: 'mud',\n rolling: 0.3,\n rollingDamping: 3.0,\n // the shovel lifts it, and the hole fills in behind the blade\n dig: { effort: 1.4, closes: true },\n debris: 'clods',\n rimShare: 0.15,\n reposeDegrees: 18,\n color: [0.11, 0.075, 0.04],\n pattern: 'mud',\n hits: {\n ballistic: { specificEnergy: 1.2e6, aspect: 0.7 },\n blunt: { specificEnergy: 3e5, aspect: 0.3, thresholdJoules: 15 },\n slash: { specificEnergy: 5e4, aspect: 0.5 },\n explosive: { specificEnergy: 1.5e6, aspect: 0.4 },\n },\n fire: { maxScorch: 0.15, scorchPerSecond: 0.03 },\n footing: { sink: 0.07, drag: 0.6, prints: true },\n splash: 'mud',\n splats: true,\n },\n {\n id: 'clay',\n rolling: 0.05,\n rollingDamping: 0.4,\n dig: { effort: 2.2 },\n debris: 'chips',\n color: [0.47, 0.27, 0.14],\n pattern: 'clay',\n hits: {\n ballistic: { specificEnergy: 1e7, aspect: 0.2, minRadius: 0.03 },\n blunt: { specificEnergy: 1.5e7, aspect: 0.15, thresholdJoules: 100 },\n slash: { specificEnergy: 6e7, aspect: 0.3, thresholdJoules: 30 },\n explosive: { specificEnergy: 8e6, aspect: 0.25 },\n },\n fire: { maxScorch: 0.35, scorchPerSecond: 0.05 },\n cracks: 4,\n },\n {\n // laterite, a soil baked hard (piçarra): no shovel goes in; only a heavy blow or a charge sinks or cracks it\n id: 'laterite',\n rolling: 0.05,\n rollingDamping: 0.4,\n debris: 'chips',\n rimShare: 0.2,\n color: [0.36, 0.17, 0.08],\n pattern: 'soil',\n hits: {\n ballistic: { specificEnergy: 5e7, aspect: 0.2, thresholdJoules: 200 },\n blunt: { specificEnergy: 8e7, aspect: 0.1, thresholdJoules: 600 },\n slash: { specificEnergy: 2e8, aspect: 0.1, thresholdJoules: 400 },\n explosive: { specificEnergy: 3e8, aspect: 0.18 },\n },\n },\n {\n id: 'snow',\n rolling: 0.1,\n rollingDamping: 1.2,\n dig: { effort: 0.6 },\n debris: 'dust',\n rimShare: 0.4,\n reposeDegrees: 38,\n color: [0.82, 0.85, 0.88],\n pattern: 'snow',\n hits: {\n ballistic: { specificEnergy: 1.5e6, aspect: 1 },\n blunt: { specificEnergy: 3e5, aspect: 0.3, thresholdJoules: 10 },\n slash: { specificEnergy: 5e4, aspect: 0.6 },\n explosive: { specificEnergy: 1.5e6, aspect: 0.5 },\n },\n fire: { maxScorch: 0, scorchPerSecond: 0, burnsAway: 0.015 },\n footing: { sink: 0.08, drag: 0.7, prints: true },\n },\n {\n id: 'cobble',\n rolling: 0.03,\n rollingDamping: 0.6,\n debris: 'blocks',\n color: [0.2, 0.19, 0.18],\n pattern: 'cobble',\n hits: {\n ballistic: { specificEnergy: 2.5e8, aspect: 0.12, minRadius: 0.015 },\n blunt: { specificEnergy: 5e7, aspect: 0.12, thresholdJoules: 250 },\n slash: { specificEnergy: 2e9, aspect: 0.2, thresholdJoules: 1500 },\n explosive: { specificEnergy: 1.5e7, aspect: 0.2 },\n },\n fire: { maxScorch: 0.4, scorchPerSecond: 0.06 },\n units: { length: 0.3, width: 0.2, looseJoules: 4000 },\n },\n {\n id: 'paver',\n rolling: 0.015,\n rollingDamping: 0.3,\n debris: 'blocks',\n color: [0.36, 0.33, 0.3],\n pattern: 'paver',\n hits: {\n ballistic: { specificEnergy: 1.5e8, aspect: 0.14, minRadius: 0.018 },\n blunt: { specificEnergy: 4e7, aspect: 0.12, thresholdJoules: 150 },\n slash: { specificEnergy: 1e9, aspect: 0.2, thresholdJoules: 800 },\n explosive: { specificEnergy: 1.2e7, aspect: 0.2 },\n },\n fire: { maxScorch: 0.45, scorchPerSecond: 0.08 },\n units: { length: 0.2, width: 0.2, looseJoules: 2500 },\n },\n]\n\n/** How far a blow is held back by the water it crosses before it reaches the bed: a round slows fast in water; a blast is pushed down by it. */\nconst WATER_BLOW_SHARE: Record<TerrainBlow, number> = { ballistic: 0.5, slash: 0.3, blunt: 0.5, explosive: 1 }\n\nexport const TERRAIN_PROFILES: readonly TerrainProfile[] = [\n { id: 'lawn', strata: [{ material: 'turf', thickness: 0.05 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'dirt', strata: [{ material: 'soil', thickness: 1.8 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'sand', strata: [{ material: 'sand', thickness: 2.5 }] },\n { id: 'road', strata: [{ material: 'asphalt', thickness: 0.05 }, { material: 'gravel', thickness: 0.25 }, { material: 'soil', thickness: 1.5 }] },\n // a pavement for walking: concrete over its gravel bed over the soil, as the road's layers (a blast digs down to the pipes under it)\n { id: 'sidewalk', strata: [{ material: 'concrete', thickness: 0.08 }, { material: 'gravel', thickness: 0.22 }, { material: 'soil', thickness: 1.5 }] },\n { id: 'concrete_slab', strata: [{ material: 'concrete', thickness: 0.12, reinforcement: { material: 'steel', cover: 0.03, spacing: 0.15, resistance: 4 } }] },\n { id: 'suspended_slab', drop: 3, strata: [{ material: 'concrete', thickness: 0.12, reinforcement: { material: 'steel', cover: 0.03, spacing: 0.15, resistance: 4 } }] },\n { id: 'tile_floor', strata: [{ material: 'ceramic', thickness: 0.008 }, { material: 'mortar', thickness: 0.03 }, { material: 'concrete', thickness: 0.1, reinforcement: { material: 'steel', cover: 0.03, spacing: 0.15, resistance: 4 } }] },\n { id: 'wood_floor', strata: [{ material: 'wood_hard', thickness: 0.022 }, { material: 'mortar', thickness: 0.03 }, { material: 'concrete', thickness: 0.1, reinforcement: { material: 'steel', cover: 0.03, spacing: 0.15, resistance: 4 } }] },\n { id: 'stone_paving', strata: [{ material: 'stone', thickness: 0.08 }, { material: 'gravel', thickness: 0.2 }, { material: 'soil', thickness: 1.2 }] },\n { id: 'mud', strata: [{ material: 'mud', thickness: 0.5 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'gravel_bed', strata: [{ material: 'gravel', thickness: 0.3 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'dry_clay', strata: [{ material: 'clay', thickness: 0.35 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'snow', strata: [{ material: 'snow', thickness: 0.3 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'cobblestone', strata: [{ material: 'cobble', thickness: 0.12 }, { material: 'sand', thickness: 0.06 }, { material: 'gravel', thickness: 0.2 }, { material: 'soil', thickness: 1.2 }] },\n // rock at the surface (an outcrop, a quarry floor): a blast only spalls it and a shot chips it\n // a yard as it is dug: topsoil, the clay under it, rock deep down\n { id: 'yard', strata: [{ material: 'soil', thickness: 0.35 }, { material: 'clay', thickness: 1.6 }, { material: 'stone', thickness: 1 }] },\n // ground baked hard (laterite over rock): no shovel goes in\n { id: 'hardpan', strata: [{ material: 'laterite', thickness: 0.8 }, { material: 'stone', thickness: 1.5 }] },\n { id: 'bedrock', surfacePattern: 'rock', strata: [{ material: 'stone', thickness: 3 }] },\n { id: 'paver_floor', strata: [{ material: 'paver', thickness: 0.08 }, { material: 'sand', thickness: 0.05 }, { material: 'gravel', thickness: 0.15 }, { material: 'soil', thickness: 1.2 }] },\n // a pond deep enough to stand chest-high in: a charge on its bed goes off under the water\n { id: 'pond', water: { liquid: 'water', depth: 1.4, drag: 0.4, blowShare: WATER_BLOW_SHARE }, strata: [{ material: 'mud', thickness: 0.2 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'shallow_water', water: { liquid: 'water', depth: 0.3, drag: 0.65, blowShare: WATER_BLOW_SHARE }, strata: [{ material: 'mud', thickness: 0.15 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n]\n\n/** About twelve grenades (200 kJ) on the same spot of bare bars. */\nexport const DEFAULT_BAR_YIELD_JOULES = 2_400_000\n\n/** A 10 mm bar of CA-50 steel: bare, a mesh of them at 15 cm holds about 450 kg on a spot. */\nexport const DEFAULT_BAR_DIAMETER = 0.01\nexport const DEFAULT_BAR_YIELD_PA = 500e6\n\n/** The profile of a floor with nothing else said: a plain slab. */\nexport const DEFAULT_PROFILE = 'concrete_slab'\n","/** A small seeded stream: the same seed digs the same crater, so a blow of a few bytes draws the same on every client. */\nexport function createRandom(seed: number): () => number {\n let state = seed | 0\n return () => {\n state = (state + 0x6d2b79f5) | 0\n let mixed = Math.imul(state ^ (state >>> 15), 1 | state)\n mixed = (mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed)) ^ mixed\n return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296\n }\n}\n","import { createRandom } from './random'\nimport type { TerrainCrack } from './types'\n\n/** Energy the reach and width of a material's cracks are given for (`TerrainCrackResponse`). */\nexport const CRACK_REFERENCE_JOULES = 1e6\n/** A new star this close to an old one, as a share of the old one's reach, lengthens it instead. */\nconst MERGE_SHARE = 0.35\n/** Lines never get thinner than a hairline, nor more than a star holds. */\nconst HAIRLINE = 0.0015\nconst MIN_RAYS = 4\nconst MAX_RAYS = 11\nconst SEGMENTS = 4\nconst BRANCH_CHANCE = 0.45\n\n/** One piece of a crack line on the ground plane, with the width at each end. */\nexport interface CrackSegment {\n readonly x0: number\n readonly z0: number\n readonly x1: number\n readonly z1: number\n readonly w0: number\n readonly w1: number\n}\n\nexport interface CrackStore {\n readonly list: TerrainCrack[]\n readonly version: number\n /** Opens a star at the point, or lengthens and widens the one already there. */\n add(spec: { x: number; z: number; reach: number; width: number; material: string; seed: number }, max: number): TerrainCrack\n clear(): void\n load(cracks: readonly TerrainCrack[]): void\n}\n\nexport function createCrackStore(): CrackStore {\n const list: TerrainCrack[] = []\n let version = 0\n let nextId = 1\n let born = 0\n return {\n list,\n get version() {\n return version\n },\n add(spec, max) {\n version++\n const near = list.find((crack) => Math.hypot(crack.x - spec.x, crack.z - spec.z) < crack.reach * MERGE_SHARE)\n if (near) {\n // a second blow on cracked ground runs the lines further and opens them: concrete fatigues, it does not heal\n near.reach = Math.max(near.reach, spec.reach) + Math.min(near.reach, spec.reach) * 0.25\n near.width = Math.max(near.width, spec.width) * 1.1\n near.rays = Math.min(MAX_RAYS, near.rays + 1)\n return near\n }\n if (list.length >= max) list.shift()\n const rays = MIN_RAYS + Math.floor(createRandom(spec.seed)() * (MAX_RAYS - MIN_RAYS - 2))\n const crack: TerrainCrack = { id: nextId++, x: spec.x, z: spec.z, reach: spec.reach, width: Math.max(HAIRLINE, spec.width), rays, seed: spec.seed, material: spec.material, born: born++ }\n list.push(crack)\n return crack\n },\n clear() {\n list.length = 0\n version++\n },\n load(cracks) {\n list.length = 0\n for (const crack of cracks) {\n list.push({ ...crack })\n nextId = Math.max(nextId, crack.id + 1)\n born = Math.max(born, crack.born + 1)\n }\n version++\n },\n }\n}\n\n/**\n * The lines of a star, from its seed: rays that wander a little as they run out and thin towards their tips, with a branch now and then. The same crack always draws the same\n * lines, so only the crack travels in a snapshot or over the network.\n */\nexport function crackLines(crack: TerrainCrack): CrackSegment[] {\n const random = createRandom(crack.seed)\n const segments: CrackSegment[] = []\n const widthAt = (distance: number): number => Math.max(HAIRLINE, crack.width * (1 - distance / crack.reach))\n for (let ray = 0; ray < crack.rays; ray++) {\n let angle = (ray / crack.rays) * Math.PI * 2 + (random() - 0.5) * 0.6\n const length = crack.reach * (0.45 + 0.55 * random())\n let x = crack.x\n let z = crack.z\n let run = 0\n for (let segment = 0; segment < SEGMENTS; segment++) {\n const step = (length / SEGMENTS) * (0.75 + 0.5 * random())\n angle += (random() - 0.5) * 0.5\n const nx = x + Math.cos(angle) * step\n const nz = z + Math.sin(angle) * step\n segments.push({ x0: x, z0: z, x1: nx, z1: nz, w0: widthAt(run), w1: widthAt(run + step) })\n if (segment > 0 && random() < BRANCH_CHANCE) {\n const side = angle + (random() < 0.5 ? -1 : 1) * (0.45 + random() * 0.5)\n const branch = step * (0.5 + 0.6 * random())\n const w = widthAt(run + step) * 0.6\n segments.push({ x0: nx, z0: nz, x1: nx + Math.cos(side) * branch, z1: nz + Math.sin(side) * branch, w0: Math.max(HAIRLINE, w), w1: HAIRLINE })\n }\n run += step\n x = nx\n z = nz\n }\n }\n return segments\n}\n","import type { TerrainDebris, TerrainDebrisKind } from './types'\n\nconst REST_SPEED = 0.6\nconst RESTITUTION = 0.25\nconst FRICTION = 0.55\nconst MAX_BOUNCES = 2\nconst REST_GAP = 0.01\n\nexport interface DebrisWorld {\n heightAt(x: number, z: number): number\n gravity: number\n /** Soft pieces join the ground where they stop; a false keeps the piece as loose rubble. */\n settle(piece: TerrainDebris): boolean\n}\n\n/** Pieces thrown by blows: they fly, hit the deformed ground, and come to rest. Past `max` the oldest at rest goes first. */\nexport interface DebrisStore {\n readonly list: TerrainDebris[]\n throwPiece(spec: { material: string; kind: TerrainDebrisKind; radius: number; position: [number, number, number]; velocity: [number, number, number]; spin: [number, number, number] }): void\n update(dt: number, world: DebrisWorld): void\n clear(): void\n}\n\nexport function createDebrisStore(max: () => number): DebrisStore {\n const list: TerrainDebris[] = []\n let serial = 0\n\n function makeRoom(): void {\n if (list.length < max()) return\n let at = 0\n let oldest = Infinity\n let oldestResting = -1\n let restingBorn = Infinity\n list.forEach((piece, index) => {\n if (piece.born < oldest) {\n oldest = piece.born\n at = index\n }\n if (piece.atRest && piece.born < restingBorn) {\n restingBorn = piece.born\n oldestResting = index\n }\n })\n list.splice(oldestResting >= 0 ? oldestResting : at, 1)\n }\n\n return {\n list,\n throwPiece(spec) {\n makeRoom()\n list.push({ ...spec, id: ++serial, born: serial, atRest: false, bounces: 0 })\n },\n update(dt, world) {\n for (let i = list.length - 1; i >= 0; i--) {\n const piece = list[i]!\n if (piece.atRest) {\n // what it lay on was dug away or heaped over: it falls again, or rides up\n const under = world.heightAt(piece.position[0], piece.position[2]) + piece.radius * 0.6\n if (piece.position[1] > under + REST_GAP) piece.atRest = false\n else if (piece.position[1] < under - REST_GAP) piece.position[1] = under\n if (piece.atRest) continue\n }\n const { position, velocity } = piece\n velocity[1] -= world.gravity * dt\n position[0] += velocity[0] * dt\n position[1] += velocity[1] * dt\n position[2] += velocity[2] * dt\n const ground = world.heightAt(position[0], position[2]) + piece.radius * 0.6\n if (position[1] > ground) continue\n position[1] = ground\n const speed = Math.hypot(velocity[0], velocity[1], velocity[2])\n if (speed < REST_SPEED || piece.bounces >= MAX_BOUNCES) {\n piece.atRest = true\n if (world.settle(piece)) list.splice(i, 1)\n continue\n }\n piece.bounces++\n velocity[1] = Math.abs(velocity[1]) * RESTITUTION\n velocity[0] *= FRICTION\n velocity[2] *= FRICTION\n }\n },\n clear() {\n list.length = 0\n serial = 0\n },\n }\n}\n","import type { GroundLoss } from '@adatechnology/game-contracts'\nimport type { TerrainVoid } from './types'\n\n/** A loss shallower than this (m below the untouched surface) is a scuff, not a void anything bears over. */\nexport const GROUND_LOSS_MIN_DEPTH = 0.02\n/** Sand that slid tells the host only where it lowered the ground by at least this much (m). */\nexport const SLIDE_LOSS_MIN_LOWERING = 0.05\n/** Under this depth (m) a vertex still counts as ground in `voidUnder`. */\nexport const VOID_MIN_DEPTH = 0.02\n\nexport interface HeightGrid {\n readonly x0: number\n readonly z0: number\n readonly cellSize: number\n readonly stride: number\n readonly columns: number\n readonly rows: number\n readonly dug: Float32Array\n}\n\n/** What one event lowered, by vertex (metres of the column, not of the loose heap on it). Lowerings of the same vertex add up; a fill counts against them. */\nexport type LossTally = Map<number, number>\n\nexport function tallyLowered(tally: LossTally, index: number, amount: number): void {\n if (amount !== 0) tally.set(index, (tally.get(index) ?? 0) + amount)\n}\n\n/**\n * The disc the tally lowered, or null when it is shallower than `GROUND_LOSS_MIN_DEPTH`. Vertices lowered less than `minLowering` are left out. `depth` is\n * the deepest the ground is now under its untouched surface there. A `bowl` (a crater, sand that slid) is told as the paraboloid that is half as deep\n * where the ground is now half as deep, so a wide shallow scrape around a deep hole does not pass for a wide deep one; a `flat` hole (a slab that opened)\n * keeps its edge.\n */\nexport function lossOf(grid: HeightGrid, tally: LossTally, spec: { source: string; minLowering: number; shape: 'bowl' | 'flat' }): GroundLoss | null {\n let weight = 0\n let centerX = 0\n let centerZ = 0\n let depth = 0\n let deepest = 0\n const kept: number[] = []\n for (const [index, amount] of tally) {\n if (amount < spec.minLowering || amount <= 0) continue\n const column = index % grid.stride\n const row = (index - column) / grid.stride\n weight += amount\n centerX += (grid.x0 + column * grid.cellSize) * amount\n centerZ += (grid.z0 + row * grid.cellSize) * amount\n depth = Math.max(depth, grid.dug[index]!)\n deepest = Math.max(deepest, amount)\n kept.push(index)\n }\n if (weight <= 0 || depth < GROUND_LOSS_MIN_DEPTH || deepest < GROUND_LOSS_MIN_DEPTH) return null\n centerX /= weight\n centerZ /= weight\n let radius = 0\n for (const index of kept) {\n if (spec.shape === 'bowl' && grid.dug[index]! < depth / 2) continue\n const column = index % grid.stride\n const row = (index - column) / grid.stride\n radius = Math.max(radius, Math.hypot(grid.x0 + column * grid.cellSize - centerX, grid.z0 + row * grid.cellSize - centerZ))\n }\n const reach = spec.shape === 'bowl' ? Math.SQRT2 * (radius + grid.cellSize / 2) : radius + grid.cellSize / 2\n return { x: centerX, z: centerZ, radius: reach, depth, removed: weight * grid.cellSize * grid.cellSize, source: spec.source }\n}\n\n/** How much of the disc (x, z, radius) has no ground under where it was: the vertices inside it, or the nearest one when the disc is smaller than a cell. */\nexport function voidUnder(grid: HeightGrid, spec: { x: number; z: number; radius: number }): TerrainVoid {\n const { x, z, radius } = spec\n const clamp = (value: number, top: number): number => Math.max(0, Math.min(top, value))\n const column0 = clamp(Math.ceil((x - radius - grid.x0) / grid.cellSize), grid.columns)\n const column1 = clamp(Math.floor((x + radius - grid.x0) / grid.cellSize), grid.columns)\n const row0 = clamp(Math.ceil((z - radius - grid.z0) / grid.cellSize), grid.rows)\n const row1 = clamp(Math.floor((z + radius - grid.z0) / grid.cellSize), grid.rows)\n let count = 0\n let sum = 0\n let depth = 0\n let open = 0\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n if (Math.hypot(grid.x0 + column * grid.cellSize - x, grid.z0 + row * grid.cellSize - z) > radius) continue\n const here = grid.dug[row * grid.stride + column]!\n count++\n sum += here\n depth = Math.max(depth, here)\n if (here >= VOID_MIN_DEPTH) open++\n }\n }\n if (count === 0) {\n const here = grid.dug[clamp(Math.round((z - grid.z0) / grid.cellSize), grid.rows) * grid.stride + clamp(Math.round((x - grid.x0) / grid.cellSize), grid.columns)]!\n return { depth: here, mean: here, fraction: here >= VOID_MIN_DEPTH ? 1 : 0 }\n }\n return { depth, mean: sum / count, fraction: open / count }\n}\n","/**\n * The ground's blend as pure functions of numbers, shared by `Terrain.heightAt`, `Terrain.heightGrid` and `heightPatchGrid`: the same code reads the terrain on the main\n * thread and a copy of its vertices anywhere else (a worker has no terrain), so the heights agree to the bit.\n */\n\n/** Where `v` falls along an axis of `count` cells of `cellSize` from `origin`, in cells, held inside the last cell: its whole part is the cell, the rest the blend across it. */\nexport const cellCoordinate = (v: number, origin: number, count: number, cellSize: number): number => Math.max(0, Math.min(count - 1e-6, (v - origin) / cellSize))\n\n/** The blend of two heights, `t` of the way from `near` to `far` (the one step every blend of the ground is made of). */\nexport const blendHeights = (near: number, far: number, t: number): number => near * (1 - t) + far * t\n\n/**\n * The terrain's vertex heights (`base - dug + loose`, as `heightAt` reads them) over a block of its cells, with what places them in the terrain: plain numbers, so a worker\n * can read the ground from them (`heightPatchGrid`) and answer what `heightGrid` does there, to the bit. Made by `Terrain.heightPatch`.\n */\nexport interface HeightPatch {\n readonly cellSize: number\n /** The terrain's first vertex (its bounds' min x and z) and its cells along x and z: where a point's cell is found, with its clamps. */\n readonly originX: number\n readonly originZ: number\n readonly columns: number\n readonly rows: number\n /** The patch's first vertex (column and row of the terrain) and how many vertices it has along x and along z. */\n readonly column0: number\n readonly row0: number\n readonly width: number\n readonly depth: number\n /** The heights, `width` per row, rows from `row0`: `heights[(row - row0) * width + column - column0]` (the array may be longer). */\n readonly heights: Float64Array\n}\n\n// the cell and the blend of each column and row a patch read finds, kept between reads (one at a time) so a read costs no new arrays\nlet patchColumns = new Int32Array(0)\nlet patchBlendX = new Float64Array(0)\nlet patchNear = new Float64Array(0)\nlet patchFar = new Float64Array(0)\n\n/**\n * The ground over a lattice from a patch: the height at (`xs[i]`, `zs[j]`) into `out[j * xs.length + i]`, to the bit what the terrain's `heightGrid` answers there (the same\n * cell, clamps and blends, on the same vertex heights). Every point must lie inside the terrain and over the patch's cells (`Terrain.heightPatch` of a rectangle holding\n * them): one that does not throws. Not reentrant (module scratch).\n */\nexport function heightPatchGrid(patch: HeightPatch, xs: ArrayLike<number>, zs: ArrayLike<number>, out: Float64Array): void {\n const width = xs.length\n const depth = zs.length\n if (out.length < width * depth) throw new RangeError(`heightPatchGrid: out holds ${out.length} heights, the grid has ${width * depth}`)\n const { cellSize, originX, originZ, columns, rows, column0, row0, heights } = patch\n const stride = patch.width\n if (patchColumns.length < width) {\n patchColumns = new Int32Array(width)\n patchBlendX = new Float64Array(width)\n patchNear = new Float64Array(width)\n patchFar = new Float64Array(width)\n }\n for (let i = 0; i < width; i++) {\n const fx = cellCoordinate(xs[i]!, originX, columns, cellSize)\n const column = (fx | 0) - column0\n if (column < 0 || column + 1 >= stride) throw new RangeError(`heightPatchGrid: x ${xs[i]} is past the patch`)\n patchColumns[i] = column\n patchBlendX[i] = fx - (fx | 0)\n }\n let blended = -1\n for (let j = 0; j < depth; j++) {\n const fz = cellCoordinate(zs[j]!, originZ, rows, cellSize)\n const row = (fz | 0) - row0\n if (row < 0 || row + 1 >= patch.depth) throw new RangeError(`heightPatchGrid: z ${zs[j]} is past the patch`)\n const tz = fz - (fz | 0)\n // the two x blends of a column depend on its row of cells only, as in `heightGrid`\n if (row !== blended) {\n blended = row\n for (let i = 0; i < width; i++) {\n const index = row * stride + patchColumns[i]!\n const tx = patchBlendX[i]!\n patchNear[i] = blendHeights(heights[index]!, heights[index + 1]!, tx)\n patchFar[i] = blendHeights(heights[index + stride]!, heights[index + stride + 1]!, tx)\n }\n }\n for (let i = 0; i < width; i++) out[j * width + i] = blendHeights(patchNear[i]!, patchFar[i]!, tz)\n }\n}\n\n/** Whether two patches hold the same vertices at the same heights (the ground they read is the same, to the bit, wherever both reach). */\nexport const samePatch = (a: HeightPatch, b: HeightPatch): boolean => {\n if (a.cellSize !== b.cellSize || a.originX !== b.originX || a.originZ !== b.originZ || a.columns !== b.columns || a.rows !== b.rows) return false\n if (a.column0 !== b.column0 || a.row0 !== b.row0 || a.width !== b.width || a.depth !== b.depth) return false\n const count = a.width * a.depth\n for (let k = 0; k < count; k++) if (a.heights[k] !== b.heights[k]) return false\n return true\n}\n","import type { TerrainBudget, TerrainMark } from './types'\n\n/** Two marks at this fraction of their radii or closer are one hole. */\nconst SAME_HOLE = 0.75\n\n/** Fine marks under a budget per area and a global one: past the budget the closest two of the area become one, and past the global one the oldest goes. */\nexport interface MarkStore {\n readonly list: TerrainMark[]\n add(spec: Omit<TerrainMark, 'id' | 'count' | 'born'>): TerrainMark\n near(x: number, z: number, radius: number): TerrainMark | undefined\n depthAt(x: number, z: number): number\n remove(mark: TerrainMark): void\n removeInside(x: number, z: number, radius: number): void\n clear(): void\n load(marks: readonly TerrainMark[]): void\n readonly version: number\n}\n\nexport function createMarkStore(budget: TerrainBudget): MarkStore {\n const list: TerrainMark[] = []\n const areas = new Map<number, TerrainMark[]>()\n let serial = 0\n let version = 0\n const areaKey = (x: number, z: number): number => Math.floor(x / budget.markAreaSize) * 100003 + Math.floor(z / budget.markAreaSize)\n\n function detach(mark: TerrainMark): void {\n const key = areaKey(mark.x, mark.z)\n const area = areas.get(key)\n if (area) {\n const at = area.indexOf(mark)\n if (at >= 0) area.splice(at, 1)\n if (area.length === 0) areas.delete(key)\n }\n const at = list.indexOf(mark)\n if (at >= 0) list.splice(at, 1)\n version++\n }\n\n function attach(mark: TerrainMark): void {\n const key = areaKey(mark.x, mark.z)\n const area = areas.get(key)\n if (area) area.push(mark)\n else areas.set(key, [mark])\n list.push(mark)\n version++\n }\n\n function mergeClosestPair(area: TerrainMark[]): void {\n let bestA = area[0]!\n let bestB = area[1]!\n let best = Infinity\n for (let i = 0; i < area.length; i++) {\n for (let j = i + 1; j < area.length; j++) {\n const distance = Math.hypot(area[i]!.x - area[j]!.x, area[i]!.z - area[j]!.z)\n if (distance < best) {\n best = distance\n bestA = area[i]!\n bestB = area[j]!\n }\n }\n }\n const weight = bestA.radius ** 2 + bestB.radius ** 2\n const shareB = weight > 0 ? bestB.radius ** 2 / weight : 0.5\n detach(bestB)\n bestA.x += (bestB.x - bestA.x) * shareB\n bestA.z += (bestB.z - bestA.z) * shareB\n bestA.radius = Math.sqrt(weight)\n bestA.depth = Math.max(bestA.depth, bestB.depth)\n bestA.count += bestB.count\n version++\n }\n\n return {\n list,\n add(spec) {\n const mark: TerrainMark = { ...spec, id: ++serial, count: 1, born: serial }\n attach(mark)\n const area = areas.get(areaKey(mark.x, mark.z))!\n if (area.length > budget.maxMarksPerArea) mergeClosestPair(area)\n if (list.length > budget.maxMarks) detach(list.reduce((oldest, candidate) => (candidate.born < oldest.born ? candidate : oldest)))\n return mark\n },\n near(x, z, radius) {\n let found: TerrainMark | undefined\n let best = Infinity\n const reach = Math.ceil((radius + 0.5) / budget.markAreaSize)\n const baseX = Math.floor(x / budget.markAreaSize)\n const baseZ = Math.floor(z / budget.markAreaSize)\n for (let dx = -reach; dx <= reach; dx++) {\n for (let dz = -reach; dz <= reach; dz++) {\n for (const mark of areas.get((baseX + dx) * 100003 + baseZ + dz) ?? []) {\n const distance = Math.hypot(mark.x - x, mark.z - z)\n if (distance < best && distance < Math.max(mark.radius, radius) * SAME_HOLE) {\n best = distance\n found = mark\n }\n }\n }\n }\n return found\n },\n depthAt(x, z) {\n let depth = 0\n for (const mark of areas.get(areaKey(x, z)) ?? []) {\n const distance = Math.hypot(mark.x - x, mark.z - z)\n if (distance < mark.radius) depth = Math.max(depth, mark.depth * (1 - (distance / mark.radius) ** 2))\n }\n return depth\n },\n remove: detach,\n removeInside(x, z, radius) {\n for (const mark of [...list]) if (Math.hypot(mark.x - x, mark.z - z) + mark.radius * 0.5 < radius) detach(mark)\n },\n clear() {\n list.length = 0\n areas.clear()\n // the numbering starts again with the ground (a loaded snapshot takes it on from its own marks); `version` only grows, the renderers follow it\n serial = 0\n version++\n },\n load(marks) {\n this.clear()\n for (const mark of marks) {\n attach({ ...mark })\n serial = Math.max(serial, mark.id)\n }\n },\n get version() {\n return version\n },\n }\n}\n","import type { Hit } from '@adatechnology/game-contracts'\nimport { DEFAULT_BAR_DIAMETER, DEFAULT_BAR_YIELD_JOULES, DEFAULT_BAR_YIELD_PA, DEFAULT_PROFILE, TERRAIN_MATERIALS, TERRAIN_PROFILES } from './catalog'\nimport { createCrackStore, CRACK_REFERENCE_JOULES } from './cracks'\nimport { createDebrisStore } from './debris'\nimport { lossOf, SLIDE_LOSS_MIN_LOWERING, tallyLowered, voidUnder } from './ground-loss'\nimport type { HeightGrid, LossTally } from './ground-loss'\nimport { blendHeights, cellCoordinate as cellCoordinateOf } from './height-patch'\nimport type { HeightPatch } from './height-patch'\nimport { createMarkStore } from './marks'\nimport { createRandom } from './random'\nimport type { GroundExcavation, GroundLayout, Terrain, TerrainDig, TerrainDigResult, TerrainFill, TerrainBlow, TerrainBlowResult, TerrainBudget, TerrainChunk, TerrainColumn, TerrainDebris, TerrainDecal, TerrainLoad, TerrainMark, TerrainMaterial, TerrainOptions, TerrainProfile, TerrainRegion, TerrainSnapshot, TerrainStratum, TerrainStrike } from './types'\n\nexport const DEFAULT_TERRAIN_BUDGET: TerrainBudget = {\n markAreaSize: 2,\n maxMarksPerArea: 24,\n maxMarks: 800,\n maxDirtyChunksPerFrame: 6,\n maxDebris: 400,\n maxDebrisPerBlow: 36,\n maxSlideCellsPerFrame: 2500,\n maxBurningCells: 300,\n maxCracks: 120,\n maxDecals: 300,\n}\n\nconst GRAVITY = 9.81\n/** A bowl narrower than this many cells cannot be drawn by the height field: it stays a fine mark. */\nconst FINE_CELLS = 1.5\n/** A hole deeper than this many cells is no longer a mark on the surface. */\nconst FINE_DEPTH_CELLS = 0.4\nconst RIGID_WIDENING = 2.5\n/** Calibre (mm) a round's crater has the material's own shape at: a thinner round goes deeper and opens less for the same energy, a thicker one opens more. */\nconst REFERENCE_CALIBER = 7.62\n/** How far a calibre bends the crater's depth over its radius: (reference / calibre) to this power, kept within `CALIBER_ASPECT_RANGE`. */\nconst CALIBER_ASPECT_POWER = 0.5\nconst CALIBER_ASPECT_RANGE = [0.6, 1.6] as const\n/** A round's crater is at least this many calibres across. */\nconst CALIBERS_ACROSS = 2.5\n\n/** Depth-over-radius factor of a round's crater: 1 without a calibre or at the reference one. */\nconst caliberAspect = (caliber: number | undefined): number =>\n caliber && caliber > 0 ? Math.min(CALIBER_ASPECT_RANGE[1], Math.max(CALIBER_ASPECT_RANGE[0], (REFERENCE_CALIBER / caliber) ** CALIBER_ASPECT_POWER)) : 1\n/** The smallest crater radius (m) a round of `caliber` mm leaves. */\nconst caliberRadius = (caliber: number | undefined): number => (caliber && caliber > 0 ? (caliber / 1000) * CALIBERS_ACROSS / 2 : 0)\n/** Bars alone do not drop a slab that still has this share of its concrete to lose. */\nconst COLLAPSE_DEPTH_SHARE = 0.75\nconst COLLAPSE_SPREAD_BEND = 0.5\n/** Metres around a weight over which bare bars share it with the weights beside it. */\nconst BARS_SHARE_REACH = 0.6\nconst RIM_REACH = 1.45\n/** Under this temperature (°C) a flame does nothing to the ground. */\nconst FLAME_MINIMUM = 200\n/** How far over the ground a flame still touches it, beyond its radius. */\nconst FLAME_REACH = 0.6\n/** How far a blast above the ground still reaches it, as a share of its radius. */\nconst BLAST_HEIGHT_REACH = 0.35\n/**\n * Metres of ground the fireball of a 1 MJ blast blackens, growing with the cube root of the energy (a frag grenade, 200 kJ: about 0.7 m), and the share of\n * the material's darkest char (`TerrainFireResponse.maxScorch`) it leaves at the centre, fading to the edge: concrete only soots, turf chars.\n */\nconst BLAST_SOOT_REACH = 1.2\nconst BLAST_SOOT = 0.9\n/** Share of a blow's energy that throws the pieces. */\nconst THROW_SHARE = 0.02\n/** Side of a square of ground that burns as one, in metres. */\nconst FIRE_CELL = 0.5\nconst FIRE_SECONDS = 7\nconst FIRE_SPREAD_PER_SECOND = 0.35\nconst SLIDE_SHARE = 0.4\nconst SLIDE_EPSILON = 0.002\n/** Radius of a thrown piece per kind: a clod is a fist of soil, a chip is a thumb of concrete. */\nconst PIECE_RADIUS: Record<TerrainMaterial['debris'], number> = { clods: 0.045, chips: 0.022, shards: 0.028, splinters: 0.02, dust: 0.012, blocks: 0.08 }\n/** Metres per second the fastest piece of a blow leaves at: a blast throws, a dropped weight only kicks. */\nconst MAX_PIECE_SPEED: Record<TerrainBlow, number> = { explosive: 14, ballistic: 5, blunt: 2.5, slash: 1.5 }\n\n/** Cells the bed takes to go from the bank down to the full depth, so that a body wades in instead of falling. */\nconst BANK_CELLS = 6\nconst CRACK_MIN_RADIUS = 0.18\nconst RIPPLE_SECONDS = 1.6\n/** Water thinner than this at the bank neither splashes nor floats anything. */\nconst WATER_MINIMUM = 0.02\n\nconst clampIndex = (value: number, max: number): number => Math.max(0, Math.min(max, value))\nconst sparse = (array: Float32Array): [number, number][] => {\n const entries: [number, number][] = []\n array.forEach((value, index) => {\n if (value !== 0) entries.push([index, value])\n })\n return entries\n}\nconst fillSparse = (array: Float32Array, entries: readonly (readonly [number, number])[]): void => {\n array.fill(0)\n for (const [index, value] of entries) array[index] = value\n}\n\n/** Layer a depth falls in; past the end, the last one. */\nfunction stratumAtDepth(profile: TerrainProfile, depth: number): { index: number; stratum: TerrainStratum; top: number } {\n let top = 0\n for (let index = 0; index < profile.strata.length; index++) {\n const stratum = profile.strata[index]!\n if (depth < top + stratum.thickness - 1e-6) return { index, stratum, top }\n top += stratum.thickness\n }\n const index = profile.strata.length - 1\n const stratum = profile.strata[index]!\n return { index, stratum, top: top - stratum.thickness }\n}\n\n/** Same stratum as `stratumAtDepth`, without allocating: per-read paths (state(), fire per vertex) must not create garbage. */\nfunction stratumMaterialAtDepth(profile: TerrainProfile, depth: number): string {\n const strata = profile.strata\n let top = 0\n for (let index = 0; index < strata.length; index++) {\n const stratum = strata[index]!\n if (depth < top + stratum.thickness - 1e-6) return stratum.material\n top += stratum.thickness\n }\n return strata[strata.length - 1]!.material\n}\nconst totalThickness = (profile: TerrainProfile): number => profile.strata.reduce((sum, stratum) => sum + stratum.thickness, 0)\n\nexport function createTerrain(options: TerrainOptions): Terrain {\n const [x0, z0, x1, z1] = options.bounds\n const cellSize = options.cellSize ?? 0.1\n const chunkCells = options.chunkCells ?? 32\n const columns = Math.max(1, Math.ceil((x1 - x0) / cellSize))\n const rows = Math.max(1, Math.ceil((z1 - z0) / cellSize))\n const stride = columns + 1\n const vertexCount = stride * (rows + 1)\n const chunksX = Math.ceil(columns / chunkCells)\n const chunksZ = Math.ceil(rows / chunkCells)\n const budget: TerrainBudget = { ...DEFAULT_TERRAIN_BUDGET, ...options.budget }\n const gravity = options.gravity ?? GRAVITY\n const materials = new Map<string, TerrainMaterial>([...TERRAIN_MATERIALS, ...(options.materials ?? [])].map((material) => [material.id, material]))\n const profileMap = new Map<string, TerrainProfile>([...TERRAIN_PROFILES, ...(options.profiles ?? [])].map((profile) => [profile.id, profile]))\n const profileList = [...profileMap.values()]\n for (const profile of profileList) {\n for (const stratum of profile.strata) if (!materials.has(stratum.material)) throw new Error(`game-terrain: profile \"${profile.id}\" uses material \"${stratum.material}\", which has no ground behaviour`)\n }\n const indexOfProfile = new Map(profileList.map((profile, index) => [profile.id, index]))\n const maxDepthOf = profileList.map(totalThickness)\n\n // `surface` is the ground as the map has it; `base` is that less the water standing on it, so that everything that stands on the ground stands on the bed\n const surface = new Float32Array(vertexCount)\n if (options.baseHeight) {\n for (let row = 0; row <= rows; row++) for (let column = 0; column <= columns; column++) surface[row * stride + column] = options.baseHeight(x0 + column * cellSize, z0 + row * cellSize)\n }\n const base = Float32Array.from(surface)\n const hasWater = profileList.some((profile) => profile.water)\n const dug = new Float32Array(vertexCount)\n const loose = new Float32Array(vertexCount)\n const scorch = new Float32Array(vertexCount)\n const barBend = new Float32Array(vertexCount)\n const profileIndex = new Uint8Array(vertexCount)\n const touched = new Uint8Array(chunksX * chunksZ)\n const mixed = new Uint8Array(chunksX * chunksZ)\n const dirty = new Set<number>()\n const marks = createMarkStore(budget)\n const cracks = createCrackStore()\n const decalList: TerrainDecal[] = []\n let decalSerial = 0\n let decalsVersion = 0\n const unitDamage = new Map<string, number>()\n const debrisStore = createDebrisStore(() => budget.maxDebris)\n const sliding = new Set<number>()\n const burning = new Map<number, number>()\n const seed = options.seed ?? 1\n let random = createRandom(seed)\n let currentLayout: GroundLayout = options.layout ?? { surface: DEFAULT_PROFILE }\n\n const deformListeners = new Set<(region: TerrainRegion) => void>()\n const emitDeform = (x: number, z: number, radius: number): void => {\n for (const listener of deformListeners) listener({ x, z, radius })\n }\n const grid: HeightGrid = { x0, z0, cellSize, stride, columns, rows, dug }\n /** Sand that is still sliding: what it lowered so far, told once it comes to rest. */\n const slideTally: LossTally = new Map()\n const emitGroundLoss = (tally: LossTally, source: string, minLowering: number): void => {\n if (!options.onGroundLoss) return\n const loss = lossOf(grid, tally, { source, minLowering, shape: source === 'slab' ? 'flat' : 'bowl' })\n if (loss) options.onGroundLoss(loss)\n }\n /** Lowers a vertex to `depth` under the untouched surface, counting it in `tally`. */\n const dropVertex = (index: number, depth: number, tally: LossTally): void => {\n tallyLowered(tally, index, depth - dug[index]!)\n dug[index] = depth\n }\n\n const chunkOfVertex = (column: number, row: number): number => Math.min(chunksZ - 1, Math.floor(row / chunkCells)) * chunksX + Math.min(chunksX - 1, Math.floor(column / chunkCells))\n /** A vertex on a chunk's edge belongs to its neighbours as well. */\n function touchVertex(column: number, row: number): void {\n const chunk = chunkOfVertex(column, row)\n touched[chunk] = 1\n dirty.add(chunk)\n if (column % chunkCells === 0 && column > 0) markChunk(chunk - 1)\n if (row % chunkCells === 0 && row > 0) markChunk(chunk - chunksX)\n if (column % chunkCells === 0 && row % chunkCells === 0 && column > 0 && row > 0) markChunk(chunk - chunksX - 1)\n }\n function markChunk(chunk: number): void {\n touched[chunk] = 1\n dirty.add(chunk)\n }\n\n const profileId = (id: string): number => indexOfProfile.get(id) ?? indexOfProfile.get(DEFAULT_PROFILE) ?? 0\n\n function applyLayout(layout: GroundLayout): void {\n currentLayout = layout\n profileIndex.fill(profileId(layout.surface))\n for (const zone of layout.zones ?? []) {\n const index = profileId(zone.surface)\n const [zx0, zz0, zx1, zz1] = zone.rect\n const column0 = clampIndex(Math.round((zx0 - x0) / cellSize), columns)\n const column1 = clampIndex(Math.round((zx1 - x0) / cellSize), columns)\n const row0 = clampIndex(Math.round((zz0 - z0) / cellSize), rows)\n const row1 = clampIndex(Math.round((zz1 - z0) / cellSize), rows)\n for (let row = row0; row <= row1; row++) profileIndex.fill(index, row * stride + column0, row * stride + column1 + 1)\n }\n if (hasWater) layBeds()\n for (let chunkZ = 0; chunkZ < chunksZ; chunkZ++) {\n for (let chunkX = 0; chunkX < chunksX; chunkX++) {\n const chunk = chunkZ * chunksX + chunkX\n const first = profileIndex[(chunkZ * chunkCells) * stride + chunkX * chunkCells]\n const firstDrop = surface[(chunkZ * chunkCells) * stride + chunkX * chunkCells]! - base[(chunkZ * chunkCells) * stride + chunkX * chunkCells]!\n let isMixed = 0\n const lastRow = Math.min(rows, (chunkZ + 1) * chunkCells)\n const lastColumn = Math.min(columns, (chunkX + 1) * chunkCells)\n for (let row = chunkZ * chunkCells; row <= lastRow && !isMixed; row++) {\n for (let column = chunkX * chunkCells; column <= lastColumn; column++) {\n if (profileIndex[row * stride + column] !== first || surface[row * stride + column]! - base[row * stride + column]! !== firstDrop) {\n isMixed = 1\n break\n }\n }\n }\n mixed[chunk] = isMixed\n dirty.add(chunk)\n }\n }\n for (const excavation of layout.excavations ?? []) excavate(excavation)\n }\n\n /**\n * Digs a construction's trench or pit: every vertex over the rectangle (the cell it starts in to the one it ends in, so the full depth spans the whole\n * rectangle and the wall slopes in the cell outside it) down to its depth, never less deep than it already was. A planned dig is no ground loss.\n */\n function excavate(excavation: GroundExcavation): void {\n const [ex0, ez0, ex1, ez1] = excavation.rect\n const column0 = clampIndex(Math.floor((ex0 - x0) / cellSize + 1e-6), columns)\n const column1 = clampIndex(Math.ceil((ex1 - x0) / cellSize - 1e-6), columns)\n const row0 = clampIndex(Math.floor((ez0 - z0) / cellSize + 1e-6), rows)\n const row1 = clampIndex(Math.ceil((ez1 - z0) / cellSize - 1e-6), rows)\n const alongX = (excavation.along ?? (ex1 - ex0 >= ez1 - ez0 ? 'x' : 'z')) === 'x'\n const from = alongX ? ex0 : ez0, length = Math.max(1e-6, alongX ? ex1 - ex0 : ez1 - ez0)\n const far = excavation.toDepth ?? excavation.depth\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n const at = alongX ? x0 + column * cellSize : z0 + row * cellSize\n const t = Math.max(0, Math.min(1, (at - from) / length))\n const depth = excavation.depth + (far - excavation.depth) * t\n if (depth <= dug[index]!) continue\n dug[index] = depth\n touchVertex(column, row)\n }\n }\n }\n\n /** Lowers the ground under the water, in a bank from the edge of each pool. */\n function layBeds(): void {\n const steps = new Uint8Array(vertexCount)\n for (let index = 0; index < vertexCount; index++) steps[index] = profileList[profileIndex[index]!]!.water ? BANK_CELLS : 0\n for (let pass = 0; pass < BANK_CELLS; pass++) {\n for (let row = 0; row <= rows; row++) {\n for (let column = 0; column <= columns; column++) {\n const index = row * stride + column\n if (steps[index] === 0) continue\n const lowest = Math.min(column > 0 ? steps[index - 1]! : BANK_CELLS, column < columns ? steps[index + 1]! : BANK_CELLS, row > 0 ? steps[index - stride]! : BANK_CELLS, row < rows ? steps[index + stride]! : BANK_CELLS)\n steps[index] = Math.min(steps[index]!, lowest + 1)\n }\n }\n }\n for (let index = 0; index < vertexCount; index++) base[index] = surface[index]! - (profileList[profileIndex[index]!]!.water?.depth ?? 0) * (steps[index]! / BANK_CELLS)\n }\n\n const vertexHeight = (column: number, row: number): number => {\n const index = row * stride + column\n return base[index]! - dug[index]! + loose[index]!\n }\n const contains = (x: number, z: number): boolean => x >= x0 && x <= x1 && z >= z0 && z <= z1\n\n function addDecal(spec: Omit<TerrainDecal, 'id' | 'age'>): void {\n if (decalList.length >= budget.maxDecals) decalList.shift()\n decalList.push({ ...spec, id: ++decalSerial, age: 0 })\n decalsVersion++\n }\n function clearDecalsInside(x: number, z: number, radius: number): void {\n const before = decalList.length\n for (let i = before - 1; i >= 0; i--) {\n const decal = decalList[i]!\n if (decal.kind !== 'ripple' && decal.kind !== 'splat' && decal.kind !== 'crack' && Math.hypot(decal.x - x, decal.z - z) < radius) decalList.splice(i, 1)\n }\n if (decalList.length !== before) decalsVersion++\n }\n\n // `heightAt` and `heightGrid` are twins: both find a point's cell with `cellCoordinate` and blend its corners with `blendCell`, so the grid answers what the point does, to the bit\n /** Where `v` falls along an axis of `count` cells from `origin`, in cells, held inside the last cell: its whole part is the cell, the rest the blend across it. */\n // the blend and the cell are `height-patch`'s, so a patch read anywhere (`heightPatchGrid`) answers what these do\n const cellCoordinate = (v: number, origin: number, count: number): number => cellCoordinateOf(v, origin, count, cellSize)\n const heightOfVertex = (index: number): number => base[index]! - dug[index]! + loose[index]!\n /** The ground in the cell whose first corner is vertex `index`, `tx` and `tz` across it. */\n const blendCell = (index: number, tx: number, tz: number): number =>\n blendHeights(blendHeights(heightOfVertex(index), heightOfVertex(index + 1), tx), blendHeights(heightOfVertex(index + stride), heightOfVertex(index + stride + 1), tx), tz)\n\n function heightAt(x: number, z: number): number {\n // beyond the terrain the ground is untouched: no blow can dig it and a piece thrown out lands on it\n if (!contains(x, z)) return options.baseHeight?.(x, z) ?? 0\n const fx = cellCoordinate(x, x0, columns)\n const fz = cellCoordinate(z, z0, rows)\n const column = fx | 0\n const row = fz | 0\n return blendCell(row * stride + column, fx - column, fz - row)\n }\n\n // the cell and the blend of each column and row a grid reads, kept between grids so a read costs no new arrays\n let gridColumns = new Int32Array(0)\n let gridBlendX = new Float64Array(0)\n let gridRows = new Int32Array(0)\n let gridBlendZ = new Float64Array(0)\n let gridNear = new Float64Array(0)\n let gridFar = new Float64Array(0)\n\n function heightGrid(xs: ArrayLike<number>, zs: ArrayLike<number>, out: Float64Array): void {\n const width = xs.length\n const depth = zs.length\n if (out.length < width * depth) throw new RangeError(`heightGrid: out holds ${out.length} heights, the grid has ${width * depth}`)\n if (gridColumns.length < width) {\n gridColumns = new Int32Array(width)\n gridBlendX = new Float64Array(width)\n }\n if (gridRows.length < depth) {\n gridRows = new Int32Array(depth)\n gridBlendZ = new Float64Array(depth)\n }\n // each column and row as `heightAt` finds it (-1: past the terrain, where the host's `baseHeight` answers), so every height is the one `heightAt` gives, to the bit\n for (let i = 0; i < width; i++) {\n const x = xs[i]!\n const fx = cellCoordinate(x, x0, columns)\n gridColumns[i] = x >= x0 && x <= x1 ? fx | 0 : -1\n gridBlendX[i] = fx - (fx | 0)\n }\n for (let j = 0; j < depth; j++) {\n const z = zs[j]!\n const fz = cellCoordinate(z, z0, rows)\n gridRows[j] = z >= z0 && z <= z1 ? fz | 0 : -1\n gridBlendZ[j] = fz - (fz | 0)\n }\n // `blendCell` blends along x first, then along z: the two x blends of a column depend on its row only, so they are made once per row of cells and\n // each point is then the same last step `blendCell` takes, on the same numbers (the same bits); a lattice finer than the cells reads each row many times\n if (gridNear.length < width) {\n gridNear = new Float64Array(width)\n gridFar = new Float64Array(width)\n }\n let blended = -2\n for (let j = 0; j < depth; j++) {\n const row = gridRows[j]!\n const tz = gridBlendZ[j]!\n if (row < 0) {\n for (let i = 0; i < width; i++) out[j * width + i] = options.baseHeight?.(xs[i]!, zs[j]!) ?? 0\n continue\n }\n if (row !== blended) {\n blended = row\n for (let i = 0; i < width; i++) {\n const column = gridColumns[i]!\n if (column < 0) continue\n const index = row * stride + column\n const tx = gridBlendX[i]!\n gridNear[i] = blendHeights(heightOfVertex(index), heightOfVertex(index + 1), tx)\n gridFar[i] = blendHeights(heightOfVertex(index + stride), heightOfVertex(index + stride + 1), tx)\n }\n }\n for (let i = 0; i < width; i++) {\n if (gridColumns[i]! < 0) {\n out[j * width + i] = options.baseHeight?.(xs[i]!, zs[j]!) ?? 0\n continue\n }\n out[j * width + i] = blendHeights(gridNear[i]!, gridFar[i]!, tz)\n }\n }\n }\n\n function heightPatch(minX: number, maxX: number, minZ: number, maxZ: number, into?: Float64Array): HeightPatch | null {\n // the same test `heightGrid` makes of each point: a rectangle wholly inside reads no `baseHeight`\n if (!(minX >= x0 && maxX <= x1 && minZ >= z0 && maxZ <= z1)) return null\n const column0 = cellCoordinate(minX, x0, columns) | 0\n const row0 = cellCoordinate(minZ, z0, rows) | 0\n const width = (cellCoordinate(maxX, x0, columns) | 0) + 2 - column0\n const depth = (cellCoordinate(maxZ, z0, rows) | 0) + 2 - row0\n const heights = into && into.length >= width * depth ? into : new Float64Array(width * depth)\n for (let j = 0; j < depth; j++) {\n const from = (row0 + j) * stride + column0\n for (let i = 0; i < width; i++) heights[j * width + i] = heightOfVertex(from + i)\n }\n return { cellSize, originX: x0, originZ: z0, columns, rows, column0, row0, width, depth, heights }\n }\n\n function heightRange(minX: number, maxX: number, minZ: number, maxZ: number): { low: number; high: number } | null {\n if (!contains(minX, minZ) || !contains(maxX, maxZ)) return null\n const cellOf = (v: number, origin: number, count: number): number => Math.floor(Math.max(0, Math.min(count - 1e-6, (v - origin) / cellSize)))\n const column0 = cellOf(minX, x0, columns)\n const column1 = cellOf(maxX, x0, columns) + 1\n const row0 = cellOf(minZ, z0, rows)\n const row1 = cellOf(maxZ, z0, rows) + 1\n let low = Infinity\n let high = -Infinity\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n const h = base[index]! - dug[index]! + loose[index]!\n if (h < low) low = h\n if (h > high) high = h\n }\n }\n return { low, high }\n }\n\n const vertexOf = (x: number, z: number): { column: number; row: number; index: number } => {\n const column = clampIndex(Math.round((x - x0) / cellSize), columns)\n const row = clampIndex(Math.round((z - z0) / cellSize), rows)\n return { column, row, index: row * stride + column }\n }\n\n function waterAt(x: number, z: number): { liquid: string; level: number; depth: number } | null {\n if (!hasWater || !contains(x, z)) return null\n const { index } = vertexOf(x, z)\n const water = profileList[profileIndex[index]!]!.water\n if (!water) return null\n const level = surface[index]!\n const depth = level - heightAt(x, z)\n return depth > WATER_MINIMUM ? { liquid: water.liquid, level, depth } : null\n }\n const exposedAt = (x: number, z: number): TerrainMaterial => {\n const { column, row } = vertexOf(x, z)\n return vertexMaterial(column, row)\n }\n const footAt = (x: number, z: number): number => {\n if (!contains(x, z)) return heightAt(x, z)\n return heightAt(x, z) - (exposedAt(x, z).footing?.sink ?? 0)\n }\n function walkFactorAt(x: number, z: number): number {\n if (!contains(x, z)) return 1\n const water = waterAt(x, z) ? profileList[profileIndex[vertexOf(x, z).index]!]!.water : null\n return Math.min(water?.drag ?? 1, exposedAt(x, z).footing?.drag ?? 1)\n }\n function ripple(x: number, z: number, radius: number): void {\n addDecal({ kind: 'ripple', x, z, radius, angle: 0, material: exposedAt(x, z).id })\n }\n function press(spec: { x: number; z: number; radius: number; angle?: number; kind?: 'print' | 'rut' }): boolean {\n if (!contains(spec.x, spec.z)) return false\n if (waterAt(spec.x, spec.z)) {\n ripple(spec.x, spec.z, spec.radius * 2)\n return true\n }\n const material = exposedAt(spec.x, spec.z)\n if (!material.footing?.prints) return false\n addDecal({ kind: spec.kind ?? 'print', x: spec.x, z: spec.z, radius: spec.radius, angle: spec.angle ?? 0, material: material.id })\n return true\n }\n\n function vertexMaterial(column: number, row: number): TerrainMaterial {\n const index = row * stride + column\n return materials.get(stratumMaterialAtDepth(profileList[profileIndex[index]!]!, dug[index]!))!\n }\n\n /** `material(columnAt(x, z).material)` without building the column: the pieces ask it for every round contact. */\n function surfaceMaterialAt(x: number, z: number): TerrainMaterial {\n const column = clampIndex(Math.round((x - x0) / cellSize), columns)\n const row = clampIndex(Math.round((z - z0) / cellSize), rows)\n const index = row * stride + column\n const which = profileIndex[index]!\n const depth = Math.min(maxDepthOf[which]!, dug[index]! + marks.depthAt(x, z))\n return materials.get(stratumMaterialAtDepth(profileList[which]!, depth))!\n }\n\n function rollingAt(x: number, z: number): number | undefined {\n return surfaceMaterialAt(x, z).rolling\n }\n\n function rollingDampingAt(x: number, z: number): number | undefined {\n return surfaceMaterialAt(x, z).rollingDamping\n }\n\n function columnAt(x: number, z: number): TerrainColumn {\n const { index } = vertexOf(x, z)\n const which = profileIndex[index]!\n const profile = profileList[which]!\n const depth = Math.min(maxDepthOf[which]!, dug[index]! + marks.depthAt(x, z))\n const layer = stratumAtDepth(profile, depth)\n return { profile: profile.id, material: layer.stratum.material, stratum: layer.index, depth, remaining: maxDepthOf[which]! - depth, scorch: scorch[index]!, loose: loose[index]! }\n }\n\n /** Removes from a vertex: what is heaped first, then the column, never past its limit. Returns what came off. */\n function removeFromVertex(index: number, amount: number): number {\n const fromLoose = Math.min(loose[index]!, amount)\n loose[index] = loose[index]! - fromLoose\n const fromColumn = Math.min(maxDepthOf[profileIndex[index]!]! - dug[index]!, amount - fromLoose)\n if (fromColumn > 0) dug[index] = dug[index]! + fromColumn\n return fromLoose + Math.max(0, fromColumn)\n }\n /** Adds to a vertex: a soft floor fills what was dug, then heaps; on a rigid one the rubble just heaps. */\n function addToVertex(index: number, amount: number, fillsColumn: boolean): void {\n const filled = fillsColumn ? Math.min(dug[index]!, amount) : 0\n dug[index] = dug[index]! - filled\n loose[index] = loose[index]! + amount - filled\n }\n const isSoftExposed = (index: number): boolean => materials.get(stratumAtDepth(profileList[profileIndex[index]!]!, dug[index]!).stratum.material)!.reposeDegrees !== undefined\n\n /** The vertices under a rectangle centred at (x, z): the cells a blade of that size bites. */\n function verticesUnder(x: number, z: number, size: readonly [number, number]): number[] {\n // as many vertices across as the size has cells (each vertex stands for its cell's area), centred on (x, z)\n const nu = Math.max(1, Math.round(size[0] / cellSize)), nv = Math.max(1, Math.round(size[1] / cellSize))\n const column0 = clampIndex(Math.round((x - x0) / cellSize - (nu - 1) / 2), columns), column1 = clampIndex(column0 + nu - 1, columns)\n const row0 = clampIndex(Math.round((z - z0) / cellSize - (nv - 1) / 2), rows), row1 = clampIndex(row0 + nv - 1, rows)\n const out: number[] = []\n for (let row = row0; row <= row1; row++) for (let column = column0; column <= column1; column++) out.push(row * stride + column)\n return out\n }\n const touchIndex = (index: number): void => touchVertex(index % stride, Math.floor(index / stride))\n /** The material a shovel meets at a vertex: the loose earth heaped there, else the stratum at the depth dug so far. */\n const materialAtVertex = (index: number): TerrainMaterial =>\n loose[index]! > 1e-4 ? materials.get('soil')! : materials.get(stratumAtDepth(profileList[profileIndex[index]!]!, dug[index]!).stratum.material)!\n\n /** Lowers a vertex by up to `depth` through what a shovel digs (heaped earth first), stopping at what it does not. Returns how far it went. */\n function digVertex(index: number, depth: number): number {\n let left = depth\n while (left > 1e-6) {\n if (loose[index]! > 1e-6) {\n const take = Math.min(loose[index]!, left)\n loose[index] = loose[index]! - take\n left -= take\n continue\n }\n const profile = profileList[profileIndex[index]!]!\n const layer = stratumAtDepth(profile, dug[index]!)\n if (!materials.get(layer.stratum.material)?.dig || dug[index]! >= maxDepthOf[profileIndex[index]!]! - 1e-6) break\n const take = Math.min(left, layer.top + layer.stratum.thickness - dug[index]!)\n if (take <= 1e-6) break\n dug[index] = dug[index]! + take\n left -= take\n }\n return depth - left\n }\n\n /** Heaps `volume` of earth round (x, z), highest in the middle, and lets it settle to its slope. */\n function heapAt(x: number, z: number, volume: number): void {\n if (volume <= 0) return\n const radius = Math.max(cellSize * 2, Math.cbrt(volume) * 1.6)\n const indices = verticesUnder(x, z, [2 * radius, 2 * radius])\n const weight = (index: number): number => {\n const px = x0 + (index % stride) * cellSize, pz = z0 + Math.floor(index / stride) * cellSize\n const q = Math.hypot(px - x, pz - z) / radius\n return q < 1 ? 1 - q * q : 0\n }\n const total = indices.reduce((sum, i) => sum + weight(i), 0)\n if (total <= 0) return\n const cellArea = cellSize * cellSize\n for (const index of indices) {\n const w = weight(index)\n if (w <= 0) continue\n loose[index] = loose[index]! + (volume * w) / (total * cellArea)\n sliding.add(index)\n touchIndex(index)\n }\n emitDeform(x, z, radius)\n }\n\n function dig(spec: TerrainDig): TerrainDigResult {\n const size = spec.size ?? [0.3, 0.3], depth = spec.depth ?? 0.2\n const centre = vertexOf(spec.x, spec.z).index\n // under water a shovel brings nothing up\n if (profileList[profileIndex[centre]!]!.water) return { volume: 0, material: 'water', effort: 0, refused: 'water' }\n const met = materialAtVertex(centre)\n if (!met.dig) return { volume: 0, material: met.id, effort: 0, refused: met.id }\n if (met.dig.closes) return { volume: 0, material: met.id, effort: met.dig.effort, closes: true }\n const cellArea = cellSize * cellSize\n const tally: LossTally = new Map()\n let volume = 0\n for (const index of verticesUnder(spec.x, spec.z, size)) {\n const before = dug[index]!\n const went = digVertex(index, depth)\n if (went <= 0) continue\n tallyLowered(tally, index, dug[index]! - before)\n volume += went * cellArea\n sliding.add(index)\n touchIndex(index)\n }\n marks.removeInside(spec.x, spec.z, Math.max(size[0], size[1]) / 2)\n emitDeform(spec.x, spec.z, Math.max(size[0], size[1]))\n // what the blade took from under a footing is ground lost under it: the structure feels it\n emitGroundLoss(tally, 'dig', 0)\n if (spec.dump) heapAt(spec.dump.x, spec.dump.z, volume)\n return { volume, material: met.id, effort: volume > 0 ? met.dig.effort : 0 }\n }\n\n function fill(spec: TerrainFill): number {\n const cellArea = cellSize * cellSize\n // the earth of the heap round `from`, nearest first, up to the volume asked\n let taken = 0\n const source = verticesUnder(spec.from.x, spec.from.z, [2 * spec.from.radius, 2 * spec.from.radius]).filter((i) => loose[i]! > 1e-6)\n for (const index of source) {\n if (taken >= spec.volume) break\n const take = Math.min(loose[index]!, (spec.volume - taken) / cellArea)\n loose[index] = loose[index]! - take\n taken += take * cellArea\n sliding.add(index)\n touchIndex(index)\n }\n if (taken <= 0) return 0\n emitDeform(spec.from.x, spec.from.z, spec.from.radius)\n // laid in the hole: the deepest vertices of the bite first, so the hole closes level\n const target = verticesUnder(spec.x, spec.z, spec.size ?? [0.3, 0.3]).sort((a, b) => dug[b]! - dug[a]!)\n let left = taken\n for (const index of target) {\n if (left <= 1e-9) break\n const amount = Math.min(left / cellArea, Math.max(dug[index]!, (left / cellArea) / target.length))\n addToVertex(index, amount, true)\n left -= amount * cellArea\n sliding.add(index)\n touchIndex(index)\n }\n if (left > 1e-9) heapAt(spec.x, spec.z, left)\n emitDeform(spec.x, spec.z, Math.max(...(spec.size ?? [0.3, 0.3])))\n return taken\n }\n\n /** Digs a lobed bowl into the height field, heaps the rim share around it. */\n function stampBowl(x: number, z: number, radius: number, depth: number, rimVolume: number, lossSource: string | null = 'crater'): void {\n const reach = radius * RIM_REACH\n const column0 = clampIndex(Math.floor((x - reach - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((x + reach - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((z - reach - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((z + reach - z0) / cellSize), rows)\n const phaseA = random() * 6.283\n const phaseB = random() * 6.283\n const shapeOf = (px: number, pz: number): number => {\n const angle = Math.atan2(pz - z, px - x)\n return Math.hypot(px - x, pz - z) / (radius * (1 + 0.12 * Math.sin(angle * 5 + phaseA) + 0.06 * Math.sin(angle * 11 + phaseB)))\n }\n let rimWeight = 0\n if (rimVolume > 0) {\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const q = shapeOf(x0 + column * cellSize, z0 + row * cellSize)\n if (q >= 1 && q < RIM_REACH) rimWeight += Math.sin(((q - 1) / (RIM_REACH - 1)) * Math.PI)\n }\n }\n }\n const cellArea = cellSize * cellSize\n const tally: LossTally = new Map()\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const q = shapeOf(x0 + column * cellSize, z0 + row * cellSize)\n const index = row * stride + column\n if (q < 1) {\n const before = dug[index]!\n removeFromVertex(index, depth * (1 - q * q) * (0.92 + random() * 0.16))\n tallyLowered(tally, index, dug[index]! - before)\n sliding.add(index)\n touchVertex(column, row)\n } else if (q < RIM_REACH && rimWeight > 0) {\n loose[index] = loose[index]! + (rimVolume * Math.sin(((q - 1) / (RIM_REACH - 1)) * Math.PI)) / (rimWeight * cellArea)\n sliding.add(index)\n touchVertex(column, row)\n }\n }\n }\n marks.removeInside(x, z, radius)\n clearDecalsInside(x, z, radius)\n emitDeform(x, z, reach)\n if (lossSource) emitGroundLoss(tally, lossSource, 0)\n }\n\n function throwPieces(spec: { x: number; y: number; z: number; volume: number; material: TerrainMaterial; energy: number; direction?: readonly number[]; quota: number; bowlRadius: number; blow: TerrainBlow }): void {\n const radius = PIECE_RADIUS[spec.material.debris]\n const pieceVolume = (4 / 3) * Math.PI * radius ** 3\n const count = Math.min(spec.quota, Math.max(1, Math.round(spec.volume / pieceVolume)))\n const mass = Math.max(1e-3, spec.volume * 1500)\n const launch = Math.min(MAX_PIECE_SPEED[spec.blow], Math.sqrt((2 * spec.energy * THROW_SHARE) / mass))\n for (let i = 0; i < count; i++) {\n const angle = random() * 6.283\n const out = spec.bowlRadius * Math.sqrt(random()) * 0.8\n const speed = launch * (0.5 + random() * 0.7)\n const spread = 0.35 + random() * 0.65\n const backX = spec.direction ? -(spec.direction[0] ?? 0) * 0.4 : 0\n const backZ = spec.direction ? -(spec.direction[2] ?? 0) * 0.4 : 0\n debrisStore.throwPiece({\n material: spec.material.id,\n kind: spec.material.debris,\n radius: radius * (0.6 + random() * 0.9),\n position: [spec.x + Math.cos(angle) * out, spec.y + 0.03, spec.z + Math.sin(angle) * out],\n velocity: [(Math.cos(angle) * spread + backX) * speed, (0.6 + random() * 0.7) * speed, (Math.sin(angle) * spread + backZ) * speed],\n spin: [(random() - 0.5) * 14, (random() - 0.5) * 14, (random() - 0.5) * 14],\n })\n }\n }\n\n function strike(blow: TerrainBlow, spec: TerrainStrike): TerrainBlowResult {\n const { x, z } = spec\n const start = columnAt(x, z)\n const profile = profileMap.get(start.profile)!\n const waterHere = waterAt(x, z)\n const waterResult = waterHere ? { water: { liquid: waterHere.liquid, level: waterHere.level } } : {}\n if (waterHere) ripple(x, z, Math.min(1.5, 0.15 + Math.cbrt(spec.energy) / 40))\n const removed: { material: string; volume: number }[] = []\n const point: [number, number, number] = [x, heightAt(x, z), z]\n const startLayer = stratumAtDepth(profile, start.depth)\n if (start.loose <= 0 && materials.get(startLayer.stratum.material)!.units) return strikeUnits(blow, spec, startLayer, profile, point)\n const blowEnergy = spec.energy * (waterHere ? (profile.water?.blowShare[blow] ?? 1) : 1)\n let energy = blowEnergy\n let depth = start.depth\n let radius = 0\n let carved = 0\n let breached = false\n const firstMaterial = materials.get(start.material)!\n if (start.loose <= 0) {\n for (;;) {\n const layer = stratumAtDepth(profile, depth)\n const bottom = layer.top + layer.stratum.thickness\n const room = bottom - depth\n if (room <= 1e-6) break\n const material = materials.get(layer.stratum.material)!\n const response = material.hits[blow]\n if (!response || energy < (response.thresholdJoules ?? 0)) break\n const bars = layer.stratum.reinforcement\n // a contact charge with enough for the whole thickness of a rigid layer breaks it right through: the shock spalls the far face and the layer goes in one piece, bars or not\n const breach = blow === 'explosive' ? material.breach : undefined\n const breachJoules = breach ? breach.joulesPerCubedThickness * layer.stratum.thickness ** 3 : Infinity\n if (breach && depth <= layer.top + 1e-6 && energy >= breachJoules) {\n const takenRadius = layer.stratum.thickness * breach.radiusOverThickness * Math.cbrt(energy / breachJoules)\n const takenVolume = (Math.PI * takenRadius * takenRadius * room) / 2\n energy -= breachJoules\n depth += room\n carved += room\n breached = true\n radius = Math.max(radius, takenRadius)\n removed.push({ material: material.id, volume: takenVolume })\n continue\n }\n const pastCover = bars !== undefined && depth - layer.top >= bars.cover - 1e-6\n const specificEnergy = response.specificEnergy * (pastCover ? bars.resistance : 1)\n const limit = bars && !pastCover ? Math.min(room, layer.top + bars.cover - depth) : room\n const aspect = response.aspect * caliberAspect(spec.caliber)\n const volume = energy / specificEnergy\n const wanted = Math.cbrt((2 * volume) / (Math.PI * aspect))\n const wantedDepth = wanted * aspect\n const takenDepth = Math.min(wantedDepth, limit)\n const takenRadius = takenDepth < wantedDepth ? takenDepth / aspect : wanted\n const takenVolume = (Math.PI * takenRadius * takenRadius * takenDepth) / 2\n energy -= takenVolume * specificEnergy\n depth += takenDepth\n carved += takenDepth\n radius = Math.max(radius, takenRadius, response.minRadius ?? 0, spec.contactRadius ?? 0, caliberRadius(spec.caliber))\n const last = removed[removed.length - 1]\n if (last?.material === material.id) (last as { volume: number }).volume += takenVolume\n else removed.push({ material: material.id, volume: takenVolume })\n if (energy <= 1e-6 || takenDepth >= wantedDepth - 1e-9) break\n }\n } else {\n // a loose heap has no strength: it takes the blow as soft ground before the column does\n const response = firstMaterial.hits[blow]\n if (response && energy >= (response.thresholdJoules ?? 0)) {\n const volume = energy / response.specificEnergy\n radius = Math.cbrt((2 * volume) / (Math.PI * response.aspect))\n carved = radius * response.aspect\n removed.push({ material: firstMaterial.id, volume })\n }\n }\n let collapsed = loadBars(blow, spec.energy, x, z, profile)\n const crack = crackAround(blow, spec.energy, x, z, start.loose > 0 ? undefined : firstMaterial)\n const extra = { ...(crack ? { crack } : {}), ...(breached ? { breached } : {}), ...waterResult }\n // a weight that lands flat (its contact as wide as the dent) presses the ground down: it packs the soil under it, it does not take it away\n const pressed = spec.contactRadius !== undefined && spec.contactRadius >= radius\n if (radius <= 0) return { point, radius: 0, depth: 0, totalDepth: columnAt(x, z).depth, removed: [], exposed: start.material, atLimit: start.remaining <= 1e-6, rebarExposed: rebarShowing(profile, start.depth), collapsed, fine: true, ...extra }\n\n // a rigid floor cannot go down any more where it is already deep: the next blow breaks the edge of the hole, so a hole in a slab opens as it deepens\n if (firstMaterial.reposeDegrees === undefined && start.loose <= 0) radius *= 1 + RIGID_WIDENING * (start.depth / maxDepthOfProfile(profile))\n\n const volumeTotal = removed.reduce((sum, entry) => sum + entry.volume, 0)\n const fine = radius < cellSize * FINE_CELLS\n if (fine) depositMark({ x, z, radius, depth: carved, blow, profile, cap: maxDepthOfProfile(profile) })\n else {\n const rimShare = materials.get(removed[0]!.material)!.rimShare ?? 0\n stampBowl(x, z, radius, carved, volumeTotal * rimShare, pressed ? null : 'crater')\n }\n if (firstMaterial.cracks) addDecal({ kind: 'crack', x, z, radius: Math.max(CRACK_MIN_RADIUS, radius * firstMaterial.cracks), angle: random() * 6.283, material: firstMaterial.id })\n // under water what comes off stays a cloud at the bottom, unless a blast opens the water\n let quota = waterHere && blow !== 'explosive' ? 0 : budget.maxDebrisPerBlow\n for (const entry of removed) {\n const material = materials.get(entry.material)!\n const thrown = entry.volume * (1 - (fine ? 0 : (material.rimShare ?? 0)))\n if (thrown <= 0 || quota <= 0) continue\n const share = Math.max(1, Math.round((quota * entry.volume) / volumeTotal))\n throwPieces({ x, y: point[1], z, volume: thrown, material, energy: spec.energy * (entry.volume / volumeTotal), direction: spec.direction, quota: share, bowlRadius: radius, blow })\n quota -= share\n }\n // a breach bares the bars under the same blow that broke the concrete, so they take that blow's load at once and, over a void, may let the floor go\n if (breached) collapsed = loadBars(blow, spec.energy, x, z, profile) || collapsed\n const after = columnAt(x, z)\n return { point, radius, depth: carved, totalDepth: after.depth, removed, exposed: after.material, atLimit: after.remaining <= 1e-4, rebarExposed: rebarShowing(profile, after.depth), collapsed, fine, ...extra }\n }\n\n /** A rigid surface cracks around a hard enough blow, the lines running out with the cube root of the energy; a soft one (soil, sand, turf) only gives way. */\n function crackAround(blow: TerrainBlow, energy: number, x: number, z: number, material: TerrainMaterial | undefined): ReturnType<typeof cracks.add> | undefined {\n const response = material?.crack\n if (!material || !response || energy < response.thresholdJoules) return undefined\n // a cut does not crack a slab; a bullet, a hammer and a blast do\n if (blow === 'slash') return undefined\n const scale = Math.cbrt(energy / CRACK_REFERENCE_JOULES)\n return cracks.add({ x, z, reach: response.reach * scale, width: response.width * scale, material: material.id, seed: Math.floor(random() * 2 ** 31) }, budget.maxCracks)\n }\n\n /**\n * A floor of separate pieces: a blow does not dig them, it shakes them. Each takes the energy that reaches it, added blow by blow, and past its limit it comes off the bed whole and is thrown.\n * Under the limit the blow only chips it.\n */\n function strikeUnits(blow: TerrainBlow, spec: TerrainStrike, layer: { stratum: TerrainStratum; top: number }, profile: TerrainProfile, point: [number, number, number]): TerrainBlowResult {\n const { x, z, energy } = spec\n const material = materials.get(layer.stratum.material)!\n const units = material.units!\n const response = material.hits[blow]\n const bottom = layer.top + layer.stratum.thickness\n const miss: TerrainBlowResult = { point, radius: 0, depth: 0, totalDepth: layer.top, removed: [], exposed: material.id, atLimit: false, rebarExposed: false, collapsed: false, fine: true }\n if (!response || energy < (response.thresholdJoules ?? 0)) return miss\n const reach = Math.max(spec.contactRadius ?? 0, response.minRadius ?? 0, caliberRadius(spec.caliber), Math.cbrt((2 * energy) / response.specificEnergy / (Math.PI * response.aspect * caliberAspect(spec.caliber))))\n const rowFirst = Math.floor((z - reach) / units.width)\n const rowLast = Math.floor((z + reach) / units.width)\n let loosened = 0\n for (let row = rowFirst; row <= rowLast; row++) {\n const shift = Math.abs(row % 2) * cellSize\n const unitFirst = Math.floor((x - reach - shift) / units.length)\n const unitLast = Math.floor((x + reach - shift) / units.length)\n for (let unit = unitFirst; unit <= unitLast; unit++) {\n const minX = unit * units.length + shift\n const minZ = row * units.width\n const near = Math.hypot(Math.max(minX - x, 0, x - minX - units.length), Math.max(minZ - z, 0, z - minZ - units.width))\n if (near > reach) continue\n const key = `${unit}:${row}`\n const taken = (unitDamage.get(key) ?? 0) + energy * (1 - (near / (reach + 1e-6)) ** 2)\n unitDamage.set(key, taken)\n if (taken >= units.looseJoules && liftUnit(minX, minZ, units, bottom, material, profile)) {\n loosened++\n const speed = Math.min(MAX_PIECE_SPEED[blow], Math.sqrt((2 * energy * THROW_SHARE) / Math.max(1, loosened * 15)))\n const angle = random() * 6.283\n debrisStore.throwPiece({ material: material.id, kind: 'blocks', radius: units.length / 2, position: [minX + units.length / 2, point[1] + 0.05, minZ + units.width / 2], velocity: [Math.cos(angle) * speed * 0.6, speed * (0.5 + random() * 0.5), Math.sin(angle) * speed * 0.6], spin: [(random() - 0.5) * 8, (random() - 0.5) * 8, (random() - 0.5) * 8] })\n }\n }\n }\n if (loosened === 0) {\n // not enough to lift a piece: a chip off its face and a hairline\n addDecal({ kind: 'crack', x, z, radius: Math.max(0.05, reach * 2), angle: random() * 6.283, material: material.id })\n throwPieces({ x, y: point[1], z, volume: 1e-5, material: { ...material, debris: 'chips' }, energy, ...(spec.direction ? { direction: spec.direction } : {}), quota: 3, bowlRadius: 0.02, blow })\n return { ...miss, radius: Math.max(0.02, Math.min(reach, 0.06)) }\n }\n emitDeform(x, z, reach + units.length)\n clearDecalsInside(x, z, reach)\n const volume = loosened * units.length * units.width * layer.stratum.thickness\n const after = columnAt(x, z)\n return { point, radius: reach, depth: layer.stratum.thickness, totalDepth: after.depth, removed: [{ material: material.id, volume }], exposed: after.material, atLimit: false, rebarExposed: false, collapsed: false, fine: false }\n }\n\n /** Takes one piece off its bed. False when it had already gone. */\n function liftUnit(minX: number, minZ: number, units: { length: number; width: number }, bottom: number, material: TerrainMaterial, profile: TerrainProfile): boolean {\n const column0 = clampIndex(Math.round((minX - x0) / cellSize), columns)\n const column1 = clampIndex(Math.round((minX + units.length - x0) / cellSize), columns)\n const row0 = clampIndex(Math.round((minZ - z0) / cellSize), rows)\n const row1 = clampIndex(Math.round((minZ + units.width - z0) / cellSize), rows)\n let lifted = false\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n if (profileList[profileIndex[index]!]!.id !== profile.id || dug[index]! >= bottom) continue\n if (materials.get(stratumAtDepth(profile, dug[index]!).stratum.material) !== material) continue\n dug[index] = bottom\n lifted = true\n touchVertex(column, row)\n }\n }\n return lifted\n }\n\n /**\n * A blow loads the bars that are bare around it: they bend, and past their limit they give way. The bowl a blow would open tells how far it reaches. Where the slab has nothing under it, the floor goes with them.\n */\n function loadBars(blow: TerrainBlow, energy: number, x: number, z: number, profile: TerrainProfile): boolean {\n const bars = profile.strata.find((stratum) => stratum.reinforcement)\n if (!bars?.reinforcement) return false\n const response = materials.get(bars.material)!.hits[blow]\n if (!response || energy < (response.thresholdJoules ?? 0)) return false\n const yieldJoules = bars.reinforcement.yieldJoules ?? DEFAULT_BAR_YIELD_JOULES\n let cover = bars.reinforcement.cover\n for (const stratum of profile.strata) {\n if (stratum === bars) break\n cover += stratum.thickness\n }\n const reach = Math.max(cellSize * FINE_CELLS, Math.cbrt((2 * energy) / response.specificEnergy / (Math.PI * response.aspect)) * (1 + RIGID_WIDENING))\n const column0 = clampIndex(Math.floor((x - reach - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((x + reach - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((z - reach - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((z + reach - z0) / cellSize), rows)\n const limit = maxDepthOfProfile(profile)\n let collapsed = false\n const tally: LossTally = new Map()\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n if (dug[index]! < cover) continue\n const q = Math.hypot(x0 + column * cellSize - x, z0 + row * cellSize - z) / reach\n if (q >= 1) continue\n barBend[index] = barBend[index]! + (energy / yieldJoules) * (1 - q * q)\n touchVertex(column, row)\n if (barBend[index]! >= 1 && profile.drop !== undefined && dug[index]! >= limit * COLLAPSE_DEPTH_SHARE && dug[index]! < limit + profile.drop) {\n dropVertex(index, limit + profile.drop, tally)\n collapsed = true\n }\n }\n }\n if (collapsed) giveWay({ x, z, reach, profile, tally })\n emitGroundLoss(tally, 'slab', 0)\n return collapsed\n }\n\n /** What gave way takes down what was already bending around it, and what stood there must look again. */\n function giveWay(spec: { x: number; z: number; reach: number; profile: TerrainProfile; tally: LossTally }): void {\n const { x, z, reach, profile, tally } = spec\n emitDeform(x, z, reach)\n if (profile.drop === undefined) return\n const limit = maxDepthOfProfile(profile)\n const column0 = clampIndex(Math.floor((x - reach - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((x + reach - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((z - reach - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((z + reach - z0) / cellSize), rows)\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n if (barBend[index]! >= COLLAPSE_SPREAD_BEND && dug[index]! < limit + profile.drop) {\n dropVertex(index, limit + profile.drop, tally)\n touchVertex(column, row)\n }\n }\n }\n }\n\n /** Depth under the surface of the bars of a profile, and the stratum that holds them. */\n function barsOf(profile: TerrainProfile): { stratum: TerrainStratum; cover: number } | null {\n const bars = profile.strata.find((stratum) => stratum.reinforcement)\n if (!bars?.reinforcement) return null\n let cover = bars.reinforcement.cover\n for (const stratum of profile.strata) {\n if (stratum === bars) break\n cover += stratum.thickness\n }\n return { stratum: bars, cover }\n }\n\n /**\n * Weights on bare bars. Each bar over the hole works as a beam that yields at its plastic moment fy·d³/6; the bars of a mesh crossing a hole of any size hold 8·Mp/spacing\n * on a spot, so the bend is the weight over that. Weights over the same bars add up (a stack, things side by side). The share of a footprint on intact concrete is carried\n * by the concrete. Bars do not spring back: the bend only grows.\n */\n function bearAll(loads: readonly TerrainLoad[]): boolean {\n const bends = new Map<number, number>()\n const touched: { load: TerrainLoad; reach: number; profile: TerrainProfile }[] = []\n for (const load of loads) {\n const spread = spreadLoad(load, bends)\n if (spread) touched.push({ load, ...spread })\n }\n let opened = false\n const tally: LossTally = new Map()\n for (const [index, bend] of bends) {\n if (barBend[index]! >= bend) continue\n barBend[index] = bend\n const column = index % stride\n const row = (index - column) / stride\n touchVertex(column, row)\n const profile = profileList[profileIndex[index]!]!\n const limit = maxDepthOfProfile(profile)\n if (bend >= 1 && profile.drop !== undefined && dug[index]! >= limit * COLLAPSE_DEPTH_SHARE && dug[index]! < limit + profile.drop) {\n dropVertex(index, limit + profile.drop, tally)\n opened = true\n }\n }\n if (opened) for (const { load, reach, profile } of touched) giveWay({ x: load.x, z: load.z, reach, profile, tally })\n emitGroundLoss(tally, 'slab', 0)\n return opened\n }\n\n /** Adds the bend one weight gives the bare bars under it to `bends`; null where it stands on no bare bars. */\n function spreadLoad(load: TerrainLoad, bends: Map<number, number>): { reach: number; profile: TerrainProfile } | null {\n if (!contains(load.x, load.z) || load.newtons <= 0) return null\n const profile = profileList[profileIndex[vertexOf(load.x, load.z).index]!]!\n const bars = barsOf(profile)\n if (!bars) return null\n const reinforcement = bars.stratum.reinforcement!\n const moment = ((reinforcement.yieldPa ?? DEFAULT_BAR_YIELD_PA) * (reinforcement.diameter ?? DEFAULT_BAR_DIAMETER) ** 3) / 6\n const holds = (8 * moment) / reinforcement.spacing\n // the footprint of a box reaches its corners: a disc of its half side would leave them standing on the slab\n const footprint = load.radius * Math.SQRT2 + cellSize\n // and the bars of a hole carry together what stands on it: weights side by side add up as a stack does\n const reach = Math.max(footprint, BARS_SHARE_REACH)\n const column0 = clampIndex(Math.floor((load.x - reach - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((load.x + reach - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((load.z - reach - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((load.z + reach - z0) / cellSize), rows)\n const bare: number[] = []\n let under = 0\n let onBars = 0\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const distance = Math.hypot(x0 + column * cellSize - load.x, z0 + row * cellSize - load.z)\n if (distance >= reach) continue\n const index = row * stride + column\n const isBare = dug[index]! >= bars.cover\n if (isBare) bare.push(index)\n if (distance >= footprint) continue\n under++\n if (isBare) onBars++\n }\n }\n if (onBars === 0) return null\n const bend = (load.newtons * (onBars / under)) / holds\n for (const index of bare) bends.set(index, (bends.get(index) ?? 0) + bend)\n return { reach, profile }\n }\n\n const maxDepthOfProfile = (profile: TerrainProfile): number => maxDepthOf[indexOfProfile.get(profile.id)!]!\n function rebarShowing(profile: TerrainProfile, depth: number): boolean {\n const layer = stratumAtDepth(profile, depth)\n return layer.stratum.reinforcement !== undefined && depth - layer.top >= layer.stratum.reinforcement.cover - 1e-6\n }\n\n function depositMark(spec: { x: number; z: number; radius: number; depth: number; blow: TerrainBlow; profile: TerrainProfile; cap: number }): void {\n const { x, z, radius, depth, blow, profile, cap } = spec\n const dugHere = dug[vertexOf(x, z).index]!\n const existing = marks.near(x, z, radius)\n let mark: TerrainMark\n if (existing) {\n existing.radius = Math.hypot(existing.radius, radius)\n existing.depth = Math.min(cap - dugHere, existing.depth + depth)\n existing.count++\n existing.blow = blow\n mark = existing\n } else {\n mark = marks.add({ x, z, radius, depth: Math.min(cap - dugHere, depth), blow, material: '' })\n }\n mark.material = stratumAtDepth(profile, dugHere + mark.depth - 1e-6).stratum.material\n if (mark.radius >= cellSize * FINE_CELLS || mark.depth >= cellSize * FINE_DEPTH_CELLS) {\n const bowlRadius = Math.max(mark.radius, cellSize * FINE_CELLS)\n const bowlDepth = mark.depth\n marks.remove(mark)\n stampBowl(mark.x, mark.z, bowlRadius, bowlDepth, 0)\n }\n }\n\n function burn(spec: { x: number; z: number; radius: number; temperature: number; seconds: number }): void {\n if (spec.temperature < FLAME_MINIMUM) return\n const column0 = clampIndex(Math.floor((spec.x - spec.radius - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((spec.x + spec.radius - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((spec.z - spec.radius - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((spec.z + spec.radius - z0) / cellSize), rows)\n let melted = false\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n if (Math.hypot(x0 + column * cellSize - spec.x, z0 + row * cellSize - spec.z) > spec.radius) continue\n // water does not catch: only what floats on it could burn\n if (hasWater && base[row * stride + column]! < surface[row * stride + column]!) continue\n melted = burnVertex(column, row, spec.seconds) || melted\n }\n }\n if (melted) emitDeform(spec.x, spec.z, spec.radius)\n }\n\n /** The soot of a blast's fireball within `radius` of (x, z): darkest at the centre, by what each material takes (`fire.maxScorch`); it lights nothing. */\n function soot(x: number, z: number, radius: number): void {\n if (radius <= 0) return\n const column0 = clampIndex(Math.floor((x - radius - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((x + radius - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((z - radius - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((z + radius - z0) / cellSize), rows)\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const distance = Math.hypot(x0 + column * cellSize - x, z0 + row * cellSize - z)\n const response = distance < radius ? vertexMaterial(column, row).fire : undefined\n if (!response) continue\n const index = row * stride + column\n const before = scorch[index]!\n scorch[index] = Math.max(before, response.maxScorch * BLAST_SOOT * Math.sqrt(1 - distance / radius))\n if (scorch[index] !== before) touchVertex(column, row)\n }\n }\n }\n\n /** True when the flame took ground away, so that what stood there must look again. */\n function burnVertex(column: number, row: number, seconds: number): boolean {\n const index = row * stride + column\n const material = vertexMaterial(column, row)\n const response = material.fire\n if (!response) return false\n const before = scorch[index]!\n scorch[index] = Math.max(before, Math.min(response.maxScorch, before + response.scorchPerSecond * seconds))\n if (response.burnsAway) removeFromVertex(index, response.burnsAway * seconds)\n if (scorch[index] !== before || response.burnsAway) touchVertex(column, row)\n if (response.flammable) ignite(x0 + column * cellSize, z0 + row * cellSize)\n return (response.burnsAway ?? 0) > 0\n }\n\n const fireKey = (x: number, z: number): number => Math.floor((z - z0) / FIRE_CELL) * 65536 + Math.floor((x - x0) / FIRE_CELL)\n function ignite(x: number, z: number): void {\n const key = fireKey(x, z)\n if (burning.has(key) || burning.size >= budget.maxBurningCells) return\n const index = vertexOf(x, z).index\n if (scorch[index]! >= 1) return\n burning.set(key, FIRE_SECONDS)\n }\n\n function updateFire(dt: number): void {\n for (const [key, remaining] of [...burning]) {\n const cellRow = Math.floor(key / 65536)\n const cellColumn = key - cellRow * 65536\n const x = x0 + (cellColumn + 0.5) * FIRE_CELL\n const z = z0 + (cellRow + 0.5) * FIRE_CELL\n burn({ x, z, radius: FIRE_CELL * 0.75, temperature: 600, seconds: dt })\n if (random() < FIRE_SPREAD_PER_SECOND * dt) {\n const angle = Math.floor(random() * 4) * (Math.PI / 2)\n const nextX = x + Math.cos(angle) * FIRE_CELL\n const nextZ = z + Math.sin(angle) * FIRE_CELL\n if (contains(nextX, nextZ)) {\n const { column, row, index } = vertexOf(nextX, nextZ)\n if (vertexMaterial(column, row).fire?.flammable && scorch[index]! < 1) ignite(nextX, nextZ)\n }\n }\n if (remaining - dt <= 0) burning.delete(key)\n else burning.set(key, remaining - dt)\n }\n }\n\n function updateSlides(): void {\n if (sliding.size === 0) return\n let budgetLeft = budget.maxSlideCellsPerFrame\n let minX = Infinity\n let minZ = Infinity\n let maxX = -Infinity\n let maxZ = -Infinity\n for (const index of sliding) {\n if (budgetLeft-- <= 0) break\n sliding.delete(index)\n const column = index % stride\n const row = (index - column) / stride\n if (!isSoftExposed(index)) continue\n const material = vertexMaterial(column, row)\n const slope = Math.tan(((material.reposeDegrees ?? 90) * Math.PI) / 180) * cellSize\n const height = vertexHeight(column, row)\n const neighbours: [number, number][] = [[column - 1, row], [column + 1, row], [column, row - 1], [column, row + 1]]\n for (const [nextColumn, nextRow] of neighbours) {\n if (nextColumn < 0 || nextRow < 0 || nextColumn > columns || nextRow > rows) continue\n const excess = height - vertexHeight(nextColumn, nextRow) - slope\n if (excess <= SLIDE_EPSILON) continue\n const before = dug[index]!\n const moved = removeFromVertex(index, excess * SLIDE_SHARE)\n if (moved <= 0) continue\n tallyLowered(slideTally, index, dug[index]! - before)\n const next = nextRow * stride + nextColumn\n const nextBefore = dug[next]!\n addToVertex(next, moved, isSoftExposed(next))\n tallyLowered(slideTally, next, dug[next]! - nextBefore)\n sliding.add(index)\n sliding.add(next)\n touchVertex(column, row)\n touchVertex(nextColumn, nextRow)\n const px = x0 + column * cellSize\n const pz = z0 + row * cellSize\n minX = Math.min(minX, px)\n maxX = Math.max(maxX, px)\n minZ = Math.min(minZ, pz)\n maxZ = Math.max(maxZ, pz)\n }\n }\n if (minX <= maxX) emitDeform((minX + maxX) / 2, (minZ + maxZ) / 2, Math.hypot(maxX - minX, maxZ - minZ) / 2 + cellSize * 2)\n if (sliding.size === 0 && slideTally.size > 0) {\n emitGroundLoss(slideTally, 'slide', SLIDE_LOSS_MIN_LOWERING)\n slideTally.clear()\n }\n }\n\n /** The box (in x, z) round the vertices that settled rubble raised in this update, told once as one deform. */\n const settledArea = { minX: Infinity, minZ: Infinity, maxX: -Infinity, maxZ: -Infinity }\n function emitSettledArea(): void {\n if (settledArea.minX > settledArea.maxX) return\n const { minX, minZ, maxX, maxZ } = settledArea\n settledArea.minX = settledArea.minZ = Infinity\n settledArea.maxX = settledArea.maxZ = -Infinity\n emitDeform((minX + maxX) / 2, (minZ + maxZ) / 2, Math.hypot(maxX - minX, maxZ - minZ) / 2 + cellSize * 2)\n }\n\n /** A piece of soft ground joins the height where it stops, so that what is thrown out piles up and can be walked on. */\n function settle(piece: TerrainDebris): boolean {\n const material = materials.get(piece.material)\n if (!material || material.reposeDegrees === undefined || material.scatters) return false\n if (material.splats && contains(piece.position[0], piece.position[2]) && !waterAt(piece.position[0], piece.position[2])) addDecal({ kind: 'splat', x: piece.position[0], z: piece.position[2], radius: piece.radius * 2.6, angle: piece.id * 2.399, material: material.id })\n if (!contains(piece.position[0], piece.position[2])) return true\n const { index, column, row } = vertexOf(piece.position[0], piece.position[2])\n addToVertex(index, ((4 / 3) * Math.PI * piece.radius ** 3) / (cellSize * cellSize), false)\n sliding.add(index)\n touchVertex(column, row)\n const px = x0 + column * cellSize, pz = z0 + row * cellSize\n settledArea.minX = Math.min(settledArea.minX, px)\n settledArea.maxX = Math.max(settledArea.maxX, px)\n settledArea.minZ = Math.min(settledArea.minZ, pz)\n settledArea.maxZ = Math.max(settledArea.maxZ, pz)\n return true\n }\n\n function applyHit(hit: Hit): TerrainBlowResult | null {\n const [x, y, z] = hit.point\n switch (hit.type) {\n case 'ballistic':\n case 'blunt':\n case 'slash': {\n if (!hit.energy) return null\n const contactRadius = hit.type === 'blunt' ? hit.radius : undefined\n const caliber = hit.type === 'ballistic' ? hit.caliber : undefined\n return strike(hit.type, { x, z, energy: hit.energy, ...(hit.direction ? { direction: hit.direction } : {}), ...(contactRadius !== undefined ? { contactRadius } : {}), ...(caliber !== undefined ? { caliber } : {}) })\n }\n case 'explosive': {\n if (!hit.energy) return null\n const above = Math.max(0, y - heightAt(x, z))\n const reach = (hit.radius ?? 1) * BLAST_HEIGHT_REACH\n if (above >= reach) return null\n const share = (1 - above / reach) ** 2\n soot(x, z, BLAST_SOOT_REACH * Math.cbrt((hit.energy * share) / 1e6))\n return strike('explosive', { x, z, energy: hit.energy * share })\n }\n case 'fire':\n case 'heat':\n if (y - heightAt(x, z) > (hit.radius ?? 0.2) + FLAME_REACH) return null\n burn({ x, z, radius: hit.radius ?? 0.2, temperature: hit.temperature ?? 0, seconds: hit.duration ?? 0.016 })\n return null\n default:\n return null\n }\n }\n\n function raycast(origin: readonly number[], direction: readonly number[], maxDistance: number): { point: [number, number, number]; distance: number; normal: [number, number, number] } | null {\n const [ox = 0, oy = 0, oz = 0] = origin\n const [dx = 0, dy = 0, dz = 0] = direction\n const step = cellSize * 0.75\n let previous = 0\n for (let t = 0; t <= maxDistance; t += step) {\n const x = ox + dx * t\n const z = oz + dz * t\n if (contains(x, z) && oy + dy * t <= heightAt(x, z)) {\n let low = previous\n let high = t\n for (let i = 0; i < 6; i++) {\n const middle = (low + high) / 2\n if (oy + dy * middle <= heightAt(ox + dx * middle, oz + dz * middle)) high = middle\n else low = middle\n }\n const px = ox + dx * high\n const pz = oz + dz * high\n const gx = heightAt(px + cellSize, pz) - heightAt(px - cellSize, pz)\n const gz = heightAt(px, pz + cellSize) - heightAt(px, pz - cellSize)\n const length = Math.hypot(gx, 2 * cellSize, gz)\n return { point: [px, oy + dy * high, pz], distance: high, normal: [-gx / length, (2 * cellSize) / length, -gz / length] }\n }\n previous = t\n }\n return null\n }\n\n function chunk(index: number): TerrainChunk {\n const chunkZ = Math.floor(index / chunksX)\n const chunkX = index - chunkZ * chunksX\n return { index, column: chunkX * chunkCells, row: chunkZ * chunkCells, cells: chunkCells, pristine: !touched[index] && !mixed[index] && !options.baseHeight }\n }\n\n function reset(): void {\n dug.fill(0)\n loose.fill(0)\n scorch.fill(0)\n barBend.fill(0)\n touched.fill(0)\n marks.clear()\n cracks.clear()\n decalList.length = 0\n decalsVersion++\n unitDamage.clear()\n debrisStore.clear()\n sliding.clear()\n slideTally.clear()\n burning.clear()\n // the craters and clods draw from here: a reset ground digs the same as a new one\n random = createRandom(seed)\n applyLayout(currentLayout)\n emitDeform((x0 + x1) / 2, (z0 + z1) / 2, Math.hypot(x1 - x0, z1 - z0) / 2)\n }\n\n applyLayout(currentLayout)\n\n return {\n bounds: options.bounds,\n cellSize,\n columns,\n rows,\n stride,\n chunkCells,\n chunksX,\n chunksZ,\n budget,\n dug,\n loose,\n scorch,\n barBend,\n profileIndex,\n profileList,\n material: (id) => {\n const material = materials.get(id)\n if (!material) throw new Error(`game-terrain: unknown material \"${id}\"`)\n return material\n },\n layout: () => currentLayout,\n setLayout(layout) {\n currentLayout = layout\n reset()\n },\n heightAt,\n heightGrid,\n heightPatch,\n heightRange,\n footAt,\n walkFactorAt,\n waterAt,\n press,\n ripple,\n decals: () => decalList,\n get decalsVersion() {\n return decalsVersion\n },\n vertexHeight,\n vertexMaterial,\n columnAt,\n rollingAt,\n rollingDampingAt,\n contains,\n raycast,\n strike,\n burn,\n open(excavation) {\n excavate(excavation)\n const [ex0, ez0, ex1, ez1] = excavation.rect\n emitDeform((ex0 + ex1) / 2, (ez0 + ez1) / 2, Math.hypot(ex1 - ex0, ez1 - ez0) / 2 + cellSize * 2)\n },\n dig,\n fill,\n applyHit,\n bear: bearAll,\n voidUnder: (x, z, radius) => voidUnder(grid, { x, z, radius }),\n onDeform(listener) {\n deformListeners.add(listener)\n return () => deformListeners.delete(listener)\n },\n update(dt) {\n debrisStore.update(dt, { heightAt, gravity, settle })\n emitSettledArea()\n updateSlides()\n updateFire(dt)\n for (let i = decalList.length - 1; i >= 0; i--) {\n const decal = decalList[i]!\n decal.age += dt\n if (decal.kind === 'ripple' && decal.age > RIPPLE_SECONDS) {\n decalList.splice(i, 1)\n decalsVersion++\n }\n }\n },\n get dirtyChunkCount() {\n return dirty.size\n },\n drainDirtyChunks(max = budget.maxDirtyChunksPerFrame) {\n const taken: TerrainChunk[] = []\n for (const index of dirty) {\n if (taken.length >= max) break\n dirty.delete(index)\n taken.push(chunk(index))\n }\n return taken\n },\n chunk,\n marks: () => marks.list,\n cracks: () => cracks.list,\n get cracksVersion() {\n return cracks.version\n },\n debris: () => debrisStore.list,\n burningPoints: () => [...burning.keys()].map((key) => {\n const cellRow = Math.floor(key / 65536)\n const cellColumn = key - cellRow * 65536\n return [x0 + (cellColumn + 0.5) * FIRE_CELL, z0 + (cellRow + 0.5) * FIRE_CELL] as const\n }),\n get marksVersion() {\n return marks.version\n },\n stats: () => ({ marks: marks.list.length, debris: debrisStore.list.length, debrisMoving: debrisStore.list.filter((piece) => !piece.atRest).length, dirtyChunks: dirty.size, burning: burning.size }),\n reset,\n serialize(): TerrainSnapshot {\n return { layout: currentLayout, dug: sparse(dug), loose: sparse(loose), scorch: sparse(scorch), barBend: sparse(barBend), marks: marks.list.map((mark) => ({ ...mark })), cracks: cracks.list.map((crack) => ({ ...crack })), decals: decalList.filter((decal) => decal.kind !== 'ripple').map((decal) => ({ ...decal })) }\n },\n load(snapshot) {\n currentLayout = snapshot.layout\n reset()\n fillSparse(dug, snapshot.dug)\n fillSparse(loose, snapshot.loose)\n fillSparse(scorch, snapshot.scorch)\n fillSparse(barBend, snapshot.barBend ?? [])\n marks.load(snapshot.marks)\n cracks.load(snapshot.cracks ?? [])\n decalList.push(...(snapshot.decals ?? []).map((decal) => ({ ...decal })))\n decalSerial = decalList.reduce((highest, decal) => Math.max(highest, decal.id), decalSerial)\n for (let chunkIndex = 0; chunkIndex < touched.length; chunkIndex++) markChunk(chunkIndex)\n emitDeform((x0 + x1) / 2, (z0 + z1) / 2, Math.hypot(x1 - x0, z1 - z0) / 2)\n },\n }\n}\n","import type { DestructibleImpl, DestructibleSpec, DestructionEvent, Hit, ObjectState, SurfaceRay, SurfaceRayHit } from '@adatechnology/game-contracts'\nimport type { Terrain, TerrainBlowResult } from './types'\n\nconst PART_ID = 'ground'\nconst PART_DEPTH = 3\nconst RAY_BACKOFF = 1\nconst GROUND_HP = 1e12\n/** Most metres the ground rises above its flat level (a heap of what a crater threw out): a ray higher than this cannot meet it. */\nconst HEAP_REACH = 3\n\nexport interface TerrainImplOptions {\n readonly id: string\n readonly name?: string\n /** Every blow that left its mark, with what it did. */\n readonly onBlow?: (result: TerrainBlowResult, hit: Hit) => void\n}\n\n/**\n * The ground as an object of the destruction world (`DestructionWorld.register`): shots, blows, blasts and flames reach it through the world's own raycast and blast like anything else.\n * The collision part is a flat box that only says where to look: the world's raycast asks `surfaceRay`, which follows the ground as it is now (craters, heaps),\n * so a round fired into a crater meets its floor, not the flat top of the box over it.\n */\nexport function createTerrainImpl(terrain: Terrain, options: TerrainImplOptions): DestructibleImpl {\n const { id } = options\n const [x0, z0, x1, z1] = terrain.bounds\n const centerColumn = Math.max(0, Math.min(terrain.columns, Math.round((x1 - x0) / 2 / terrain.cellSize)))\n const centerRow = Math.max(0, Math.min(terrain.rows, Math.round((z1 - z0) / 2 / terrain.cellSize)))\n const centerMaterial = (): string => terrain.vertexMaterial(centerColumn, centerRow).id\n const buildSpec = (material: string): DestructibleSpec => ({\n name: options.name ?? 'Ground',\n parts: [\n {\n id: PART_ID,\n material,\n shape: { kind: 'box', size: [x1 - x0, PART_DEPTH, z1 - z0] },\n position: [(x0 + x1) / 2, -PART_DEPTH / 2, (z0 + z1) / 2],\n hp: GROUND_HP,\n anchored: true,\n tags: ['terrain'],\n },\n ],\n joints: [],\n })\n let cachedSpec: DestructibleSpec | undefined\n const spec = (): DestructibleSpec => {\n const material = centerMaterial()\n if (cachedSpec?.parts[0]?.material !== material) cachedSpec = buildSpec(material)\n return cachedSpec\n }\n const buildState = (material: string): ObjectState => ({\n id,\n position: [0, 0, 0],\n rotation: [0, 0, 0, 1],\n parts: [{ id: PART_ID, material, status: 'intact', hp: GROUND_HP, maxHp: GROUND_HP, mass: 0, temperature: 0, burning: false, fuel: 0, char: 0, melt: 0, dents: [], holes: [], cracks: [], group: 0 }],\n joints: [],\n groups: [[PART_ID]],\n destroyed: false,\n })\n let cachedState: ObjectState | undefined\n const state = (): ObjectState => {\n const material = centerMaterial()\n if (cachedState?.parts[0]?.material !== material) cachedState = buildState(material)\n return cachedState\n }\n const resolve = (hit: Hit): Hit => {\n if (hit.type !== 'ballistic' && hit.type !== 'blunt' && hit.type !== 'slash') return hit\n if (!hit.direction) return { ...hit, point: [hit.point[0], terrain.heightAt(hit.point[0], hit.point[2]), hit.point[2]] }\n const [dx, dy, dz] = hit.direction\n const from = [hit.point[0] - dx * RAY_BACKOFF, hit.point[1] - dy * RAY_BACKOFF, hit.point[2] - dz * RAY_BACKOFF]\n const onGround = terrain.raycast(from, hit.direction, RAY_BACKOFF + PART_DEPTH)\n return onGround ? { ...hit, point: onGround.point } : hit\n }\n /** The ground as it is now along the ray, marched only where the ray is within the depth of the ground and the height of a heap. */\n const surfaceRay = (ray: SurfaceRay): SurfaceRayHit | null => {\n if (ray.ignored?.(PART_ID)) return null\n const [ox, oy, oz] = ray.origin\n const [dx, dy, dz] = ray.direction\n const enter = dy < 0 ? Math.max(0, (oy - HEAP_REACH) / -dy) : oy <= HEAP_REACH ? 0 : Infinity\n const leave = dy < 0 ? (oy + PART_DEPTH) / -dy : Math.hypot(x1 - x0, z1 - z0) + Math.hypot(ox - (x0 + x1) / 2, oz - (z0 + z1) / 2)\n const far = Math.min(ray.maxDistance, leave)\n if (!(enter <= far)) return null\n const hit = terrain.raycast([ox + dx * enter, oy + dy * enter, oz + dz * enter], ray.direction, far - enter)\n if (!hit) return null\n return { part: PART_ID, point: hit.point, normal: hit.normal, distance: enter + hit.distance, pathLen: PART_DEPTH }\n }\n return {\n id,\n ...(options.name ? { name: options.name } : {}),\n describe: spec,\n surfaceRay,\n hit(hit): DestructionEvent[] {\n const landed = resolve(hit)\n const result = terrain.applyHit(landed)\n if (!result || result.radius <= 0) return []\n options.onBlow?.(result, landed)\n return [{ type: 'damage', object: id, time: 0, part: PART_ID, amount: 0, hp: GROUND_HP, damageType: hit.type, ...(hit.source ? { source: hit.source } : {}) }]\n },\n update(dt) {\n terrain.update(dt)\n return []\n },\n state,\n reset() {\n terrain.reset()\n },\n serialize: () => terrain.serialize(),\n load(data) {\n terrain.load(data as ReturnType<Terrain['serialize']>)\n },\n }\n}\n","import type { GroundExcavation, GroundLayout, GroundLoss, Hit } from '@adatechnology/game-contracts'\n\nimport type { HeightPatch } from './height-patch'\n\nexport type { GroundExcavation, GroundLayout, GroundZone } from '@adatechnology/game-contracts'\n\n/** The blows that remove ground. Fire and heat char it instead (`TerrainMaterial.fire`). */\nexport type TerrainBlow = 'ballistic' | 'blunt' | 'slash' | 'explosive'\n\n/** A blow at (x, z): `energy` in joules, `direction` where it travels, `contactRadius` of a blunt tool, `caliber` (mm) of a round, which shapes its crater. */\nexport type TerrainStrike = { x: number; z: number; energy: number; direction?: readonly number[]; contactRadius?: number; caliber?: number }\n\n/** What one kind of blow does to a material. */\nexport interface TerrainBlowResponse {\n /** Joules it takes to remove one cubic metre. */\n readonly specificEnergy: number\n /** Depth over radius of the bowl it leaves: a soft ground craters deep, a hard one spalls wide and shallow. */\n readonly aspect: number\n /** A blow under this many joules leaves nothing (a punch on a slab). */\n readonly thresholdJoules?: number\n /** The bowl is never narrower: a tile comes off as a piece, not as the size of the bullet. */\n readonly minRadius?: number\n}\n\nexport type TerrainDebrisKind = 'clods' | 'chips' | 'shards' | 'splinters' | 'dust' | 'blocks'\n\n/** How a material of the destruction catalogue behaves as ground. `id` is the catalogue's. */\nexport interface TerrainMaterial {\n readonly id: string\n readonly hits: Partial<Record<TerrainBlow, TerrainBlowResponse>>\n readonly debris: TerrainDebrisKind\n /** Share of what a blow removes that piles up on the rim; the rest is thrown. Rigid materials have none. */\n readonly rimShare?: number\n /** Steepest slope in degrees it holds; loose ground slides until it is back to it. */\n readonly reposeDegrees?: number\n /** A shovel digs it: `effort` is how hard a shovelful is against loose soil (1); a material without it (concrete, stone, asphalt) is not dug by hand. */\n readonly dig?: { readonly effort: number; readonly closes?: boolean }\n readonly fire?: TerrainFireResponse\n /** Linear rgb, 0..1, of the material where it is exposed. */\n readonly color: readonly [number, number, number]\n /** Surface pattern a renderer draws while the stratum is intact (`TERRAIN_PATTERNS`). */\n readonly pattern?: TerrainPattern\n /** A rigid surface cracks around a hard blow instead of only losing a bowl: lines that run out from the point (concrete, asphalt, tile, stone). */\n readonly crack?: TerrainCrackResponse\n /** A rigid layer a contact charge breaks right through once it has enough for the whole thickness (the scabbing of a slab): `explosive` only. */\n readonly breach?: TerrainBreachResponse\n /** What a foot does on it. */\n readonly footing?: TerrainFooting\n /**\n * Its rolling resistance (C_rr) to a round thing rolling on it (a can, a rod, a casing): the moment C_rr x weight x radius that slows the roll. Soft ground (sand, mud,\n * grass) gives under the roller and holds it back far more than a hard one (asphalt, concrete). Left out: the host's default (a hard floor).\n */\n readonly rolling?: number\n /**\n * Its rolling damping (1/s): the share of its spin a round thing rolling on it loses per second on top of `rolling`, from what drags more the faster it rolls (grass\n * blades, ploughed sand). Added to the roller's own. Left out: the host's default (a hard floor).\n */\n readonly rollingDamping?: number\n /** Liquid (of the fluids catalogue) a blow on it throws up. */\n readonly splash?: string\n /** Its pieces do not join the ground where they land: they stay as loose stones. */\n readonly scatters?: boolean\n /** Its pieces leave a splat on whatever they land on. */\n readonly splats?: boolean\n /** A brittle crust: each blow runs cracks this many bowl radii around it. */\n readonly cracks?: number\n /** Laid in separate pieces on a bed: a blow loosens whole pieces instead of digging a bowl. */\n readonly units?: TerrainUnits\n}\n\nexport interface TerrainCrackResponse {\n /** Metres the longest line runs for a blow of 1 MJ; it grows with the cube root of the energy. */\n readonly reach: number\n /** Metres wide the lines open at the point for 1 MJ, also by the cube root, never under a hairline. */\n readonly width: number\n /** A blow under this many joules leaves no crack (a punch on a slab). */\n readonly thresholdJoules: number\n}\n\nexport interface TerrainBreachResponse {\n /** Joules over the cube of the layer's thickness (J/m³) that break the whole layer through: for reinforced concrete about 1 kg of TNT for 12 cm. */\n readonly joulesPerCubedThickness: number\n /** Radius of the breach over the thickness at that energy; it grows with the cube root of the excess. */\n readonly radiusOverThickness: number\n}\n\nexport interface TerrainFooting {\n /** Metres the foot goes in. */\n readonly sink: number\n /** What is left of the walking speed, 0..1. */\n readonly drag: number\n /** Keeps the print of what presses it. */\n readonly prints?: boolean\n}\n\nexport interface TerrainUnits {\n /** Metres along x, in rows that shift every other one. Multiples of the cell keep the hole sharp. */\n readonly length: number\n /** Metres along z. */\n readonly width: number\n /** Joules a piece takes, added blow by blow, before it comes off its bed. */\n readonly looseJoules: number\n}\n\nexport interface TerrainFireResponse {\n /** How black it gets, 0..1: concrete only soots, wood and turf char through. */\n readonly maxScorch: number\n /** Scorch gained per second in a flame. */\n readonly scorchPerSecond: number\n /** Metres per second the flame eats away (wood char). */\n readonly burnsAway?: number\n /** Catches and carries the fire to the next cells on its own. */\n readonly flammable?: boolean\n}\n\nexport const TERRAIN_PATTERNS = ['plain', 'grass', 'soil', 'sand', 'asphalt', 'concrete', 'tile', 'planks', 'stone', 'mud', 'gravel', 'clay', 'snow', 'cobble', 'paver', 'rock'] as const\nexport type TerrainPattern = (typeof TERRAIN_PATTERNS)[number]\n\n/** One layer of a column, from the top down. */\nexport interface TerrainStratum {\n /** A `TerrainMaterial.id`. */\n readonly material: string\n /** Metres. */\n readonly thickness: number\n /** Bars inside the layer: exposed at `cover`, they make the digging `resistance` times harder. */\n readonly reinforcement?: {\n readonly material: string\n readonly cover: number\n readonly spacing: number\n readonly resistance: number\n /** Joules on one spot of bare bars before they give way (default `DEFAULT_BAR_YIELD_JOULES`). */\n readonly yieldJoules?: number\n /** Metres across one bar (default `DEFAULT_BAR_DIAMETER`): with `yieldPa` it says what weight bare bars hold. */\n readonly diameter?: number\n /** Pascals at which the steel yields (default `DEFAULT_BAR_YIELD_PA`). */\n readonly yieldPa?: number\n }\n}\n\n/** Weight standing still on the ground: a body, a fridge, a car. */\nexport interface TerrainLoad {\n readonly x: number\n readonly z: number\n /** Metres: half the side of the footprint it stands on. */\n readonly radius: number\n readonly newtons: number\n}\n\n/** What a column of ground is made of. The strata end at the digging limit: under them nothing is removed. */\nexport interface TerrainProfile {\n readonly id: string\n readonly strata: readonly TerrainStratum[]\n /** A slab with nothing under it: where its bars give way the floor opens, and the ground is this many metres further down (the floor below). Without it the ground under the slab holds it up. */\n readonly drop?: number\n /** How the untouched top layer is drawn when it is not its material's way: bare rock is stone, but not laid as paving. Dug, the material's own shows. */\n readonly surfacePattern?: TerrainPattern\n /** Water standing over the column: the strata are its bed. */\n readonly water?: TerrainWater\n}\n\nexport interface TerrainWater {\n /** A liquid of the fluids catalogue. */\n readonly liquid: string\n /** Metres from the surface to the bed. */\n readonly depth: number\n /** What is left of the walking speed, 0..1. */\n readonly drag: number\n /** Share of a blow that reaches the bed. */\n readonly blowShare: Partial<Record<TerrainBlow, number>>\n}\n\nexport interface TerrainBudget {\n /** Side in metres of the squares that hold a limited number of marks. */\n readonly markAreaSize: number\n readonly maxMarksPerArea: number\n readonly maxMarks: number\n /** Chunks a renderer redraws per frame; the rest wait. */\n readonly maxDirtyChunksPerFrame: number\n readonly maxDebris: number\n /** Thrown pieces of one blow. */\n readonly maxDebrisPerBlow: number\n /** Cells checked for sliding per frame. */\n readonly maxSlideCellsPerFrame: number\n /** Cells on fire at once. */\n readonly maxBurningCells: number\n /** Stars of cracks kept; past it the oldest goes. */\n readonly maxCracks: number\n /** Cracks, prints, ruts, splats and ripples at once; past it the oldest goes. */\n readonly maxDecals: number\n}\n\nexport interface TerrainOptions {\n /** World rectangle `[x0, z0, x1, z1]` in metres. */\n readonly bounds: readonly [number, number, number, number]\n /** Metres per cell (default 0.1). */\n readonly cellSize?: number\n /** Cells per side of a chunk (default 32). */\n readonly chunkCells?: number\n /** Which profile is where. */\n readonly layout?: GroundLayout\n /** Extra or overriding profiles, by id. */\n readonly profiles?: readonly TerrainProfile[]\n /** Extra or overriding materials, by id. */\n readonly materials?: readonly TerrainMaterial[]\n readonly budget?: Partial<TerrainBudget>\n /** Height of the untouched ground (default flat at 0). */\n readonly baseHeight?: (x: number, z: number) => number\n /** Metres per second squared. */\n readonly gravity?: number\n readonly seed?: number\n /**\n * Ground taken away from under the surface: a crater (`crater`), a slab that gave way into the void under it (`slab`), sand that slid off a slope\n * (`slide`). The host hands it to what stands there (`DestructionWorld.groundLoss`), so foundations over it settle or lose their support.\n */\n readonly onGroundLoss?: (loss: GroundLoss) => void\n}\n\n/** A shovelful (`Terrain.dig`): the blade's footprint at (x, z), how deep it goes in, where the earth is thrown (a heap on the ground there). */\nexport interface TerrainDig {\n readonly x: number\n readonly z: number\n /** Width and length of the blade's bite, metres (default 0.3 x 0.3). */\n readonly size?: readonly [number, number]\n /** How deep one shovelful goes, metres (default 0.2). */\n readonly depth?: number\n /** Where the earth lands: heaped round this point. Without it, it is lost (carried away). */\n readonly dump?: { readonly x: number; readonly z: number }\n}\n\n/** What a shovelful took. */\nexport interface TerrainDigResult {\n /** Cubic metres taken out (and heaped at `dump`). */\n readonly volume: number\n /** The material dug (the one at the bite's centre). */\n readonly material: string\n /** How hard it was against loose soil (1): a shovelful of it takes that much longer. 0 when nothing was dug. */\n readonly effort: number\n /** The material that stopped the blade (concrete, stone...), when it could not dig; `water` where the ground is under water. */\n readonly refused?: string\n /** The blade lifted it but the hole closed behind it (mud): nothing changed. */\n readonly closes?: true\n}\n\n/** Earth thrown back into a hole (`Terrain.fill`): taken from the heap round `from`, laid into the hole at (x, z), at most `volume`. */\nexport interface TerrainFill {\n readonly x: number\n readonly z: number\n readonly size?: readonly [number, number]\n readonly from: { readonly x: number; readonly z: number; readonly radius: number }\n readonly volume: number\n}\n\n/** What is missing under a disc of the ground (`Terrain.voidUnder`). */\nexport interface TerrainVoid {\n /** Metres under the untouched surface at the deepest vertex. */\n readonly depth: number\n /** Metres under the untouched surface, averaged over the disc. */\n readonly mean: number\n /** 0..1, the share of the disc's vertices that are void (dug at least `VOID_MIN_DEPTH`). */\n readonly fraction: number\n}\n\n/** A fine mark: a bullet pock or a chip, smaller than a cell. It grows with the blows on it until it is dug into the height field. */\nexport interface TerrainMark {\n readonly id: number\n x: number\n z: number\n radius: number\n depth: number\n /** The material the mark shows at the bottom. */\n material: string\n blow: TerrainBlow\n /** Blows and marks merged into this one. */\n count: number\n /** Order of creation: the oldest is the one recycled. */\n born: number\n}\n\nexport type TerrainDecalKind = 'crack' | 'print' | 'rut' | 'splat' | 'ripple'\n\n/** A mark with no depth of its own: drawn over the surface, it changes nothing that stands there. */\nexport interface TerrainDecal {\n readonly id: number\n readonly kind: TerrainDecalKind\n readonly x: number\n readonly z: number\n readonly radius: number\n /** Radians around y. */\n readonly angle: number\n /** The material whose colour it takes. */\n readonly material: string\n /** Seconds it has been there; a ripple fades with it. */\n age: number\n}\n\nexport interface TerrainDebris {\n readonly id: number\n readonly material: string\n readonly kind: TerrainDebrisKind\n readonly radius: number\n readonly position: [number, number, number]\n readonly velocity: [number, number, number]\n readonly spin: [number, number, number]\n atRest: boolean\n bounces: number\n /** Order of creation: the oldest is the one recycled. */\n readonly born: number\n}\n\n/** A star of cracks on a rigid surface. The lines themselves come from `crackLines`, drawn from the seed, so a snapshot keeps only this. */\nexport interface TerrainCrack {\n readonly id: number\n readonly x: number\n readonly z: number\n /** Metres the longest line runs. */\n reach: number\n /** Metres wide the lines are at the point. */\n width: number\n rays: number\n readonly seed: number\n readonly material: string\n /** Order of creation: the oldest is the one recycled. */\n readonly born: number\n}\n\n/** What a blow did. */\nexport interface TerrainBlowResult {\n readonly point: readonly [number, number, number]\n /** Bowl radius in metres; 0 when the blow left nothing. */\n readonly radius: number\n /** Metres removed at the point. */\n readonly depth: number\n /** Metres under the untouched surface the point is now. */\n readonly totalDepth: number\n /** Materials removed, top first, with the cubic metres of each. */\n readonly removed: readonly { readonly material: string; readonly volume: number }[]\n /** Material now exposed at the point. */\n readonly exposed: string\n /** The column has no more to give here: the slab's bottom, the end of the rock. */\n readonly atLimit: boolean\n /** Reinforcement is showing at the point. */\n readonly rebarExposed: boolean\n /** The bars gave way here and the slab opened (`TerrainProfile.drop`). */\n readonly collapsed: boolean\n /** Left a fine mark (`true`) or dug the height field (`false`). */\n readonly fine: boolean\n /** The cracks it opened or lengthened around the point, if the surface is rigid. */\n readonly crack?: TerrainCrack\n /** A contact charge broke the rigid layer right through (`TerrainMaterial.breach`). */\n readonly breached?: boolean\n /** The water the blow crossed: `level` is where the splash goes up. */\n readonly water?: { readonly liquid: string; readonly level: number }\n}\n\n/** The water standing at a point. */\nexport interface TerrainWaterHere {\n readonly liquid: string\n readonly level: number\n readonly depth: number\n}\n\nexport interface TerrainRegion {\n readonly x: number\n readonly z: number\n readonly radius: number\n}\n\nexport interface TerrainColumn {\n readonly profile: string\n readonly material: string\n readonly stratum: number\n /** Metres under the untouched surface. */\n readonly depth: number\n /** Metres that can still be dug here. */\n readonly remaining: number\n readonly scorch: number\n readonly loose: number\n}\n\nexport interface TerrainStats {\n readonly marks: number\n readonly debris: number\n readonly debrisMoving: number\n readonly dirtyChunks: number\n readonly burning: number\n}\n\nexport interface TerrainChunk {\n readonly index: number\n /** First column and row of the chunk's vertices. */\n readonly column: number\n readonly row: number\n readonly cells: number\n /** True while nothing touched it and it has one profile: one flat quad draws it. */\n readonly pristine: boolean\n}\n\nexport interface Terrain {\n readonly bounds: readonly [number, number, number, number]\n readonly cellSize: number\n readonly columns: number\n readonly rows: number\n /** Vertices per row. */\n readonly stride: number\n readonly chunkCells: number\n readonly chunksX: number\n readonly chunksZ: number\n readonly budget: TerrainBudget\n /** Per vertex: metres removed under the untouched surface. */\n readonly dug: Float32Array\n /** Per vertex: metres of loose ground heaped on top. */\n readonly loose: Float32Array\n /** Per vertex: 0..1, how burnt. */\n readonly scorch: Float32Array\n /** Per vertex: how far the bare bars have given, 0 straight, 1 or more gone. */\n readonly barBend: Float32Array\n /** Per vertex: index in `profileList`. */\n readonly profileIndex: Uint8Array\n readonly profileList: readonly TerrainProfile[]\n material(id: string): TerrainMaterial\n layout(): GroundLayout\n setLayout(layout: GroundLayout): void\n /** Height at (x, z) as things stand on it. */\n heightAt(x: number, z: number): number\n /**\n * `heightAt` over a grid, in one pass: the height at (`xs[i]`, `zs[j]`) into `out[j * xs.length + i]`, to the bit what `heightAt` answers there (the same cell, blend and\n * vertices; past the terrain, the host's `baseHeight`). For a reader of many points on a lattice (a physics engine's ground tile), which saves a call per point.\n * Not reentrant: it keeps its scratch between calls, so a `baseHeight` must not call it back.\n */\n heightGrid(xs: ArrayLike<number>, zs: ArrayLike<number>, out: Float64Array): void\n /**\n * The vertex heights under a rectangle (the cells `heightGrid` reads for any point in it), as plain numbers a worker can read the ground from (`heightPatchGrid`, to the\n * bit what `heightGrid` answers there); null when the rectangle is not wholly inside the terrain (past it the host's `baseHeight` answers). Writes into `into` when it is\n * long enough, else a new array. A 2.4 m square at 10 cm cells is 26 x 26 numbers.\n */\n heightPatch(minX: number, maxX: number, minZ: number, maxZ: number, into?: Float64Array): HeightPatch | null\n /**\n * The lowest and the highest `heightAt` can answer over the rectangle, exact bounds (the height between vertices is a blend of the four around it, so no\n * point is under the lowest or over the highest vertex of the cells the rectangle covers); null when the rectangle is not wholly inside the terrain, where the ground is the\n * host's `baseHeight` and no bound is known. Costs the vertices the rectangle covers, not a read per sample.\n */\n heightRange(minX: number, maxX: number, minZ: number, maxZ: number): { readonly low: number; readonly high: number } | null\n /** Height of vertex (column, row). */\n vertexHeight(column: number, row: number): number\n /** Material exposed at a vertex. */\n vertexMaterial(column: number, row: number): TerrainMaterial\n columnAt(x: number, z: number): TerrainColumn\n /** The rolling resistance (`TerrainMaterial.rolling`) of the material exposed at (x, z), as `columnAt` reads it, without building the column; undefined: the host's default. */\n rollingAt(x: number, z: number): number | undefined\n /** The rolling damping (`TerrainMaterial.rollingDamping`) of the material exposed at (x, z), read as `rollingAt`; undefined: the host's default. */\n rollingDampingAt(x: number, z: number): number | undefined\n contains(x: number, z: number): boolean\n /** First point of the ground along a ray, or null. */\n raycast(origin: readonly number[], direction: readonly number[], maxDistance: number): { point: [number, number, number]; distance: number; normal: [number, number, number] } | null\n /** A blow at (x, z). `energy` in joules, `direction` where it travels (it throws the pieces back along it). */\n strike(blow: TerrainBlow, spec: TerrainStrike): TerrainBlowResult\n /**\n * Opens a pit in the ground as it stands now (a shaft a blast threw its cover off): the same dig as an excavation of the layout, never less deep than the ground already is there, and\n * no ground loss. The layout is left alone, so the next `reset` closes it with the craters.\n */\n open(excavation: GroundExcavation): void\n /** A shovelful at (x, z): takes the earth down through what a shovel digs, stops at what it does not (concrete, rock), heaps it at `dump`. */\n dig(spec: TerrainDig): TerrainDigResult\n /** Earth thrown back from a heap into a hole: fills what was dug first, then heaps. Returns the cubic metres moved. */\n fill(spec: TerrainFill): number\n /** A flame over a disc for `seconds`. */\n burn(spec: { x: number; z: number; radius: number; temperature: number; seconds: number }): void\n /** Applies a world hit (`Hit` of the destruction contract); null when it does nothing to the ground. */\n applyHit(hit: Hit): TerrainBlowResult | null\n /** What stands still on the ground now. Where it stands over bare bars they sag under it, and past what they hold they give way; a slab over a void then opens. True when it opened. */\n bear(loads: readonly TerrainLoad[]): boolean\n /** How much ground is missing under the disc (x, z, radius), measured from the untouched surface. */\n voidUnder(x: number, z: number, radius: number): TerrainVoid\n /** Height a foot stands at: the ground less what it sinks in. */\n footAt(x: number, z: number): number\n /** What is left of the walking speed here, 0..1. */\n walkFactorAt(x: number, z: number): number\n /** The water standing here, or null. */\n waterAt(x: number, z: number): TerrainWaterHere | null\n /** A foot or a wheel on the ground: it leaves its print where the ground keeps one, a ripple in water. False where it leaves nothing. */\n press(spec: { x: number; z: number; radius: number; angle?: number; kind?: 'print' | 'rut' }): boolean\n /** Rings on the water at (x, z). */\n ripple(x: number, z: number, radius: number): void\n decals(): readonly TerrainDecal[]\n /** Goes up when the decals change. */\n readonly decalsVersion: number\n /** Follow the ground changing: `region` is the disc it changed in. What rests there has lost its support and must look again. Returns the unsubscribe function. */\n onDeform(listener: (region: TerrainRegion) => void): () => void\n /** Moves the pieces, the sliding ground and the fire. */\n update(dt: number): void\n /** Chunks waiting to be redrawn; every chunk at once means the floor was just laid anew (a layout, a reset). */\n readonly dirtyChunkCount: number\n /** Takes up to the budget's chunks that changed since the last call. */\n drainDirtyChunks(max?: number): TerrainChunk[]\n chunk(index: number): TerrainChunk\n marks(): readonly TerrainMark[]\n cracks(): readonly TerrainCrack[]\n /** Changes whenever a crack is added or grows, so a renderer redraws only then. */\n readonly cracksVersion: number\n debris(): readonly TerrainDebris[]\n /** Cells on fire now, as world points. */\n burningPoints(): readonly (readonly [number, number])[]\n /** Goes up when the marks change. */\n readonly marksVersion: number\n stats(): TerrainStats\n /** Back to the untouched ground. */\n reset(): void\n serialize(): TerrainSnapshot\n load(snapshot: TerrainSnapshot): void\n}\n\nexport interface TerrainSnapshot {\n readonly layout: GroundLayout\n readonly dug: readonly (readonly [number, number])[]\n readonly loose: readonly (readonly [number, number])[]\n readonly scorch: readonly (readonly [number, number])[]\n readonly barBend?: readonly (readonly [number, number])[]\n readonly marks: readonly TerrainMark[]\n readonly cracks?: readonly TerrainCrack[]\n readonly decals?: readonly TerrainDecal[]\n}\n","import type { Terrain } from './types'\n\nconst STRIDE = 0.72\nconst FOOT_LENGTH = 0.15\nconst FOOT_APART = 0.11\n\nexport interface Footprints {\n /** Call as the walker moves; it leaves a print each stride, left and right in turn. */\n update(x: number, z: number): void\n reset(): void\n}\n\n/** The trail of something walking: whoever moves on the ground reports where it is, and the ground keeps the prints it can keep. */\nexport function createFootprints(terrain: Terrain, options: { readonly stride?: number; readonly footLength?: number } = {}): Footprints {\n const stride = options.stride ?? STRIDE\n const footLength = options.footLength ?? FOOT_LENGTH\n let lastX: number | null = null\n let lastZ = 0\n let side = 1\n return {\n update(x, z) {\n if (lastX === null) {\n lastX = x\n lastZ = z\n return\n }\n const dx = x - lastX\n const dz = z - lastZ\n const walked = Math.hypot(dx, dz)\n if (walked < stride) return\n lastX = x\n lastZ = z\n // a jump of many strides is a teleport, not a walk\n if (walked > stride * 3) return\n const angle = Math.atan2(dx, dz)\n side = -side\n terrain.press({ x: x + (Math.cos(angle) * FOOT_APART * side), z: z - (Math.sin(angle) * FOOT_APART * side), radius: footLength, angle })\n },\n reset() {\n lastX = null\n },\n }\n}\n","const GRAVITY = 9.81\n/** Per second, the share of a body's speed water takes when it is all under: a body in water bobs once and stops, it does not bounce. */\nconst WATER_DRAG = 9\n/** The liquid does not throw a very light body out: past this many times its weight the push has nothing more to give. */\nconst MAX_LIFT_WEIGHTS = 1.6\n\nexport interface WaterLiftParams {\n /** Kilograms. */\n readonly mass: number\n /** Cubic metres of the whole body. */\n readonly volume: number\n /** Share of the body under the surface, 0..1. */\n readonly submerged: number\n /** Kilograms per cubic metre of the liquid. */\n readonly liquidDensity?: number\n readonly gravity?: number\n}\n\nexport interface WaterLift {\n /** Upward metres per second squared the liquid gives the body. */\n readonly acceleration: number\n /** Per second, the part of the speed the liquid takes. */\n readonly drag: number\n /** Lighter than the liquid it displaces. */\n readonly floats: boolean\n}\n\n/** Archimedes on a body in a liquid: what it displaces lifts it, so a light log floats and a concrete block goes to the bed. */\nexport function waterLift(params: WaterLiftParams): WaterLift {\n const density = params.liquidDensity ?? 1000\n const submerged = Math.max(0, Math.min(1, params.submerged))\n const mass = Math.max(1e-6, params.mass)\n const gravity = params.gravity ?? GRAVITY\n return {\n acceleration: Math.min(MAX_LIFT_WEIGHTS * gravity, (density * params.volume * submerged * gravity) / mass),\n drag: WATER_DRAG * submerged,\n floats: mass / Math.max(1e-9, params.volume) < density,\n }\n}\n","/**\n * The engine collides with a tile's ground at a coarser grid than the tile is read at, as Unreal's \"Simple Collision\" mip level 1 does: every second corner of the 2.5 cm\n * grid, so a 5 cm height field. The read grid stays where the steps are found and the solid under the ground is made; the engine's narrow phase meets a quarter of the\n * triangles under a piece (the frame after a blast was mostly a piece resting on 2.5 cm triangles, T3.8ah). Owner decision 2026-11-17. The collision surface is off the drawn\n * ground by the bend of the ground across one of its cells: a tile keeps the coarse field only where that, with the engine's own 8 bit steps, is within 5 mm everywhere\n * on it, and has no step (`collisionFieldOf`); else it collides at the read grid.\n */\nexport const GROUND_COLLISION_CELL = 0.05\n\n/** The most (m) the collision surface may be off the drawn ground anywhere on a tile for the tile to collide at `GROUND_COLLISION_CELL` (the owner's bound). */\nexport const COLLISION_TOLERANCE = 0.005\n/**\n * A tile on the read grid goes to the coarse field only under this (m): one near the bound does not change field at every change of its ground (the bound stays hard). Not\n * lower: a room crater tile is 4.47 mm off at 5 cm, and a piece rests on it the frame after the blast.\n */\nexport const COLLISION_ENTER = 0.0045\n/** Samples a side of the engine's height field blocks (`game-physics-jolt` `HEIGHT_BLOCK`): each block's heights are 8 bit steps of its own range. */\nconst ENGINE_BLOCK = 4\n\n/** How many read cells (of `readCell` m, `cells` a side) a collision cell would span: 1 keeps the read grid (a collision cell that does not divide the tile). */\nexport const coarseStep = (cells: number, readCell: number): number => {\n const k = Math.max(1, Math.round(GROUND_COLLISION_CELL / readCell))\n return cells % k === 0 ? k : 1\n}\n\n/** A tile's collision field: every `step`-th corner of its read heights (1: the heights themselves). */\nexport interface CollisionField {\n readonly step: number\n readonly field: Float32Array\n}\n\n/**\n * A tile's collision field: the coarse one (`GROUND_COLLISION_CELL`) when the tile has no step boxes (a step's edge is between read corners, and a coarser field ramps or grooves\n * across it: 14 cm by a terrace's wall) and the coarse surface, on either diagonal and with the engine's 8 bit steps, is within `COLLISION_TOLERANCE` of the drawn ground at\n * every read corner (both are flat between them); within `COLLISION_ENTER` when the tile was on the read grid before (`wasCoarse` false: a fresh tile is one); else the read\n * grid itself.\n */\nexport const collisionFieldOf = (heights: Float32Array, cells: number, readCell: number, hasSteps: boolean, wasCoarse = false): CollisionField => {\n const k = coarseStep(cells, readCell)\n const fine = { step: 1, field: heights }\n if (k === 1 || hasSteps || heights.length === 0) return fine\n const m = cells + 1\n const get = (p: number, q: number): number => heights[q * m + p]!\n let off = 0\n for (let q = 0; q <= cells; q++) {\n for (let p = 0; p <= cells; p++) {\n collisionBoth(get, p, q, k)\n const h = heights[q * m + p]!\n off = Math.max(off, h - both[0]!, both[1]! - h)\n }\n }\n const field = collisionOf(heights, cells, k)\n return off + quantumOf(field, cells / k) <= (wasCoarse ? COLLISION_TOLERANCE : COLLISION_ENTER) ? { step: k, field } : fine\n}\n\n/** The most the engine's 8 bit heights may be off the field's own, over its blocks: half a step of a block's range. */\nconst quantumOf = (field: Float32Array, cells: number): number => {\n const m = cells + 1\n let most = 0\n for (let bj = 0; bj < cells; bj += ENGINE_BLOCK) {\n for (let bi = 0; bi < cells; bi += ENGINE_BLOCK) {\n let lo = Infinity, hi = -Infinity\n for (let j = bj; j <= Math.min(cells, bj + ENGINE_BLOCK); j++) {\n for (let i = bi; i <= Math.min(cells, bi + ENGINE_BLOCK); i++) {\n lo = Math.min(lo, field[j * m + i]!)\n hi = Math.max(hi, field[j * m + i]!)\n }\n }\n most = Math.max(most, (hi - lo) / 510)\n }\n }\n return most\n}\n\n/** The collision field of a tile's heights (`(cells + 1)^2`, x fastest): every `k`-th corner, `(cells / k + 1)^2` of them. */\nexport const collisionOf = (heights: Float32Array, cells: number, k: number): Float32Array => {\n if (k === 1) return heights\n const m = cells + 1\n const n = cells / k + 1\n const out = new Float32Array(n * n)\n for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) out[j * n + i] = heights[j * k * m + i * k]!\n return out\n}\n\n/**\n * The collision surface at the read corner (`p`, `q`) (any integers: past the tile too), from `get` of the corners on the collision grid (multiples of `k`): the lower of the\n * two ways the engine may cut the collision cell into triangles, so whichever it uses is no lower than this.\n */\nexport const collisionAt = (get: (p: number, q: number) => number, p: number, q: number, k: number): number => {\n collisionBoth(get, p, q, k)\n return both[0]!\n}\n\n/** Where `collisionBoth` writes, the lower then the higher (one array for the module: no array per corner). */\nconst both = new Float64Array(2)\n\n/** The collision surface at the read corner (`p`, `q`) on the two ways a collision cell may be cut, into `both`: the lower then the higher. */\nconst collisionBoth = (get: (p: number, q: number) => number, p: number, q: number, k: number): void => {\n const p0 = Math.floor(p / k) * k, q0 = Math.floor(q / k) * k\n const u = (p - p0) / k, v = (q - q0) / k\n if (u === 0 && v === 0) {\n both[0] = both[1] = get(p0, q0)\n return\n }\n // on a collision cell's edge only that edge's corners are asked for (the tile's last row and column have no cell past them)\n const p1 = u === 0 ? p0 : p0 + k, q1 = v === 0 ? q0 : q0 + k\n const h00 = get(p0, q0), h10 = get(p1, q0), h01 = get(p0, q1), h11 = get(p1, q1)\n // the diagonal from (0, 0) to (1, 1), and the one from (1, 0) to (0, 1)\n const main = u >= v ? h00 + u * (h10 - h00) + v * (h11 - h10) : h00 + v * (h01 - h00) + u * (h11 - h01)\n const cross = u + v <= 1 ? h00 + u * (h10 - h00) + v * (h01 - h00) : h11 + (1 - u) * (h01 - h11) + (1 - v) * (h10 - h11)\n both[0] = Math.min(main, cross)\n both[1] = Math.max(main, cross)\n}\n\n/**\n * A tile's read heights lowered, corner by corner, to the collision surface where it is lower: a grid nothing over which (taken flat between corners, as the engine takes\n * both surfaces) rises over either surface. What must stay under the ground (the solid under it, §12) is made over this.\n */\nexport const underBoth = (heights: Float32Array, cells: number, k: number): Float32Array => {\n if (k === 1) return heights\n const m = cells + 1\n const get = (p: number, q: number): number => heights[q * m + p]!\n const out = new Float32Array(m * m)\n for (let q = 0; q <= cells; q++) for (let p = 0; p <= cells; p++) out[q * m + p] = Math.min(heights[q * m + p]!, collisionAt(get, p, q, k))\n return out\n}\n","/** How far (m) a sample may leave its cell's corners before the cell counts as holding a step. */\nexport const STEP_TOLERANCE = 0.005\n\n/**\n * Whether a cell holds a step, from its nine samples in `s`: the corners (x0 z0, x1 z0, x0 z1, x1 z1), the centre, and the middles of its edges (z0, z1, x0, x1). A step\n * moves the centre or an edge's middle off its corners. The one test the tile (`engine-ground`) and the ring past it (`engine-ground-ring`) make, so both see the same cells.\n */\nconst off = (a: number, b: number): boolean => Math.abs(a - b) > STEP_TOLERANCE\n\nexport const holdsStep = (s: ArrayLike<number>): boolean => {\n const c00 = s[0]!, c10 = s[1]!, c01 = s[2]!, c11 = s[3]!\n return off(s[4]!, (c00 + c10 + c01 + c11) / 4) || off(s[5]!, (c00 + c10) / 2) || off(s[6]!, (c01 + c11) / 2) || off(s[7]!, (c00 + c01) / 2) || off(s[8]!, (c10 + c11) / 2)\n}\n","import { collisionAt } from './engine-ground-collision'\nimport { holdsStep } from './engine-ground-step'\n\n/**\n * The ground a tile's solid reads around the tile: its own heights inside, and past its edges, as far as `SOLID_RING`, the ground the neighbour tile is made from (`groundAt`),\n * read only where a block of the solid reaches and once each. Every sample read past the edge is kept (`read`): the solid depends on them, so a change there makes it again.\n */\n\n/**\n * How far (m) past its tile's edges a block of the solid may reach: a cell of overlap, the skew of a top turned about both axes (a cell or two at the edge's block sizes), and a\n * box at least 15 cm deep at any slope (`engine-ground-solid` caps the depth of a box that would lean further). The host's changes this close to a tile make its solid again.\n */\nexport const SOLID_RING = 0.2\n/** One cell's nine samples, for `holdsStep`. */\nconst nine = new Float64Array(9)\n\n/**\n * Where the ring reads the ground past the tile's edges: the host's `groundAt`, or a band read ahead of time (`engine-ground-job` `readGroundBand`), one height per half cell\n * `(a, b)` at `(b + 2 * ring) * width + a + 2 * ring` (`width` = `2 * (cells + 2 * ring) + 1`), each the very height `groundAt` answers there. A worker has no `groundAt`.\n */\nexport type GroundSource = ((x: number, z: number) => number) | Float64Array\n\nexport interface GroundRing {\n /** How many cells the ring is wide. */\n readonly cells: number\n /** The four corners (`(i, j)`, `(i + 1, j)`, `(i, j + 1)`, `(i + 1, j + 1)`) of a cell past the tile's edge into `out`; a cell holding a step (`holdsStep`, as the neighbour builds it) has its lowest of nine samples at all four. */\n cell(i: number, j: number, out: Float64Array): void\n /** The samples read past the edge: x, z and height, three numbers each. */\n readonly read: number[]\n}\n\n// the samples and cells read for the ring being made, marked by the build they belong to (one at a time), so a ring costs no new arrays\nlet build = 0\nlet heldSamples = new Float64Array(0)\nlet sampleBuild = new Uint32Array(0)\nlet heldCells = new Float64Array(0)\nlet cellBuild = new Uint32Array(0)\n\n/**\n * `heights` are the tile's own (already under its collision field), `fieldStep` how many read cells a neighbour's coarse collision cell spans: past the edge a corner is the lower of\n * the ground there and that coarse field at it (the neighbour collides with it or with the ground itself).\n */\nexport const createGroundRing = (heights: Float32Array, cells: number, x0: number, z0: number, cell: number, groundAt: GroundSource, fieldStep = 1): GroundRing => {\n const band = typeof groundAt === 'function' ? null : groundAt\n const ring = Math.round(SOLID_RING / cell)\n const m = cells + 1\n const width = 2 * (cells + 2 * ring) + 1\n const across = cells + 2 * ring\n if (sampleBuild.length < width * width) {\n heldSamples = new Float64Array(width * width)\n sampleBuild = new Uint32Array(width * width)\n }\n if (cellBuild.length < across * across) {\n heldCells = new Float64Array(4 * across * across)\n cellBuild = new Uint32Array(across * across)\n }\n const mark = ++build\n const read: number[] = []\n /** The ground at the half cell (`a` / 2, `b` / 2): the tile's own height at its corners, the neighbour's ground elsewhere. */\n const half = (a: number, b: number): number => {\n if (a % 2 === 0 && b % 2 === 0 && a >= 0 && b >= 0 && a <= 2 * cells && b <= 2 * cells) return heights[(b / 2) * m + a / 2]!\n const key = (b + 2 * ring) * width + a + 2 * ring\n if (sampleBuild[key] === mark) return heldSamples[key]!\n const x = x0 + (a / 2) * cell\n const z = z0 + (b / 2) * cell\n const h = band === null ? (groundAt as (x: number, z: number) => number)(x, z) : band[key]!\n heldSamples[key] = h\n sampleBuild[key] = mark\n read.push(x, z, h)\n return h\n }\n /** The ground at the read corner (`p`, `q`). */\n const fine = (p: number, q: number): number => half(2 * p, 2 * q)\n return {\n cells: ring,\n read,\n cell(i, j, out) {\n const key = (j + ring) * across + i + ring\n if (cellBuild[key] !== mark) {\n const a = 2 * i, b = 2 * j\n nine[0] = half(a, b)\n nine[1] = half(a + 2, b)\n nine[2] = half(a, b + 2)\n nine[3] = half(a + 2, b + 2)\n nine[4] = half(a + 1, b + 1)\n nine[5] = half(a + 1, b)\n nine[6] = half(a + 1, b + 2)\n nine[7] = half(a, b + 1)\n nine[8] = half(a + 2, b + 1)\n // a cell the neighbour builds as a step: where the step runs in it is not known, so the ground there is no lower than its lowest sample\n const step = holdsStep(nine)\n let floor = Infinity\n for (let k = 0; k < 9; k++) floor = Math.min(floor, nine[k]!)\n const corner = (p: number, q: number, h: number): number => (fieldStep === 1 ? h : Math.min(h, collisionAt(fine, p, q, fieldStep)))\n const c00 = corner(i, j, nine[0]!), c10 = corner(i + 1, j, nine[1]!), c01 = corner(i, j + 1, nine[2]!), c11 = corner(i + 1, j + 1, nine[3]!)\n heldCells[4 * key] = step ? floor : c00\n heldCells[4 * key + 1] = step ? floor : c10\n heldCells[4 * key + 2] = step ? floor : c01\n heldCells[4 * key + 3] = step ? floor : c11\n cellBuild[key] = mark\n }\n for (let k = 0; k < 4; k++) out[k] = heldCells[4 * key + k]!\n },\n }\n}\n","import type { GroundRing } from './engine-ground-ring'\n\n/**\n * How far a turned box rises above the ground, over every column it has a point in, its leaning sides as much as its top: what it must be lowered by to be under the ground\n * everywhere (§12). The ground between a cell's corners is flat (the engine's two triangles, or bilinear), so a plane rises over it the most at a corner.\n * - Its top: the top's plane over every corner under the top's extent.\n * - Its sides, which lean uphill under the top: the box is its top slid down along -n, so where the ground over the box's shadow is nowhere steeper than the top's slope\n * allows (1 / its slope), no point of it is further over the ground than its top is. Else every cell of the shadow: a column's highest point is under each face that\n * looks up (the top, and the uphill side of each tilted axis), so over a cell under the lowest of those planes, found from the top down over a pyramid of planes under the\n * tile's ground (a block of cells whose plane is above every plane of the box over it is skipped whole).\n * - Past the tile's edges, every cell of the shadow there, over the ring's ground (`engine-ground-ring`).\n */\n\n/** A box: its centre, axes (x, y, z: the y axis is the normal of its top) and half sizes. */\nexport interface ReachBox {\n readonly c: ArrayLike<number>\n readonly axes: ReadonlyArray<ArrayLike<number>>\n readonly half: ArrayLike<number>\n}\n\n/**\n * Under each block of 2^l by 2^l cells (l from 1 up to one block over the whole tile), a plane no sample of the block is under: the block's corner slopes, lowered to its\n * lowest sample. Three numbers a block (its height at the block's first corner, and its slopes along x and z per cell), made when first asked for: over a slope or a\n * crater's wall the plane follows the ground, so a box whose planes are under it there is skipped whole.\n */\nexport interface LowPyramid {\n readonly heights: Float32Array\n readonly cells: number\n readonly sizes: readonly number[]\n readonly planes: readonly Float64Array[]\n /** The square of the steepest the ground is (m per m, any way) over each block: a cell's from its edges (its two triangles, or bilinear, are no steeper), a block's the steepest of its four. */\n readonly steepest: readonly Float64Array[]\n}\n\nexport const buildLowPyramid = (heights: Float32Array, cells: number, cell: number): LowPyramid => {\n const m = cells + 1\n const first = new Float64Array(cells * cells)\n for (let j = 0; j < cells; j++) {\n for (let i = 0; i < cells; i++) {\n const h00 = heights[j * m + i]!, h10 = heights[j * m + i + 1]!, h01 = heights[(j + 1) * m + i]!, h11 = heights[(j + 1) * m + i + 1]!\n const dx = Math.max(Math.abs(h10 - h00), Math.abs(h11 - h01)), dz = Math.max(Math.abs(h01 - h00), Math.abs(h11 - h10))\n first[j * cells + i] = (dx * dx + dz * dz) / (cell * cell)\n }\n }\n const sizes: number[] = [cells]\n const planes: Float64Array[] = [new Float64Array(0)]\n const steepest: Float64Array[] = [first]\n for (let s = 2; s < 2 * cells; s *= 2) {\n const below = steepest[steepest.length - 1]!\n const n = sizes[sizes.length - 1]!\n const k = Math.ceil(cells / s)\n const level = new Float64Array(k * k)\n for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) level[(j >> 1) * k + (i >> 1)] = Math.max(level[(j >> 1) * k + (i >> 1)]!, below[j * n + i]!)\n sizes.push(k)\n planes.push(new Float64Array(3 * k * k).fill(NaN))\n steepest.push(level)\n }\n return { heights, cells, sizes, planes, steepest }\n}\n\n/** Whether the ground is steeper than `limit` (m per m) anywhere over the cells `ia`..`ib` (not included) by `ja`..`jb`. */\n// the question `steeperOver` is asking, for `visit` (one at a time)\nlet steepPyramid: LowPyramid | null = null\nlet steepSquare = 0\nlet steepIa = 0, steepIb = 0, steepJa = 0, steepJb = 0\n\nconst visit = (l: number, bi: number, bj: number): boolean => {\n const pyramid = steepPyramid!\n if (pyramid.steepest[l]![bj * pyramid.sizes[l]! + bi]! <= steepSquare) return false\n const s = 1 << l\n const a = bi * s, c = bj * s\n const b = Math.min(pyramid.cells, a + s), d = Math.min(pyramid.cells, c + s)\n if (a >= steepIb || b <= steepIa || c >= steepJb || d <= steepJa) return false\n if (l === 0) return true\n for (let dj = 0; dj < 2; dj++) for (let di = 0; di < 2; di++) if (visit(l - 1, 2 * bi + di, 2 * bj + dj)) return true\n return false\n}\n\nconst steeperOver = (pyramid: LowPyramid, ia: number, ib: number, ja: number, jb: number, limit: number): boolean => {\n steepPyramid = pyramid\n steepSquare = limit * limit\n steepIa = ia\n steepIb = ib\n steepJa = ja\n steepJb = jb\n const steeper = visit(pyramid.sizes.length - 1, 0, 0)\n // the last pyramid is not kept past the call (§8)\n steepPyramid = null\n return steeper\n}\n\n/** Where the plane under the block (`bi`, `bj`) of level `l` is in `pyramid.planes[l]`, made now if it was not. */\nconst planeUnder = (pyramid: LowPyramid, l: number, bi: number, bj: number): number => {\n const level = pyramid.planes[l]!\n const at = 3 * (bj * pyramid.sizes[l]! + bi)\n if (!Number.isNaN(level[at]!)) return at\n const { heights, cells } = pyramid\n const m = cells + 1\n const s = 1 << l\n const ia = bi * s, ja = bj * s, ib = Math.min(cells, ia + s), jb = Math.min(cells, ja + s)\n const h00 = heights[ja * m + ia]!, h10 = heights[ja * m + ib]!, h01 = heights[jb * m + ia]!, h11 = heights[jb * m + ib]!\n const sx = (h10 - h00 + h11 - h01) / 2 / (ib - ia), sz = (h01 - h00 + h11 - h10) / 2 / (jb - ja)\n let under = 0\n for (let j = ja; j <= jb; j++) for (let i = ia; i <= ib; i++) under = Math.min(under, heights[j * m + i]! - (h00 + sx * (i - ia) + sz * (j - ja)))\n level[at] = h00 + under\n level[at + 1] = sx\n level[at + 2] = sz\n return at\n}\n\nexport interface ReachTile {\n readonly heights: Float32Array\n readonly cells: number\n readonly x0: number\n readonly z0: number\n readonly cell: number\n readonly pyramid: LowPyramid\n readonly ring: GroundRing\n}\n\nexport interface Reach {\n /** The most the box rises over the ground of the tile's cells (0 when it is nowhere above), and over the ring's cells past its edges. */\n readonly tile: number\n readonly ring: number\n}\n\nconst corner4 = new Float64Array(4)\n/** A block whose bound is within this (m) of the most found is skipped: the heights are 32 bit floats, and a plane through them is that close to a plane under them. */\nconst PRUNE_SLACK = 1e-6\n// one box at a time: its planes (a, bx, bz each), the directions of its shadow's sides (x, z each) and its extent along each (low, high)\nconst planes = new Float64Array(9)\nconst dirs = new Float64Array(10)\nconst spans = new Float64Array(10)\nlet planeCount = 0\nlet dirCount = 0\n\n/** Whether the rectangle and the box's shadow are apart along one of its sides' directions. */\nconst apart = (xa: number, xb: number, za: number, zb: number): boolean => {\n for (let d = 0; d < dirCount; d += 2) {\n const dx = dirs[d]!, dz = dirs[d + 1]!\n const lo = (dx > 0 ? xa * dx : xb * dx) + (dz > 0 ? za * dz : zb * dz)\n const hi = (dx > 0 ? xb * dx : xa * dx) + (dz > 0 ? zb * dz : za * dz)\n if (hi < spans[d]! - 1e-9 || lo > spans[d + 1]! + 1e-9) return true\n }\n return false\n}\n\n/** The least, over the box's planes, of the most each rises over the four corner heights (`corner4`) of the rectangle. */\nconst over = (xa: number, xb: number, za: number, zb: number): number => {\n let best = Infinity\n for (let p = 0; p < planeCount; p += 3) {\n const a = planes[p]!, bx = planes[p + 1]!, bz = planes[p + 2]!\n const most = Math.max(a + bx * xa + bz * za - corner4[0]!, a + bx * xb + bz * za - corner4[1]!, a + bx * xa + bz * zb - corner4[2]!, a + bx * xb + bz * zb - corner4[3]!)\n if (most < best) best = most\n }\n return best\n}\n\n// the tile and box `search` walks (one at a time): the top's own extent in cells (from, to along x, then z), and the most found so far\nlet searchTile: ReachTile | null = null\nconst searchTop = new Int32Array(4)\nlet searchMost = 0\n\n/** The cell (`ia`, `ja`): its corners, and how far the box rises over them. */\nconst leaf = (ia: number, ja: number): void => {\n const { heights, cells, x0, z0, cell } = searchTile!\n const m = cells + 1\n const xa = x0 + ia * cell, za = z0 + ja * cell\n corner4[0] = heights[ja * m + ia]!\n corner4[1] = heights[ja * m + ia + 1]!\n corner4[2] = heights[(ja + 1) * m + ia]!\n corner4[3] = heights[(ja + 1) * m + ia + 1]!\n const e = over(xa, xa + cell, za, za + cell)\n if (e > searchMost) searchMost = e\n}\n\n/** The block (`bi`, `bj`) of level `l`, skipped when the box is apart from it or no higher over its low plane than the most found already, else its four. */\nconst search = (l: number, bi: number, bj: number): void => {\n const { cells, x0, z0, cell, pyramid } = searchTile!\n const s = 1 << l\n const ia = bi * s, ja = bj * s\n if (ia >= cells || ja >= cells) return\n const ib = Math.min(cells, ia + s), jb = Math.min(cells, ja + s)\n if (ia >= searchTop[0]! && ib <= searchTop[1]! && ja >= searchTop[2]! && jb <= searchTop[3]!) return\n const xa = x0 + ia * cell, xb = x0 + ib * cell, za = z0 + ja * cell, zb = z0 + jb * cell\n if (apart(xa, xb, za, zb)) return\n if (l === 0) return leaf(ia, ja)\n const level = pyramid.planes[l]!\n const at = planeUnder(pyramid, l, bi, bj)\n const h = level[at]!, sx = level[at + 1]!, sz = level[at + 2]!\n corner4[0] = h\n corner4[1] = h + sx * (ib - ia)\n corner4[2] = h + sz * (jb - ja)\n corner4[3] = h + sx * (ib - ia) + sz * (jb - ja)\n if (over(xa, xb, za, zb) <= searchMost + PRUNE_SLACK) return\n for (let dj = 0; dj < 2; dj++) for (let di = 0; di < 2; di++) search(l - 1, 2 * bi + di, 2 * bj + dj)\n}\n\nexport const reachOf = (box: ReachBox, t: ReachTile): Reach => {\n const { heights, cells, x0, z0, cell, pyramid, ring } = t\n const m = cells + 1\n // the planes over the box's columns, y <= a + bx x + bz z: one per axis, the face of it that looks up\n planeCount = 0\n for (let k = 0; k < 3; k++) {\n const a = box.axes[k]!\n if (Math.abs(a[1]!) < 1e-9) continue\n const bx = -a[0]! / a[1]!, bz = -a[2]! / a[1]!\n planes[planeCount++] = box.c[1]! + box.half[k]! / Math.abs(a[1]!) - bx * box.c[0]! - bz * box.c[2]!\n planes[planeCount++] = bx\n planes[planeCount++] = bz\n }\n // the box's shadow as a convex polygon: its extent along x, z and across each axis seen from above\n dirs[0] = 1\n dirs[1] = 0\n dirs[2] = 0\n dirs[3] = 1\n dirCount = 4\n for (const a of box.axes) {\n const l = Math.hypot(a[0]!, a[2]!)\n if (l < 1e-9) continue\n dirs[dirCount++] = -a[2]! / l\n dirs[dirCount++] = a[0]! / l\n }\n for (let d = 0; d < dirCount; d += 2) {\n const dx = dirs[d]!, dz = dirs[d + 1]!\n let r = 0\n for (let k = 0; k < 3; k++) r += box.half[k]! * Math.abs(box.axes[k]![0]! * dx + box.axes[k]![2]! * dz)\n const mid = box.c[0]! * dx + box.c[2]! * dz\n spans[d] = mid - r\n spans[d + 1] = mid + r\n }\n let inTile = 0\n // under the top's own extent, the top's plane over every corner (each cell's most is at a corner): the most found there skips most of the rest\n const n = box.axes[1]!, ax = box.axes[0]!, az = box.axes[2]!\n const tx = box.c[0]! + n[0]! * box.half[1]!, ty = box.c[1]! + n[1]! * box.half[1]!, tz = box.c[2]! + n[2]! * box.half[1]!\n const rx = box.half[0]! * Math.abs(ax[0]!) + box.half[2]! * Math.abs(az[0]!), rz = box.half[0]! * Math.abs(ax[2]!) + box.half[2]! * Math.abs(az[2]!)\n const ta = Math.max(0, Math.floor((tx - rx - x0) / cell)), tb = Math.min(cells, Math.ceil((tx + rx - x0) / cell))\n const sa = Math.max(0, Math.floor((tz - rz - z0) / cell)), sb = Math.min(cells, Math.ceil((tz + rz - z0) / cell))\n const bx = -n[0]! / n[1]!, bz = -n[2]! / n[1]!\n for (let j = sa; j <= sb; j++) {\n for (let i = ta; i <= tb; i++) {\n const e = ty + bx * (x0 + i * cell - tx) + bz * (z0 + j * cell - tz) - heights[j * m + i]!\n if (e > inTile) inTile = e\n }\n }\n // the box is its top slid down along -n: a point of it a slide s from the top at q stands s n_y under the top, over ground at most s |n_h| (the steepest) under q's.\n // Where the ground is nowhere steeper than 1 / (its top's slope), no point of the box is further over the ground than its top over its own extent (all in the tile)\n const ia = Math.floor((spans[0]! - x0) / cell), ib = Math.ceil((spans[1]! - x0) / cell)\n const ja = Math.floor((spans[2]! - z0) / cell), jb = Math.ceil((spans[3]! - z0) / cell)\n const within = ia >= 0 && ja >= 0 && ib <= cells && jb <= cells\n if (within && !steeperOver(pyramid, ia, ib, ja, jb, n[1]! / Math.max(1e-12, Math.hypot(n[0]!, n[2]!)))) return { tile: inTile, ring: 0 }\n searchTile = t\n searchTop[0] = ta\n searchTop[1] = tb\n searchTop[2] = sa\n searchTop[3] = sb\n searchMost = inTile\n // else every cell of its shadow, from the level whose blocks are as wide as the shadow's extent along x and z, over the (at most four) of them it covers\n const ua = Math.max(0, ia), ub = Math.min(cells, ib), va = Math.max(0, ja), vb = Math.min(cells, jb)\n if (ua < ub && va < vb) {\n let l = 0\n while (1 << l < Math.max(ub - ua, vb - va) && l < pyramid.sizes.length - 1) l++\n for (let bj = va >> l; bj <= (vb - 1) >> l; bj++) for (let bi = ua >> l; bi <= (ub - 1) >> l; bi++) search(l, bi, bj)\n }\n inTile = searchMost\n // the last tile (and the host's ground its ring holds) is not kept past the call (§8)\n searchTile = null\n // past the edges: the ring's cells the shadow's extent reaches\n let inRing = 0\n const r = ring.cells\n if (within) return { tile: inTile, ring: 0 }\n for (let j = Math.max(-r, ja); j < Math.min(cells + r, jb); j++) {\n const across = j >= 0 && j < cells\n for (let i = Math.max(-r, ia); i < Math.min(cells + r, ib); i++) {\n // over the tile, along the row: on to its far edge\n if (across && i >= 0 && i < cells) i = cells\n if (i >= Math.min(cells + r, ib)) break\n const xa = x0 + i * cell, za = z0 + j * cell\n if (apart(xa, xa + cell, za, za + cell)) continue\n ring.cell(i, j, corner4)\n const e = over(xa, xa + cell, za, za + cell)\n if (e > inRing) inRing = e\n }\n }\n return { tile: inTile, ring: inRing }\n}\n","import { coarseStep, underBoth } from './engine-ground-collision'\nimport { createGroundRing } from './engine-ground-ring'\nimport type { GroundSource } from './engine-ground-ring'\nimport { buildLowPyramid, reachOf } from './engine-ground-reach'\n\n/**\n * The solid under a height field. Jolt's height field is a surface: a body that ends up wholly below it (ground raised under a sleeping piece, a piece that\n * tunnelled) has nothing to push it out and falls for good. Under the surface of a tile there are blocks, from the lowest ground of the tile less `SOLID_DEPTH`\n * up to a top close under the surface and never above it (§12). A block is split until a plane through its corners is within `SOLID_RELIEF` of the surface or it is\n * `SOLID_MIN_CELLS` cells wide. A level block is a box topped at its lowest ground less `SOLID_MARGIN`; a sloped block is one box turned to its corner plane, its top that\n * plane over the block and a cell past it each way (turned boxes side by side lean apart under their tops: what is pushed out sideways meets the next one), lowered by the\n * most any point of it, top or leaning side, rises over the ground under it (`engine-ground-reach`) and `SOLID_MARGIN`. Where it reaches past the tile, the ground there is\n * the neighbour's (`engine-ground-ring`), read up to `SOLID_RING` out; a box that would lean further is made shallower. Under each turned box is its block's upright box\n * (topped at the block's lowest ground less `SOLID_MARGIN`): turned boxes side by side part under their tops, and what slips between them rests on it, its top no further\n * under the ground than the block's relief and its own size.\n * Every block is boxes: a sloped one used to be a prism (a convex hull each), and a crater tile's 400 hulls were most of the frame after the blast (T3.8ag).\n */\n\n/** How far (m) under the lowest corner of its tile the solid goes. */\nexport const SOLID_DEPTH = 0.5\n/** How far (m) under the surface a block's top may be before the block is split, unless it is already `SOLID_MIN_CELLS` cells wide. */\nconst SOLID_RELIEF = 0.005\nconst SOLID_MIN_CELLS = 3\n/**\n * A top is this far (m) under the lowest ground it stands for: 2 mm put the solid in the contacts of what rests on the surface and the bowl's seed 18 gained 4 cm. The engine\n * holds a height field's samples in 8 bit steps of each 4-sample block's range, up to half a step off (range / 510: 0.15 mm on a 0.75 slope at 2.5 cm, 0.3 mm at 5 cm), well\n * inside this margin.\n */\nexport const SOLID_MARGIN = 0.005\n/** The thinnest (m) a turned box is made; where that would lean past the ring, the block is split, or (at its smallest) left to its upright box. */\nconst SOLID_THINNEST = 0.05\n/** How much (m) more a block's box must be lowered for the ground past the tile than for its own before the block is split, so a fold at the seam lowers a narrow box only. */\nconst SEAM_SPLIT = 0.01\n/** Numbers per block in `SolidVolume.boxes`. */\nexport const SOLID_STRIDE = 10\n\nexport interface SolidVolume {\n /** The blocks: centre x, y, z, half x, y, z and turn x, y, z, w (`SOLID_STRIDE` numbers each); the box's own y is the normal of its top. */\n readonly boxes: readonly number[] | Float64Array\n /** The ground read past the tile's edges, x, z and height each (`engine-ground-ring`): the blocks are made again when one of these changes. */\n readonly ring: readonly number[] | Float64Array\n}\n\nexport const NO_SOLID: SolidVolume = { boxes: [], ring: [] }\n\n/** The unit vector along (x, y, z), into `out`. */\nconst unitInto = (out: Float64Array, x: number, y: number, z: number): Float64Array => {\n const l = Math.hypot(x, y, z)\n out[0] = x / l\n out[1] = y / l\n out[2] = z / l\n return out\n}\n\n// one block at a time: its corner plane's slopes, and the box the reach is asked about (filled in place, no arrays per block)\nconst slopes = new Float64Array(2)\nconst reachAxes = [new Float64Array(3), new Float64Array(3), new Float64Array(3)] as const\nconst reachBox = { c: new Float64Array(3), axes: [reachAxes[0], reachAxes[1], reachAxes[2]], half: new Float64Array(3) }\n\n/** The quaternion of the turn whose columns are the axes `a` (x), `b` (y) and `c` (z). */\nconst quatOfAxes = (a: ArrayLike<number>, b: ArrayLike<number>, c: ArrayLike<number>): [number, number, number, number] => {\n const m00 = a[0]!, m10 = a[1]!, m20 = a[2]!, m01 = b[0]!, m11 = b[1]!, m21 = b[2]!, m02 = c[0]!, m12 = c[1]!, m22 = c[2]!\n const trace = m00 + m11 + m22\n if (trace > 0) {\n const s = 0.5 / Math.sqrt(trace + 1)\n return [(m21 - m12) * s, (m02 - m20) * s, (m10 - m01) * s, 0.25 / s]\n }\n if (m00 > m11 && m00 > m22) {\n const s = 2 * Math.sqrt(1 + m00 - m11 - m22)\n return [0.25 * s, (m01 + m10) / s, (m02 + m20) / s, (m21 - m12) / s]\n }\n if (m11 > m22) {\n const s = 2 * Math.sqrt(1 + m11 - m00 - m22)\n return [(m01 + m10) / s, 0.25 * s, (m12 + m21) / s, (m02 - m20) / s]\n }\n const s = 2 * Math.sqrt(1 + m22 - m00 - m11)\n return [(m02 + m20) / s, (m12 + m21) / s, 0.25 * s, (m10 - m01) / s]\n}\n\n/** How thick (m) a box whose bottom moves by `lean` per metre of thickness may be and stay within `lo`..`hi`, its top spanning `low`..`high` (no thickness when the top does not fit). */\nconst thickWithin = (lean: number, low: number, high: number, lo: number, hi: number): number => {\n if (low < lo || high > hi) return -Infinity\n return lean > 1e-12 ? (hi - high) / lean : lean < -1e-12 ? (low - lo) / -lean : Infinity\n}\n\n/**\n * The blocks under a tile of `cells` cells of side `cell` from (`x0`, `z0`), over its `read` heights (`(cells + 1)^2`, x fastest) and the engine's coarser collision field of\n * them (`step`: every how many corners it is), and the ground around it (`groundAt`, read only past the tile's edges, up to `SOLID_RING`, and its collision field there too).\n */\nexport const buildSolidVolume = (read: Float32Array, cells: number, x0: number, z0: number, cell: number, groundAt: GroundSource, step = 1): SolidVolume => {\n // under the drawn ground and the engine's collision field (every `step`-th corner, `engine-ground-collision`) both, whichever is lower at each corner\n const heights = underBoth(read, cells, step)\n const m = cells + 1\n let low = Infinity\n for (const h of heights) low = Math.min(low, h)\n const bottom = low - SOLID_DEPTH\n const boxes: number[] = []\n // past the edge, under the neighbour's coarse field too, whichever it collides with\n const ring = createGroundRing(heights, cells, x0, z0, cell, groundAt, coarseStep(cells, cell))\n const reachTile = { heights, cells, x0, z0, cell, pyramid: buildLowPyramid(heights, cells, cell), ring }\n const outer = ring.cells * cell\n const loX = x0 - outer, hiX = x0 + cells * cell + outer, loZ = z0 - outer, hiZ = z0 + cells * cell + outer\n const at = (i: number, j: number): number => heights[j * m + i]!\n /** The slopes (per cell) of the plane through the block's corners, into `slopes` (x then z). */\n const slopesOf = (i0: number, j0: number, i1: number, j1: number): void => {\n slopes[0] = (at(i1, j0) - at(i0, j0) + at(i1, j1) - at(i0, j1)) / 2 / (i1 - i0)\n slopes[1] = (at(i0, j1) - at(i0, j0) + at(i1, j1) - at(i1, j0)) / 2 / (j1 - j0)\n }\n\n /** How far the surface rises above the plane through the block's corners lowered to its lowest sample: the block is split while it is more. */\n const planeGap = (i0: number, j0: number, i1: number, j1: number): number => {\n slopesOf(i0, j0, i1, j1)\n const sx = slopes[0]!, sz = slopes[1]!\n let least = Infinity\n let most = -Infinity\n for (let j = j0; j <= j1; j++) {\n for (let i = i0; i <= i1; i++) {\n const above = at(i, j) - (at(i0, j0) + sx * (i - i0) + sz * (j - j0))\n if (above < least) least = above\n if (above > most) most = above\n }\n }\n return most - least\n }\n\n /** A level block: an upright box topped at its lowest ground less `SOLID_MARGIN`. */\n const level = (i0: number, j0: number, i1: number, j1: number, least: number): void => {\n const top = least - SOLID_MARGIN\n boxes.push(x0 + ((i0 + i1) / 2) * cell, (top + bottom) / 2, z0 + ((j0 + j1) / 2) * cell, ((i1 - i0) * cell) / 2, (top - bottom) / 2, ((j1 - j0) * cell) / 2, 0, 0, 0, 1)\n }\n\n /**\n * A sloped block: one box turned to the plane through its corners, its top the rectangle on that plane over the block and a cell past it each way, down to under the\n * solid's bottom, lowered by the most it rises over the ground anywhere (`reachOf`) and `SOLID_MARGIN`. A box that would lean past the ring is made as deep as stays in\n * it (the block's upright box is under it); a box lowered by more than the block's relief is the upright box alone. False when the block should be split instead: its box would not\n * fit the ring, or the ground past the tile lowers it much more than its own.\n */\n const sloped = (i0: number, j0: number, i1: number, j1: number, least: number, most: number): boolean => {\n const span = Math.max(i1 - i0, j1 - j0)\n slopesOf(i0, j0, i1, j1)\n const gx = slopes[0]! / cell\n const gz = slopes[1]! / cell\n const ox = x0 + i0 * cell\n const oz = z0 + j0 * cell\n const base = at(i0, j0)\n // the box's axes, in the scratch the reach reads them from: n the normal of its top, ax along x up the slope, az across both\n const n = unitInto(reachAxes[1]!, -gx, 1, -gz)\n const ax = unitInto(reachAxes[0]!, 1, gx, 0)\n const az = reachAxes[2]!\n az[0] = ax[1]! * n[2]! - ax[2]! * n[1]!\n az[1] = ax[2]! * n[0]! - ax[0]! * n[2]!\n az[2] = ax[0]! * n[1]! - ax[1]! * n[0]!\n const xa = ox, xb = x0 + i1 * cell, za = oz, zb = z0 + j1 * cell\n const cx = (xa + xb) / 2, cz = (za + zb) / 2, cy = base + gx * (cx - ox) + gz * (cz - oz)\n let hx = 0\n let hz = 0\n for (let a = 0; a < 2; a++) {\n const x = a === 0 ? xa : xb\n for (let b = 0; b < 2; b++) {\n const z = b === 0 ? za : zb\n const d0 = x - cx, d1 = base + gx * (x - ox) + gz * (z - oz) - cy, d2 = z - cz\n hx = Math.max(hx, Math.abs(d0 * ax[0]! + d1 * ax[1]! + d2 * ax[2]!))\n hz = Math.max(hz, Math.abs(d0 * az[0]! + d1 * az[1]! + d2 * az[2]!))\n }\n }\n hx += cell\n hz += cell\n let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity, highest = -Infinity\n for (let a = 0; a < 2; a++) {\n const su = a === 0 ? -1 : 1\n for (let b = 0; b < 2; b++) {\n const sw = b === 0 ? -1 : 1\n const qx = cx + su * hx * ax[0] + sw * hz * az[0]\n const qz = cz + su * hx * ax[2] + sw * hz * az[2]\n minX = Math.min(minX, qx)\n maxX = Math.max(maxX, qx)\n minZ = Math.min(minZ, qz)\n maxZ = Math.max(maxZ, qz)\n highest = Math.max(highest, cy + su * hx * ax[1] + sw * hz * az[1])\n }\n }\n // deep enough that its bottom face is under the solid's bottom everywhere (a box made only as deep as its block's upright box let what it pushed out the bottom through:\n // 17 of the 48 boxes of the push-up sweep fell, as with a730b5450's slab), unless its bottom would lean (uphill: by -n per metre of thickness) past the ring\n const deep = (highest - bottom) / n[1]\n const fits = Math.min(thickWithin(-n[0], minX, maxX, loX, hiX), thickWithin(-n[2], minZ, maxZ, loZ, hiZ))\n const thick = Math.max(SOLID_THINNEST, Math.min(deep, fits))\n if (fits < thick) {\n if (span > SOLID_MIN_CELLS) return false\n level(i0, j0, i1, j1, least)\n return true\n }\n const hy = thick / 2\n const centre = reachBox.c\n centre[0] = cx - n[0]! * hy\n centre[1] = cy - n[1]! * hy\n centre[2] = cz - n[2]! * hy\n reachBox.half[0] = hx\n reachBox.half[1] = hy\n reachBox.half[2] = hz\n const reach = reachOf(reachBox, reachTile)\n if (reach.ring > reach.tile + SEAM_SPLIT && span > SOLID_MIN_CELLS) return false\n const drop = SOLID_MARGIN + Math.max(reach.tile, reach.ring)\n // lowered further than the block's own relief, its top would be further under the ground than the upright box's\n if (drop - SOLID_MARGIN >= most - least) {\n level(i0, j0, i1, j1, least)\n return true\n }\n // and under it the block's upright box: what slips between two turned boxes (they part under their tops; a cell's overlap closes only so deep) rests on it, no\n // further under the ground than the block's relief\n level(i0, j0, i1, j1, least)\n const q = quatOfAxes(ax, n, az)\n boxes.push(centre[0]!, centre[1]! - drop, centre[2]!, hx, hy, hz, q[0], q[1], q[2], q[3])\n return true\n }\n\n const fill = (i0: number, j0: number, i1: number, j1: number): void => {\n let least = Infinity\n let most = -Infinity\n for (let j = j0; j <= j1; j++) {\n for (let i = i0; i <= i1; i++) {\n const h = at(i, j)\n if (h < least) least = h\n if (h > most) most = h\n }\n }\n if (most - least <= SOLID_RELIEF) return level(i0, j0, i1, j1, least)\n const span = Math.max(i1 - i0, j1 - j0)\n if ((planeGap(i0, j0, i1, j1) > SOLID_RELIEF && span > SOLID_MIN_CELLS) || !sloped(i0, j0, i1, j1, least, most)) {\n // in halves (a side under two cells stays whole), x's halves first\n const im = i1 - i0 < 2 ? i1 : (i0 + i1) >> 1\n const jm = j1 - j0 < 2 ? j1 : (j0 + j1) >> 1\n for (let a = i0; a < i1; a = im) {\n const b = a === i0 ? im : i1\n for (let d = j0; d < j1; d = jm) {\n const e = d === j0 ? jm : j1\n fill(a, d, b, e)\n if (e === j1) break\n }\n if (b === i1) break\n }\n }\n }\n fill(0, 0, cells, cells)\n return { boxes, ring: ring.read }\n}\n\n/** The same blocks. */\nexport const sameSolid = (a: SolidVolume, b: SolidVolume): boolean => same(a.boxes, b.boxes)\n\n/** The same numbers, in order (plain or typed arrays alike). */\nexport const sameNumbers = (a: ArrayLike<number>, b: ArrayLike<number>): boolean => {\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false\n return true\n}\n\nconst same = sameNumbers\n","import type { HeightPatch } from '@adatechnology/game-terrain'\n\nimport { NO_SOLID, buildSolidVolume } from './engine-ground-solid'\nimport type { SolidVolume } from './engine-ground-solid'\nimport { collisionFieldOf } from './engine-ground-collision'\nimport { holdsStep } from './engine-ground-step'\n\n/**\n * The ground a physics engine stands the pieces on, one tile of `groundAt` at a time: a height field over the cell corners for what is smooth, and solid boxes\n * for the cells a hard step runs through (a crater's rim, a terraced slope) and the cells around them. A box's top is its cell's centre height and its\n * sides are vertical, so a step keeps its edge (within half a cell of where it is) instead of a ramp one cell wide; under the boxes the height field is lowered so\n * it does not ramp up through them. A level tile is one slab, solid below.\n *\n * Why not triangles: the step-keeping triangle mesh this replaces was one-sided (a thin piece pressed half through a triangle fell through for good) and had to be\n * made again, as a new body, for every change, which threw away the engine's contact cache. A height field of the same tile is made in about 0.3 ms and can be\n * swapped on the same body (`EnginePieces`), so the pieces on it keep their contacts.\n *\n * The tile is read at `GROUND_CELL`; the engine collides with every second corner of it, a 5 cm field (`engine-ground-collision`, owner decision 2026-11-17), and the solid\n * under it stays under both.\n */\n\n/** Cells of a tile (m), as Rapier's spike measured good enough for a 4 cm plate. */\nexport const GROUND_CELL = 0.025\n/** How far (m) under the lowest ground around them the step boxes go, and how far the height field drops under them. */\nconst BOX_DEPTH = 0.05\nconst UNDER_BOX = 0.01\n\nexport interface GroundTile {\n /** Corner heights, `(cells + 1)^2`, x fastest: `heights[iz * (cells + 1) + ix]`. Empty when the tile is level. */\n readonly heights: Float32Array\n readonly cells: number\n /** The height field the engine collides with (`engine-ground-collision`): every `cells / collisionCells`-th corner of `heights`, `(collisionCells + 1)^2`. Empty when level. */\n readonly collision: Float32Array\n readonly collisionCells: number\n /** The step boxes: centre x, y, z and half x, y, z, six numbers each (a typed array when the tile came from a worker, `engine-ground-job`). */\n readonly boxes: readonly number[] | Float64Array\n /** The solid under the height field (`engine-ground-solid`); none when the tile is level (a slab is solid already). */\n readonly solid: SolidVolume\n /** The height of a level tile (every sample equal), or null. */\n readonly level: number | null\n /** Every sample read, to tell whether the ground changed since; null for a tile proved level from the terrain's own bounds (`flatTile`), whose samples were never read. */\n readonly samples: Float64Array | null\n /** The terrain's vertices the tile was made from (`readGroundPatch`; its samples are then null): what tells whether the ground changed since. */\n readonly patch?: HeightPatch\n}\n\nconst NO_HEIGHTS = new Float32Array(0)\n/** One cell's nine samples, for `holdsStep`. */\nconst cellSamples = new Float64Array(9)\n\n/** The tile of a level `size` at `level`, laid without a sample read: the caller has proved, from the ground's own data, that every sample there is `level` (to 1e-9, as `shapeGround` calls level). */\nexport const flatTile = (level: number, size: number): GroundTile => ({ heights: NO_HEIGHTS, cells: Math.round(size / GROUND_CELL), collision: NO_HEIGHTS, collisionCells: 0, boxes: [], solid: NO_SOLID, level, samples: null })\n\n/** A rectangle of the ground, world x and z. */\nexport interface GroundRect {\n readonly minX: number\n readonly maxX: number\n readonly minZ: number\n readonly maxZ: number\n}\n\n/**\n * The four series of samples of a tile, one after the other in `samples`: the corners, the cells' centres, the middles of the edges along x and those along z.\n * `ox` and `oz` are where the series sits in a cell (0 or half), `width` and `rows` how many samples it has along x and along z.\n */\nconst seriesOf = (n: number): ReadonlyArray<{ offset: number; width: number; rows: number; ox: number; oz: number }> => {\n const m = n + 1\n return [\n { offset: 0, width: m, rows: m, ox: 0, oz: 0 },\n { offset: m * m, width: n, rows: n, ox: 0.5, oz: 0.5 },\n { offset: m * m + n * n, width: n, rows: m, ox: 0.5, oz: 0 },\n { offset: m * m + n * n + n * m, width: m, rows: n, ox: 0, oz: 0.5 },\n ]\n}\n\n/** The `samples` array of a tile of `n` cells. */\nexport const sampleCount = (n: number): number => (n + 1) * (n + 1) + n * n + 2 * n * (n + 1)\n\n/**\n * The ground over a lattice in one pass: the height at (`xs[i]`, `zs[j]`) into `out[j * xs.length + i]`, to the bit what the tile's `groundAt` answers at each point\n * (`Terrain.heightGrid` is one). A tile reads its 26 000 samples through it instead of a call each.\n */\nexport type GroundGrid = (xs: ArrayLike<number>, zs: ArrayLike<number>, out: Float64Array) => void\n\n// the points a grid read asks for and what it answers, kept between reads (one at a time) so a read does not make them again\nlet seriesX = new Float64Array(0)\nlet seriesZ = new Float64Array(0)\nlet seriesHeights = new Float64Array(0)\n\n/**\n * Reads the ground of the tile at (x0, z0) into `samples`: every sample, or only those a rectangle reaches (a sample a cell outside it is read too, so what the\n * rectangle's edge touches is not left old). True when a sample read differs from the one held. A crater in a corner of a tile asks `groundAt` for the corner.\n * With a `grid` each series is read in one pass over its own points, each the one `groundAt` would be asked for (`x0 + (i + ox) * c`), so the same heights.\n * Not reentrant: the points are module scratch, so neither reader may read a tile in turn.\n */\nexport const readGround = (groundAt: (x: number, z: number) => number, samples: Float64Array, x0: number, z0: number, size: number, rect?: GroundRect, grid?: GroundGrid): boolean => {\n const n = Math.round(size / GROUND_CELL)\n const c = size / n\n let changed = false\n for (const { offset, width, rows, ox, oz } of seriesOf(n)) {\n const i0 = rect ? Math.max(0, Math.floor((rect.minX - x0) / c - ox)) : 0\n const i1 = rect ? Math.min(width - 1, Math.ceil((rect.maxX - x0) / c - ox)) : width - 1\n const j0 = rect ? Math.max(0, Math.floor((rect.minZ - z0) / c - oz)) : 0\n const j1 = rect ? Math.min(rows - 1, Math.ceil((rect.maxZ - z0) / c - oz)) : rows - 1\n if (i0 > i1 || j0 > j1) continue\n if (!grid) {\n for (let j = j0; j <= j1; j++) {\n for (let i = i0; i <= i1; i++) {\n const h = groundAt(x0 + (i + ox) * c, z0 + (j + oz) * c)\n if (samples[offset + j * width + i] !== h) changed = true\n samples[offset + j * width + i] = h\n }\n }\n continue\n }\n const across = i1 - i0 + 1\n const along = j1 - j0 + 1\n if (seriesX.length < across) seriesX = new Float64Array(across)\n if (seriesZ.length < along) seriesZ = new Float64Array(along)\n if (seriesHeights.length < across * along) seriesHeights = new Float64Array(across * along)\n for (let i = 0; i < across; i++) seriesX[i] = x0 + (i0 + i + ox) * c\n for (let j = 0; j < along; j++) seriesZ[j] = z0 + (j0 + j + oz) * c\n grid(seriesX.subarray(0, across), seriesZ.subarray(0, along), seriesHeights)\n for (let j = 0; j < along; j++) {\n const from = j * across\n const to = offset + (j0 + j) * width + i0\n if (!changed) {\n for (let i = 0; i < across; i++) {\n if (samples[to + i] !== seriesHeights[from + i]) {\n changed = true\n break\n }\n }\n }\n samples.set(seriesHeights.subarray(from, from + across), to)\n }\n }\n return changed\n}\n\nexport const buildGroundTile = (groundAt: (x: number, z: number) => number, x0: number, z0: number, size: number, withSolid = true, grid?: GroundGrid): GroundTile => {\n const samples = new Float64Array(sampleCount(Math.round(size / GROUND_CELL)))\n readGround(groundAt, samples, x0, z0, size, undefined, grid)\n return shapeGround(samples, x0, z0, size, withSolid ? groundAt : null)\n}\n\n/**\n * The tile the samples make: level, or its height field, step boxes and (given the ground, which it reads past the tile's edges; else `NO_SOLID`, for a caller that may\n * not need it) the solid under it. Pure of the samples (and that ground), so a tile made from samples patched in place is the one made from all of them read again, but\n * for its collision field near the bound, which keeps the coarse one it had (`wasCoarse`, `collisionFieldOf`).\n */\nexport const shapeGround = (samples: Float64Array, x0: number, z0: number, size: number, solidGround: ((x: number, z: number) => number) | null, wasCoarse = false): GroundTile => {\n const n = Math.round(size / GROUND_CELL)\n const c = size / n\n const m = n + 1\n const [cornerSeries, centreSeries, midXSeries, midZSeries] = seriesOf(n)\n const corners = samples.subarray(cornerSeries!.offset, centreSeries!.offset)\n const centres = samples.subarray(centreSeries!.offset, midXSeries!.offset)\n const midX = samples.subarray(midXSeries!.offset, midZSeries!.offset)\n const midZ = samples.subarray(midZSeries!.offset)\n let low = Infinity\n let high = -Infinity\n for (const h of samples) {\n low = Math.min(low, h)\n high = Math.max(high, h)\n }\n if (high - low < 1e-9) return { heights: new Float32Array(0), cells: n, collision: NO_HEIGHTS, collisionCells: 0, boxes: [], solid: NO_SOLID, level: high, samples }\n const corner = (i: number, j: number): number => corners[j * m + i]\n // a cell whose centre or an edge's middle leaves its corners holds a step; it and the cells around it become boxes\n const mask = new Uint8Array(n * n)\n for (let j = 0; j < n; j++) {\n for (let i = 0; i < n; i++) {\n cellSamples[0] = corner(i, j)\n cellSamples[1] = corner(i + 1, j)\n cellSamples[2] = corner(i, j + 1)\n cellSamples[3] = corner(i + 1, j + 1)\n cellSamples[4] = centres[j * n + i]\n cellSamples[5] = midX[j * n + i]\n cellSamples[6] = midX[(j + 1) * n + i]\n cellSamples[7] = midZ[j * m + i]\n cellSamples[8] = midZ[j * m + i + 1]\n if (!holdsStep(cellSamples)) continue\n for (let dj = -1; dj <= 1; dj++) for (let di = -1; di <= 1; di++) if (i + di >= 0 && j + dj >= 0 && i + di < n && j + dj < n) mask[(j + dj) * n + i + di] = 1\n }\n }\n const heights = new Float32Array(m * m)\n for (let j = 0; j <= n; j++) {\n for (let i = 0; i <= n; i++) {\n // a corner whose four cells are all boxes goes under the lowest of them\n let inside = true\n let least = corner(i, j)\n for (let dj = -1; dj <= 0 && inside; dj++) for (let di = -1; di <= 0; di++) {\n const ii = i + di, jj = j + dj\n if (ii < 0 || jj < 0 || ii >= n || jj >= n || !mask[jj * n + ii]) {\n inside = false\n break\n }\n least = Math.min(least, centres[jj * n + ii], corner(ii, jj), corner(ii + 1, jj), corner(ii, jj + 1), corner(ii + 1, jj + 1))\n }\n heights[j * m + i] = inside ? least - UNDER_BOX : corner(i, j)\n }\n }\n // the boxes: runs along x of masked cells at one height, down to under the lowest ground around them\n const boxes: number[] = []\n for (let j = 0; j < n; j++) {\n let i = 0\n while (i < n) {\n if (!mask[j * n + i]) {\n i++\n continue\n }\n const top = centres[j * n + i]\n let end = i + 1\n while (end < n && mask[j * n + end] && Math.abs(centres[j * n + end] - top) < 0.001) end++\n let bottom = top\n for (let k = Math.max(0, i - 1); k <= Math.min(n, end + 1); k++) for (let jj = Math.max(0, j - 1); jj <= Math.min(n, j + 2); jj++) bottom = Math.min(bottom, corner(k, jj))\n bottom -= BOX_DEPTH\n boxes.push(x0 + ((i + end) / 2) * c, (top + bottom) / 2, z0 + (j + 0.5) * c, ((end - i) * c) / 2, (top - bottom) / 2, c / 2)\n i = end\n }\n }\n const { step, field } = collisionFieldOf(heights, n, c, boxes.length > 0, wasCoarse)\n return { heights, cells: n, collision: field, collisionCells: n / step, boxes, solid: solidGround ? buildSolidVolume(heights, n, x0, z0, c, solidGround, step) : NO_SOLID, level: null, samples }\n}\n","import { cellCoordinate, heightPatchGrid } from '@adatechnology/game-terrain'\nimport type { HeightPatch } from '@adatechnology/game-terrain'\n\nimport { GROUND_CELL, readGround, sampleCount, shapeGround } from './engine-ground'\nimport type { GroundGrid, GroundTile } from './engine-ground'\nimport { SOLID_RING } from './engine-ground-ring'\nimport { NO_SOLID, buildSolidVolume } from './engine-ground-solid'\n\n/**\n * A tile of the engine's ground as plain data, so it can be made off the main thread (`engine-ground-port`): the main thread reads the tile's samples and the band of ground\n * past its edges its solid may read (`readGroundBand`), and the tile is a pure function of those (`computeGroundTile`), the same bits wherever it runs. Nothing here calls back\n * into the host: a worker has no `groundAt`.\n */\n\n/** What a tile is made from: its samples (`readGround`) and the band past its edges (`readGroundBand`), both read on the main thread at the frame it was asked for. */\nexport interface GroundTileJob {\n readonly id: number\n readonly x0: number\n readonly z0: number\n readonly size: number\n /** Whether the tile collided on the coarse field before (`collisionFieldOf`). */\n readonly wasCoarse: boolean\n /** Empty in a patch job (`patch`), whose samples and band are made where the tile is. */\n readonly samples: Float64Array\n readonly band: Float64Array\n /**\n * The terrain's vertices under the tile and its ring (`readGroundPatch`), in place of the samples and the band: about 26 x 26 numbers instead of 60 000. The tile is made from\n * the samples and band the patch gives (`heightPatchGrid`, the terrain's own blend), the same bits as read from the terrain on the main thread.\n */\n readonly patch?: HeightPatch\n}\n\n/** A tile made from a job, as arrays that cross threads; `samples` and `band` are the job's own, handed back for the next job. */\nexport interface GroundTileResult {\n readonly id: number\n readonly cells: number\n readonly collisionCells: number\n readonly level: number | null\n readonly heights: Float32Array\n readonly collision: Float32Array\n readonly boxes: Float64Array\n readonly solid: Float64Array\n readonly ring: Float64Array\n readonly samples: Float64Array\n readonly band: Float64Array\n /** A patch job's vertex heights, handed back for the next job. */\n readonly patch?: Float64Array\n}\n\n/** How many read cells the ring past a tile of `cells` cells of side `cell` is wide (`createGroundRing`). */\nconst ringOf = (cell: number): number => Math.round(SOLID_RING / cell)\n\n/** The length of the band of a tile of `size` m: one height per half cell over the tile and its ring (`GroundSource`). */\nexport const bandLength = (size: number): number => {\n const n = Math.round(size / GROUND_CELL)\n const width = 2 * (n + 2 * ringOf(size / n)) + 1\n return width * width\n}\n\n// the lattice of a band read through the grid, kept between reads (one at a time)\nlet lineX = new Float64Array(0)\nlet lineZ = new Float64Array(0)\nlet sideOut = new Float64Array(0)\n\n/**\n * Reads into `band` the ground past the tile's edges, as far as its solid may read it (`SOLID_RING`) and on the edges themselves: every half cell `(a, b)` with `a` or `b` on or\n * past an edge, at the very point the ring asks `groundAt` for (`x0 + (a / 2) * cell`). Through `grid` in four strips, else a call each. The tile's inside is left as it was.\n */\nexport const readGroundBand = (groundAt: (x: number, z: number) => number, band: Float64Array, x0: number, z0: number, size: number, grid?: GroundGrid): void => {\n const n = Math.round(size / GROUND_CELL)\n const cell = size / n\n const r = ringOf(cell)\n const lo = -2 * r\n const hi = 2 * n + 2 * r\n const width = hi - lo + 1\n const xAt = (a: number): number => x0 + (a / 2) * cell\n const zAt = (b: number): number => z0 + (b / 2) * cell\n if (!grid) {\n for (let b = lo; b <= hi; b++) {\n for (let a = lo; a <= hi; a++) {\n if (a > 0 && a < 2 * n && b > 0 && b < 2 * n) continue\n band[(b - lo) * width + a - lo] = groundAt(xAt(a), zAt(b))\n }\n }\n return\n }\n const strip = 2 * r + 1\n const middle = 2 * n - 1\n if (lineX.length < width) lineX = new Float64Array(width)\n if (lineZ.length < width) lineZ = new Float64Array(width)\n if (sideOut.length < strip * middle) sideOut = new Float64Array(strip * middle)\n for (let a = lo; a <= hi; a++) lineX[a - lo] = xAt(a)\n const xs = lineX.subarray(0, width)\n // the rows under the tile and over it, whole: straight into the band\n for (const from of [lo, 2 * n]) {\n for (let k = 0; k < strip; k++) lineZ[k] = zAt(from + k)\n grid(xs, lineZ.subarray(0, strip), band.subarray((from - lo) * width, (from - lo + strip) * width))\n }\n // the columns left and right of it, between those rows\n for (let k = 0; k < middle; k++) lineZ[k] = zAt(1 + k)\n const zs = lineZ.subarray(0, middle)\n for (const from of [lo, 2 * n]) {\n grid(lineX.subarray(from - lo, from - lo + strip), zs, sideOut)\n for (let k = 0; k < middle; k++) for (let i = 0; i < strip; i++) band[(1 + k - lo) * width + from - lo + i] = sideOut[k * strip + i]!\n }\n}\n\n/** The host's terrain as vertex heights under a rectangle (min x, max x, min z, max z), or null where it cannot (`Terrain.heightPatch` is one); written into `into` when long enough. */\nexport type GroundPatchRead = (minX: number, maxX: number, minZ: number, maxZ: number, into?: Float64Array) => HeightPatch | null\n\n/**\n * The terrain's vertices under the tile at (x0, z0) and its ring, the rectangle every sample and band point lies in (the band's own outermost points, as `readGroundBand` computes\n * them); null where the host has none (a tile crossing the terrain's bounds, where its `baseHeight` answers): that tile is read as before.\n */\nexport const readGroundPatch = (read: GroundPatchRead, x0: number, z0: number, size: number, into?: Float64Array): HeightPatch | null => {\n const n = Math.round(size / GROUND_CELL)\n const cell = size / n\n const r = ringOf(cell)\n const lo = -2 * r\n const hi = 2 * n + 2 * r\n return read(x0 + (lo / 2) * cell, x0 + (hi / 2) * cell, z0 + (lo / 2) * cell, z0 + (hi / 2) * cell, into)\n}\n\n/** The cell of `latticePatchRead`'s ground (m): a terrain's usual one. */\nconst LATTICE_CELL = 0.1\n\n/**\n * A `GroundPatchRead` of any ground as a terrain would hold it: `ground` sampled at the vertices of a `LATTICE_CELL` lattice laid a metre and more around each rectangle asked,\n * the patch found with the terrain's own cell rule (`cellCoordinate`). For the warm job of a patch tile, which has no terrain: whatever the tile size and ring are, its patch\n * covers them, as a real one does.\n */\nexport const latticePatchRead = (ground: (x: number, z: number) => number): GroundPatchRead => (minX, maxX, minZ, maxZ, into) => {\n const originX = Math.floor(minX) - 1\n const originZ = Math.floor(minZ) - 1\n const columns = Math.ceil((maxX - originX) / LATTICE_CELL) + 2\n const rows = Math.ceil((maxZ - originZ) / LATTICE_CELL) + 2\n const column0 = cellCoordinate(minX, originX, columns, LATTICE_CELL) | 0\n const row0 = cellCoordinate(minZ, originZ, rows, LATTICE_CELL) | 0\n const width = (cellCoordinate(maxX, originX, columns, LATTICE_CELL) | 0) + 2 - column0\n const depth = (cellCoordinate(maxZ, originZ, rows, LATTICE_CELL) | 0) + 2 - row0\n const heights = into && into.length >= width * depth ? into : new Float64Array(width * depth)\n for (let j = 0; j < depth; j++) for (let i = 0; i < width; i++) heights[j * width + i] = ground(originX + (column0 + i) * LATTICE_CELL, originZ + (row0 + j) * LATTICE_CELL)\n return { cellSize: LATTICE_CELL, originX, originZ, columns, rows, column0, row0, width, depth, heights }\n}\n\nconst NO_GROUND = (): number => {\n throw new Error('engine-ground-job: a patch job reads its patch only')\n}\n// the patch the grid below reads, and the samples and band a patch job is made into, kept between jobs (one at a time) so a job makes no arrays for them\nlet gridPatch: HeightPatch | null = null\nconst patchGrid: GroundGrid = (xs, zs, out) => heightPatchGrid(gridPatch as HeightPatch, xs, zs, out)\nlet patchSamples = new Float64Array(0)\nlet patchBand = new Float64Array(0)\n\n/** The samples and band of a patch job, read from its patch through the same lattices `readGround` and `readGroundBand` read the terrain at (module scratch: not reentrant). */\nconst groundOfPatch = (job: GroundTileJob, patch: HeightPatch): { samples: Float64Array; band: Float64Array } => {\n const count = sampleCount(Math.round(job.size / GROUND_CELL))\n if (patchSamples.length !== count) patchSamples = new Float64Array(count)\n if (patchBand.length !== bandLength(job.size)) patchBand = new Float64Array(bandLength(job.size))\n gridPatch = patch\n readGround(NO_GROUND, patchSamples, job.x0, job.z0, job.size, undefined, patchGrid)\n readGroundBand(NO_GROUND, patchBand, job.x0, job.z0, job.size, patchGrid)\n gridPatch = null\n return { samples: patchSamples, band: patchBand }\n}\n\n/**\n * The tile a job makes: `shapeGround` of its samples and, under a height field, its solid over the band (both made from its patch first, in a patch job). Pure of the job.\n * Not reentrant: a patch job's samples and band, and `readGround`'s lattice, are module scratch (one job at a time per thread, as a worker and the schedule run them).\n */\nexport const computeGroundTile = (job: GroundTileJob): GroundTileResult => {\n const { samples, band } = job.patch ? groundOfPatch(job, job.patch) : job\n const t = shapeGround(samples, job.x0, job.z0, job.size, null, job.wasCoarse)\n const solid = t.level === null ? buildSolidVolume(t.heights, t.cells, job.x0, job.z0, job.size / t.cells, band, t.cells / t.collisionCells) : NO_SOLID\n return {\n id: job.id, cells: t.cells, collisionCells: t.collisionCells, level: t.level, heights: t.heights, collision: t.collision,\n boxes: Float64Array.from(t.boxes), solid: Float64Array.from(solid.boxes), ring: Float64Array.from(solid.ring), samples: job.samples, band: job.band,\n ...(job.patch ? { patch: job.patch.heights } : {}),\n }\n}\n\n/** Each buffer of the arrays once, none empty (an empty one may be shared, and a buffer transferred twice throws). */\nconst buffersOf = (arrays: ReadonlyArray<Float32Array | Float64Array | undefined>): ArrayBuffer[] => {\n const out: ArrayBuffer[] = []\n for (const array of arrays) {\n const buffer = array?.buffer as ArrayBuffer | undefined\n if (buffer && buffer.byteLength > 0 && !out.includes(buffer)) out.push(buffer)\n }\n return out\n}\n\n/** The buffers a result hands over, each once and none empty (a height field may be its own collision field). */\nexport const transferOf = (r: GroundTileResult): ArrayBuffer[] => buffersOf([r.heights, r.collision, r.boxes, r.solid, r.ring, r.samples, r.band, r.patch])\n\n/** The buffers a job hands over: its samples and band, or its patch. */\nexport const jobTransferOf = (job: GroundTileJob): ArrayBuffer[] => buffersOf([job.samples, job.band, job.patch?.heights])\n\n/** The tile a result stands for, over the samples the main thread keeps for the tile (none for a patch tile, which keeps its patch instead). */\nexport const tileOfResult = (r: GroundTileResult, samples: Float64Array | null, patch?: HeightPatch): GroundTile => ({\n heights: r.heights, cells: r.cells, collision: r.collision, collisionCells: r.collisionCells, boxes: r.boxes,\n solid: r.level === null ? { boxes: r.solid, ring: r.ring } : NO_SOLID, level: r.level, samples, ...(patch ? { patch } : {}),\n})\n","import { isWorkerInputLost } from '@adatechnology/game-contracts'\nimport type { WorkerCoordinator } from '@adatechnology/game-contracts'\nimport type { WorkerLike, WorkerScopeLike } from '@adatechnology/game-shapes'\n\nimport { computeGroundTile, jobTransferOf, transferOf } from './engine-ground-job'\nimport type { GroundTileJob, GroundTileResult } from './engine-ground-job'\nimport { groundTilesKind } from './worker-kinds'\n\n/**\n * Where the engine's ground tiles are made (`RendererOptions.groundWorker`): the main thread posts a job (`GroundTileJob`, plain arrays, transferred) and takes the tile back\n * when it comes. The engine applies a tile exactly `groundWorkerFrames` updates after it asked for it, from the answer if it came, else made on the main thread from the same\n * job: the answer is the same bits either way, so when it comes changes nothing but where the work ran (`GroundSchedule`).\n *\n * - `transfer`: the game's worker coordinator (`createCoordinatorGroundPort`, the `destruction.ground-tiles` kind, CLAUDE.md §14), or a\n * worker of the host's (`createWorkerGroundPort`, over game-shapes' `WorkerLike`); the answer comes whenever its event loop delivers it.\n * - `inline`: this thread, at once when posted (`createInlineGroundPort`): tests, Node.\n * - `none`: never answers and nothing is posted (`createMainThreadGroundPort`): every tile made on the main thread at its frame, the reference the other two match.\n */\nexport interface GroundWorkerPort {\n /** May turn `none` later (a worker that failed): read it at each job. */\n readonly transport: 'transfer' | 'inline' | 'none'\n /** Takes the job's arrays (they may be transferred: not to be read after). */\n postTile(job: GroundTileJob): void\n /** The one handler the answers go to. */\n onTile(handler: (result: GroundTileResult) => void): void\n /** Stops the worker, if any; no answer comes after. */\n dispose(): void\n}\n\n/** The one handler of a port: a port serves one engine, so a second one is an error (it would take the answers of the first). */\nconst oneHandler = (): { set(h: (result: GroundTileResult) => void): void; get(): ((result: GroundTileResult) => void) | null; drop(): void } => {\n let handler: ((result: GroundTileResult) => void) | null = null\n return {\n set: (h) => {\n if (handler) throw new Error('GroundWorkerPort: onTile set twice (a port serves one engine)')\n handler = h\n },\n get: () => handler,\n drop: () => {\n handler = null\n },\n }\n}\n\nexport const createInlineGroundPort = (): GroundWorkerPort => {\n const handler = oneHandler()\n return {\n transport: 'inline',\n postTile: (job) => handler.get()?.(computeGroundTile(job)),\n onTile: handler.set,\n dispose: handler.drop,\n }\n}\n\nexport const createMainThreadGroundPort = (): GroundWorkerPort => {\n const handler = oneHandler()\n return { transport: 'none', postTile: () => undefined, onTile: handler.set, dispose: handler.drop }\n}\n\n/**\n * A worker running `installGroundWorker` (the package's `ground-worker` entry): jobs and answers cross with their buffers transferred; `dispose` terminates it. A worker that\n * fails (`onerror`: its script did not load, it threw) is posted nothing more: the port turns `none` and every tile is made on the main thread at its update, as it would have\n * been anyway (game-shapes' pool fails its jobs the same way).\n */\nexport const createWorkerGroundPort = (worker: WorkerLike): GroundWorkerPort => {\n const handler = oneHandler()\n let failed = false\n worker.onmessage = (event) => handler.get()?.(event.data as GroundTileResult)\n worker.onerror = () => {\n failed = true\n }\n return {\n get transport() {\n return failed ? 'none' : 'transfer'\n },\n postTile: (job) => {\n if (!failed) worker.postMessage(job, jobTransferOf(job))\n },\n onTile: handler.set,\n dispose: () => {\n handler.drop()\n worker.onmessage = null\n worker.onerror = null\n worker.terminate()\n },\n }\n}\n\n/**\n * The tiles through the game's worker coordinator (CLAUDE.md §14): each job is a `destruction.ground-tiles` task the coordinator hands to a\n * worker, awaited (the engine's `GroundSchedule` applies the tile at its update, from the answer if it came, else made here from the same\n * job). A coordinator with no workers is posted nothing (`none`): every tile is made at its update, with no job run twice. The coordinator\n * is the game's: `dispose` lets go of the answers, not of the workers. The job's arrays are transferred (the kind's `transferAwaitedInput`):\n * `GroundSchedule` posts copies from its pool and keeps its own for the fallback. A job lost with its worker (it died holding it) is made here at\n * its update and the next ones still go to the workers (the coordinator replaces a dying worker a few times, then lets it go: `none` when none\n * is left); any other rejection (a worker that cannot run the kind) and nothing more is posted.\n */\nexport const createCoordinatorGroundPort = (workers: WorkerCoordinator): GroundWorkerPort => {\n const handler = oneHandler()\n let disposed = false\n let failed = false\n return {\n get transport() {\n return failed || workers.stats().workers === 0 ? 'none' : 'transfer'\n },\n postTile: (job) => {\n if (disposed || failed || workers.stats().workers === 0) return\n workers.run(groundTilesKind, job).then(\n (result) => {\n if (!disposed) handler.get()?.(result)\n },\n // the tile is made here at its update; a job lost with its worker leaves the next ones to the workers, anything else posts nothing more\n (error: unknown) => {\n if (!isWorkerInputLost(error)) failed = true\n },\n )\n },\n onTile: handler.set,\n dispose: () => {\n disposed = true\n handler.drop()\n },\n }\n}\n\n/** The worker side: each job answered with its tile, every array transferred back (the job's own included, for the main thread's pool). */\nexport const installGroundWorker = (scope: WorkerScopeLike): void => {\n scope.onmessage = (event) => {\n const result = computeGroundTile(event.data as GroundTileJob)\n scope.postMessage(result, transferOf(result))\n }\n}\n","import type { WorkerScopeLike } from '@adatechnology/game-shapes'\n\nimport { installGroundWorker } from './engine-ground-port'\n\n// the worker script a host starts for `createWorkerGroundPort` (dist/ground-worker.js as a module, or d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A,MAAO,SAAS,EAAE;AAAA,MAAS,WAAW,EAAE;AAAA,MAC/G,OAAO,aAAa,KAAK,EAAE,KAAK;AAAA,MAAG,OAAO,aAAa,KAAK,MAAM,KAAK;AAAA,MAAG,MAAM,aAAa,KAAK,MAAM,IAAI;AAAA,MAAG,SAAS,IAAI;AAAA,MAAS,MAAM,IAAI;AAAA,MAC/I,GAAI,IAAI,QAAQ,EAAE,OAAO,IAAI,MAAM,QAAQ,IAAI,CAAC;AAAA,IAClD;AAAA,EACF;AAGA,MAAM,YAAY,CAAC,WAAkF;AACnG,UAAM,MAAqB,CAAC;AAC5B,eAAW,SAAS,QAAQ;AAC1B,YAAM,SAAS,OAAO;AACtB,UAAI,UAAU,OAAO,aAAa,KAAK,CAAC,IAAI,SAAS,MAAM,EAAG,KAAI,KAAK,MAAM;AAAA,IAC/E;AACA,WAAO;AAAA,EACT;AAGO,MAAM,aAAa,CAAC,MAAuC,UAAU,CAAC,EAAE,SAAS,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,CAAC;;;AClEnJ,MAAM,sBAAsB,CAAC,UAAiC;AACnE,UAAM,YAAY,CAAC,UAAU;AAC3B,YAAM,SAAS,kBAAkB,MAAM,IAAqB;AAC5D,YAAM,YAAY,QAAQ,WAAW,MAAM,CAAC;AAAA,IAC9C;AAAA,EACF;;;AC9HA,sBAAoB,UAAwC;","names":["off","planes","bx","bz","r","s"]}
1
+ {"version":3,"sources":["../../game-terrain/src/terrain.ts","../../game-terrain/src/catalog.ts","../../game-terrain/src/random.ts","../../game-terrain/src/cracks.ts","../../game-terrain/src/debris.ts","../../game-terrain/src/ground-loss.ts","../../game-terrain/src/height-patch.ts","../../game-terrain/src/marks.ts","../../game-terrain/src/impl.ts","../../game-terrain/src/types.ts","../../game-terrain/src/footprints.ts","../../game-terrain/src/buoyancy.ts","../src/engine-ground-collision.ts","../src/engine-ground-step.ts","../src/engine-ground-ring.ts","../src/engine-ground-reach.ts","../src/engine-ground-solid.ts","../src/engine-ground.ts","../src/engine-ground-job.ts","../src/engine-ground-port.ts","../src/ground-worker.ts"],"sourcesContent":["import { TNT_JOULES } from '@adatechnology/game-contracts'\nimport type { Hit } from '@adatechnology/game-contracts'\nimport { DEFAULT_BAR_DIAMETER, DEFAULT_BAR_YIELD_JOULES, DEFAULT_BAR_YIELD_PA, DEFAULT_PROFILE, TERRAIN_MATERIALS, TERRAIN_PROFILES } from './catalog'\nimport { createCrackStore, CRACK_REFERENCE_JOULES } from './cracks'\nimport { createDebrisStore } from './debris'\nimport { lossOf, SLIDE_LOSS_MIN_LOWERING, tallyLowered, voidUnder } from './ground-loss'\nimport type { HeightGrid, LossTally } from './ground-loss'\nimport { blendHeights, cellCoordinate as cellCoordinateOf } from './height-patch'\nimport type { HeightPatch } from './height-patch'\nimport { createMarkStore } from './marks'\nimport { createRandom } from './random'\nimport type { GroundExcavation, GroundLayout, Terrain, TerrainDig, TerrainDigResult, TerrainFill, TerrainBlow, TerrainBlowResult, TerrainBudget, TerrainChunk, TerrainColumn, TerrainDebris, TerrainDecal, TerrainLoad, TerrainMark, TerrainMaterial, TerrainOptions, TerrainProfile, TerrainRegion, TerrainSnapshot, TerrainStratum, TerrainStrike } from './types'\n\nexport const DEFAULT_TERRAIN_BUDGET: TerrainBudget = {\n markAreaSize: 2,\n maxMarksPerArea: 24,\n maxMarks: 800,\n maxDirtyChunksPerFrame: 6,\n maxDebris: 400,\n maxDebrisPerBlow: 36,\n maxSlideCellsPerFrame: 2500,\n maxBurningCells: 300,\n maxCracks: 120,\n maxDecals: 300,\n}\n\nconst GRAVITY = 9.81\n/** A bowl narrower than this many cells cannot be drawn by the height field: it stays a fine mark. */\nconst FINE_CELLS = 1.5\n/** A hole deeper than this many cells is no longer a mark on the surface. */\nconst FINE_DEPTH_CELLS = 0.4\nconst RIGID_WIDENING = 2.5\n/** Calibre (mm) a round's crater has the material's own shape at: a thinner round goes deeper and opens less for the same energy, a thicker one opens more. */\nconst REFERENCE_CALIBER = 7.62\n/** How far a calibre bends the crater's depth over its radius: (reference / calibre) to this power, kept within `CALIBER_ASPECT_RANGE`. */\nconst CALIBER_ASPECT_POWER = 0.5\nconst CALIBER_ASPECT_RANGE = [0.6, 1.6] as const\n/** A round's crater is at least this many calibres across. */\nconst CALIBERS_ACROSS = 2.5\n\n/** Depth-over-radius factor of a round's crater: 1 without a calibre or at the reference one. */\nconst caliberAspect = (caliber: number | undefined): number =>\n caliber && caliber > 0 ? Math.min(CALIBER_ASPECT_RANGE[1], Math.max(CALIBER_ASPECT_RANGE[0], (REFERENCE_CALIBER / caliber) ** CALIBER_ASPECT_POWER)) : 1\n/** The smallest crater radius (m) a round of `caliber` mm leaves. */\nconst caliberRadius = (caliber: number | undefined): number => (caliber && caliber > 0 ? (caliber / 1000) * CALIBERS_ACROSS / 2 : 0)\n/** Bars alone do not drop a slab that still has this share of its concrete to lose. */\nconst COLLAPSE_DEPTH_SHARE = 0.75\nconst COLLAPSE_SPREAD_BEND = 0.5\n/** Metres around a weight over which bare bars share it with the weights beside it. */\nconst BARS_SHARE_REACH = 0.6\nconst RIM_REACH = 1.45\n/** Under this temperature (°C) a flame does nothing to the ground. */\nconst FLAME_MINIMUM = 200\n/** How far over the ground a flame still touches it, beyond its radius. */\nconst FLAME_REACH = 0.6\n/** How far a blast above the ground still reaches it, as a share of its radius. */\nconst BLAST_HEIGHT_REACH = 0.35\n/**\n * Metres of ground the fireball of a 1 MJ blast blackens, growing with the cube root of the energy (a frag grenade, 200 kJ: about 0.7 m), and the share of\n * the material's darkest char (`TerrainFireResponse.maxScorch`) it leaves at the centre, fading to the edge: concrete only soots, turf chars.\n */\nconst BLAST_SOOT_REACH = 1.2\nconst BLAST_SOOT = 0.9\n/** Share of a blow's energy that throws the pieces. */\nconst THROW_SHARE = 0.02\n/** Side of a square of ground that burns as one, in metres. */\nconst FIRE_CELL = 0.5\nconst FIRE_SECONDS = 7\nconst FIRE_SPREAD_PER_SECOND = 0.35\nconst SLIDE_SHARE = 0.4\nconst SLIDE_EPSILON = 0.002\n/** Radius of a thrown piece per kind: a clod is a fist of soil, a chip is a thumb of concrete. */\nconst PIECE_RADIUS: Record<TerrainMaterial['debris'], number> = { clods: 0.045, chips: 0.022, shards: 0.028, splinters: 0.02, dust: 0.012, blocks: 0.08 }\n/** Metres per second the fastest piece of a blow leaves at: a blast throws, a dropped weight only kicks. */\nconst MAX_PIECE_SPEED: Record<TerrainBlow, number> = { explosive: 14, ballistic: 5, blunt: 2.5, slash: 1.5 }\n\n/** Cells the bed takes to go from the bank down to the full depth, so that a body wades in instead of falling. */\nconst BANK_CELLS = 6\nconst CRACK_MIN_RADIUS = 0.18\nconst RIPPLE_SECONDS = 1.6\n/** Water thinner than this at the bank neither splashes nor floats anything. */\nconst WATER_MINIMUM = 0.02\n\nconst clampIndex = (value: number, max: number): number => Math.max(0, Math.min(max, value))\nconst sparse = (array: Float32Array): [number, number][] => {\n const entries: [number, number][] = []\n array.forEach((value, index) => {\n if (value !== 0) entries.push([index, value])\n })\n return entries\n}\nconst fillSparse = (array: Float32Array, entries: readonly (readonly [number, number])[]): void => {\n array.fill(0)\n for (const [index, value] of entries) array[index] = value\n}\n\n/** Layer a depth falls in; past the end, the last one. */\nfunction stratumAtDepth(profile: TerrainProfile, depth: number): { index: number; stratum: TerrainStratum; top: number } {\n let top = 0\n for (let index = 0; index < profile.strata.length; index++) {\n const stratum = profile.strata[index]!\n if (depth < top + stratum.thickness - 1e-6) return { index, stratum, top }\n top += stratum.thickness\n }\n const index = profile.strata.length - 1\n const stratum = profile.strata[index]!\n return { index, stratum, top: top - stratum.thickness }\n}\n\n/** Same stratum as `stratumAtDepth`, without allocating: per-read paths (state(), fire per vertex) must not create garbage. */\nfunction stratumMaterialAtDepth(profile: TerrainProfile, depth: number): string {\n const strata = profile.strata\n let top = 0\n for (let index = 0; index < strata.length; index++) {\n const stratum = strata[index]!\n if (depth < top + stratum.thickness - 1e-6) return stratum.material\n top += stratum.thickness\n }\n return strata[strata.length - 1]!.material\n}\nconst totalThickness = (profile: TerrainProfile): number => profile.strata.reduce((sum, stratum) => sum + stratum.thickness, 0)\n\nexport function createTerrain(options: TerrainOptions): Terrain {\n const [x0, z0, x1, z1] = options.bounds\n const cellSize = options.cellSize ?? 0.1\n const chunkCells = options.chunkCells ?? 32\n const columns = Math.max(1, Math.ceil((x1 - x0) / cellSize))\n const rows = Math.max(1, Math.ceil((z1 - z0) / cellSize))\n const stride = columns + 1\n const vertexCount = stride * (rows + 1)\n const chunksX = Math.ceil(columns / chunkCells)\n const chunksZ = Math.ceil(rows / chunkCells)\n const budget: TerrainBudget = { ...DEFAULT_TERRAIN_BUDGET, ...options.budget }\n const gravity = options.gravity ?? GRAVITY\n const materials = new Map<string, TerrainMaterial>([...TERRAIN_MATERIALS, ...(options.materials ?? [])].map((material) => [material.id, material]))\n const profileMap = new Map<string, TerrainProfile>([...TERRAIN_PROFILES, ...(options.profiles ?? [])].map((profile) => [profile.id, profile]))\n const profileList = [...profileMap.values()]\n for (const profile of profileList) {\n for (const stratum of profile.strata) if (!materials.has(stratum.material)) throw new Error(`game-terrain: profile \"${profile.id}\" uses material \"${stratum.material}\", which has no ground behaviour`)\n }\n const indexOfProfile = new Map(profileList.map((profile, index) => [profile.id, index]))\n const maxDepthOf = profileList.map(totalThickness)\n\n // `surface` is the ground as the map has it; `base` is that less the water standing on it, so that everything that stands on the ground stands on the bed\n const surface = new Float32Array(vertexCount)\n if (options.baseHeight) {\n for (let row = 0; row <= rows; row++) for (let column = 0; column <= columns; column++) surface[row * stride + column] = options.baseHeight(x0 + column * cellSize, z0 + row * cellSize)\n }\n const base = Float32Array.from(surface)\n const hasWater = profileList.some((profile) => profile.water)\n const dug = new Float32Array(vertexCount)\n const loose = new Float32Array(vertexCount)\n const scorch = new Float32Array(vertexCount)\n const barBend = new Float32Array(vertexCount)\n const profileIndex = new Uint8Array(vertexCount)\n const touched = new Uint8Array(chunksX * chunksZ)\n const mixed = new Uint8Array(chunksX * chunksZ)\n const dirty = new Set<number>()\n const marks = createMarkStore(budget)\n const cracks = createCrackStore()\n const decalList: TerrainDecal[] = []\n let decalSerial = 0\n let decalsVersion = 0\n const unitDamage = new Map<string, number>()\n const debrisStore = createDebrisStore(() => budget.maxDebris)\n const sliding = new Set<number>()\n const burning = new Map<number, number>()\n const seed = options.seed ?? 1\n let random = createRandom(seed)\n let currentLayout: GroundLayout = options.layout ?? { surface: DEFAULT_PROFILE }\n\n const deformListeners = new Set<(region: TerrainRegion) => void>()\n const emitDeform = (x: number, z: number, radius: number): void => {\n for (const listener of deformListeners) listener({ x, z, radius })\n }\n const grid: HeightGrid = { x0, z0, cellSize, stride, columns, rows, dug }\n /** Sand that is still sliding: what it lowered so far, told once it comes to rest. */\n const slideTally: LossTally = new Map()\n const emitGroundLoss = (tally: LossTally, source: string, minLowering: number): void => {\n if (!options.onGroundLoss) return\n const loss = lossOf(grid, tally, { source, minLowering, shape: source === 'slab' ? 'flat' : 'bowl' })\n if (loss) options.onGroundLoss(loss)\n }\n /** Lowers a vertex to `depth` under the untouched surface, counting it in `tally`. */\n const dropVertex = (index: number, depth: number, tally: LossTally): void => {\n tallyLowered(tally, index, depth - dug[index]!)\n dug[index] = depth\n }\n\n const chunkOfVertex = (column: number, row: number): number => Math.min(chunksZ - 1, Math.floor(row / chunkCells)) * chunksX + Math.min(chunksX - 1, Math.floor(column / chunkCells))\n /** A vertex on a chunk's edge belongs to its neighbours as well. */\n function touchVertex(column: number, row: number): void {\n const chunk = chunkOfVertex(column, row)\n touched[chunk] = 1\n dirty.add(chunk)\n if (column % chunkCells === 0 && column > 0) markChunk(chunk - 1)\n if (row % chunkCells === 0 && row > 0) markChunk(chunk - chunksX)\n if (column % chunkCells === 0 && row % chunkCells === 0 && column > 0 && row > 0) markChunk(chunk - chunksX - 1)\n }\n function markChunk(chunk: number): void {\n touched[chunk] = 1\n dirty.add(chunk)\n }\n\n const profileId = (id: string): number => indexOfProfile.get(id) ?? indexOfProfile.get(DEFAULT_PROFILE) ?? 0\n\n function applyLayout(layout: GroundLayout): void {\n currentLayout = layout\n profileIndex.fill(profileId(layout.surface))\n for (const zone of layout.zones ?? []) {\n const index = profileId(zone.surface)\n const [zx0, zz0, zx1, zz1] = zone.rect\n const column0 = clampIndex(Math.round((zx0 - x0) / cellSize), columns)\n const column1 = clampIndex(Math.round((zx1 - x0) / cellSize), columns)\n const row0 = clampIndex(Math.round((zz0 - z0) / cellSize), rows)\n const row1 = clampIndex(Math.round((zz1 - z0) / cellSize), rows)\n for (let row = row0; row <= row1; row++) profileIndex.fill(index, row * stride + column0, row * stride + column1 + 1)\n }\n if (hasWater) layBeds()\n for (let chunkZ = 0; chunkZ < chunksZ; chunkZ++) {\n for (let chunkX = 0; chunkX < chunksX; chunkX++) {\n const chunk = chunkZ * chunksX + chunkX\n const first = profileIndex[(chunkZ * chunkCells) * stride + chunkX * chunkCells]\n const firstDrop = surface[(chunkZ * chunkCells) * stride + chunkX * chunkCells]! - base[(chunkZ * chunkCells) * stride + chunkX * chunkCells]!\n let isMixed = 0\n const lastRow = Math.min(rows, (chunkZ + 1) * chunkCells)\n const lastColumn = Math.min(columns, (chunkX + 1) * chunkCells)\n for (let row = chunkZ * chunkCells; row <= lastRow && !isMixed; row++) {\n for (let column = chunkX * chunkCells; column <= lastColumn; column++) {\n if (profileIndex[row * stride + column] !== first || surface[row * stride + column]! - base[row * stride + column]! !== firstDrop) {\n isMixed = 1\n break\n }\n }\n }\n mixed[chunk] = isMixed\n dirty.add(chunk)\n }\n }\n for (const excavation of layout.excavations ?? []) excavate(excavation)\n }\n\n /**\n * Digs a construction's trench or pit: every vertex over the rectangle (the cell it starts in to the one it ends in, so the full depth spans the whole\n * rectangle and the wall slopes in the cell outside it) down to its depth, never less deep than it already was. A planned dig is no ground loss.\n */\n function excavate(excavation: GroundExcavation): void {\n const [ex0, ez0, ex1, ez1] = excavation.rect\n const column0 = clampIndex(Math.floor((ex0 - x0) / cellSize + 1e-6), columns)\n const column1 = clampIndex(Math.ceil((ex1 - x0) / cellSize - 1e-6), columns)\n const row0 = clampIndex(Math.floor((ez0 - z0) / cellSize + 1e-6), rows)\n const row1 = clampIndex(Math.ceil((ez1 - z0) / cellSize - 1e-6), rows)\n const alongX = (excavation.along ?? (ex1 - ex0 >= ez1 - ez0 ? 'x' : 'z')) === 'x'\n const from = alongX ? ex0 : ez0, length = Math.max(1e-6, alongX ? ex1 - ex0 : ez1 - ez0)\n const far = excavation.toDepth ?? excavation.depth\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n const at = alongX ? x0 + column * cellSize : z0 + row * cellSize\n const t = Math.max(0, Math.min(1, (at - from) / length))\n const depth = excavation.depth + (far - excavation.depth) * t\n if (depth <= dug[index]!) continue\n dug[index] = depth\n touchVertex(column, row)\n }\n }\n }\n\n /** Lowers the ground under the water, in a bank from the edge of each pool. */\n function layBeds(): void {\n const steps = new Uint8Array(vertexCount)\n for (let index = 0; index < vertexCount; index++) steps[index] = profileList[profileIndex[index]!]!.water ? BANK_CELLS : 0\n for (let pass = 0; pass < BANK_CELLS; pass++) {\n for (let row = 0; row <= rows; row++) {\n for (let column = 0; column <= columns; column++) {\n const index = row * stride + column\n if (steps[index] === 0) continue\n const lowest = Math.min(column > 0 ? steps[index - 1]! : BANK_CELLS, column < columns ? steps[index + 1]! : BANK_CELLS, row > 0 ? steps[index - stride]! : BANK_CELLS, row < rows ? steps[index + stride]! : BANK_CELLS)\n steps[index] = Math.min(steps[index]!, lowest + 1)\n }\n }\n }\n for (let index = 0; index < vertexCount; index++) base[index] = surface[index]! - (profileList[profileIndex[index]!]!.water?.depth ?? 0) * (steps[index]! / BANK_CELLS)\n }\n\n const vertexHeight = (column: number, row: number): number => {\n const index = row * stride + column\n return base[index]! - dug[index]! + loose[index]!\n }\n const contains = (x: number, z: number): boolean => x >= x0 && x <= x1 && z >= z0 && z <= z1\n\n function addDecal(spec: Omit<TerrainDecal, 'id' | 'age'>): void {\n if (decalList.length >= budget.maxDecals) decalList.shift()\n decalList.push({ ...spec, id: ++decalSerial, age: 0 })\n decalsVersion++\n }\n function clearDecalsInside(x: number, z: number, radius: number): void {\n const before = decalList.length\n for (let i = before - 1; i >= 0; i--) {\n const decal = decalList[i]!\n if (decal.kind !== 'ripple' && decal.kind !== 'splat' && decal.kind !== 'crack' && Math.hypot(decal.x - x, decal.z - z) < radius) decalList.splice(i, 1)\n }\n if (decalList.length !== before) decalsVersion++\n }\n\n // `heightAt` and `heightGrid` are twins: both find a point's cell with `cellCoordinate` and blend its corners with `blendCell`, so the grid answers what the point does, to the bit\n /** Where `v` falls along an axis of `count` cells from `origin`, in cells, held inside the last cell: its whole part is the cell, the rest the blend across it. */\n // the blend and the cell are `height-patch`'s, so a patch read anywhere (`heightPatchGrid`) answers what these do\n const cellCoordinate = (v: number, origin: number, count: number): number => cellCoordinateOf(v, origin, count, cellSize)\n const heightOfVertex = (index: number): number => base[index]! - dug[index]! + loose[index]!\n /** The ground in the cell whose first corner is vertex `index`, `tx` and `tz` across it. */\n const blendCell = (index: number, tx: number, tz: number): number =>\n blendHeights(blendHeights(heightOfVertex(index), heightOfVertex(index + 1), tx), blendHeights(heightOfVertex(index + stride), heightOfVertex(index + stride + 1), tx), tz)\n\n function heightAt(x: number, z: number): number {\n // beyond the terrain the ground is untouched: no blow can dig it and a piece thrown out lands on it\n if (!contains(x, z)) return options.baseHeight?.(x, z) ?? 0\n const fx = cellCoordinate(x, x0, columns)\n const fz = cellCoordinate(z, z0, rows)\n const column = fx | 0\n const row = fz | 0\n return blendCell(row * stride + column, fx - column, fz - row)\n }\n\n // the cell and the blend of each column and row a grid reads, kept between grids so a read costs no new arrays\n let gridColumns = new Int32Array(0)\n let gridBlendX = new Float64Array(0)\n let gridRows = new Int32Array(0)\n let gridBlendZ = new Float64Array(0)\n let gridNear = new Float64Array(0)\n let gridFar = new Float64Array(0)\n\n function heightGrid(xs: ArrayLike<number>, zs: ArrayLike<number>, out: Float64Array): void {\n const width = xs.length\n const depth = zs.length\n if (out.length < width * depth) throw new RangeError(`heightGrid: out holds ${out.length} heights, the grid has ${width * depth}`)\n if (gridColumns.length < width) {\n gridColumns = new Int32Array(width)\n gridBlendX = new Float64Array(width)\n }\n if (gridRows.length < depth) {\n gridRows = new Int32Array(depth)\n gridBlendZ = new Float64Array(depth)\n }\n // each column and row as `heightAt` finds it (-1: past the terrain, where the host's `baseHeight` answers), so every height is the one `heightAt` gives, to the bit\n for (let i = 0; i < width; i++) {\n const x = xs[i]!\n const fx = cellCoordinate(x, x0, columns)\n gridColumns[i] = x >= x0 && x <= x1 ? fx | 0 : -1\n gridBlendX[i] = fx - (fx | 0)\n }\n for (let j = 0; j < depth; j++) {\n const z = zs[j]!\n const fz = cellCoordinate(z, z0, rows)\n gridRows[j] = z >= z0 && z <= z1 ? fz | 0 : -1\n gridBlendZ[j] = fz - (fz | 0)\n }\n // `blendCell` blends along x first, then along z: the two x blends of a column depend on its row only, so they are made once per row of cells and\n // each point is then the same last step `blendCell` takes, on the same numbers (the same bits); a lattice finer than the cells reads each row many times\n if (gridNear.length < width) {\n gridNear = new Float64Array(width)\n gridFar = new Float64Array(width)\n }\n let blended = -2\n for (let j = 0; j < depth; j++) {\n const row = gridRows[j]!\n const tz = gridBlendZ[j]!\n if (row < 0) {\n for (let i = 0; i < width; i++) out[j * width + i] = options.baseHeight?.(xs[i]!, zs[j]!) ?? 0\n continue\n }\n if (row !== blended) {\n blended = row\n for (let i = 0; i < width; i++) {\n const column = gridColumns[i]!\n if (column < 0) continue\n const index = row * stride + column\n const tx = gridBlendX[i]!\n gridNear[i] = blendHeights(heightOfVertex(index), heightOfVertex(index + 1), tx)\n gridFar[i] = blendHeights(heightOfVertex(index + stride), heightOfVertex(index + stride + 1), tx)\n }\n }\n for (let i = 0; i < width; i++) {\n if (gridColumns[i]! < 0) {\n out[j * width + i] = options.baseHeight?.(xs[i]!, zs[j]!) ?? 0\n continue\n }\n out[j * width + i] = blendHeights(gridNear[i]!, gridFar[i]!, tz)\n }\n }\n }\n\n function heightPatch(minX: number, maxX: number, minZ: number, maxZ: number, into?: Float64Array): HeightPatch | null {\n // the same test `heightGrid` makes of each point: a rectangle wholly inside reads no `baseHeight`\n if (!(minX >= x0 && maxX <= x1 && minZ >= z0 && maxZ <= z1)) return null\n const column0 = cellCoordinate(minX, x0, columns) | 0\n const row0 = cellCoordinate(minZ, z0, rows) | 0\n const width = (cellCoordinate(maxX, x0, columns) | 0) + 2 - column0\n const depth = (cellCoordinate(maxZ, z0, rows) | 0) + 2 - row0\n const heights = into && into.length >= width * depth ? into : new Float64Array(width * depth)\n for (let j = 0; j < depth; j++) {\n const from = (row0 + j) * stride + column0\n for (let i = 0; i < width; i++) heights[j * width + i] = heightOfVertex(from + i)\n }\n return { cellSize, originX: x0, originZ: z0, columns, rows, column0, row0, width, depth, heights }\n }\n\n function heightRange(minX: number, maxX: number, minZ: number, maxZ: number): { low: number; high: number } | null {\n if (!contains(minX, minZ) || !contains(maxX, maxZ)) return null\n const cellOf = (v: number, origin: number, count: number): number => Math.floor(Math.max(0, Math.min(count - 1e-6, (v - origin) / cellSize)))\n const column0 = cellOf(minX, x0, columns)\n const column1 = cellOf(maxX, x0, columns) + 1\n const row0 = cellOf(minZ, z0, rows)\n const row1 = cellOf(maxZ, z0, rows) + 1\n let low = Infinity\n let high = -Infinity\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n const h = base[index]! - dug[index]! + loose[index]!\n if (h < low) low = h\n if (h > high) high = h\n }\n }\n return { low, high }\n }\n\n const vertexOf = (x: number, z: number): { column: number; row: number; index: number } => {\n const column = clampIndex(Math.round((x - x0) / cellSize), columns)\n const row = clampIndex(Math.round((z - z0) / cellSize), rows)\n return { column, row, index: row * stride + column }\n }\n\n function waterAt(x: number, z: number): { liquid: string; level: number; depth: number } | null {\n if (!hasWater || !contains(x, z)) return null\n const { index } = vertexOf(x, z)\n const water = profileList[profileIndex[index]!]!.water\n if (!water) return null\n const level = surface[index]!\n const depth = level - heightAt(x, z)\n return depth > WATER_MINIMUM ? { liquid: water.liquid, level, depth } : null\n }\n const exposedAt = (x: number, z: number): TerrainMaterial => {\n const { column, row } = vertexOf(x, z)\n return vertexMaterial(column, row)\n }\n const footAt = (x: number, z: number): number => {\n if (!contains(x, z)) return heightAt(x, z)\n return heightAt(x, z) - (exposedAt(x, z).footing?.sink ?? 0)\n }\n function walkFactorAt(x: number, z: number): number {\n if (!contains(x, z)) return 1\n const water = waterAt(x, z) ? profileList[profileIndex[vertexOf(x, z).index]!]!.water : null\n return Math.min(water?.drag ?? 1, exposedAt(x, z).footing?.drag ?? 1)\n }\n function ripple(x: number, z: number, radius: number): void {\n addDecal({ kind: 'ripple', x, z, radius, angle: 0, material: exposedAt(x, z).id })\n }\n function press(spec: { x: number; z: number; radius: number; angle?: number; kind?: 'print' | 'rut' }): boolean {\n if (!contains(spec.x, spec.z)) return false\n if (waterAt(spec.x, spec.z)) {\n ripple(spec.x, spec.z, spec.radius * 2)\n return true\n }\n const material = exposedAt(spec.x, spec.z)\n if (!material.footing?.prints) return false\n addDecal({ kind: spec.kind ?? 'print', x: spec.x, z: spec.z, radius: spec.radius, angle: spec.angle ?? 0, material: material.id })\n return true\n }\n\n function vertexMaterial(column: number, row: number): TerrainMaterial {\n const index = row * stride + column\n return materials.get(stratumMaterialAtDepth(profileList[profileIndex[index]!]!, dug[index]!))!\n }\n\n /** `material(columnAt(x, z).material)` without building the column: the pieces ask it for every round contact. */\n function surfaceMaterialAt(x: number, z: number): TerrainMaterial {\n const column = clampIndex(Math.round((x - x0) / cellSize), columns)\n const row = clampIndex(Math.round((z - z0) / cellSize), rows)\n const index = row * stride + column\n const which = profileIndex[index]!\n const depth = Math.min(maxDepthOf[which]!, dug[index]! + marks.depthAt(x, z))\n return materials.get(stratumMaterialAtDepth(profileList[which]!, depth))!\n }\n\n function rollingAt(x: number, z: number): number | undefined {\n return surfaceMaterialAt(x, z).rolling\n }\n\n function rollingDampingAt(x: number, z: number): number | undefined {\n return surfaceMaterialAt(x, z).rollingDamping\n }\n\n function columnAt(x: number, z: number): TerrainColumn {\n const { index } = vertexOf(x, z)\n const which = profileIndex[index]!\n const profile = profileList[which]!\n const depth = Math.min(maxDepthOf[which]!, dug[index]! + marks.depthAt(x, z))\n const layer = stratumAtDepth(profile, depth)\n return { profile: profile.id, material: layer.stratum.material, stratum: layer.index, depth, remaining: maxDepthOf[which]! - depth, scorch: scorch[index]!, loose: loose[index]! }\n }\n\n /** Removes from a vertex: what is heaped first, then the column, never past its limit. Returns what came off. */\n function removeFromVertex(index: number, amount: number): number {\n const fromLoose = Math.min(loose[index]!, amount)\n loose[index] = loose[index]! - fromLoose\n const fromColumn = Math.min(maxDepthOf[profileIndex[index]!]! - dug[index]!, amount - fromLoose)\n if (fromColumn > 0) dug[index] = dug[index]! + fromColumn\n return fromLoose + Math.max(0, fromColumn)\n }\n /** Adds to a vertex: a soft floor fills what was dug, then heaps; on a rigid one the rubble just heaps. */\n function addToVertex(index: number, amount: number, fillsColumn: boolean): void {\n const filled = fillsColumn ? Math.min(dug[index]!, amount) : 0\n dug[index] = dug[index]! - filled\n loose[index] = loose[index]! + amount - filled\n }\n const isSoftExposed = (index: number): boolean => materials.get(stratumAtDepth(profileList[profileIndex[index]!]!, dug[index]!).stratum.material)!.reposeDegrees !== undefined\n\n /** The vertices under a rectangle centred at (x, z): the cells a blade of that size bites. */\n function verticesUnder(x: number, z: number, size: readonly [number, number]): number[] {\n // as many vertices across as the size has cells (each vertex stands for its cell's area), centred on (x, z)\n const nu = Math.max(1, Math.round(size[0] / cellSize)), nv = Math.max(1, Math.round(size[1] / cellSize))\n const column0 = clampIndex(Math.round((x - x0) / cellSize - (nu - 1) / 2), columns), column1 = clampIndex(column0 + nu - 1, columns)\n const row0 = clampIndex(Math.round((z - z0) / cellSize - (nv - 1) / 2), rows), row1 = clampIndex(row0 + nv - 1, rows)\n const out: number[] = []\n for (let row = row0; row <= row1; row++) for (let column = column0; column <= column1; column++) out.push(row * stride + column)\n return out\n }\n const touchIndex = (index: number): void => touchVertex(index % stride, Math.floor(index / stride))\n /** The material a shovel meets at a vertex: the loose earth heaped there, else the stratum at the depth dug so far. */\n const materialAtVertex = (index: number): TerrainMaterial =>\n loose[index]! > 1e-4 ? materials.get('soil')! : materials.get(stratumAtDepth(profileList[profileIndex[index]!]!, dug[index]!).stratum.material)!\n\n /** Lowers a vertex by up to `depth` through what a shovel digs (heaped earth first), stopping at what it does not. Returns how far it went. */\n function digVertex(index: number, depth: number): number {\n let left = depth\n while (left > 1e-6) {\n if (loose[index]! > 1e-6) {\n const take = Math.min(loose[index]!, left)\n loose[index] = loose[index]! - take\n left -= take\n continue\n }\n const profile = profileList[profileIndex[index]!]!\n const layer = stratumAtDepth(profile, dug[index]!)\n if (!materials.get(layer.stratum.material)?.dig || dug[index]! >= maxDepthOf[profileIndex[index]!]! - 1e-6) break\n const take = Math.min(left, layer.top + layer.stratum.thickness - dug[index]!)\n if (take <= 1e-6) break\n dug[index] = dug[index]! + take\n left -= take\n }\n return depth - left\n }\n\n /** Heaps `volume` of earth round (x, z), highest in the middle, and lets it settle to its slope. */\n function heapAt(x: number, z: number, volume: number): void {\n if (volume <= 0) return\n const radius = Math.max(cellSize * 2, Math.cbrt(volume) * 1.6)\n const indices = verticesUnder(x, z, [2 * radius, 2 * radius])\n const weight = (index: number): number => {\n const px = x0 + (index % stride) * cellSize, pz = z0 + Math.floor(index / stride) * cellSize\n const q = Math.hypot(px - x, pz - z) / radius\n return q < 1 ? 1 - q * q : 0\n }\n const total = indices.reduce((sum, i) => sum + weight(i), 0)\n if (total <= 0) return\n const cellArea = cellSize * cellSize\n for (const index of indices) {\n const w = weight(index)\n if (w <= 0) continue\n loose[index] = loose[index]! + (volume * w) / (total * cellArea)\n sliding.add(index)\n touchIndex(index)\n }\n emitDeform(x, z, radius)\n }\n\n function dig(spec: TerrainDig): TerrainDigResult {\n const size = spec.size ?? [0.3, 0.3], depth = spec.depth ?? 0.2\n const centre = vertexOf(spec.x, spec.z).index\n // under water a shovel brings nothing up\n if (profileList[profileIndex[centre]!]!.water) return { volume: 0, material: 'water', effort: 0, refused: 'water' }\n const met = materialAtVertex(centre)\n if (!met.dig) return { volume: 0, material: met.id, effort: 0, refused: met.id }\n if (met.dig.closes) return { volume: 0, material: met.id, effort: met.dig.effort, closes: true }\n const cellArea = cellSize * cellSize\n const tally: LossTally = new Map()\n let volume = 0\n for (const index of verticesUnder(spec.x, spec.z, size)) {\n const before = dug[index]!\n const went = digVertex(index, depth)\n if (went <= 0) continue\n tallyLowered(tally, index, dug[index]! - before)\n volume += went * cellArea\n sliding.add(index)\n touchIndex(index)\n }\n marks.removeInside(spec.x, spec.z, Math.max(size[0], size[1]) / 2)\n emitDeform(spec.x, spec.z, Math.max(size[0], size[1]))\n // what the blade took from under a footing is ground lost under it: the structure feels it\n emitGroundLoss(tally, 'dig', 0)\n if (spec.dump) heapAt(spec.dump.x, spec.dump.z, volume)\n return { volume, material: met.id, effort: volume > 0 ? met.dig.effort : 0 }\n }\n\n function fill(spec: TerrainFill): number {\n const cellArea = cellSize * cellSize\n // the earth of the heap round `from`, nearest first, up to the volume asked\n let taken = 0\n const source = verticesUnder(spec.from.x, spec.from.z, [2 * spec.from.radius, 2 * spec.from.radius]).filter((i) => loose[i]! > 1e-6)\n for (const index of source) {\n if (taken >= spec.volume) break\n const take = Math.min(loose[index]!, (spec.volume - taken) / cellArea)\n loose[index] = loose[index]! - take\n taken += take * cellArea\n sliding.add(index)\n touchIndex(index)\n }\n if (taken <= 0) return 0\n emitDeform(spec.from.x, spec.from.z, spec.from.radius)\n // laid in the hole: the deepest vertices of the bite first, so the hole closes level\n const target = verticesUnder(spec.x, spec.z, spec.size ?? [0.3, 0.3]).sort((a, b) => dug[b]! - dug[a]!)\n let left = taken\n for (const index of target) {\n if (left <= 1e-9) break\n const amount = Math.min(left / cellArea, Math.max(dug[index]!, (left / cellArea) / target.length))\n addToVertex(index, amount, true)\n left -= amount * cellArea\n sliding.add(index)\n touchIndex(index)\n }\n if (left > 1e-9) heapAt(spec.x, spec.z, left)\n emitDeform(spec.x, spec.z, Math.max(...(spec.size ?? [0.3, 0.3])))\n return taken\n }\n\n /** Digs a lobed bowl into the height field, heaps the rim share around it. */\n function stampBowl(x: number, z: number, radius: number, depth: number, rimVolume: number, lossSource: string | null = 'crater'): void {\n const reach = radius * RIM_REACH\n const column0 = clampIndex(Math.floor((x - reach - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((x + reach - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((z - reach - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((z + reach - z0) / cellSize), rows)\n const phaseA = random() * 6.283\n const phaseB = random() * 6.283\n const shapeOf = (px: number, pz: number): number => {\n const angle = Math.atan2(pz - z, px - x)\n return Math.hypot(px - x, pz - z) / (radius * (1 + 0.12 * Math.sin(angle * 5 + phaseA) + 0.06 * Math.sin(angle * 11 + phaseB)))\n }\n let rimWeight = 0\n if (rimVolume > 0) {\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const q = shapeOf(x0 + column * cellSize, z0 + row * cellSize)\n if (q >= 1 && q < RIM_REACH) rimWeight += Math.sin(((q - 1) / (RIM_REACH - 1)) * Math.PI)\n }\n }\n }\n const cellArea = cellSize * cellSize\n const tally: LossTally = new Map()\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const q = shapeOf(x0 + column * cellSize, z0 + row * cellSize)\n const index = row * stride + column\n if (q < 1) {\n const before = dug[index]!\n removeFromVertex(index, depth * (1 - q * q) * (0.92 + random() * 0.16))\n tallyLowered(tally, index, dug[index]! - before)\n sliding.add(index)\n touchVertex(column, row)\n } else if (q < RIM_REACH && rimWeight > 0) {\n loose[index] = loose[index]! + (rimVolume * Math.sin(((q - 1) / (RIM_REACH - 1)) * Math.PI)) / (rimWeight * cellArea)\n sliding.add(index)\n touchVertex(column, row)\n }\n }\n }\n marks.removeInside(x, z, radius)\n clearDecalsInside(x, z, radius)\n emitDeform(x, z, reach)\n if (lossSource) emitGroundLoss(tally, lossSource, 0)\n }\n\n function throwPieces(spec: { x: number; y: number; z: number; volume: number; material: TerrainMaterial; energy: number; direction?: readonly number[]; quota: number; bowlRadius: number; blow: TerrainBlow }): void {\n const radius = PIECE_RADIUS[spec.material.debris]\n const pieceVolume = (4 / 3) * Math.PI * radius ** 3\n const count = Math.min(spec.quota, Math.max(1, Math.round(spec.volume / pieceVolume)))\n const mass = Math.max(1e-3, spec.volume * 1500)\n const launch = Math.min(MAX_PIECE_SPEED[spec.blow], Math.sqrt((2 * spec.energy * THROW_SHARE) / mass))\n for (let i = 0; i < count; i++) {\n const angle = random() * 6.283\n const out = spec.bowlRadius * Math.sqrt(random()) * 0.8\n const speed = launch * (0.5 + random() * 0.7)\n const spread = 0.35 + random() * 0.65\n const backX = spec.direction ? -(spec.direction[0] ?? 0) * 0.4 : 0\n const backZ = spec.direction ? -(spec.direction[2] ?? 0) * 0.4 : 0\n debrisStore.throwPiece({\n material: spec.material.id,\n kind: spec.material.debris,\n radius: radius * (0.6 + random() * 0.9),\n position: [spec.x + Math.cos(angle) * out, spec.y + 0.03, spec.z + Math.sin(angle) * out],\n velocity: [(Math.cos(angle) * spread + backX) * speed, (0.6 + random() * 0.7) * speed, (Math.sin(angle) * spread + backZ) * speed],\n spin: [(random() - 0.5) * 14, (random() - 0.5) * 14, (random() - 0.5) * 14],\n })\n }\n }\n\n function strike(blow: TerrainBlow, spec: TerrainStrike): TerrainBlowResult {\n const { x, z } = spec\n const start = columnAt(x, z)\n const profile = profileMap.get(start.profile)!\n const waterHere = waterAt(x, z)\n const waterResult = waterHere ? { water: { liquid: waterHere.liquid, level: waterHere.level } } : {}\n if (waterHere) ripple(x, z, Math.min(1.5, 0.15 + Math.cbrt(spec.energy) / 40))\n const removed: { material: string; volume: number }[] = []\n const point: [number, number, number] = [x, heightAt(x, z), z]\n const startLayer = stratumAtDepth(profile, start.depth)\n if (start.loose <= 0 && materials.get(startLayer.stratum.material)!.units) return strikeUnits(blow, spec, startLayer, profile, point)\n const blowEnergy = spec.energy * (waterHere ? (profile.water?.blowShare[blow] ?? 1) : 1)\n let energy = blowEnergy\n let depth = start.depth\n let radius = 0\n let carved = 0\n let breached = false\n const firstMaterial = materials.get(start.material)!\n if (start.loose <= 0) {\n for (;;) {\n const layer = stratumAtDepth(profile, depth)\n const bottom = layer.top + layer.stratum.thickness\n const room = bottom - depth\n if (room <= 1e-6) break\n const material = materials.get(layer.stratum.material)!\n const response = material.hits[blow]\n if (!response || energy < (response.thresholdJoules ?? 0)) break\n const bars = layer.stratum.reinforcement\n // a contact charge with enough for the whole thickness of a rigid layer breaks it right through: the shock spalls the far face and the layer goes in one piece, bars or not\n const breach = blow === 'explosive' ? material.breach : undefined\n const breachJoules = breach ? breach.joulesPerCubedThickness * layer.stratum.thickness ** 3 : Infinity\n if (breach && depth <= layer.top + 1e-6 && energy >= breachJoules) {\n const takenRadius = layer.stratum.thickness * breach.radiusOverThickness * Math.cbrt(energy / breachJoules)\n const takenVolume = (Math.PI * takenRadius * takenRadius * room) / 2\n energy -= breachJoules\n depth += room\n carved += room\n breached = true\n radius = Math.max(radius, takenRadius)\n removed.push({ material: material.id, volume: takenVolume })\n continue\n }\n const pastCover = bars !== undefined && depth - layer.top >= bars.cover - 1e-6\n const specificEnergy = response.specificEnergy * (pastCover ? bars.resistance : 1)\n const limit = bars && !pastCover ? Math.min(room, layer.top + bars.cover - depth) : room\n const aspect = response.aspect * caliberAspect(spec.caliber)\n const volume = energy / specificEnergy\n const wanted = Math.cbrt((2 * volume) / (Math.PI * aspect))\n const wantedDepth = wanted * aspect\n const takenDepth = Math.min(wantedDepth, limit)\n const takenRadius = takenDepth < wantedDepth ? takenDepth / aspect : wanted\n const takenVolume = (Math.PI * takenRadius * takenRadius * takenDepth) / 2\n energy -= takenVolume * specificEnergy\n depth += takenDepth\n carved += takenDepth\n radius = Math.max(radius, takenRadius, response.minRadius ?? 0, spec.contactRadius ?? 0, caliberRadius(spec.caliber))\n const last = removed[removed.length - 1]\n if (last?.material === material.id) (last as { volume: number }).volume += takenVolume\n else removed.push({ material: material.id, volume: takenVolume })\n if (energy <= 1e-6 || takenDepth >= wantedDepth - 1e-9) break\n }\n } else {\n // a loose heap has no strength: it takes the blow as soft ground before the column does\n const response = firstMaterial.hits[blow]\n if (response && energy >= (response.thresholdJoules ?? 0)) {\n const volume = energy / response.specificEnergy\n radius = Math.cbrt((2 * volume) / (Math.PI * response.aspect))\n carved = radius * response.aspect\n removed.push({ material: firstMaterial.id, volume })\n }\n }\n let collapsed = loadBars(blow, spec.energy, x, z, profile)\n const crack = crackAround(blow, spec.energy, x, z, start.loose > 0 ? undefined : firstMaterial)\n const extra = { ...(crack ? { crack } : {}), ...(breached ? { breached } : {}), ...waterResult }\n // a weight that lands flat (its contact as wide as the dent) presses the ground down: it packs the soil under it, it does not take it away\n const pressed = spec.contactRadius !== undefined && spec.contactRadius >= radius\n if (radius <= 0) return { point, radius: 0, depth: 0, totalDepth: columnAt(x, z).depth, removed: [], exposed: start.material, atLimit: start.remaining <= 1e-6, rebarExposed: rebarShowing(profile, start.depth), collapsed, fine: true, ...extra }\n\n // a rigid floor cannot go down any more where it is already deep: the next blow breaks the edge of the hole, so a hole in a slab opens as it deepens\n if (firstMaterial.reposeDegrees === undefined && start.loose <= 0) radius *= 1 + RIGID_WIDENING * (start.depth / maxDepthOfProfile(profile))\n\n const volumeTotal = removed.reduce((sum, entry) => sum + entry.volume, 0)\n const fine = radius < cellSize * FINE_CELLS\n if (fine) depositMark({ x, z, radius, depth: carved, blow, profile, cap: maxDepthOfProfile(profile) })\n else {\n const rimShare = materials.get(removed[0]!.material)!.rimShare ?? 0\n stampBowl(x, z, radius, carved, volumeTotal * rimShare, pressed ? null : 'crater')\n }\n if (firstMaterial.cracks) addDecal({ kind: 'crack', x, z, radius: Math.max(CRACK_MIN_RADIUS, radius * firstMaterial.cracks), angle: random() * 6.283, material: firstMaterial.id })\n // under water what comes off stays a cloud at the bottom, unless a blast opens the water\n let quota = waterHere && blow !== 'explosive' ? 0 : budget.maxDebrisPerBlow\n for (const entry of removed) {\n const material = materials.get(entry.material)!\n const thrown = entry.volume * (1 - (fine ? 0 : (material.rimShare ?? 0)))\n if (thrown <= 0 || quota <= 0) continue\n const share = Math.max(1, Math.round((quota * entry.volume) / volumeTotal))\n throwPieces({ x, y: point[1], z, volume: thrown, material, energy: spec.energy * (entry.volume / volumeTotal), direction: spec.direction, quota: share, bowlRadius: radius, blow })\n quota -= share\n }\n // a breach bares the bars under the same blow that broke the concrete, so they take that blow's load at once and, over a void, may let the floor go\n if (breached) collapsed = loadBars(blow, spec.energy, x, z, profile) || collapsed\n const after = columnAt(x, z)\n return { point, radius, depth: carved, totalDepth: after.depth, removed, exposed: after.material, atLimit: after.remaining <= 1e-4, rebarExposed: rebarShowing(profile, after.depth), collapsed, fine, ...extra }\n }\n\n /** A rigid surface cracks around a hard enough blow, the lines running out with the cube root of the energy; a soft one (soil, sand, turf) only gives way. */\n function crackAround(blow: TerrainBlow, energy: number, x: number, z: number, material: TerrainMaterial | undefined): ReturnType<typeof cracks.add> | undefined {\n const response = material?.crack\n if (!material || !response || energy < response.thresholdJoules) return undefined\n // a cut does not crack a slab; a bullet, a hammer and a blast do\n if (blow === 'slash') return undefined\n const scale = Math.cbrt(energy / CRACK_REFERENCE_JOULES)\n return cracks.add({ x, z, reach: response.reach * scale, width: response.width * scale, material: material.id, seed: Math.floor(random() * 2 ** 31) }, budget.maxCracks)\n }\n\n /**\n * A floor of separate pieces: a blow does not dig them, it shakes them. Each takes the energy that reaches it, added blow by blow, and past its limit it comes off the bed whole and is thrown.\n * Under the limit the blow only chips it.\n */\n function strikeUnits(blow: TerrainBlow, spec: TerrainStrike, layer: { stratum: TerrainStratum; top: number }, profile: TerrainProfile, point: [number, number, number]): TerrainBlowResult {\n const { x, z, energy } = spec\n const material = materials.get(layer.stratum.material)!\n const units = material.units!\n const response = material.hits[blow]\n const bottom = layer.top + layer.stratum.thickness\n const miss: TerrainBlowResult = { point, radius: 0, depth: 0, totalDepth: layer.top, removed: [], exposed: material.id, atLimit: false, rebarExposed: false, collapsed: false, fine: true }\n if (!response || energy < (response.thresholdJoules ?? 0)) return miss\n const reach = Math.max(spec.contactRadius ?? 0, response.minRadius ?? 0, caliberRadius(spec.caliber), Math.cbrt((2 * energy) / response.specificEnergy / (Math.PI * response.aspect * caliberAspect(spec.caliber))))\n const rowFirst = Math.floor((z - reach) / units.width)\n const rowLast = Math.floor((z + reach) / units.width)\n let loosened = 0\n for (let row = rowFirst; row <= rowLast; row++) {\n const shift = Math.abs(row % 2) * cellSize\n const unitFirst = Math.floor((x - reach - shift) / units.length)\n const unitLast = Math.floor((x + reach - shift) / units.length)\n for (let unit = unitFirst; unit <= unitLast; unit++) {\n const minX = unit * units.length + shift\n const minZ = row * units.width\n const near = Math.hypot(Math.max(minX - x, 0, x - minX - units.length), Math.max(minZ - z, 0, z - minZ - units.width))\n if (near > reach) continue\n const key = `${unit}:${row}`\n const taken = (unitDamage.get(key) ?? 0) + energy * (1 - (near / (reach + 1e-6)) ** 2)\n unitDamage.set(key, taken)\n if (taken >= units.looseJoules && liftUnit(minX, minZ, units, bottom, material, profile)) {\n loosened++\n const speed = Math.min(MAX_PIECE_SPEED[blow], Math.sqrt((2 * energy * THROW_SHARE) / Math.max(1, loosened * 15)))\n const angle = random() * 6.283\n debrisStore.throwPiece({ material: material.id, kind: 'blocks', radius: units.length / 2, position: [minX + units.length / 2, point[1] + 0.05, minZ + units.width / 2], velocity: [Math.cos(angle) * speed * 0.6, speed * (0.5 + random() * 0.5), Math.sin(angle) * speed * 0.6], spin: [(random() - 0.5) * 8, (random() - 0.5) * 8, (random() - 0.5) * 8] })\n }\n }\n }\n if (loosened === 0) {\n // not enough to lift a piece: a chip off its face and a hairline\n addDecal({ kind: 'crack', x, z, radius: Math.max(0.05, reach * 2), angle: random() * 6.283, material: material.id })\n throwPieces({ x, y: point[1], z, volume: 1e-5, material: { ...material, debris: 'chips' }, energy, ...(spec.direction ? { direction: spec.direction } : {}), quota: 3, bowlRadius: 0.02, blow })\n return { ...miss, radius: Math.max(0.02, Math.min(reach, 0.06)) }\n }\n emitDeform(x, z, reach + units.length)\n clearDecalsInside(x, z, reach)\n const volume = loosened * units.length * units.width * layer.stratum.thickness\n const after = columnAt(x, z)\n return { point, radius: reach, depth: layer.stratum.thickness, totalDepth: after.depth, removed: [{ material: material.id, volume }], exposed: after.material, atLimit: false, rebarExposed: false, collapsed: false, fine: false }\n }\n\n /** Takes one piece off its bed. False when it had already gone. */\n function liftUnit(minX: number, minZ: number, units: { length: number; width: number }, bottom: number, material: TerrainMaterial, profile: TerrainProfile): boolean {\n const column0 = clampIndex(Math.round((minX - x0) / cellSize), columns)\n const column1 = clampIndex(Math.round((minX + units.length - x0) / cellSize), columns)\n const row0 = clampIndex(Math.round((minZ - z0) / cellSize), rows)\n const row1 = clampIndex(Math.round((minZ + units.width - z0) / cellSize), rows)\n let lifted = false\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n if (profileList[profileIndex[index]!]!.id !== profile.id || dug[index]! >= bottom) continue\n if (materials.get(stratumAtDepth(profile, dug[index]!).stratum.material) !== material) continue\n dug[index] = bottom\n lifted = true\n touchVertex(column, row)\n }\n }\n return lifted\n }\n\n /**\n * A blow loads the bars that are bare around it: they bend, and past their limit they give way. The bowl a blow would open tells how far it reaches. Where the slab has nothing under it, the floor goes with them.\n */\n function loadBars(blow: TerrainBlow, energy: number, x: number, z: number, profile: TerrainProfile): boolean {\n const bars = profile.strata.find((stratum) => stratum.reinforcement)\n if (!bars?.reinforcement) return false\n const response = materials.get(bars.material)!.hits[blow]\n if (!response || energy < (response.thresholdJoules ?? 0)) return false\n const yieldJoules = bars.reinforcement.yieldJoules ?? DEFAULT_BAR_YIELD_JOULES\n let cover = bars.reinforcement.cover\n for (const stratum of profile.strata) {\n if (stratum === bars) break\n cover += stratum.thickness\n }\n const reach = Math.max(cellSize * FINE_CELLS, Math.cbrt((2 * energy) / response.specificEnergy / (Math.PI * response.aspect)) * (1 + RIGID_WIDENING))\n const column0 = clampIndex(Math.floor((x - reach - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((x + reach - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((z - reach - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((z + reach - z0) / cellSize), rows)\n const limit = maxDepthOfProfile(profile)\n let collapsed = false\n const tally: LossTally = new Map()\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n if (dug[index]! < cover) continue\n const q = Math.hypot(x0 + column * cellSize - x, z0 + row * cellSize - z) / reach\n if (q >= 1) continue\n barBend[index] = barBend[index]! + (energy / yieldJoules) * (1 - q * q)\n touchVertex(column, row)\n if (barBend[index]! >= 1 && profile.drop !== undefined && dug[index]! >= limit * COLLAPSE_DEPTH_SHARE && dug[index]! < limit + profile.drop) {\n dropVertex(index, limit + profile.drop, tally)\n collapsed = true\n }\n }\n }\n if (collapsed) giveWay({ x, z, reach, profile, tally })\n emitGroundLoss(tally, 'slab', 0)\n return collapsed\n }\n\n /** What gave way takes down what was already bending around it, and what stood there must look again. */\n function giveWay(spec: { x: number; z: number; reach: number; profile: TerrainProfile; tally: LossTally }): void {\n const { x, z, reach, profile, tally } = spec\n emitDeform(x, z, reach)\n if (profile.drop === undefined) return\n const limit = maxDepthOfProfile(profile)\n const column0 = clampIndex(Math.floor((x - reach - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((x + reach - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((z - reach - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((z + reach - z0) / cellSize), rows)\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n if (barBend[index]! >= COLLAPSE_SPREAD_BEND && dug[index]! < limit + profile.drop) {\n dropVertex(index, limit + profile.drop, tally)\n touchVertex(column, row)\n }\n }\n }\n }\n\n /** Depth under the surface of the bars of a profile, and the stratum that holds them. */\n function barsOf(profile: TerrainProfile): { stratum: TerrainStratum; cover: number } | null {\n const bars = profile.strata.find((stratum) => stratum.reinforcement)\n if (!bars?.reinforcement) return null\n let cover = bars.reinforcement.cover\n for (const stratum of profile.strata) {\n if (stratum === bars) break\n cover += stratum.thickness\n }\n return { stratum: bars, cover }\n }\n\n /**\n * Weights on bare bars. Each bar over the hole works as a beam that yields at its plastic moment fy·d³/6; the bars of a mesh crossing a hole of any size hold 8·Mp/spacing\n * on a spot, so the bend is the weight over that. Weights over the same bars add up (a stack, things side by side). The share of a footprint on intact concrete is carried\n * by the concrete. Bars do not spring back: the bend only grows.\n */\n function bearAll(loads: readonly TerrainLoad[]): boolean {\n const bends = new Map<number, number>()\n const touched: { load: TerrainLoad; reach: number; profile: TerrainProfile }[] = []\n for (const load of loads) {\n const spread = spreadLoad(load, bends)\n if (spread) touched.push({ load, ...spread })\n }\n let opened = false\n const tally: LossTally = new Map()\n for (const [index, bend] of bends) {\n if (barBend[index]! >= bend) continue\n barBend[index] = bend\n const column = index % stride\n const row = (index - column) / stride\n touchVertex(column, row)\n const profile = profileList[profileIndex[index]!]!\n const limit = maxDepthOfProfile(profile)\n if (bend >= 1 && profile.drop !== undefined && dug[index]! >= limit * COLLAPSE_DEPTH_SHARE && dug[index]! < limit + profile.drop) {\n dropVertex(index, limit + profile.drop, tally)\n opened = true\n }\n }\n if (opened) for (const { load, reach, profile } of touched) giveWay({ x: load.x, z: load.z, reach, profile, tally })\n emitGroundLoss(tally, 'slab', 0)\n return opened\n }\n\n /** Adds the bend one weight gives the bare bars under it to `bends`; null where it stands on no bare bars. */\n function spreadLoad(load: TerrainLoad, bends: Map<number, number>): { reach: number; profile: TerrainProfile } | null {\n if (!contains(load.x, load.z) || load.newtons <= 0) return null\n const profile = profileList[profileIndex[vertexOf(load.x, load.z).index]!]!\n const bars = barsOf(profile)\n if (!bars) return null\n const reinforcement = bars.stratum.reinforcement!\n const moment = ((reinforcement.yieldPa ?? DEFAULT_BAR_YIELD_PA) * (reinforcement.diameter ?? DEFAULT_BAR_DIAMETER) ** 3) / 6\n const holds = (8 * moment) / reinforcement.spacing\n // the footprint of a box reaches its corners: a disc of its half side would leave them standing on the slab\n const footprint = load.radius * Math.SQRT2 + cellSize\n // and the bars of a hole carry together what stands on it: weights side by side add up as a stack does\n const reach = Math.max(footprint, BARS_SHARE_REACH)\n const column0 = clampIndex(Math.floor((load.x - reach - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((load.x + reach - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((load.z - reach - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((load.z + reach - z0) / cellSize), rows)\n const bare: number[] = []\n let under = 0\n let onBars = 0\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const distance = Math.hypot(x0 + column * cellSize - load.x, z0 + row * cellSize - load.z)\n if (distance >= reach) continue\n const index = row * stride + column\n const isBare = dug[index]! >= bars.cover\n if (isBare) bare.push(index)\n if (distance >= footprint) continue\n under++\n if (isBare) onBars++\n }\n }\n if (onBars === 0) return null\n const bend = (load.newtons * (onBars / under)) / holds\n for (const index of bare) bends.set(index, (bends.get(index) ?? 0) + bend)\n return { reach, profile }\n }\n\n const maxDepthOfProfile = (profile: TerrainProfile): number => maxDepthOf[indexOfProfile.get(profile.id)!]!\n function rebarShowing(profile: TerrainProfile, depth: number): boolean {\n const layer = stratumAtDepth(profile, depth)\n return layer.stratum.reinforcement !== undefined && depth - layer.top >= layer.stratum.reinforcement.cover - 1e-6\n }\n\n function depositMark(spec: { x: number; z: number; radius: number; depth: number; blow: TerrainBlow; profile: TerrainProfile; cap: number }): void {\n const { x, z, radius, depth, blow, profile, cap } = spec\n const dugHere = dug[vertexOf(x, z).index]!\n const existing = marks.near(x, z, radius)\n let mark: TerrainMark\n if (existing) {\n existing.radius = Math.hypot(existing.radius, radius)\n existing.depth = Math.min(cap - dugHere, existing.depth + depth)\n existing.count++\n existing.blow = blow\n mark = existing\n } else {\n mark = marks.add({ x, z, radius, depth: Math.min(cap - dugHere, depth), blow, material: '' })\n }\n mark.material = stratumAtDepth(profile, dugHere + mark.depth - 1e-6).stratum.material\n if (mark.radius >= cellSize * FINE_CELLS || mark.depth >= cellSize * FINE_DEPTH_CELLS) {\n const bowlRadius = Math.max(mark.radius, cellSize * FINE_CELLS)\n const bowlDepth = mark.depth\n marks.remove(mark)\n stampBowl(mark.x, mark.z, bowlRadius, bowlDepth, 0)\n }\n }\n\n function burn(spec: { x: number; z: number; radius: number; temperature: number; seconds: number }): void {\n if (spec.temperature < FLAME_MINIMUM) return\n const column0 = clampIndex(Math.floor((spec.x - spec.radius - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((spec.x + spec.radius - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((spec.z - spec.radius - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((spec.z + spec.radius - z0) / cellSize), rows)\n let melted = false\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n if (Math.hypot(x0 + column * cellSize - spec.x, z0 + row * cellSize - spec.z) > spec.radius) continue\n // water does not catch: only what floats on it could burn\n if (hasWater && base[row * stride + column]! < surface[row * stride + column]!) continue\n melted = burnVertex(column, row, spec.seconds) || melted\n }\n }\n if (melted) emitDeform(spec.x, spec.z, spec.radius)\n }\n\n /** The soot of a blast's fireball within `radius` of (x, z): darkest at the centre, by what each material takes (`fire.maxScorch`); it lights nothing. */\n function soot(x: number, z: number, radius: number): void {\n if (radius <= 0) return\n const column0 = clampIndex(Math.floor((x - radius - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((x + radius - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((z - radius - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((z + radius - z0) / cellSize), rows)\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const distance = Math.hypot(x0 + column * cellSize - x, z0 + row * cellSize - z)\n const response = distance < radius ? vertexMaterial(column, row).fire : undefined\n if (!response) continue\n const index = row * stride + column\n const before = scorch[index]!\n scorch[index] = Math.max(before, response.maxScorch * BLAST_SOOT * Math.sqrt(1 - distance / radius))\n if (scorch[index] !== before) touchVertex(column, row)\n }\n }\n }\n\n /** True when the flame took ground away, so that what stood there must look again. */\n function burnVertex(column: number, row: number, seconds: number): boolean {\n const index = row * stride + column\n const material = vertexMaterial(column, row)\n const response = material.fire\n if (!response) return false\n const before = scorch[index]!\n scorch[index] = Math.max(before, Math.min(response.maxScorch, before + response.scorchPerSecond * seconds))\n if (response.burnsAway) removeFromVertex(index, response.burnsAway * seconds)\n if (scorch[index] !== before || response.burnsAway) touchVertex(column, row)\n if (response.flammable) ignite(x0 + column * cellSize, z0 + row * cellSize)\n return (response.burnsAway ?? 0) > 0\n }\n\n const fireKey = (x: number, z: number): number => Math.floor((z - z0) / FIRE_CELL) * 65536 + Math.floor((x - x0) / FIRE_CELL)\n function ignite(x: number, z: number): void {\n const key = fireKey(x, z)\n if (burning.has(key) || burning.size >= budget.maxBurningCells) return\n const index = vertexOf(x, z).index\n if (scorch[index]! >= 1) return\n burning.set(key, FIRE_SECONDS)\n }\n\n function updateFire(dt: number): void {\n for (const [key, remaining] of [...burning]) {\n const cellRow = Math.floor(key / 65536)\n const cellColumn = key - cellRow * 65536\n const x = x0 + (cellColumn + 0.5) * FIRE_CELL\n const z = z0 + (cellRow + 0.5) * FIRE_CELL\n burn({ x, z, radius: FIRE_CELL * 0.75, temperature: 600, seconds: dt })\n if (random() < FIRE_SPREAD_PER_SECOND * dt) {\n const angle = Math.floor(random() * 4) * (Math.PI / 2)\n const nextX = x + Math.cos(angle) * FIRE_CELL\n const nextZ = z + Math.sin(angle) * FIRE_CELL\n if (contains(nextX, nextZ)) {\n const { column, row, index } = vertexOf(nextX, nextZ)\n if (vertexMaterial(column, row).fire?.flammable && scorch[index]! < 1) ignite(nextX, nextZ)\n }\n }\n if (remaining - dt <= 0) burning.delete(key)\n else burning.set(key, remaining - dt)\n }\n }\n\n function updateSlides(): void {\n if (sliding.size === 0) return\n let budgetLeft = budget.maxSlideCellsPerFrame\n let minX = Infinity\n let minZ = Infinity\n let maxX = -Infinity\n let maxZ = -Infinity\n for (const index of sliding) {\n if (budgetLeft-- <= 0) break\n sliding.delete(index)\n const column = index % stride\n const row = (index - column) / stride\n if (!isSoftExposed(index)) continue\n const material = vertexMaterial(column, row)\n const slope = Math.tan(((material.reposeDegrees ?? 90) * Math.PI) / 180) * cellSize\n const height = vertexHeight(column, row)\n const neighbours: [number, number][] = [[column - 1, row], [column + 1, row], [column, row - 1], [column, row + 1]]\n for (const [nextColumn, nextRow] of neighbours) {\n if (nextColumn < 0 || nextRow < 0 || nextColumn > columns || nextRow > rows) continue\n const excess = height - vertexHeight(nextColumn, nextRow) - slope\n if (excess <= SLIDE_EPSILON) continue\n const before = dug[index]!\n const moved = removeFromVertex(index, excess * SLIDE_SHARE)\n if (moved <= 0) continue\n tallyLowered(slideTally, index, dug[index]! - before)\n const next = nextRow * stride + nextColumn\n const nextBefore = dug[next]!\n addToVertex(next, moved, isSoftExposed(next))\n tallyLowered(slideTally, next, dug[next]! - nextBefore)\n sliding.add(index)\n sliding.add(next)\n touchVertex(column, row)\n touchVertex(nextColumn, nextRow)\n const px = x0 + column * cellSize\n const pz = z0 + row * cellSize\n minX = Math.min(minX, px)\n maxX = Math.max(maxX, px)\n minZ = Math.min(minZ, pz)\n maxZ = Math.max(maxZ, pz)\n }\n }\n if (minX <= maxX) emitDeform((minX + maxX) / 2, (minZ + maxZ) / 2, Math.hypot(maxX - minX, maxZ - minZ) / 2 + cellSize * 2)\n if (sliding.size === 0 && slideTally.size > 0) {\n emitGroundLoss(slideTally, 'slide', SLIDE_LOSS_MIN_LOWERING)\n slideTally.clear()\n }\n }\n\n /** The box (in x, z) round the vertices that settled rubble raised in this update, told once as one deform. */\n const settledArea = { minX: Infinity, minZ: Infinity, maxX: -Infinity, maxZ: -Infinity }\n function emitSettledArea(): void {\n if (settledArea.minX > settledArea.maxX) return\n const { minX, minZ, maxX, maxZ } = settledArea\n settledArea.minX = settledArea.minZ = Infinity\n settledArea.maxX = settledArea.maxZ = -Infinity\n emitDeform((minX + maxX) / 2, (minZ + maxZ) / 2, Math.hypot(maxX - minX, maxZ - minZ) / 2 + cellSize * 2)\n }\n\n /** A piece of soft ground joins the height where it stops, so that what is thrown out piles up and can be walked on. */\n function settle(piece: TerrainDebris): boolean {\n const material = materials.get(piece.material)\n if (!material || material.reposeDegrees === undefined || material.scatters) return false\n if (material.splats && contains(piece.position[0], piece.position[2]) && !waterAt(piece.position[0], piece.position[2])) addDecal({ kind: 'splat', x: piece.position[0], z: piece.position[2], radius: piece.radius * 2.6, angle: piece.id * 2.399, material: material.id })\n if (!contains(piece.position[0], piece.position[2])) return true\n const { index, column, row } = vertexOf(piece.position[0], piece.position[2])\n addToVertex(index, ((4 / 3) * Math.PI * piece.radius ** 3) / (cellSize * cellSize), false)\n sliding.add(index)\n touchVertex(column, row)\n const px = x0 + column * cellSize, pz = z0 + row * cellSize\n settledArea.minX = Math.min(settledArea.minX, px)\n settledArea.maxX = Math.max(settledArea.maxX, px)\n settledArea.minZ = Math.min(settledArea.minZ, pz)\n settledArea.maxZ = Math.max(settledArea.maxZ, pz)\n return true\n }\n\n function applyHit(hit: Hit): TerrainBlowResult | null {\n const [x, y, z] = hit.point\n switch (hit.type) {\n case 'ballistic':\n case 'blunt':\n case 'slash': {\n if (!hit.energy) return null\n const contactRadius = hit.type === 'blunt' ? hit.radius : undefined\n const caliber = hit.type === 'ballistic' ? hit.caliber : undefined\n return strike(hit.type, { x, z, energy: hit.energy, ...(hit.direction ? { direction: hit.direction } : {}), ...(contactRadius !== undefined ? { contactRadius } : {}), ...(caliber !== undefined ? { caliber } : {}) })\n }\n case 'explosive': {\n if (!hit.energy) return null\n const above = Math.max(0, y - heightAt(x, z))\n const reach = (hit.radius ?? 1) * BLAST_HEIGHT_REACH\n if (above >= reach) return null\n const share = (1 - above / reach) ** 2\n // the ground's specific energies are of real joules (a kilogram of TNT is 4.184 MJ): a charge the blast was told says them; its `energy` is the arsenal's damage scale\n soot(x, z, BLAST_SOOT_REACH * Math.cbrt((hit.energy * share) / 1e6))\n return strike('explosive', { x, z, energy: (hit.hasCharge && hit.tnt !== undefined && hit.tnt > 0 ? hit.tnt * TNT_JOULES : hit.energy) * share })\n }\n case 'fire':\n case 'heat':\n if (y - heightAt(x, z) > (hit.radius ?? 0.2) + FLAME_REACH) return null\n burn({ x, z, radius: hit.radius ?? 0.2, temperature: hit.temperature ?? 0, seconds: hit.duration ?? 0.016 })\n return null\n default:\n return null\n }\n }\n\n function raycast(origin: readonly number[], direction: readonly number[], maxDistance: number): { point: [number, number, number]; distance: number; normal: [number, number, number] } | null {\n const [ox = 0, oy = 0, oz = 0] = origin\n const [dx = 0, dy = 0, dz = 0] = direction\n const step = cellSize * 0.75\n let previous = 0\n for (let t = 0; t <= maxDistance; t += step) {\n const x = ox + dx * t\n const z = oz + dz * t\n if (contains(x, z) && oy + dy * t <= heightAt(x, z)) {\n let low = previous\n let high = t\n for (let i = 0; i < 6; i++) {\n const middle = (low + high) / 2\n if (oy + dy * middle <= heightAt(ox + dx * middle, oz + dz * middle)) high = middle\n else low = middle\n }\n const px = ox + dx * high\n const pz = oz + dz * high\n const gx = heightAt(px + cellSize, pz) - heightAt(px - cellSize, pz)\n const gz = heightAt(px, pz + cellSize) - heightAt(px, pz - cellSize)\n const length = Math.hypot(gx, 2 * cellSize, gz)\n return { point: [px, oy + dy * high, pz], distance: high, normal: [-gx / length, (2 * cellSize) / length, -gz / length] }\n }\n previous = t\n }\n return null\n }\n\n function chunk(index: number): TerrainChunk {\n const chunkZ = Math.floor(index / chunksX)\n const chunkX = index - chunkZ * chunksX\n return { index, column: chunkX * chunkCells, row: chunkZ * chunkCells, cells: chunkCells, pristine: !touched[index] && !mixed[index] && !options.baseHeight }\n }\n\n function reset(): void {\n dug.fill(0)\n loose.fill(0)\n scorch.fill(0)\n barBend.fill(0)\n touched.fill(0)\n marks.clear()\n cracks.clear()\n decalList.length = 0\n decalsVersion++\n unitDamage.clear()\n debrisStore.clear()\n sliding.clear()\n slideTally.clear()\n burning.clear()\n // the craters and clods draw from here: a reset ground digs the same as a new one\n random = createRandom(seed)\n applyLayout(currentLayout)\n emitDeform((x0 + x1) / 2, (z0 + z1) / 2, Math.hypot(x1 - x0, z1 - z0) / 2)\n }\n\n applyLayout(currentLayout)\n\n return {\n bounds: options.bounds,\n cellSize,\n columns,\n rows,\n stride,\n chunkCells,\n chunksX,\n chunksZ,\n budget,\n dug,\n loose,\n scorch,\n barBend,\n profileIndex,\n profileList,\n material: (id) => {\n const material = materials.get(id)\n if (!material) throw new Error(`game-terrain: unknown material \"${id}\"`)\n return material\n },\n layout: () => currentLayout,\n setLayout(layout) {\n currentLayout = layout\n reset()\n },\n heightAt,\n heightGrid,\n heightPatch,\n heightRange,\n footAt,\n walkFactorAt,\n waterAt,\n press,\n ripple,\n decals: () => decalList,\n get decalsVersion() {\n return decalsVersion\n },\n vertexHeight,\n vertexMaterial,\n columnAt,\n rollingAt,\n rollingDampingAt,\n contains,\n raycast,\n strike,\n burn,\n open(excavation) {\n excavate(excavation)\n const [ex0, ez0, ex1, ez1] = excavation.rect\n emitDeform((ex0 + ex1) / 2, (ez0 + ez1) / 2, Math.hypot(ex1 - ex0, ez1 - ez0) / 2 + cellSize * 2)\n },\n dig,\n fill,\n applyHit,\n bear: bearAll,\n voidUnder: (x, z, radius) => voidUnder(grid, { x, z, radius }),\n onDeform(listener) {\n deformListeners.add(listener)\n return () => deformListeners.delete(listener)\n },\n update(dt) {\n debrisStore.update(dt, { heightAt, gravity, settle })\n emitSettledArea()\n updateSlides()\n updateFire(dt)\n for (let i = decalList.length - 1; i >= 0; i--) {\n const decal = decalList[i]!\n decal.age += dt\n if (decal.kind === 'ripple' && decal.age > RIPPLE_SECONDS) {\n decalList.splice(i, 1)\n decalsVersion++\n }\n }\n },\n get dirtyChunkCount() {\n return dirty.size\n },\n drainDirtyChunks(max = budget.maxDirtyChunksPerFrame) {\n const taken: TerrainChunk[] = []\n for (const index of dirty) {\n if (taken.length >= max) break\n dirty.delete(index)\n taken.push(chunk(index))\n }\n return taken\n },\n chunk,\n marks: () => marks.list,\n cracks: () => cracks.list,\n get cracksVersion() {\n return cracks.version\n },\n debris: () => debrisStore.list,\n burningPoints: () => [...burning.keys()].map((key) => {\n const cellRow = Math.floor(key / 65536)\n const cellColumn = key - cellRow * 65536\n return [x0 + (cellColumn + 0.5) * FIRE_CELL, z0 + (cellRow + 0.5) * FIRE_CELL] as const\n }),\n get marksVersion() {\n return marks.version\n },\n stats: () => ({ marks: marks.list.length, debris: debrisStore.list.length, debrisMoving: debrisStore.list.filter((piece) => !piece.atRest).length, dirtyChunks: dirty.size, burning: burning.size }),\n reset,\n serialize(): TerrainSnapshot {\n return { layout: currentLayout, dug: sparse(dug), loose: sparse(loose), scorch: sparse(scorch), barBend: sparse(barBend), marks: marks.list.map((mark) => ({ ...mark })), cracks: cracks.list.map((crack) => ({ ...crack })), decals: decalList.filter((decal) => decal.kind !== 'ripple').map((decal) => ({ ...decal })) }\n },\n load(snapshot) {\n currentLayout = snapshot.layout\n reset()\n fillSparse(dug, snapshot.dug)\n fillSparse(loose, snapshot.loose)\n fillSparse(scorch, snapshot.scorch)\n fillSparse(barBend, snapshot.barBend ?? [])\n marks.load(snapshot.marks)\n cracks.load(snapshot.cracks ?? [])\n decalList.push(...(snapshot.decals ?? []).map((decal) => ({ ...decal })))\n decalSerial = decalList.reduce((highest, decal) => Math.max(highest, decal.id), decalSerial)\n for (let chunkIndex = 0; chunkIndex < touched.length; chunkIndex++) markChunk(chunkIndex)\n emitDeform((x0 + x1) / 2, (z0 + z1) / 2, Math.hypot(x1 - x0, z1 - z0) / 2)\n },\n }\n}\n","import type { TerrainBlow, TerrainMaterial, TerrainProfile } from './types'\n\n// Specific energies are what the marks of real blows imply: a 500 J pistol round leaves about 120 cm³ in soil and 3 cm³ in concrete, an 800 kJ grenade a 1.3 m crater in soil and a 25 cm spall on a slab.\n// Cracks run about a metre from a grenade on a slab and half that on asphalt; a contact charge breaks a reinforced slab right through at about 1 kg of TNT (4.2 MJ) for 12 cm,\n// the thickness cubed (the breaching rule of thumb), leaving a hole about one and a half thicknesses wide with the bars across it.\n// Rolling resistance (C_rr) of each ground, for a round thing rolling on it. Tyre tables (Engineering ToolBox \"Rolling Resistance\", after Gillespie, Fundamentals of Vehicle\n// Dynamics, 1992; Wong, Theory of Ground Vehicles): concrete and new asphalt 0.010-0.015, small new cobbles 0.010-0.015, large worn cobbles 0.03, solid sand, loose gravel and\n// medium hard soil 0.04-0.08, loose sand 0.2-0.4. Grass: a mown golf green 0.07-0.13 (Penner, The physics of putting, Can. J. Phys. 80, 2002), a lawn is longer and slower.\n// A tyre spreads its load; a small rigid roller (a rod, a casing) sinks deeper for its size, so on soft ground the high end of each range is taken. Mud is taken as loose sand\n// (the wheel sinks), dry clay and laterite as medium hard soil at its low end, loose snow (0.3 m, a foot sinks 8 cm) an estimate between packed snow (~0.03) and sand.\n// The rough hard floors keep the 0.015 the kit has always used; a smooth one (glazed tile 0.008, a hardwood floor 0.01) holds a small roller back less, so a bottle rolls farther on it.\n// Rolling damping (1/s, `rollingDamping`): the share of its spin a roller loses per second on top of C_rr, from what drags more the faster it rolls (grass blades, ploughed sand\n// and mud, crunched gravel and snow). Rough hard floors lose 0.3 a second (grit, joints, the floor's own give), glazed tile and hardwood about a third of that; grass 1.5, so a can rolling onto a lawn stops within a metre\n// or two, as one does; loose sand and mud the most. Estimates from the stop distances of a ball or a can on each ground, not a table: no standard publishes them.\nexport const TERRAIN_MATERIALS: readonly TerrainMaterial[] = [\n {\n id: 'turf',\n rolling: 0.15,\n rollingDamping: 1.5,\n dig: { effort: 1.3 },\n debris: 'clods',\n rimShare: 0.25,\n reposeDegrees: 55,\n color: [0.09, 0.2, 0.04],\n pattern: 'grass',\n hits: {\n ballistic: { specificEnergy: 3e6, aspect: 0.6 },\n blunt: { specificEnergy: 2e6, aspect: 0.2, thresholdJoules: 60 },\n slash: { specificEnergy: 3e5, aspect: 0.5 },\n explosive: { specificEnergy: 3e6, aspect: 0.45 },\n },\n fire: { maxScorch: 1, scorchPerSecond: 0.45, flammable: true },\n },\n {\n id: 'soil',\n rolling: 0.08,\n rollingDamping: 0.6,\n dig: { effort: 1 },\n debris: 'clods',\n rimShare: 0.35,\n reposeDegrees: 40,\n color: [0.2, 0.12, 0.06],\n pattern: 'soil',\n hits: {\n ballistic: { specificEnergy: 4e6, aspect: 0.6 },\n blunt: { specificEnergy: 2e6, aspect: 0.2, thresholdJoules: 60 },\n slash: { specificEnergy: 3e5, aspect: 0.5 },\n explosive: { specificEnergy: 4e6, aspect: 0.45 },\n },\n fire: { maxScorch: 0.6, scorchPerSecond: 0.15 },\n },\n {\n id: 'sand',\n rolling: 0.3,\n rollingDamping: 2.0,\n dig: { effort: 0.8 },\n debris: 'dust',\n rimShare: 0.5,\n reposeDegrees: 33,\n color: [0.62, 0.5, 0.3],\n pattern: 'sand',\n hits: {\n ballistic: { specificEnergy: 2.5e6, aspect: 0.5 },\n blunt: { specificEnergy: 1e6, aspect: 0.2, thresholdJoules: 30 },\n slash: { specificEnergy: 1.5e5, aspect: 0.5 },\n explosive: { specificEnergy: 3e6, aspect: 0.35 },\n },\n fire: { maxScorch: 0.2, scorchPerSecond: 0.05 },\n },\n {\n id: 'gravel',\n rolling: 0.08,\n rollingDamping: 1.0,\n dig: { effort: 1.6 },\n debris: 'chips',\n rimShare: 0.15,\n reposeDegrees: 38,\n color: [0.27, 0.25, 0.22],\n pattern: 'gravel',\n hits: {\n ballistic: { specificEnergy: 8e6, aspect: 0.4 },\n blunt: { specificEnergy: 8e6, aspect: 0.2, thresholdJoules: 200 },\n slash: { specificEnergy: 3e7, aspect: 0.3, thresholdJoules: 400 },\n explosive: { specificEnergy: 1e7, aspect: 0.35 },\n },\n fire: { maxScorch: 0.3, scorchPerSecond: 0.06 },\n scatters: true,\n },\n {\n id: 'asphalt',\n rolling: 0.015,\n rollingDamping: 0.35,\n debris: 'chips',\n color: [0.05, 0.05, 0.055],\n pattern: 'asphalt',\n crack: { reach: 0.6, width: 0.008, thresholdJoules: 800 },\n hits: {\n ballistic: { specificEnergy: 3e7, aspect: 0.2, minRadius: 0.03 },\n blunt: { specificEnergy: 1e8, aspect: 0.1, thresholdJoules: 400 },\n slash: { specificEnergy: 3e8, aspect: 0.2, thresholdJoules: 400 },\n explosive: { specificEnergy: 2e8, aspect: 0.12 },\n },\n fire: { maxScorch: 0.85, scorchPerSecond: 0.1, burnsAway: 0.00005 },\n },\n {\n id: 'concrete',\n rolling: 0.015,\n rollingDamping: 0.3,\n debris: 'chips',\n color: [0.33, 0.33, 0.31],\n pattern: 'concrete',\n crack: { reach: 1, width: 0.006, thresholdJoules: 300 },\n breach: { joulesPerCubedThickness: 2.4e9, radiusOverThickness: 1.5 },\n hits: {\n ballistic: { specificEnergy: 1.5e8, aspect: 0.14, minRadius: 0.018 },\n blunt: { specificEnergy: 3e8, aspect: 0.08, thresholdJoules: 800 },\n slash: { specificEnergy: 1e9, aspect: 0.2, thresholdJoules: 800 },\n explosive: { specificEnergy: 2.7e9, aspect: 0.12 },\n },\n fire: { maxScorch: 0.45, scorchPerSecond: 0.08 },\n },\n {\n id: 'mortar',\n rollingDamping: 0.3,\n debris: 'chips',\n color: [0.42, 0.4, 0.36],\n pattern: 'plain',\n hits: {\n ballistic: { specificEnergy: 4e7, aspect: 0.2 },\n blunt: { specificEnergy: 8e7, aspect: 0.1, thresholdJoules: 300 },\n slash: { specificEnergy: 3e8, aspect: 0.2, thresholdJoules: 300 },\n explosive: { specificEnergy: 8e8, aspect: 0.14 },\n },\n fire: { maxScorch: 0.45, scorchPerSecond: 0.08 },\n },\n {\n id: 'ceramic',\n rolling: 0.008,\n rollingDamping: 0.1,\n debris: 'shards',\n color: [0.72, 0.7, 0.66],\n pattern: 'tile',\n crack: { reach: 0.5, width: 0.002, thresholdJoules: 40 },\n hits: {\n ballistic: { specificEnergy: 8e6, aspect: 0.1, minRadius: 0.05 },\n blunt: { specificEnergy: 1e7, aspect: 0.08, thresholdJoules: 80, minRadius: 0.06 },\n slash: { specificEnergy: 2e8, aspect: 0.1, thresholdJoules: 200, minRadius: 0.03 },\n explosive: { specificEnergy: 1e8, aspect: 0.03, minRadius: 0.12 },\n },\n fire: { maxScorch: 0.5, scorchPerSecond: 0.08 },\n },\n {\n id: 'wood_hard',\n rolling: 0.01,\n rollingDamping: 0.12,\n debris: 'splinters',\n color: [0.3, 0.16, 0.07],\n pattern: 'planks',\n hits: {\n ballistic: { specificEnergy: 2.5e7, aspect: 0.35, minRadius: 0.012 },\n blunt: { specificEnergy: 8e7, aspect: 0.1, thresholdJoules: 120 },\n slash: { specificEnergy: 1.5e7, aspect: 0.4, thresholdJoules: 15 },\n explosive: { specificEnergy: 2e8, aspect: 0.1, minRadius: 0.1 },\n },\n fire: { maxScorch: 1, scorchPerSecond: 0.2, burnsAway: 0.0012, flammable: true },\n },\n {\n id: 'stone',\n rolling: 0.015,\n rollingDamping: 0.3,\n debris: 'chips',\n color: [0.23, 0.22, 0.2],\n pattern: 'stone',\n crack: { reach: 0.5, width: 0.004, thresholdJoules: 1000 },\n hits: {\n ballistic: { specificEnergy: 2.5e8, aspect: 0.12, minRadius: 0.015 },\n blunt: { specificEnergy: 5e8, aspect: 0.08, thresholdJoules: 1500 },\n slash: { specificEnergy: 2e9, aspect: 0.2, thresholdJoules: 1500 },\n explosive: { specificEnergy: 4e9, aspect: 0.14 },\n },\n fire: { maxScorch: 0.4, scorchPerSecond: 0.06 },\n },\n {\n id: 'mud',\n rolling: 0.3,\n rollingDamping: 3.0,\n // the shovel lifts it, and the hole fills in behind the blade\n dig: { effort: 1.4, closes: true },\n debris: 'clods',\n rimShare: 0.15,\n reposeDegrees: 18,\n color: [0.11, 0.075, 0.04],\n pattern: 'mud',\n hits: {\n ballistic: { specificEnergy: 1.2e6, aspect: 0.7 },\n blunt: { specificEnergy: 3e5, aspect: 0.3, thresholdJoules: 15 },\n slash: { specificEnergy: 5e4, aspect: 0.5 },\n explosive: { specificEnergy: 1.5e6, aspect: 0.4 },\n },\n fire: { maxScorch: 0.15, scorchPerSecond: 0.03 },\n footing: { sink: 0.07, drag: 0.6, prints: true },\n splash: 'mud',\n splats: true,\n },\n {\n id: 'clay',\n rolling: 0.05,\n rollingDamping: 0.4,\n dig: { effort: 2.2 },\n debris: 'chips',\n color: [0.47, 0.27, 0.14],\n pattern: 'clay',\n hits: {\n ballistic: { specificEnergy: 1e7, aspect: 0.2, minRadius: 0.03 },\n blunt: { specificEnergy: 1.5e7, aspect: 0.15, thresholdJoules: 100 },\n slash: { specificEnergy: 6e7, aspect: 0.3, thresholdJoules: 30 },\n explosive: { specificEnergy: 8e6, aspect: 0.25 },\n },\n fire: { maxScorch: 0.35, scorchPerSecond: 0.05 },\n cracks: 4,\n },\n {\n // laterite, a soil baked hard (piçarra): no shovel goes in; only a heavy blow or a charge sinks or cracks it\n id: 'laterite',\n rolling: 0.05,\n rollingDamping: 0.4,\n debris: 'chips',\n rimShare: 0.2,\n color: [0.36, 0.17, 0.08],\n pattern: 'soil',\n hits: {\n ballistic: { specificEnergy: 5e7, aspect: 0.2, thresholdJoules: 200 },\n blunt: { specificEnergy: 8e7, aspect: 0.1, thresholdJoules: 600 },\n slash: { specificEnergy: 2e8, aspect: 0.1, thresholdJoules: 400 },\n explosive: { specificEnergy: 3e8, aspect: 0.18 },\n },\n },\n {\n id: 'snow',\n rolling: 0.1,\n rollingDamping: 1.2,\n dig: { effort: 0.6 },\n debris: 'dust',\n rimShare: 0.4,\n reposeDegrees: 38,\n color: [0.82, 0.85, 0.88],\n pattern: 'snow',\n hits: {\n ballistic: { specificEnergy: 1.5e6, aspect: 1 },\n blunt: { specificEnergy: 3e5, aspect: 0.3, thresholdJoules: 10 },\n slash: { specificEnergy: 5e4, aspect: 0.6 },\n explosive: { specificEnergy: 1.5e6, aspect: 0.5 },\n },\n fire: { maxScorch: 0, scorchPerSecond: 0, burnsAway: 0.015 },\n footing: { sink: 0.08, drag: 0.7, prints: true },\n },\n {\n id: 'cobble',\n rolling: 0.03,\n rollingDamping: 0.6,\n debris: 'blocks',\n color: [0.2, 0.19, 0.18],\n pattern: 'cobble',\n hits: {\n ballistic: { specificEnergy: 2.5e8, aspect: 0.12, minRadius: 0.015 },\n blunt: { specificEnergy: 5e7, aspect: 0.12, thresholdJoules: 250 },\n slash: { specificEnergy: 2e9, aspect: 0.2, thresholdJoules: 1500 },\n explosive: { specificEnergy: 1.5e7, aspect: 0.2 },\n },\n fire: { maxScorch: 0.4, scorchPerSecond: 0.06 },\n units: { length: 0.3, width: 0.2, looseJoules: 4000 },\n },\n {\n id: 'paver',\n rolling: 0.015,\n rollingDamping: 0.3,\n debris: 'blocks',\n color: [0.36, 0.33, 0.3],\n pattern: 'paver',\n hits: {\n ballistic: { specificEnergy: 1.5e8, aspect: 0.14, minRadius: 0.018 },\n blunt: { specificEnergy: 4e7, aspect: 0.12, thresholdJoules: 150 },\n slash: { specificEnergy: 1e9, aspect: 0.2, thresholdJoules: 800 },\n explosive: { specificEnergy: 1.2e7, aspect: 0.2 },\n },\n fire: { maxScorch: 0.45, scorchPerSecond: 0.08 },\n units: { length: 0.2, width: 0.2, looseJoules: 2500 },\n },\n]\n\n/** How far a blow is held back by the water it crosses before it reaches the bed: a round slows fast in water; a blast is pushed down by it. */\nconst WATER_BLOW_SHARE: Record<TerrainBlow, number> = { ballistic: 0.5, slash: 0.3, blunt: 0.5, explosive: 1 }\n\nexport const TERRAIN_PROFILES: readonly TerrainProfile[] = [\n { id: 'lawn', strata: [{ material: 'turf', thickness: 0.05 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'dirt', strata: [{ material: 'soil', thickness: 1.8 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'sand', strata: [{ material: 'sand', thickness: 2.5 }] },\n { id: 'road', strata: [{ material: 'asphalt', thickness: 0.05 }, { material: 'gravel', thickness: 0.25 }, { material: 'soil', thickness: 1.5 }] },\n // a pavement for walking: concrete over its gravel bed over the soil, as the road's layers (a blast digs down to the pipes under it)\n { id: 'sidewalk', strata: [{ material: 'concrete', thickness: 0.08 }, { material: 'gravel', thickness: 0.22 }, { material: 'soil', thickness: 1.5 }] },\n { id: 'concrete_slab', strata: [{ material: 'concrete', thickness: 0.12, reinforcement: { material: 'steel', cover: 0.03, spacing: 0.15, resistance: 4 } }] },\n { id: 'suspended_slab', drop: 3, strata: [{ material: 'concrete', thickness: 0.12, reinforcement: { material: 'steel', cover: 0.03, spacing: 0.15, resistance: 4 } }] },\n { id: 'tile_floor', strata: [{ material: 'ceramic', thickness: 0.008 }, { material: 'mortar', thickness: 0.03 }, { material: 'concrete', thickness: 0.1, reinforcement: { material: 'steel', cover: 0.03, spacing: 0.15, resistance: 4 } }] },\n { id: 'wood_floor', strata: [{ material: 'wood_hard', thickness: 0.022 }, { material: 'mortar', thickness: 0.03 }, { material: 'concrete', thickness: 0.1, reinforcement: { material: 'steel', cover: 0.03, spacing: 0.15, resistance: 4 } }] },\n { id: 'stone_paving', strata: [{ material: 'stone', thickness: 0.08 }, { material: 'gravel', thickness: 0.2 }, { material: 'soil', thickness: 1.2 }] },\n { id: 'mud', strata: [{ material: 'mud', thickness: 0.5 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'gravel_bed', strata: [{ material: 'gravel', thickness: 0.3 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'dry_clay', strata: [{ material: 'clay', thickness: 0.35 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'snow', strata: [{ material: 'snow', thickness: 0.3 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'cobblestone', strata: [{ material: 'cobble', thickness: 0.12 }, { material: 'sand', thickness: 0.06 }, { material: 'gravel', thickness: 0.2 }, { material: 'soil', thickness: 1.2 }] },\n // rock at the surface (an outcrop, a quarry floor): a blast only spalls it and a shot chips it\n // a yard as it is dug: topsoil, the clay under it, rock deep down\n { id: 'yard', strata: [{ material: 'soil', thickness: 0.35 }, { material: 'clay', thickness: 1.6 }, { material: 'stone', thickness: 1 }] },\n // ground baked hard (laterite over rock): no shovel goes in\n { id: 'hardpan', strata: [{ material: 'laterite', thickness: 0.8 }, { material: 'stone', thickness: 1.5 }] },\n { id: 'bedrock', surfacePattern: 'rock', strata: [{ material: 'stone', thickness: 3 }] },\n { id: 'paver_floor', strata: [{ material: 'paver', thickness: 0.08 }, { material: 'sand', thickness: 0.05 }, { material: 'gravel', thickness: 0.15 }, { material: 'soil', thickness: 1.2 }] },\n // a pond deep enough to stand chest-high in: a charge on its bed goes off under the water\n { id: 'pond', water: { liquid: 'water', depth: 1.4, drag: 0.4, blowShare: WATER_BLOW_SHARE }, strata: [{ material: 'mud', thickness: 0.2 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'shallow_water', water: { liquid: 'water', depth: 0.3, drag: 0.65, blowShare: WATER_BLOW_SHARE }, strata: [{ material: 'mud', thickness: 0.15 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n]\n\n/** About twelve grenades (200 kJ) on the same spot of bare bars. */\nexport const DEFAULT_BAR_YIELD_JOULES = 2_400_000\n\n/** A 10 mm bar of CA-50 steel: bare, a mesh of them at 15 cm holds about 450 kg on a spot. */\nexport const DEFAULT_BAR_DIAMETER = 0.01\nexport const DEFAULT_BAR_YIELD_PA = 500e6\n\n/** The profile of a floor with nothing else said: a plain slab. */\nexport const DEFAULT_PROFILE = 'concrete_slab'\n","/** A small seeded stream: the same seed digs the same crater, so a blow of a few bytes draws the same on every client. */\nexport function createRandom(seed: number): () => number {\n let state = seed | 0\n return () => {\n state = (state + 0x6d2b79f5) | 0\n let mixed = Math.imul(state ^ (state >>> 15), 1 | state)\n mixed = (mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed)) ^ mixed\n return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296\n }\n}\n","import { createRandom } from './random'\nimport type { TerrainCrack } from './types'\n\n/** Energy the reach and width of a material's cracks are given for (`TerrainCrackResponse`). */\nexport const CRACK_REFERENCE_JOULES = 1e6\n/** A new star this close to an old one, as a share of the old one's reach, lengthens it instead. */\nconst MERGE_SHARE = 0.35\n/** Lines never get thinner than a hairline, nor more than a star holds. */\nconst HAIRLINE = 0.0015\nconst MIN_RAYS = 4\nconst MAX_RAYS = 11\nconst SEGMENTS = 4\nconst BRANCH_CHANCE = 0.45\n\n/** One piece of a crack line on the ground plane, with the width at each end. */\nexport interface CrackSegment {\n readonly x0: number\n readonly z0: number\n readonly x1: number\n readonly z1: number\n readonly w0: number\n readonly w1: number\n}\n\nexport interface CrackStore {\n readonly list: TerrainCrack[]\n readonly version: number\n /** Opens a star at the point, or lengthens and widens the one already there. */\n add(spec: { x: number; z: number; reach: number; width: number; material: string; seed: number }, max: number): TerrainCrack\n clear(): void\n load(cracks: readonly TerrainCrack[]): void\n}\n\nexport function createCrackStore(): CrackStore {\n const list: TerrainCrack[] = []\n let version = 0\n let nextId = 1\n let born = 0\n return {\n list,\n get version() {\n return version\n },\n add(spec, max) {\n version++\n const near = list.find((crack) => Math.hypot(crack.x - spec.x, crack.z - spec.z) < crack.reach * MERGE_SHARE)\n if (near) {\n // a second blow on cracked ground runs the lines further and opens them: concrete fatigues, it does not heal\n near.reach = Math.max(near.reach, spec.reach) + Math.min(near.reach, spec.reach) * 0.25\n near.width = Math.max(near.width, spec.width) * 1.1\n near.rays = Math.min(MAX_RAYS, near.rays + 1)\n return near\n }\n if (list.length >= max) list.shift()\n const rays = MIN_RAYS + Math.floor(createRandom(spec.seed)() * (MAX_RAYS - MIN_RAYS - 2))\n const crack: TerrainCrack = { id: nextId++, x: spec.x, z: spec.z, reach: spec.reach, width: Math.max(HAIRLINE, spec.width), rays, seed: spec.seed, material: spec.material, born: born++ }\n list.push(crack)\n return crack\n },\n clear() {\n list.length = 0\n version++\n },\n load(cracks) {\n list.length = 0\n for (const crack of cracks) {\n list.push({ ...crack })\n nextId = Math.max(nextId, crack.id + 1)\n born = Math.max(born, crack.born + 1)\n }\n version++\n },\n }\n}\n\n/**\n * The lines of a star, from its seed: rays that wander a little as they run out and thin towards their tips, with a branch now and then. The same crack always draws the same\n * lines, so only the crack travels in a snapshot or over the network.\n */\nexport function crackLines(crack: TerrainCrack): CrackSegment[] {\n const random = createRandom(crack.seed)\n const segments: CrackSegment[] = []\n const widthAt = (distance: number): number => Math.max(HAIRLINE, crack.width * (1 - distance / crack.reach))\n for (let ray = 0; ray < crack.rays; ray++) {\n let angle = (ray / crack.rays) * Math.PI * 2 + (random() - 0.5) * 0.6\n const length = crack.reach * (0.45 + 0.55 * random())\n let x = crack.x\n let z = crack.z\n let run = 0\n for (let segment = 0; segment < SEGMENTS; segment++) {\n const step = (length / SEGMENTS) * (0.75 + 0.5 * random())\n angle += (random() - 0.5) * 0.5\n const nx = x + Math.cos(angle) * step\n const nz = z + Math.sin(angle) * step\n segments.push({ x0: x, z0: z, x1: nx, z1: nz, w0: widthAt(run), w1: widthAt(run + step) })\n if (segment > 0 && random() < BRANCH_CHANCE) {\n const side = angle + (random() < 0.5 ? -1 : 1) * (0.45 + random() * 0.5)\n const branch = step * (0.5 + 0.6 * random())\n const w = widthAt(run + step) * 0.6\n segments.push({ x0: nx, z0: nz, x1: nx + Math.cos(side) * branch, z1: nz + Math.sin(side) * branch, w0: Math.max(HAIRLINE, w), w1: HAIRLINE })\n }\n run += step\n x = nx\n z = nz\n }\n }\n return segments\n}\n","import type { TerrainDebris, TerrainDebrisKind } from './types'\n\nconst REST_SPEED = 0.6\nconst RESTITUTION = 0.25\nconst FRICTION = 0.55\nconst MAX_BOUNCES = 2\nconst REST_GAP = 0.01\n\nexport interface DebrisWorld {\n heightAt(x: number, z: number): number\n gravity: number\n /** Soft pieces join the ground where they stop; a false keeps the piece as loose rubble. */\n settle(piece: TerrainDebris): boolean\n}\n\n/** Pieces thrown by blows: they fly, hit the deformed ground, and come to rest. Past `max` the oldest at rest goes first. */\nexport interface DebrisStore {\n readonly list: TerrainDebris[]\n throwPiece(spec: { material: string; kind: TerrainDebrisKind; radius: number; position: [number, number, number]; velocity: [number, number, number]; spin: [number, number, number] }): void\n update(dt: number, world: DebrisWorld): void\n clear(): void\n}\n\nexport function createDebrisStore(max: () => number): DebrisStore {\n const list: TerrainDebris[] = []\n let serial = 0\n\n function makeRoom(): void {\n if (list.length < max()) return\n let at = 0\n let oldest = Infinity\n let oldestResting = -1\n let restingBorn = Infinity\n list.forEach((piece, index) => {\n if (piece.born < oldest) {\n oldest = piece.born\n at = index\n }\n if (piece.atRest && piece.born < restingBorn) {\n restingBorn = piece.born\n oldestResting = index\n }\n })\n list.splice(oldestResting >= 0 ? oldestResting : at, 1)\n }\n\n return {\n list,\n throwPiece(spec) {\n makeRoom()\n list.push({ ...spec, id: ++serial, born: serial, atRest: false, bounces: 0 })\n },\n update(dt, world) {\n for (let i = list.length - 1; i >= 0; i--) {\n const piece = list[i]!\n if (piece.atRest) {\n // what it lay on was dug away or heaped over: it falls again, or rides up\n const under = world.heightAt(piece.position[0], piece.position[2]) + piece.radius * 0.6\n if (piece.position[1] > under + REST_GAP) piece.atRest = false\n else if (piece.position[1] < under - REST_GAP) piece.position[1] = under\n if (piece.atRest) continue\n }\n const { position, velocity } = piece\n velocity[1] -= world.gravity * dt\n position[0] += velocity[0] * dt\n position[1] += velocity[1] * dt\n position[2] += velocity[2] * dt\n const ground = world.heightAt(position[0], position[2]) + piece.radius * 0.6\n if (position[1] > ground) continue\n position[1] = ground\n const speed = Math.hypot(velocity[0], velocity[1], velocity[2])\n if (speed < REST_SPEED || piece.bounces >= MAX_BOUNCES) {\n piece.atRest = true\n if (world.settle(piece)) list.splice(i, 1)\n continue\n }\n piece.bounces++\n velocity[1] = Math.abs(velocity[1]) * RESTITUTION\n velocity[0] *= FRICTION\n velocity[2] *= FRICTION\n }\n },\n clear() {\n list.length = 0\n serial = 0\n },\n }\n}\n","import type { GroundLoss } from '@adatechnology/game-contracts'\nimport type { TerrainVoid } from './types'\n\n/** A loss shallower than this (m below the untouched surface) is a scuff, not a void anything bears over. */\nexport const GROUND_LOSS_MIN_DEPTH = 0.02\n/** Sand that slid tells the host only where it lowered the ground by at least this much (m). */\nexport const SLIDE_LOSS_MIN_LOWERING = 0.05\n/** Under this depth (m) a vertex still counts as ground in `voidUnder`. */\nexport const VOID_MIN_DEPTH = 0.02\n\nexport interface HeightGrid {\n readonly x0: number\n readonly z0: number\n readonly cellSize: number\n readonly stride: number\n readonly columns: number\n readonly rows: number\n readonly dug: Float32Array\n}\n\n/** What one event lowered, by vertex (metres of the column, not of the loose heap on it). Lowerings of the same vertex add up; a fill counts against them. */\nexport type LossTally = Map<number, number>\n\nexport function tallyLowered(tally: LossTally, index: number, amount: number): void {\n if (amount !== 0) tally.set(index, (tally.get(index) ?? 0) + amount)\n}\n\n/**\n * The disc the tally lowered, or null when it is shallower than `GROUND_LOSS_MIN_DEPTH`. Vertices lowered less than `minLowering` are left out. `depth` is\n * the deepest the ground is now under its untouched surface there. A `bowl` (a crater, sand that slid) is told as the paraboloid that is half as deep\n * where the ground is now half as deep, so a wide shallow scrape around a deep hole does not pass for a wide deep one; a `flat` hole (a slab that opened)\n * keeps its edge.\n */\nexport function lossOf(grid: HeightGrid, tally: LossTally, spec: { source: string; minLowering: number; shape: 'bowl' | 'flat' }): GroundLoss | null {\n let weight = 0\n let centerX = 0\n let centerZ = 0\n let depth = 0\n let deepest = 0\n const kept: number[] = []\n for (const [index, amount] of tally) {\n if (amount < spec.minLowering || amount <= 0) continue\n const column = index % grid.stride\n const row = (index - column) / grid.stride\n weight += amount\n centerX += (grid.x0 + column * grid.cellSize) * amount\n centerZ += (grid.z0 + row * grid.cellSize) * amount\n depth = Math.max(depth, grid.dug[index]!)\n deepest = Math.max(deepest, amount)\n kept.push(index)\n }\n if (weight <= 0 || depth < GROUND_LOSS_MIN_DEPTH || deepest < GROUND_LOSS_MIN_DEPTH) return null\n centerX /= weight\n centerZ /= weight\n let radius = 0\n for (const index of kept) {\n if (spec.shape === 'bowl' && grid.dug[index]! < depth / 2) continue\n const column = index % grid.stride\n const row = (index - column) / grid.stride\n radius = Math.max(radius, Math.hypot(grid.x0 + column * grid.cellSize - centerX, grid.z0 + row * grid.cellSize - centerZ))\n }\n const reach = spec.shape === 'bowl' ? Math.SQRT2 * (radius + grid.cellSize / 2) : radius + grid.cellSize / 2\n return { x: centerX, z: centerZ, radius: reach, depth, removed: weight * grid.cellSize * grid.cellSize, source: spec.source }\n}\n\n/** How much of the disc (x, z, radius) has no ground under where it was: the vertices inside it, or the nearest one when the disc is smaller than a cell. */\nexport function voidUnder(grid: HeightGrid, spec: { x: number; z: number; radius: number }): TerrainVoid {\n const { x, z, radius } = spec\n const clamp = (value: number, top: number): number => Math.max(0, Math.min(top, value))\n const column0 = clamp(Math.ceil((x - radius - grid.x0) / grid.cellSize), grid.columns)\n const column1 = clamp(Math.floor((x + radius - grid.x0) / grid.cellSize), grid.columns)\n const row0 = clamp(Math.ceil((z - radius - grid.z0) / grid.cellSize), grid.rows)\n const row1 = clamp(Math.floor((z + radius - grid.z0) / grid.cellSize), grid.rows)\n let count = 0\n let sum = 0\n let depth = 0\n let open = 0\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n if (Math.hypot(grid.x0 + column * grid.cellSize - x, grid.z0 + row * grid.cellSize - z) > radius) continue\n const here = grid.dug[row * grid.stride + column]!\n count++\n sum += here\n depth = Math.max(depth, here)\n if (here >= VOID_MIN_DEPTH) open++\n }\n }\n if (count === 0) {\n const here = grid.dug[clamp(Math.round((z - grid.z0) / grid.cellSize), grid.rows) * grid.stride + clamp(Math.round((x - grid.x0) / grid.cellSize), grid.columns)]!\n return { depth: here, mean: here, fraction: here >= VOID_MIN_DEPTH ? 1 : 0 }\n }\n return { depth, mean: sum / count, fraction: open / count }\n}\n","/**\n * The ground's blend as pure functions of numbers, shared by `Terrain.heightAt`, `Terrain.heightGrid` and `heightPatchGrid`: the same code reads the terrain on the main\n * thread and a copy of its vertices anywhere else (a worker has no terrain), so the heights agree to the bit.\n */\n\n/** Where `v` falls along an axis of `count` cells of `cellSize` from `origin`, in cells, held inside the last cell: its whole part is the cell, the rest the blend across it. */\nexport const cellCoordinate = (v: number, origin: number, count: number, cellSize: number): number => Math.max(0, Math.min(count - 1e-6, (v - origin) / cellSize))\n\n/** The blend of two heights, `t` of the way from `near` to `far` (the one step every blend of the ground is made of). */\nexport const blendHeights = (near: number, far: number, t: number): number => near * (1 - t) + far * t\n\n/**\n * The terrain's vertex heights (`base - dug + loose`, as `heightAt` reads them) over a block of its cells, with what places them in the terrain: plain numbers, so a worker\n * can read the ground from them (`heightPatchGrid`) and answer what `heightGrid` does there, to the bit. Made by `Terrain.heightPatch`.\n */\nexport interface HeightPatch {\n readonly cellSize: number\n /** The terrain's first vertex (its bounds' min x and z) and its cells along x and z: where a point's cell is found, with its clamps. */\n readonly originX: number\n readonly originZ: number\n readonly columns: number\n readonly rows: number\n /** The patch's first vertex (column and row of the terrain) and how many vertices it has along x and along z. */\n readonly column0: number\n readonly row0: number\n readonly width: number\n readonly depth: number\n /** The heights, `width` per row, rows from `row0`: `heights[(row - row0) * width + column - column0]` (the array may be longer). */\n readonly heights: Float64Array\n}\n\n// the cell and the blend of each column and row a patch read finds, kept between reads (one at a time) so a read costs no new arrays\nlet patchColumns = new Int32Array(0)\nlet patchBlendX = new Float64Array(0)\nlet patchNear = new Float64Array(0)\nlet patchFar = new Float64Array(0)\n\n/**\n * The ground over a lattice from a patch: the height at (`xs[i]`, `zs[j]`) into `out[j * xs.length + i]`, to the bit what the terrain's `heightGrid` answers there (the same\n * cell, clamps and blends, on the same vertex heights). Every point must lie inside the terrain and over the patch's cells (`Terrain.heightPatch` of a rectangle holding\n * them): one that does not throws. Not reentrant (module scratch).\n */\nexport function heightPatchGrid(patch: HeightPatch, xs: ArrayLike<number>, zs: ArrayLike<number>, out: Float64Array): void {\n const width = xs.length\n const depth = zs.length\n if (out.length < width * depth) throw new RangeError(`heightPatchGrid: out holds ${out.length} heights, the grid has ${width * depth}`)\n const { cellSize, originX, originZ, columns, rows, column0, row0, heights } = patch\n const stride = patch.width\n if (patchColumns.length < width) {\n patchColumns = new Int32Array(width)\n patchBlendX = new Float64Array(width)\n patchNear = new Float64Array(width)\n patchFar = new Float64Array(width)\n }\n for (let i = 0; i < width; i++) {\n const fx = cellCoordinate(xs[i]!, originX, columns, cellSize)\n const column = (fx | 0) - column0\n if (column < 0 || column + 1 >= stride) throw new RangeError(`heightPatchGrid: x ${xs[i]} is past the patch`)\n patchColumns[i] = column\n patchBlendX[i] = fx - (fx | 0)\n }\n let blended = -1\n for (let j = 0; j < depth; j++) {\n const fz = cellCoordinate(zs[j]!, originZ, rows, cellSize)\n const row = (fz | 0) - row0\n if (row < 0 || row + 1 >= patch.depth) throw new RangeError(`heightPatchGrid: z ${zs[j]} is past the patch`)\n const tz = fz - (fz | 0)\n // the two x blends of a column depend on its row of cells only, as in `heightGrid`\n if (row !== blended) {\n blended = row\n for (let i = 0; i < width; i++) {\n const index = row * stride + patchColumns[i]!\n const tx = patchBlendX[i]!\n patchNear[i] = blendHeights(heights[index]!, heights[index + 1]!, tx)\n patchFar[i] = blendHeights(heights[index + stride]!, heights[index + stride + 1]!, tx)\n }\n }\n for (let i = 0; i < width; i++) out[j * width + i] = blendHeights(patchNear[i]!, patchFar[i]!, tz)\n }\n}\n\n/** Whether two patches hold the same vertices at the same heights (the ground they read is the same, to the bit, wherever both reach). */\nexport const samePatch = (a: HeightPatch, b: HeightPatch): boolean => {\n if (a.cellSize !== b.cellSize || a.originX !== b.originX || a.originZ !== b.originZ || a.columns !== b.columns || a.rows !== b.rows) return false\n if (a.column0 !== b.column0 || a.row0 !== b.row0 || a.width !== b.width || a.depth !== b.depth) return false\n const count = a.width * a.depth\n for (let k = 0; k < count; k++) if (a.heights[k] !== b.heights[k]) return false\n return true\n}\n","import type { TerrainBudget, TerrainMark } from './types'\n\n/** Two marks at this fraction of their radii or closer are one hole. */\nconst SAME_HOLE = 0.75\n\n/** Fine marks under a budget per area and a global one: past the budget the closest two of the area become one, and past the global one the oldest goes. */\nexport interface MarkStore {\n readonly list: TerrainMark[]\n add(spec: Omit<TerrainMark, 'id' | 'count' | 'born'>): TerrainMark\n near(x: number, z: number, radius: number): TerrainMark | undefined\n depthAt(x: number, z: number): number\n remove(mark: TerrainMark): void\n removeInside(x: number, z: number, radius: number): void\n clear(): void\n load(marks: readonly TerrainMark[]): void\n readonly version: number\n}\n\nexport function createMarkStore(budget: TerrainBudget): MarkStore {\n const list: TerrainMark[] = []\n const areas = new Map<number, TerrainMark[]>()\n let serial = 0\n let version = 0\n const areaKey = (x: number, z: number): number => Math.floor(x / budget.markAreaSize) * 100003 + Math.floor(z / budget.markAreaSize)\n\n function detach(mark: TerrainMark): void {\n const key = areaKey(mark.x, mark.z)\n const area = areas.get(key)\n if (area) {\n const at = area.indexOf(mark)\n if (at >= 0) area.splice(at, 1)\n if (area.length === 0) areas.delete(key)\n }\n const at = list.indexOf(mark)\n if (at >= 0) list.splice(at, 1)\n version++\n }\n\n function attach(mark: TerrainMark): void {\n const key = areaKey(mark.x, mark.z)\n const area = areas.get(key)\n if (area) area.push(mark)\n else areas.set(key, [mark])\n list.push(mark)\n version++\n }\n\n function mergeClosestPair(area: TerrainMark[]): void {\n let bestA = area[0]!\n let bestB = area[1]!\n let best = Infinity\n for (let i = 0; i < area.length; i++) {\n for (let j = i + 1; j < area.length; j++) {\n const distance = Math.hypot(area[i]!.x - area[j]!.x, area[i]!.z - area[j]!.z)\n if (distance < best) {\n best = distance\n bestA = area[i]!\n bestB = area[j]!\n }\n }\n }\n const weight = bestA.radius ** 2 + bestB.radius ** 2\n const shareB = weight > 0 ? bestB.radius ** 2 / weight : 0.5\n detach(bestB)\n bestA.x += (bestB.x - bestA.x) * shareB\n bestA.z += (bestB.z - bestA.z) * shareB\n bestA.radius = Math.sqrt(weight)\n bestA.depth = Math.max(bestA.depth, bestB.depth)\n bestA.count += bestB.count\n version++\n }\n\n return {\n list,\n add(spec) {\n const mark: TerrainMark = { ...spec, id: ++serial, count: 1, born: serial }\n attach(mark)\n const area = areas.get(areaKey(mark.x, mark.z))!\n if (area.length > budget.maxMarksPerArea) mergeClosestPair(area)\n if (list.length > budget.maxMarks) detach(list.reduce((oldest, candidate) => (candidate.born < oldest.born ? candidate : oldest)))\n return mark\n },\n near(x, z, radius) {\n let found: TerrainMark | undefined\n let best = Infinity\n const reach = Math.ceil((radius + 0.5) / budget.markAreaSize)\n const baseX = Math.floor(x / budget.markAreaSize)\n const baseZ = Math.floor(z / budget.markAreaSize)\n for (let dx = -reach; dx <= reach; dx++) {\n for (let dz = -reach; dz <= reach; dz++) {\n for (const mark of areas.get((baseX + dx) * 100003 + baseZ + dz) ?? []) {\n const distance = Math.hypot(mark.x - x, mark.z - z)\n if (distance < best && distance < Math.max(mark.radius, radius) * SAME_HOLE) {\n best = distance\n found = mark\n }\n }\n }\n }\n return found\n },\n depthAt(x, z) {\n let depth = 0\n for (const mark of areas.get(areaKey(x, z)) ?? []) {\n const distance = Math.hypot(mark.x - x, mark.z - z)\n if (distance < mark.radius) depth = Math.max(depth, mark.depth * (1 - (distance / mark.radius) ** 2))\n }\n return depth\n },\n remove: detach,\n removeInside(x, z, radius) {\n for (const mark of [...list]) if (Math.hypot(mark.x - x, mark.z - z) + mark.radius * 0.5 < radius) detach(mark)\n },\n clear() {\n list.length = 0\n areas.clear()\n // the numbering starts again with the ground (a loaded snapshot takes it on from its own marks); `version` only grows, the renderers follow it\n serial = 0\n version++\n },\n load(marks) {\n this.clear()\n for (const mark of marks) {\n attach({ ...mark })\n serial = Math.max(serial, mark.id)\n }\n },\n get version() {\n return version\n },\n }\n}\n","import type { DestructibleImpl, DestructibleSpec, DestructionEvent, Hit, ObjectState, SurfaceRay, SurfaceRayHit } from '@adatechnology/game-contracts'\nimport type { Terrain, TerrainBlowResult } from './types'\n\nconst PART_ID = 'ground'\nconst PART_DEPTH = 3\nconst RAY_BACKOFF = 1\nconst GROUND_HP = 1e12\n/** Most metres the ground rises above its flat level (a heap of what a crater threw out): a ray higher than this cannot meet it. */\nconst HEAP_REACH = 3\n\nexport interface TerrainImplOptions {\n readonly id: string\n readonly name?: string\n /** Every blow that left its mark, with what it did. */\n readonly onBlow?: (result: TerrainBlowResult, hit: Hit) => void\n}\n\n/**\n * The ground as an object of the destruction world (`DestructionWorld.register`): shots, blows, blasts and flames reach it through the world's own raycast and blast like anything else.\n * The collision part is a flat box that only says where to look: the world's raycast asks `surfaceRay`, which follows the ground as it is now (craters, heaps),\n * so a round fired into a crater meets its floor, not the flat top of the box over it.\n */\nexport function createTerrainImpl(terrain: Terrain, options: TerrainImplOptions): DestructibleImpl {\n const { id } = options\n const [x0, z0, x1, z1] = terrain.bounds\n const centerColumn = Math.max(0, Math.min(terrain.columns, Math.round((x1 - x0) / 2 / terrain.cellSize)))\n const centerRow = Math.max(0, Math.min(terrain.rows, Math.round((z1 - z0) / 2 / terrain.cellSize)))\n const centerMaterial = (): string => terrain.vertexMaterial(centerColumn, centerRow).id\n const buildSpec = (material: string): DestructibleSpec => ({\n name: options.name ?? 'Ground',\n parts: [\n {\n id: PART_ID,\n material,\n shape: { kind: 'box', size: [x1 - x0, PART_DEPTH, z1 - z0] },\n position: [(x0 + x1) / 2, -PART_DEPTH / 2, (z0 + z1) / 2],\n hp: GROUND_HP,\n anchored: true,\n tags: ['terrain'],\n },\n ],\n joints: [],\n })\n let cachedSpec: DestructibleSpec | undefined\n const spec = (): DestructibleSpec => {\n const material = centerMaterial()\n if (cachedSpec?.parts[0]?.material !== material) cachedSpec = buildSpec(material)\n return cachedSpec\n }\n const buildState = (material: string): ObjectState => ({\n id,\n position: [0, 0, 0],\n rotation: [0, 0, 0, 1],\n parts: [{ id: PART_ID, material, status: 'intact', hp: GROUND_HP, maxHp: GROUND_HP, mass: 0, temperature: 0, burning: false, fuel: 0, char: 0, melt: 0, dents: [], holes: [], cracks: [], group: 0 }],\n joints: [],\n groups: [[PART_ID]],\n destroyed: false,\n })\n let cachedState: ObjectState | undefined\n const state = (): ObjectState => {\n const material = centerMaterial()\n if (cachedState?.parts[0]?.material !== material) cachedState = buildState(material)\n return cachedState\n }\n const resolve = (hit: Hit): Hit => {\n if (hit.type !== 'ballistic' && hit.type !== 'blunt' && hit.type !== 'slash') return hit\n if (!hit.direction) return { ...hit, point: [hit.point[0], terrain.heightAt(hit.point[0], hit.point[2]), hit.point[2]] }\n const [dx, dy, dz] = hit.direction\n const from = [hit.point[0] - dx * RAY_BACKOFF, hit.point[1] - dy * RAY_BACKOFF, hit.point[2] - dz * RAY_BACKOFF]\n const onGround = terrain.raycast(from, hit.direction, RAY_BACKOFF + PART_DEPTH)\n return onGround ? { ...hit, point: onGround.point } : hit\n }\n /** The ground as it is now along the ray, marched only where the ray is within the depth of the ground and the height of a heap. */\n const surfaceRay = (ray: SurfaceRay): SurfaceRayHit | null => {\n if (ray.ignored?.(PART_ID)) return null\n const [ox, oy, oz] = ray.origin\n const [dx, dy, dz] = ray.direction\n const enter = dy < 0 ? Math.max(0, (oy - HEAP_REACH) / -dy) : oy <= HEAP_REACH ? 0 : Infinity\n const leave = dy < 0 ? (oy + PART_DEPTH) / -dy : Math.hypot(x1 - x0, z1 - z0) + Math.hypot(ox - (x0 + x1) / 2, oz - (z0 + z1) / 2)\n const far = Math.min(ray.maxDistance, leave)\n if (!(enter <= far)) return null\n const hit = terrain.raycast([ox + dx * enter, oy + dy * enter, oz + dz * enter], ray.direction, far - enter)\n if (!hit) return null\n return { part: PART_ID, point: hit.point, normal: hit.normal, distance: enter + hit.distance, pathLen: PART_DEPTH }\n }\n return {\n id,\n ...(options.name ? { name: options.name } : {}),\n describe: spec,\n surfaceRay,\n hit(hit): DestructionEvent[] {\n const landed = resolve(hit)\n const result = terrain.applyHit(landed)\n if (!result || result.radius <= 0) return []\n options.onBlow?.(result, landed)\n return [{ type: 'damage', object: id, time: 0, part: PART_ID, amount: 0, hp: GROUND_HP, damageType: hit.type, ...(hit.source ? { source: hit.source } : {}) }]\n },\n update(dt) {\n terrain.update(dt)\n return []\n },\n state,\n reset() {\n terrain.reset()\n },\n serialize: () => terrain.serialize(),\n load(data) {\n terrain.load(data as ReturnType<Terrain['serialize']>)\n },\n }\n}\n","import type { GroundExcavation, GroundLayout, GroundLoss, Hit } from '@adatechnology/game-contracts'\n\nimport type { HeightPatch } from './height-patch'\n\nexport type { GroundExcavation, GroundLayout, GroundZone } from '@adatechnology/game-contracts'\n\n/** The blows that remove ground. Fire and heat char it instead (`TerrainMaterial.fire`). */\nexport type TerrainBlow = 'ballistic' | 'blunt' | 'slash' | 'explosive'\n\n/** A blow at (x, z): `energy` in joules, `direction` where it travels, `contactRadius` of a blunt tool, `caliber` (mm) of a round, which shapes its crater. */\nexport type TerrainStrike = { x: number; z: number; energy: number; direction?: readonly number[]; contactRadius?: number; caliber?: number }\n\n/** What one kind of blow does to a material. */\nexport interface TerrainBlowResponse {\n /** Joules it takes to remove one cubic metre. */\n readonly specificEnergy: number\n /** Depth over radius of the bowl it leaves: a soft ground craters deep, a hard one spalls wide and shallow. */\n readonly aspect: number\n /** A blow under this many joules leaves nothing (a punch on a slab). */\n readonly thresholdJoules?: number\n /** The bowl is never narrower: a tile comes off as a piece, not as the size of the bullet. */\n readonly minRadius?: number\n}\n\nexport type TerrainDebrisKind = 'clods' | 'chips' | 'shards' | 'splinters' | 'dust' | 'blocks'\n\n/** How a material of the destruction catalogue behaves as ground. `id` is the catalogue's. */\nexport interface TerrainMaterial {\n readonly id: string\n readonly hits: Partial<Record<TerrainBlow, TerrainBlowResponse>>\n readonly debris: TerrainDebrisKind\n /** Share of what a blow removes that piles up on the rim; the rest is thrown. Rigid materials have none. */\n readonly rimShare?: number\n /** Steepest slope in degrees it holds; loose ground slides until it is back to it. */\n readonly reposeDegrees?: number\n /** A shovel digs it: `effort` is how hard a shovelful is against loose soil (1); a material without it (concrete, stone, asphalt) is not dug by hand. */\n readonly dig?: { readonly effort: number; readonly closes?: boolean }\n readonly fire?: TerrainFireResponse\n /** Linear rgb, 0..1, of the material where it is exposed. */\n readonly color: readonly [number, number, number]\n /** Surface pattern a renderer draws while the stratum is intact (`TERRAIN_PATTERNS`). */\n readonly pattern?: TerrainPattern\n /** A rigid surface cracks around a hard blow instead of only losing a bowl: lines that run out from the point (concrete, asphalt, tile, stone). */\n readonly crack?: TerrainCrackResponse\n /** A rigid layer a contact charge breaks right through once it has enough for the whole thickness (the scabbing of a slab): `explosive` only. */\n readonly breach?: TerrainBreachResponse\n /** What a foot does on it. */\n readonly footing?: TerrainFooting\n /**\n * Its rolling resistance (C_rr) to a round thing rolling on it (a can, a rod, a casing): the moment C_rr x weight x radius that slows the roll. Soft ground (sand, mud,\n * grass) gives under the roller and holds it back far more than a hard one (asphalt, concrete). Left out: the host's default (a hard floor).\n */\n readonly rolling?: number\n /**\n * Its rolling damping (1/s): the share of its spin a round thing rolling on it loses per second on top of `rolling`, from what drags more the faster it rolls (grass\n * blades, ploughed sand). Added to the roller's own. Left out: the host's default (a hard floor).\n */\n readonly rollingDamping?: number\n /** Liquid (of the fluids catalogue) a blow on it throws up. */\n readonly splash?: string\n /** Its pieces do not join the ground where they land: they stay as loose stones. */\n readonly scatters?: boolean\n /** Its pieces leave a splat on whatever they land on. */\n readonly splats?: boolean\n /** A brittle crust: each blow runs cracks this many bowl radii around it. */\n readonly cracks?: number\n /** Laid in separate pieces on a bed: a blow loosens whole pieces instead of digging a bowl. */\n readonly units?: TerrainUnits\n}\n\nexport interface TerrainCrackResponse {\n /** Metres the longest line runs for a blow of 1 MJ; it grows with the cube root of the energy. */\n readonly reach: number\n /** Metres wide the lines open at the point for 1 MJ, also by the cube root, never under a hairline. */\n readonly width: number\n /** A blow under this many joules leaves no crack (a punch on a slab). */\n readonly thresholdJoules: number\n}\n\nexport interface TerrainBreachResponse {\n /** Joules over the cube of the layer's thickness (J/m³) that break the whole layer through: for reinforced concrete about 1 kg of TNT for 12 cm. */\n readonly joulesPerCubedThickness: number\n /** Radius of the breach over the thickness at that energy; it grows with the cube root of the excess. */\n readonly radiusOverThickness: number\n}\n\nexport interface TerrainFooting {\n /** Metres the foot goes in. */\n readonly sink: number\n /** What is left of the walking speed, 0..1. */\n readonly drag: number\n /** Keeps the print of what presses it. */\n readonly prints?: boolean\n}\n\nexport interface TerrainUnits {\n /** Metres along x, in rows that shift every other one. Multiples of the cell keep the hole sharp. */\n readonly length: number\n /** Metres along z. */\n readonly width: number\n /** Joules a piece takes, added blow by blow, before it comes off its bed. */\n readonly looseJoules: number\n}\n\nexport interface TerrainFireResponse {\n /** How black it gets, 0..1: concrete only soots, wood and turf char through. */\n readonly maxScorch: number\n /** Scorch gained per second in a flame. */\n readonly scorchPerSecond: number\n /** Metres per second the flame eats away (wood char). */\n readonly burnsAway?: number\n /** Catches and carries the fire to the next cells on its own. */\n readonly flammable?: boolean\n}\n\nexport const TERRAIN_PATTERNS = ['plain', 'grass', 'soil', 'sand', 'asphalt', 'concrete', 'tile', 'planks', 'stone', 'mud', 'gravel', 'clay', 'snow', 'cobble', 'paver', 'rock'] as const\nexport type TerrainPattern = (typeof TERRAIN_PATTERNS)[number]\n\n/** One layer of a column, from the top down. */\nexport interface TerrainStratum {\n /** A `TerrainMaterial.id`. */\n readonly material: string\n /** Metres. */\n readonly thickness: number\n /** Bars inside the layer: exposed at `cover`, they make the digging `resistance` times harder. */\n readonly reinforcement?: {\n readonly material: string\n readonly cover: number\n readonly spacing: number\n readonly resistance: number\n /** Joules on one spot of bare bars before they give way (default `DEFAULT_BAR_YIELD_JOULES`). */\n readonly yieldJoules?: number\n /** Metres across one bar (default `DEFAULT_BAR_DIAMETER`): with `yieldPa` it says what weight bare bars hold. */\n readonly diameter?: number\n /** Pascals at which the steel yields (default `DEFAULT_BAR_YIELD_PA`). */\n readonly yieldPa?: number\n }\n}\n\n/** Weight standing still on the ground: a body, a fridge, a car. */\nexport interface TerrainLoad {\n readonly x: number\n readonly z: number\n /** Metres: half the side of the footprint it stands on. */\n readonly radius: number\n readonly newtons: number\n}\n\n/** What a column of ground is made of. The strata end at the digging limit: under them nothing is removed. */\nexport interface TerrainProfile {\n readonly id: string\n readonly strata: readonly TerrainStratum[]\n /** A slab with nothing under it: where its bars give way the floor opens, and the ground is this many metres further down (the floor below). Without it the ground under the slab holds it up. */\n readonly drop?: number\n /** How the untouched top layer is drawn when it is not its material's way: bare rock is stone, but not laid as paving. Dug, the material's own shows. */\n readonly surfacePattern?: TerrainPattern\n /** Water standing over the column: the strata are its bed. */\n readonly water?: TerrainWater\n}\n\nexport interface TerrainWater {\n /** A liquid of the fluids catalogue. */\n readonly liquid: string\n /** Metres from the surface to the bed. */\n readonly depth: number\n /** What is left of the walking speed, 0..1. */\n readonly drag: number\n /** Share of a blow that reaches the bed. */\n readonly blowShare: Partial<Record<TerrainBlow, number>>\n}\n\nexport interface TerrainBudget {\n /** Side in metres of the squares that hold a limited number of marks. */\n readonly markAreaSize: number\n readonly maxMarksPerArea: number\n readonly maxMarks: number\n /** Chunks a renderer redraws per frame; the rest wait. */\n readonly maxDirtyChunksPerFrame: number\n readonly maxDebris: number\n /** Thrown pieces of one blow. */\n readonly maxDebrisPerBlow: number\n /** Cells checked for sliding per frame. */\n readonly maxSlideCellsPerFrame: number\n /** Cells on fire at once. */\n readonly maxBurningCells: number\n /** Stars of cracks kept; past it the oldest goes. */\n readonly maxCracks: number\n /** Cracks, prints, ruts, splats and ripples at once; past it the oldest goes. */\n readonly maxDecals: number\n}\n\nexport interface TerrainOptions {\n /** World rectangle `[x0, z0, x1, z1]` in metres. */\n readonly bounds: readonly [number, number, number, number]\n /** Metres per cell (default 0.1). */\n readonly cellSize?: number\n /** Cells per side of a chunk (default 32). */\n readonly chunkCells?: number\n /** Which profile is where. */\n readonly layout?: GroundLayout\n /** Extra or overriding profiles, by id. */\n readonly profiles?: readonly TerrainProfile[]\n /** Extra or overriding materials, by id. */\n readonly materials?: readonly TerrainMaterial[]\n readonly budget?: Partial<TerrainBudget>\n /** Height of the untouched ground (default flat at 0). */\n readonly baseHeight?: (x: number, z: number) => number\n /** Metres per second squared. */\n readonly gravity?: number\n readonly seed?: number\n /**\n * Ground taken away from under the surface: a crater (`crater`), a slab that gave way into the void under it (`slab`), sand that slid off a slope\n * (`slide`). The host hands it to what stands there (`DestructionWorld.groundLoss`), so foundations over it settle or lose their support.\n */\n readonly onGroundLoss?: (loss: GroundLoss) => void\n}\n\n/** A shovelful (`Terrain.dig`): the blade's footprint at (x, z), how deep it goes in, where the earth is thrown (a heap on the ground there). */\nexport interface TerrainDig {\n readonly x: number\n readonly z: number\n /** Width and length of the blade's bite, metres (default 0.3 x 0.3). */\n readonly size?: readonly [number, number]\n /** How deep one shovelful goes, metres (default 0.2). */\n readonly depth?: number\n /** Where the earth lands: heaped round this point. Without it, it is lost (carried away). */\n readonly dump?: { readonly x: number; readonly z: number }\n}\n\n/** What a shovelful took. */\nexport interface TerrainDigResult {\n /** Cubic metres taken out (and heaped at `dump`). */\n readonly volume: number\n /** The material dug (the one at the bite's centre). */\n readonly material: string\n /** How hard it was against loose soil (1): a shovelful of it takes that much longer. 0 when nothing was dug. */\n readonly effort: number\n /** The material that stopped the blade (concrete, stone...), when it could not dig; `water` where the ground is under water. */\n readonly refused?: string\n /** The blade lifted it but the hole closed behind it (mud): nothing changed. */\n readonly closes?: true\n}\n\n/** Earth thrown back into a hole (`Terrain.fill`): taken from the heap round `from`, laid into the hole at (x, z), at most `volume`. */\nexport interface TerrainFill {\n readonly x: number\n readonly z: number\n readonly size?: readonly [number, number]\n readonly from: { readonly x: number; readonly z: number; readonly radius: number }\n readonly volume: number\n}\n\n/** What is missing under a disc of the ground (`Terrain.voidUnder`). */\nexport interface TerrainVoid {\n /** Metres under the untouched surface at the deepest vertex. */\n readonly depth: number\n /** Metres under the untouched surface, averaged over the disc. */\n readonly mean: number\n /** 0..1, the share of the disc's vertices that are void (dug at least `VOID_MIN_DEPTH`). */\n readonly fraction: number\n}\n\n/** A fine mark: a bullet pock or a chip, smaller than a cell. It grows with the blows on it until it is dug into the height field. */\nexport interface TerrainMark {\n readonly id: number\n x: number\n z: number\n radius: number\n depth: number\n /** The material the mark shows at the bottom. */\n material: string\n blow: TerrainBlow\n /** Blows and marks merged into this one. */\n count: number\n /** Order of creation: the oldest is the one recycled. */\n born: number\n}\n\nexport type TerrainDecalKind = 'crack' | 'print' | 'rut' | 'splat' | 'ripple'\n\n/** A mark with no depth of its own: drawn over the surface, it changes nothing that stands there. */\nexport interface TerrainDecal {\n readonly id: number\n readonly kind: TerrainDecalKind\n readonly x: number\n readonly z: number\n readonly radius: number\n /** Radians around y. */\n readonly angle: number\n /** The material whose colour it takes. */\n readonly material: string\n /** Seconds it has been there; a ripple fades with it. */\n age: number\n}\n\nexport interface TerrainDebris {\n readonly id: number\n readonly material: string\n readonly kind: TerrainDebrisKind\n readonly radius: number\n readonly position: [number, number, number]\n readonly velocity: [number, number, number]\n readonly spin: [number, number, number]\n atRest: boolean\n bounces: number\n /** Order of creation: the oldest is the one recycled. */\n readonly born: number\n}\n\n/** A star of cracks on a rigid surface. The lines themselves come from `crackLines`, drawn from the seed, so a snapshot keeps only this. */\nexport interface TerrainCrack {\n readonly id: number\n readonly x: number\n readonly z: number\n /** Metres the longest line runs. */\n reach: number\n /** Metres wide the lines are at the point. */\n width: number\n rays: number\n readonly seed: number\n readonly material: string\n /** Order of creation: the oldest is the one recycled. */\n readonly born: number\n}\n\n/** What a blow did. */\nexport interface TerrainBlowResult {\n readonly point: readonly [number, number, number]\n /** Bowl radius in metres; 0 when the blow left nothing. */\n readonly radius: number\n /** Metres removed at the point. */\n readonly depth: number\n /** Metres under the untouched surface the point is now. */\n readonly totalDepth: number\n /** Materials removed, top first, with the cubic metres of each. */\n readonly removed: readonly { readonly material: string; readonly volume: number }[]\n /** Material now exposed at the point. */\n readonly exposed: string\n /** The column has no more to give here: the slab's bottom, the end of the rock. */\n readonly atLimit: boolean\n /** Reinforcement is showing at the point. */\n readonly rebarExposed: boolean\n /** The bars gave way here and the slab opened (`TerrainProfile.drop`). */\n readonly collapsed: boolean\n /** Left a fine mark (`true`) or dug the height field (`false`). */\n readonly fine: boolean\n /** The cracks it opened or lengthened around the point, if the surface is rigid. */\n readonly crack?: TerrainCrack\n /** A contact charge broke the rigid layer right through (`TerrainMaterial.breach`). */\n readonly breached?: boolean\n /** The water the blow crossed: `level` is where the splash goes up. */\n readonly water?: { readonly liquid: string; readonly level: number }\n}\n\n/** The water standing at a point. */\nexport interface TerrainWaterHere {\n readonly liquid: string\n readonly level: number\n readonly depth: number\n}\n\nexport interface TerrainRegion {\n readonly x: number\n readonly z: number\n readonly radius: number\n}\n\nexport interface TerrainColumn {\n readonly profile: string\n readonly material: string\n readonly stratum: number\n /** Metres under the untouched surface. */\n readonly depth: number\n /** Metres that can still be dug here. */\n readonly remaining: number\n readonly scorch: number\n readonly loose: number\n}\n\nexport interface TerrainStats {\n readonly marks: number\n readonly debris: number\n readonly debrisMoving: number\n readonly dirtyChunks: number\n readonly burning: number\n}\n\nexport interface TerrainChunk {\n readonly index: number\n /** First column and row of the chunk's vertices. */\n readonly column: number\n readonly row: number\n readonly cells: number\n /** True while nothing touched it and it has one profile: one flat quad draws it. */\n readonly pristine: boolean\n}\n\nexport interface Terrain {\n readonly bounds: readonly [number, number, number, number]\n readonly cellSize: number\n readonly columns: number\n readonly rows: number\n /** Vertices per row. */\n readonly stride: number\n readonly chunkCells: number\n readonly chunksX: number\n readonly chunksZ: number\n readonly budget: TerrainBudget\n /** Per vertex: metres removed under the untouched surface. */\n readonly dug: Float32Array\n /** Per vertex: metres of loose ground heaped on top. */\n readonly loose: Float32Array\n /** Per vertex: 0..1, how burnt. */\n readonly scorch: Float32Array\n /** Per vertex: how far the bare bars have given, 0 straight, 1 or more gone. */\n readonly barBend: Float32Array\n /** Per vertex: index in `profileList`. */\n readonly profileIndex: Uint8Array\n readonly profileList: readonly TerrainProfile[]\n material(id: string): TerrainMaterial\n layout(): GroundLayout\n setLayout(layout: GroundLayout): void\n /** Height at (x, z) as things stand on it. */\n heightAt(x: number, z: number): number\n /**\n * `heightAt` over a grid, in one pass: the height at (`xs[i]`, `zs[j]`) into `out[j * xs.length + i]`, to the bit what `heightAt` answers there (the same cell, blend and\n * vertices; past the terrain, the host's `baseHeight`). For a reader of many points on a lattice (a physics engine's ground tile), which saves a call per point.\n * Not reentrant: it keeps its scratch between calls, so a `baseHeight` must not call it back.\n */\n heightGrid(xs: ArrayLike<number>, zs: ArrayLike<number>, out: Float64Array): void\n /**\n * The vertex heights under a rectangle (the cells `heightGrid` reads for any point in it), as plain numbers a worker can read the ground from (`heightPatchGrid`, to the\n * bit what `heightGrid` answers there); null when the rectangle is not wholly inside the terrain (past it the host's `baseHeight` answers). Writes into `into` when it is\n * long enough, else a new array. A 2.4 m square at 10 cm cells is 26 x 26 numbers.\n */\n heightPatch(minX: number, maxX: number, minZ: number, maxZ: number, into?: Float64Array): HeightPatch | null\n /**\n * The lowest and the highest `heightAt` can answer over the rectangle, exact bounds (the height between vertices is a blend of the four around it, so no\n * point is under the lowest or over the highest vertex of the cells the rectangle covers); null when the rectangle is not wholly inside the terrain, where the ground is the\n * host's `baseHeight` and no bound is known. Costs the vertices the rectangle covers, not a read per sample.\n */\n heightRange(minX: number, maxX: number, minZ: number, maxZ: number): { readonly low: number; readonly high: number } | null\n /** Height of vertex (column, row). */\n vertexHeight(column: number, row: number): number\n /** Material exposed at a vertex. */\n vertexMaterial(column: number, row: number): TerrainMaterial\n columnAt(x: number, z: number): TerrainColumn\n /** The rolling resistance (`TerrainMaterial.rolling`) of the material exposed at (x, z), as `columnAt` reads it, without building the column; undefined: the host's default. */\n rollingAt(x: number, z: number): number | undefined\n /** The rolling damping (`TerrainMaterial.rollingDamping`) of the material exposed at (x, z), read as `rollingAt`; undefined: the host's default. */\n rollingDampingAt(x: number, z: number): number | undefined\n contains(x: number, z: number): boolean\n /** First point of the ground along a ray, or null. */\n raycast(origin: readonly number[], direction: readonly number[], maxDistance: number): { point: [number, number, number]; distance: number; normal: [number, number, number] } | null\n /** A blow at (x, z). `energy` in joules, `direction` where it travels (it throws the pieces back along it). */\n strike(blow: TerrainBlow, spec: TerrainStrike): TerrainBlowResult\n /**\n * Opens a pit in the ground as it stands now (a shaft a blast threw its cover off): the same dig as an excavation of the layout, never less deep than the ground already is there, and\n * no ground loss. The layout is left alone, so the next `reset` closes it with the craters.\n */\n open(excavation: GroundExcavation): void\n /** A shovelful at (x, z): takes the earth down through what a shovel digs, stops at what it does not (concrete, rock), heaps it at `dump`. */\n dig(spec: TerrainDig): TerrainDigResult\n /** Earth thrown back from a heap into a hole: fills what was dug first, then heaps. Returns the cubic metres moved. */\n fill(spec: TerrainFill): number\n /** A flame over a disc for `seconds`. */\n burn(spec: { x: number; z: number; radius: number; temperature: number; seconds: number }): void\n /** Applies a world hit (`Hit` of the destruction contract); null when it does nothing to the ground. */\n applyHit(hit: Hit): TerrainBlowResult | null\n /** What stands still on the ground now. Where it stands over bare bars they sag under it, and past what they hold they give way; a slab over a void then opens. True when it opened. */\n bear(loads: readonly TerrainLoad[]): boolean\n /** How much ground is missing under the disc (x, z, radius), measured from the untouched surface. */\n voidUnder(x: number, z: number, radius: number): TerrainVoid\n /** Height a foot stands at: the ground less what it sinks in. */\n footAt(x: number, z: number): number\n /** What is left of the walking speed here, 0..1. */\n walkFactorAt(x: number, z: number): number\n /** The water standing here, or null. */\n waterAt(x: number, z: number): TerrainWaterHere | null\n /** A foot or a wheel on the ground: it leaves its print where the ground keeps one, a ripple in water. False where it leaves nothing. */\n press(spec: { x: number; z: number; radius: number; angle?: number; kind?: 'print' | 'rut' }): boolean\n /** Rings on the water at (x, z). */\n ripple(x: number, z: number, radius: number): void\n decals(): readonly TerrainDecal[]\n /** Goes up when the decals change. */\n readonly decalsVersion: number\n /** Follow the ground changing: `region` is the disc it changed in. What rests there has lost its support and must look again. Returns the unsubscribe function. */\n onDeform(listener: (region: TerrainRegion) => void): () => void\n /** Moves the pieces, the sliding ground and the fire. */\n update(dt: number): void\n /** Chunks waiting to be redrawn; every chunk at once means the floor was just laid anew (a layout, a reset). */\n readonly dirtyChunkCount: number\n /** Takes up to the budget's chunks that changed since the last call. */\n drainDirtyChunks(max?: number): TerrainChunk[]\n chunk(index: number): TerrainChunk\n marks(): readonly TerrainMark[]\n cracks(): readonly TerrainCrack[]\n /** Changes whenever a crack is added or grows, so a renderer redraws only then. */\n readonly cracksVersion: number\n debris(): readonly TerrainDebris[]\n /** Cells on fire now, as world points. */\n burningPoints(): readonly (readonly [number, number])[]\n /** Goes up when the marks change. */\n readonly marksVersion: number\n stats(): TerrainStats\n /** Back to the untouched ground. */\n reset(): void\n serialize(): TerrainSnapshot\n load(snapshot: TerrainSnapshot): void\n}\n\nexport interface TerrainSnapshot {\n readonly layout: GroundLayout\n readonly dug: readonly (readonly [number, number])[]\n readonly loose: readonly (readonly [number, number])[]\n readonly scorch: readonly (readonly [number, number])[]\n readonly barBend?: readonly (readonly [number, number])[]\n readonly marks: readonly TerrainMark[]\n readonly cracks?: readonly TerrainCrack[]\n readonly decals?: readonly TerrainDecal[]\n}\n","import type { Terrain } from './types'\n\nconst STRIDE = 0.72\nconst FOOT_LENGTH = 0.15\nconst FOOT_APART = 0.11\n\nexport interface Footprints {\n /** Call as the walker moves; it leaves a print each stride, left and right in turn. */\n update(x: number, z: number): void\n reset(): void\n}\n\n/** The trail of something walking: whoever moves on the ground reports where it is, and the ground keeps the prints it can keep. */\nexport function createFootprints(terrain: Terrain, options: { readonly stride?: number; readonly footLength?: number } = {}): Footprints {\n const stride = options.stride ?? STRIDE\n const footLength = options.footLength ?? FOOT_LENGTH\n let lastX: number | null = null\n let lastZ = 0\n let side = 1\n return {\n update(x, z) {\n if (lastX === null) {\n lastX = x\n lastZ = z\n return\n }\n const dx = x - lastX\n const dz = z - lastZ\n const walked = Math.hypot(dx, dz)\n if (walked < stride) return\n lastX = x\n lastZ = z\n // a jump of many strides is a teleport, not a walk\n if (walked > stride * 3) return\n const angle = Math.atan2(dx, dz)\n side = -side\n terrain.press({ x: x + (Math.cos(angle) * FOOT_APART * side), z: z - (Math.sin(angle) * FOOT_APART * side), radius: footLength, angle })\n },\n reset() {\n lastX = null\n },\n }\n}\n","const GRAVITY = 9.81\n/** Per second, the share of a body's speed water takes when it is all under: a body in water bobs once and stops, it does not bounce. */\nconst WATER_DRAG = 9\n/** The liquid does not throw a very light body out: past this many times its weight the push has nothing more to give. */\nconst MAX_LIFT_WEIGHTS = 1.6\n\nexport interface WaterLiftParams {\n /** Kilograms. */\n readonly mass: number\n /** Cubic metres of the whole body. */\n readonly volume: number\n /** Share of the body under the surface, 0..1. */\n readonly submerged: number\n /** Kilograms per cubic metre of the liquid. */\n readonly liquidDensity?: number\n readonly gravity?: number\n}\n\nexport interface WaterLift {\n /** Upward metres per second squared the liquid gives the body. */\n readonly acceleration: number\n /** Per second, the part of the speed the liquid takes. */\n readonly drag: number\n /** Lighter than the liquid it displaces. */\n readonly floats: boolean\n}\n\n/** Archimedes on a body in a liquid: what it displaces lifts it, so a light log floats and a concrete block goes to the bed. */\nexport function waterLift(params: WaterLiftParams): WaterLift {\n const density = params.liquidDensity ?? 1000\n const submerged = Math.max(0, Math.min(1, params.submerged))\n const mass = Math.max(1e-6, params.mass)\n const gravity = params.gravity ?? GRAVITY\n return {\n acceleration: Math.min(MAX_LIFT_WEIGHTS * gravity, (density * params.volume * submerged * gravity) / mass),\n drag: WATER_DRAG * submerged,\n floats: mass / Math.max(1e-9, params.volume) < density,\n }\n}\n","/**\n * The engine collides with a tile's ground at a coarser grid than the tile is read at, as Unreal's \"Simple Collision\" mip level 1 does: every second corner of the 2.5 cm\n * grid, so a 5 cm height field. The read grid stays where the steps are found and the solid under the ground is made; the engine's narrow phase meets a quarter of the\n * triangles under a piece (the frame after a blast was mostly a piece resting on 2.5 cm triangles, T3.8ah). Owner decision 2026-11-17. The collision surface is off the drawn\n * ground by the bend of the ground across one of its cells: a tile keeps the coarse field only where that, with the engine's own 8 bit steps, is within 5 mm everywhere\n * on it, and has no step (`collisionFieldOf`); else it collides at the read grid.\n */\nexport const GROUND_COLLISION_CELL = 0.05\n\n/** The most (m) the collision surface may be off the drawn ground anywhere on a tile for the tile to collide at `GROUND_COLLISION_CELL` (the owner's bound). */\nexport const COLLISION_TOLERANCE = 0.005\n/**\n * A tile on the read grid goes to the coarse field only under this (m): one near the bound does not change field at every change of its ground (the bound stays hard). Not\n * lower: a room crater tile is 4.47 mm off at 5 cm, and a piece rests on it the frame after the blast.\n */\nexport const COLLISION_ENTER = 0.0045\n/** Samples a side of the engine's height field blocks (`game-physics-jolt` `HEIGHT_BLOCK`): each block's heights are 8 bit steps of its own range. */\nconst ENGINE_BLOCK = 4\n\n/** How many read cells (of `readCell` m, `cells` a side) a collision cell would span: 1 keeps the read grid (a collision cell that does not divide the tile). */\nexport const coarseStep = (cells: number, readCell: number): number => {\n const k = Math.max(1, Math.round(GROUND_COLLISION_CELL / readCell))\n return cells % k === 0 ? k : 1\n}\n\n/** A tile's collision field: every `step`-th corner of its read heights (1: the heights themselves). */\nexport interface CollisionField {\n readonly step: number\n readonly field: Float32Array\n}\n\n/**\n * A tile's collision field: the coarse one (`GROUND_COLLISION_CELL`) when the tile has no step boxes (a step's edge is between read corners, and a coarser field ramps or grooves\n * across it: 14 cm by a terrace's wall) and the coarse surface, on either diagonal and with the engine's 8 bit steps, is within `COLLISION_TOLERANCE` of the drawn ground at\n * every read corner (both are flat between them); within `COLLISION_ENTER` when the tile was on the read grid before (`wasCoarse` false: a fresh tile is one); else the read\n * grid itself.\n */\nexport const collisionFieldOf = (heights: Float32Array, cells: number, readCell: number, hasSteps: boolean, wasCoarse = false): CollisionField => {\n const k = coarseStep(cells, readCell)\n const fine = { step: 1, field: heights }\n if (k === 1 || hasSteps || heights.length === 0) return fine\n const m = cells + 1\n const get = (p: number, q: number): number => heights[q * m + p]!\n let off = 0\n for (let q = 0; q <= cells; q++) {\n for (let p = 0; p <= cells; p++) {\n collisionBoth(get, p, q, k)\n const h = heights[q * m + p]!\n off = Math.max(off, h - both[0]!, both[1]! - h)\n }\n }\n const field = collisionOf(heights, cells, k)\n return off + quantumOf(field, cells / k) <= (wasCoarse ? COLLISION_TOLERANCE : COLLISION_ENTER) ? { step: k, field } : fine\n}\n\n/** The most the engine's 8 bit heights may be off the field's own, over its blocks: half a step of a block's range. */\nconst quantumOf = (field: Float32Array, cells: number): number => {\n const m = cells + 1\n let most = 0\n for (let bj = 0; bj < cells; bj += ENGINE_BLOCK) {\n for (let bi = 0; bi < cells; bi += ENGINE_BLOCK) {\n let lo = Infinity, hi = -Infinity\n for (let j = bj; j <= Math.min(cells, bj + ENGINE_BLOCK); j++) {\n for (let i = bi; i <= Math.min(cells, bi + ENGINE_BLOCK); i++) {\n lo = Math.min(lo, field[j * m + i]!)\n hi = Math.max(hi, field[j * m + i]!)\n }\n }\n most = Math.max(most, (hi - lo) / 510)\n }\n }\n return most\n}\n\n/** The collision field of a tile's heights (`(cells + 1)^2`, x fastest): every `k`-th corner, `(cells / k + 1)^2` of them. */\nexport const collisionOf = (heights: Float32Array, cells: number, k: number): Float32Array => {\n if (k === 1) return heights\n const m = cells + 1\n const n = cells / k + 1\n const out = new Float32Array(n * n)\n for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) out[j * n + i] = heights[j * k * m + i * k]!\n return out\n}\n\n/**\n * The collision surface at the read corner (`p`, `q`) (any integers: past the tile too), from `get` of the corners on the collision grid (multiples of `k`): the lower of the\n * two ways the engine may cut the collision cell into triangles, so whichever it uses is no lower than this.\n */\nexport const collisionAt = (get: (p: number, q: number) => number, p: number, q: number, k: number): number => {\n collisionBoth(get, p, q, k)\n return both[0]!\n}\n\n/** Where `collisionBoth` writes, the lower then the higher (one array for the module: no array per corner). */\nconst both = new Float64Array(2)\n\n/** The collision surface at the read corner (`p`, `q`) on the two ways a collision cell may be cut, into `both`: the lower then the higher. */\nconst collisionBoth = (get: (p: number, q: number) => number, p: number, q: number, k: number): void => {\n const p0 = Math.floor(p / k) * k, q0 = Math.floor(q / k) * k\n const u = (p - p0) / k, v = (q - q0) / k\n if (u === 0 && v === 0) {\n both[0] = both[1] = get(p0, q0)\n return\n }\n // on a collision cell's edge only that edge's corners are asked for (the tile's last row and column have no cell past them)\n const p1 = u === 0 ? p0 : p0 + k, q1 = v === 0 ? q0 : q0 + k\n const h00 = get(p0, q0), h10 = get(p1, q0), h01 = get(p0, q1), h11 = get(p1, q1)\n // the diagonal from (0, 0) to (1, 1), and the one from (1, 0) to (0, 1)\n const main = u >= v ? h00 + u * (h10 - h00) + v * (h11 - h10) : h00 + v * (h01 - h00) + u * (h11 - h01)\n const cross = u + v <= 1 ? h00 + u * (h10 - h00) + v * (h01 - h00) : h11 + (1 - u) * (h01 - h11) + (1 - v) * (h10 - h11)\n both[0] = Math.min(main, cross)\n both[1] = Math.max(main, cross)\n}\n\n/**\n * A tile's read heights lowered, corner by corner, to the collision surface where it is lower: a grid nothing over which (taken flat between corners, as the engine takes\n * both surfaces) rises over either surface. What must stay under the ground (the solid under it, §12) is made over this.\n */\nexport const underBoth = (heights: Float32Array, cells: number, k: number): Float32Array => {\n if (k === 1) return heights\n const m = cells + 1\n const get = (p: number, q: number): number => heights[q * m + p]!\n const out = new Float32Array(m * m)\n for (let q = 0; q <= cells; q++) for (let p = 0; p <= cells; p++) out[q * m + p] = Math.min(heights[q * m + p]!, collisionAt(get, p, q, k))\n return out\n}\n","/** How far (m) a sample may leave its cell's corners before the cell counts as holding a step. */\nexport const STEP_TOLERANCE = 0.005\n\n/**\n * Whether a cell holds a step, from its nine samples in `s`: the corners (x0 z0, x1 z0, x0 z1, x1 z1), the centre, and the middles of its edges (z0, z1, x0, x1). A step\n * moves the centre or an edge's middle off its corners. The one test the tile (`engine-ground`) and the ring past it (`engine-ground-ring`) make, so both see the same cells.\n */\nconst off = (a: number, b: number): boolean => Math.abs(a - b) > STEP_TOLERANCE\n\nexport const holdsStep = (s: ArrayLike<number>): boolean => {\n const c00 = s[0]!, c10 = s[1]!, c01 = s[2]!, c11 = s[3]!\n return off(s[4]!, (c00 + c10 + c01 + c11) / 4) || off(s[5]!, (c00 + c10) / 2) || off(s[6]!, (c01 + c11) / 2) || off(s[7]!, (c00 + c01) / 2) || off(s[8]!, (c10 + c11) / 2)\n}\n","import { collisionAt } from './engine-ground-collision'\nimport { holdsStep } from './engine-ground-step'\n\n/**\n * The ground a tile's solid reads around the tile: its own heights inside, and past its edges, as far as `SOLID_RING`, the ground the neighbour tile is made from (`groundAt`),\n * read only where a block of the solid reaches and once each. Every sample read past the edge is kept (`read`): the solid depends on them, so a change there makes it again.\n */\n\n/**\n * How far (m) past its tile's edges a block of the solid may reach: a cell of overlap, the skew of a top turned about both axes (a cell or two at the edge's block sizes), and a\n * box at least 15 cm deep at any slope (`engine-ground-solid` caps the depth of a box that would lean further). The host's changes this close to a tile make its solid again.\n */\nexport const SOLID_RING = 0.2\n/** One cell's nine samples, for `holdsStep`. */\nconst nine = new Float64Array(9)\n\n/**\n * Where the ring reads the ground past the tile's edges: the host's `groundAt`, or a band read ahead of time (`engine-ground-job` `readGroundBand`), one height per half cell\n * `(a, b)` at `(b + 2 * ring) * width + a + 2 * ring` (`width` = `2 * (cells + 2 * ring) + 1`), each the very height `groundAt` answers there. A worker has no `groundAt`.\n */\nexport type GroundSource = ((x: number, z: number) => number) | Float64Array\n\nexport interface GroundRing {\n /** How many cells the ring is wide. */\n readonly cells: number\n /** The four corners (`(i, j)`, `(i + 1, j)`, `(i, j + 1)`, `(i + 1, j + 1)`) of a cell past the tile's edge into `out`; a cell holding a step (`holdsStep`, as the neighbour builds it) has its lowest of nine samples at all four. */\n cell(i: number, j: number, out: Float64Array): void\n /** The samples read past the edge: x, z and height, three numbers each. */\n readonly read: number[]\n}\n\n// the samples and cells read for the ring being made, marked by the build they belong to (one at a time), so a ring costs no new arrays\nlet build = 0\nlet heldSamples = new Float64Array(0)\nlet sampleBuild = new Uint32Array(0)\nlet heldCells = new Float64Array(0)\nlet cellBuild = new Uint32Array(0)\n\n/**\n * `heights` are the tile's own (already under its collision field), `fieldStep` how many read cells a neighbour's coarse collision cell spans: past the edge a corner is the lower of\n * the ground there and that coarse field at it (the neighbour collides with it or with the ground itself).\n */\nexport const createGroundRing = (heights: Float32Array, cells: number, x0: number, z0: number, cell: number, groundAt: GroundSource, fieldStep = 1): GroundRing => {\n const band = typeof groundAt === 'function' ? null : groundAt\n const ring = Math.round(SOLID_RING / cell)\n const m = cells + 1\n const width = 2 * (cells + 2 * ring) + 1\n const across = cells + 2 * ring\n if (sampleBuild.length < width * width) {\n heldSamples = new Float64Array(width * width)\n sampleBuild = new Uint32Array(width * width)\n }\n if (cellBuild.length < across * across) {\n heldCells = new Float64Array(4 * across * across)\n cellBuild = new Uint32Array(across * across)\n }\n const mark = ++build\n const read: number[] = []\n /** The ground at the half cell (`a` / 2, `b` / 2): the tile's own height at its corners, the neighbour's ground elsewhere. */\n const half = (a: number, b: number): number => {\n if (a % 2 === 0 && b % 2 === 0 && a >= 0 && b >= 0 && a <= 2 * cells && b <= 2 * cells) return heights[(b / 2) * m + a / 2]!\n const key = (b + 2 * ring) * width + a + 2 * ring\n if (sampleBuild[key] === mark) return heldSamples[key]!\n const x = x0 + (a / 2) * cell\n const z = z0 + (b / 2) * cell\n const h = band === null ? (groundAt as (x: number, z: number) => number)(x, z) : band[key]!\n heldSamples[key] = h\n sampleBuild[key] = mark\n read.push(x, z, h)\n return h\n }\n /** The ground at the read corner (`p`, `q`). */\n const fine = (p: number, q: number): number => half(2 * p, 2 * q)\n return {\n cells: ring,\n read,\n cell(i, j, out) {\n const key = (j + ring) * across + i + ring\n if (cellBuild[key] !== mark) {\n const a = 2 * i, b = 2 * j\n nine[0] = half(a, b)\n nine[1] = half(a + 2, b)\n nine[2] = half(a, b + 2)\n nine[3] = half(a + 2, b + 2)\n nine[4] = half(a + 1, b + 1)\n nine[5] = half(a + 1, b)\n nine[6] = half(a + 1, b + 2)\n nine[7] = half(a, b + 1)\n nine[8] = half(a + 2, b + 1)\n // a cell the neighbour builds as a step: where the step runs in it is not known, so the ground there is no lower than its lowest sample\n const step = holdsStep(nine)\n let floor = Infinity\n for (let k = 0; k < 9; k++) floor = Math.min(floor, nine[k]!)\n const corner = (p: number, q: number, h: number): number => (fieldStep === 1 ? h : Math.min(h, collisionAt(fine, p, q, fieldStep)))\n const c00 = corner(i, j, nine[0]!), c10 = corner(i + 1, j, nine[1]!), c01 = corner(i, j + 1, nine[2]!), c11 = corner(i + 1, j + 1, nine[3]!)\n heldCells[4 * key] = step ? floor : c00\n heldCells[4 * key + 1] = step ? floor : c10\n heldCells[4 * key + 2] = step ? floor : c01\n heldCells[4 * key + 3] = step ? floor : c11\n cellBuild[key] = mark\n }\n for (let k = 0; k < 4; k++) out[k] = heldCells[4 * key + k]!\n },\n }\n}\n","import type { GroundRing } from './engine-ground-ring'\n\n/**\n * How far a turned box rises above the ground, over every column it has a point in, its leaning sides as much as its top: what it must be lowered by to be under the ground\n * everywhere (§12). The ground between a cell's corners is flat (the engine's two triangles, or bilinear), so a plane rises over it the most at a corner.\n * - Its top: the top's plane over every corner under the top's extent.\n * - Its sides, which lean uphill under the top: the box is its top slid down along -n, so where the ground over the box's shadow is nowhere steeper than the top's slope\n * allows (1 / its slope), no point of it is further over the ground than its top is. Else every cell of the shadow: a column's highest point is under each face that\n * looks up (the top, and the uphill side of each tilted axis), so over a cell under the lowest of those planes, found from the top down over a pyramid of planes under the\n * tile's ground (a block of cells whose plane is above every plane of the box over it is skipped whole).\n * - Past the tile's edges, every cell of the shadow there, over the ring's ground (`engine-ground-ring`).\n */\n\n/** A box: its centre, axes (x, y, z: the y axis is the normal of its top) and half sizes. */\nexport interface ReachBox {\n readonly c: ArrayLike<number>\n readonly axes: ReadonlyArray<ArrayLike<number>>\n readonly half: ArrayLike<number>\n}\n\n/**\n * Under each block of 2^l by 2^l cells (l from 1 up to one block over the whole tile), a plane no sample of the block is under: the block's corner slopes, lowered to its\n * lowest sample. Three numbers a block (its height at the block's first corner, and its slopes along x and z per cell), made when first asked for: over a slope or a\n * crater's wall the plane follows the ground, so a box whose planes are under it there is skipped whole.\n */\nexport interface LowPyramid {\n readonly heights: Float32Array\n readonly cells: number\n readonly sizes: readonly number[]\n readonly planes: readonly Float64Array[]\n /** The square of the steepest the ground is (m per m, any way) over each block: a cell's from its edges (its two triangles, or bilinear, are no steeper), a block's the steepest of its four. */\n readonly steepest: readonly Float64Array[]\n}\n\nexport const buildLowPyramid = (heights: Float32Array, cells: number, cell: number): LowPyramid => {\n const m = cells + 1\n const first = new Float64Array(cells * cells)\n for (let j = 0; j < cells; j++) {\n for (let i = 0; i < cells; i++) {\n const h00 = heights[j * m + i]!, h10 = heights[j * m + i + 1]!, h01 = heights[(j + 1) * m + i]!, h11 = heights[(j + 1) * m + i + 1]!\n const dx = Math.max(Math.abs(h10 - h00), Math.abs(h11 - h01)), dz = Math.max(Math.abs(h01 - h00), Math.abs(h11 - h10))\n first[j * cells + i] = (dx * dx + dz * dz) / (cell * cell)\n }\n }\n const sizes: number[] = [cells]\n const planes: Float64Array[] = [new Float64Array(0)]\n const steepest: Float64Array[] = [first]\n for (let s = 2; s < 2 * cells; s *= 2) {\n const below = steepest[steepest.length - 1]!\n const n = sizes[sizes.length - 1]!\n const k = Math.ceil(cells / s)\n const level = new Float64Array(k * k)\n for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) level[(j >> 1) * k + (i >> 1)] = Math.max(level[(j >> 1) * k + (i >> 1)]!, below[j * n + i]!)\n sizes.push(k)\n planes.push(new Float64Array(3 * k * k).fill(NaN))\n steepest.push(level)\n }\n return { heights, cells, sizes, planes, steepest }\n}\n\n/** Whether the ground is steeper than `limit` (m per m) anywhere over the cells `ia`..`ib` (not included) by `ja`..`jb`. */\n// the question `steeperOver` is asking, for `visit` (one at a time)\nlet steepPyramid: LowPyramid | null = null\nlet steepSquare = 0\nlet steepIa = 0, steepIb = 0, steepJa = 0, steepJb = 0\n\nconst visit = (l: number, bi: number, bj: number): boolean => {\n const pyramid = steepPyramid!\n if (pyramid.steepest[l]![bj * pyramid.sizes[l]! + bi]! <= steepSquare) return false\n const s = 1 << l\n const a = bi * s, c = bj * s\n const b = Math.min(pyramid.cells, a + s), d = Math.min(pyramid.cells, c + s)\n if (a >= steepIb || b <= steepIa || c >= steepJb || d <= steepJa) return false\n if (l === 0) return true\n for (let dj = 0; dj < 2; dj++) for (let di = 0; di < 2; di++) if (visit(l - 1, 2 * bi + di, 2 * bj + dj)) return true\n return false\n}\n\nconst steeperOver = (pyramid: LowPyramid, ia: number, ib: number, ja: number, jb: number, limit: number): boolean => {\n steepPyramid = pyramid\n steepSquare = limit * limit\n steepIa = ia\n steepIb = ib\n steepJa = ja\n steepJb = jb\n const steeper = visit(pyramid.sizes.length - 1, 0, 0)\n // the last pyramid is not kept past the call (§8)\n steepPyramid = null\n return steeper\n}\n\n/** Where the plane under the block (`bi`, `bj`) of level `l` is in `pyramid.planes[l]`, made now if it was not. */\nconst planeUnder = (pyramid: LowPyramid, l: number, bi: number, bj: number): number => {\n const level = pyramid.planes[l]!\n const at = 3 * (bj * pyramid.sizes[l]! + bi)\n if (!Number.isNaN(level[at]!)) return at\n const { heights, cells } = pyramid\n const m = cells + 1\n const s = 1 << l\n const ia = bi * s, ja = bj * s, ib = Math.min(cells, ia + s), jb = Math.min(cells, ja + s)\n const h00 = heights[ja * m + ia]!, h10 = heights[ja * m + ib]!, h01 = heights[jb * m + ia]!, h11 = heights[jb * m + ib]!\n const sx = (h10 - h00 + h11 - h01) / 2 / (ib - ia), sz = (h01 - h00 + h11 - h10) / 2 / (jb - ja)\n let under = 0\n for (let j = ja; j <= jb; j++) for (let i = ia; i <= ib; i++) under = Math.min(under, heights[j * m + i]! - (h00 + sx * (i - ia) + sz * (j - ja)))\n level[at] = h00 + under\n level[at + 1] = sx\n level[at + 2] = sz\n return at\n}\n\nexport interface ReachTile {\n readonly heights: Float32Array\n readonly cells: number\n readonly x0: number\n readonly z0: number\n readonly cell: number\n readonly pyramid: LowPyramid\n readonly ring: GroundRing\n}\n\nexport interface Reach {\n /** The most the box rises over the ground of the tile's cells (0 when it is nowhere above), and over the ring's cells past its edges. */\n readonly tile: number\n readonly ring: number\n}\n\nconst corner4 = new Float64Array(4)\n/** A block whose bound is within this (m) of the most found is skipped: the heights are 32 bit floats, and a plane through them is that close to a plane under them. */\nconst PRUNE_SLACK = 1e-6\n// one box at a time: its planes (a, bx, bz each), the directions of its shadow's sides (x, z each) and its extent along each (low, high)\nconst planes = new Float64Array(9)\nconst dirs = new Float64Array(10)\nconst spans = new Float64Array(10)\nlet planeCount = 0\nlet dirCount = 0\n\n/** Whether the rectangle and the box's shadow are apart along one of its sides' directions. */\nconst apart = (xa: number, xb: number, za: number, zb: number): boolean => {\n for (let d = 0; d < dirCount; d += 2) {\n const dx = dirs[d]!, dz = dirs[d + 1]!\n const lo = (dx > 0 ? xa * dx : xb * dx) + (dz > 0 ? za * dz : zb * dz)\n const hi = (dx > 0 ? xb * dx : xa * dx) + (dz > 0 ? zb * dz : za * dz)\n if (hi < spans[d]! - 1e-9 || lo > spans[d + 1]! + 1e-9) return true\n }\n return false\n}\n\n/** The least, over the box's planes, of the most each rises over the four corner heights (`corner4`) of the rectangle. */\nconst over = (xa: number, xb: number, za: number, zb: number): number => {\n let best = Infinity\n for (let p = 0; p < planeCount; p += 3) {\n const a = planes[p]!, bx = planes[p + 1]!, bz = planes[p + 2]!\n const most = Math.max(a + bx * xa + bz * za - corner4[0]!, a + bx * xb + bz * za - corner4[1]!, a + bx * xa + bz * zb - corner4[2]!, a + bx * xb + bz * zb - corner4[3]!)\n if (most < best) best = most\n }\n return best\n}\n\n// the tile and box `search` walks (one at a time): the top's own extent in cells (from, to along x, then z), and the most found so far\nlet searchTile: ReachTile | null = null\nconst searchTop = new Int32Array(4)\nlet searchMost = 0\n\n/** The cell (`ia`, `ja`): its corners, and how far the box rises over them. */\nconst leaf = (ia: number, ja: number): void => {\n const { heights, cells, x0, z0, cell } = searchTile!\n const m = cells + 1\n const xa = x0 + ia * cell, za = z0 + ja * cell\n corner4[0] = heights[ja * m + ia]!\n corner4[1] = heights[ja * m + ia + 1]!\n corner4[2] = heights[(ja + 1) * m + ia]!\n corner4[3] = heights[(ja + 1) * m + ia + 1]!\n const e = over(xa, xa + cell, za, za + cell)\n if (e > searchMost) searchMost = e\n}\n\n/** The block (`bi`, `bj`) of level `l`, skipped when the box is apart from it or no higher over its low plane than the most found already, else its four. */\nconst search = (l: number, bi: number, bj: number): void => {\n const { cells, x0, z0, cell, pyramid } = searchTile!\n const s = 1 << l\n const ia = bi * s, ja = bj * s\n if (ia >= cells || ja >= cells) return\n const ib = Math.min(cells, ia + s), jb = Math.min(cells, ja + s)\n if (ia >= searchTop[0]! && ib <= searchTop[1]! && ja >= searchTop[2]! && jb <= searchTop[3]!) return\n const xa = x0 + ia * cell, xb = x0 + ib * cell, za = z0 + ja * cell, zb = z0 + jb * cell\n if (apart(xa, xb, za, zb)) return\n if (l === 0) return leaf(ia, ja)\n const level = pyramid.planes[l]!\n const at = planeUnder(pyramid, l, bi, bj)\n const h = level[at]!, sx = level[at + 1]!, sz = level[at + 2]!\n corner4[0] = h\n corner4[1] = h + sx * (ib - ia)\n corner4[2] = h + sz * (jb - ja)\n corner4[3] = h + sx * (ib - ia) + sz * (jb - ja)\n if (over(xa, xb, za, zb) <= searchMost + PRUNE_SLACK) return\n for (let dj = 0; dj < 2; dj++) for (let di = 0; di < 2; di++) search(l - 1, 2 * bi + di, 2 * bj + dj)\n}\n\nexport const reachOf = (box: ReachBox, t: ReachTile): Reach => {\n const { heights, cells, x0, z0, cell, pyramid, ring } = t\n const m = cells + 1\n // the planes over the box's columns, y <= a + bx x + bz z: one per axis, the face of it that looks up\n planeCount = 0\n for (let k = 0; k < 3; k++) {\n const a = box.axes[k]!\n if (Math.abs(a[1]!) < 1e-9) continue\n const bx = -a[0]! / a[1]!, bz = -a[2]! / a[1]!\n planes[planeCount++] = box.c[1]! + box.half[k]! / Math.abs(a[1]!) - bx * box.c[0]! - bz * box.c[2]!\n planes[planeCount++] = bx\n planes[planeCount++] = bz\n }\n // the box's shadow as a convex polygon: its extent along x, z and across each axis seen from above\n dirs[0] = 1\n dirs[1] = 0\n dirs[2] = 0\n dirs[3] = 1\n dirCount = 4\n for (const a of box.axes) {\n const l = Math.hypot(a[0]!, a[2]!)\n if (l < 1e-9) continue\n dirs[dirCount++] = -a[2]! / l\n dirs[dirCount++] = a[0]! / l\n }\n for (let d = 0; d < dirCount; d += 2) {\n const dx = dirs[d]!, dz = dirs[d + 1]!\n let r = 0\n for (let k = 0; k < 3; k++) r += box.half[k]! * Math.abs(box.axes[k]![0]! * dx + box.axes[k]![2]! * dz)\n const mid = box.c[0]! * dx + box.c[2]! * dz\n spans[d] = mid - r\n spans[d + 1] = mid + r\n }\n let inTile = 0\n // under the top's own extent, the top's plane over every corner (each cell's most is at a corner): the most found there skips most of the rest\n const n = box.axes[1]!, ax = box.axes[0]!, az = box.axes[2]!\n const tx = box.c[0]! + n[0]! * box.half[1]!, ty = box.c[1]! + n[1]! * box.half[1]!, tz = box.c[2]! + n[2]! * box.half[1]!\n const rx = box.half[0]! * Math.abs(ax[0]!) + box.half[2]! * Math.abs(az[0]!), rz = box.half[0]! * Math.abs(ax[2]!) + box.half[2]! * Math.abs(az[2]!)\n const ta = Math.max(0, Math.floor((tx - rx - x0) / cell)), tb = Math.min(cells, Math.ceil((tx + rx - x0) / cell))\n const sa = Math.max(0, Math.floor((tz - rz - z0) / cell)), sb = Math.min(cells, Math.ceil((tz + rz - z0) / cell))\n const bx = -n[0]! / n[1]!, bz = -n[2]! / n[1]!\n for (let j = sa; j <= sb; j++) {\n for (let i = ta; i <= tb; i++) {\n const e = ty + bx * (x0 + i * cell - tx) + bz * (z0 + j * cell - tz) - heights[j * m + i]!\n if (e > inTile) inTile = e\n }\n }\n // the box is its top slid down along -n: a point of it a slide s from the top at q stands s n_y under the top, over ground at most s |n_h| (the steepest) under q's.\n // Where the ground is nowhere steeper than 1 / (its top's slope), no point of the box is further over the ground than its top over its own extent (all in the tile)\n const ia = Math.floor((spans[0]! - x0) / cell), ib = Math.ceil((spans[1]! - x0) / cell)\n const ja = Math.floor((spans[2]! - z0) / cell), jb = Math.ceil((spans[3]! - z0) / cell)\n const within = ia >= 0 && ja >= 0 && ib <= cells && jb <= cells\n if (within && !steeperOver(pyramid, ia, ib, ja, jb, n[1]! / Math.max(1e-12, Math.hypot(n[0]!, n[2]!)))) return { tile: inTile, ring: 0 }\n searchTile = t\n searchTop[0] = ta\n searchTop[1] = tb\n searchTop[2] = sa\n searchTop[3] = sb\n searchMost = inTile\n // else every cell of its shadow, from the level whose blocks are as wide as the shadow's extent along x and z, over the (at most four) of them it covers\n const ua = Math.max(0, ia), ub = Math.min(cells, ib), va = Math.max(0, ja), vb = Math.min(cells, jb)\n if (ua < ub && va < vb) {\n let l = 0\n while (1 << l < Math.max(ub - ua, vb - va) && l < pyramid.sizes.length - 1) l++\n for (let bj = va >> l; bj <= (vb - 1) >> l; bj++) for (let bi = ua >> l; bi <= (ub - 1) >> l; bi++) search(l, bi, bj)\n }\n inTile = searchMost\n // the last tile (and the host's ground its ring holds) is not kept past the call (§8)\n searchTile = null\n // past the edges: the ring's cells the shadow's extent reaches\n let inRing = 0\n const r = ring.cells\n if (within) return { tile: inTile, ring: 0 }\n for (let j = Math.max(-r, ja); j < Math.min(cells + r, jb); j++) {\n const across = j >= 0 && j < cells\n for (let i = Math.max(-r, ia); i < Math.min(cells + r, ib); i++) {\n // over the tile, along the row: on to its far edge\n if (across && i >= 0 && i < cells) i = cells\n if (i >= Math.min(cells + r, ib)) break\n const xa = x0 + i * cell, za = z0 + j * cell\n if (apart(xa, xa + cell, za, za + cell)) continue\n ring.cell(i, j, corner4)\n const e = over(xa, xa + cell, za, za + cell)\n if (e > inRing) inRing = e\n }\n }\n return { tile: inTile, ring: inRing }\n}\n","import { coarseStep, underBoth } from './engine-ground-collision'\nimport { createGroundRing } from './engine-ground-ring'\nimport type { GroundSource } from './engine-ground-ring'\nimport { buildLowPyramid, reachOf } from './engine-ground-reach'\n\n/**\n * The solid under a height field. Jolt's height field is a surface: a body that ends up wholly below it (ground raised under a sleeping piece, a piece that\n * tunnelled) has nothing to push it out and falls for good. Under the surface of a tile there are blocks, from the lowest ground of the tile less `SOLID_DEPTH`\n * up to a top close under the surface and never above it (§12). A block is split until a plane through its corners is within `SOLID_RELIEF` of the surface or it is\n * `SOLID_MIN_CELLS` cells wide. A level block is a box topped at its lowest ground less `SOLID_MARGIN`; a sloped block is one box turned to its corner plane, its top that\n * plane over the block and a cell past it each way (turned boxes side by side lean apart under their tops: what is pushed out sideways meets the next one), lowered by the\n * most any point of it, top or leaning side, rises over the ground under it (`engine-ground-reach`) and `SOLID_MARGIN`. Where it reaches past the tile, the ground there is\n * the neighbour's (`engine-ground-ring`), read up to `SOLID_RING` out; a box that would lean further is made shallower. Under each turned box is its block's upright box\n * (topped at the block's lowest ground less `SOLID_MARGIN`): turned boxes side by side part under their tops, and what slips between them rests on it, its top no further\n * under the ground than the block's relief and its own size.\n * Every block is boxes: a sloped one used to be a prism (a convex hull each), and a crater tile's 400 hulls were most of the frame after the blast (T3.8ag).\n */\n\n/** How far (m) under the lowest corner of its tile the solid goes. */\nexport const SOLID_DEPTH = 0.5\n/** How far (m) under the surface a block's top may be before the block is split, unless it is already `SOLID_MIN_CELLS` cells wide. */\nconst SOLID_RELIEF = 0.005\nconst SOLID_MIN_CELLS = 3\n/**\n * A top is this far (m) under the lowest ground it stands for: 2 mm put the solid in the contacts of what rests on the surface and the bowl's seed 18 gained 4 cm. The engine\n * holds a height field's samples in 8 bit steps of each 4-sample block's range, up to half a step off (range / 510: 0.15 mm on a 0.75 slope at 2.5 cm, 0.3 mm at 5 cm), well\n * inside this margin.\n */\nexport const SOLID_MARGIN = 0.005\n/** The thinnest (m) a turned box is made; where that would lean past the ring, the block is split, or (at its smallest) left to its upright box. */\nconst SOLID_THINNEST = 0.05\n/** How much (m) more a block's box must be lowered for the ground past the tile than for its own before the block is split, so a fold at the seam lowers a narrow box only. */\nconst SEAM_SPLIT = 0.01\n/** Numbers per block in `SolidVolume.boxes`. */\nexport const SOLID_STRIDE = 10\n\nexport interface SolidVolume {\n /** The blocks: centre x, y, z, half x, y, z and turn x, y, z, w (`SOLID_STRIDE` numbers each); the box's own y is the normal of its top. */\n readonly boxes: readonly number[] | Float64Array\n /** The ground read past the tile's edges, x, z and height each (`engine-ground-ring`): the blocks are made again when one of these changes. */\n readonly ring: readonly number[] | Float64Array\n}\n\nexport const NO_SOLID: SolidVolume = { boxes: [], ring: [] }\n\n/** The unit vector along (x, y, z), into `out`. */\nconst unitInto = (out: Float64Array, x: number, y: number, z: number): Float64Array => {\n const l = Math.hypot(x, y, z)\n out[0] = x / l\n out[1] = y / l\n out[2] = z / l\n return out\n}\n\n// one block at a time: its corner plane's slopes, and the box the reach is asked about (filled in place, no arrays per block)\nconst slopes = new Float64Array(2)\nconst reachAxes = [new Float64Array(3), new Float64Array(3), new Float64Array(3)] as const\nconst reachBox = { c: new Float64Array(3), axes: [reachAxes[0], reachAxes[1], reachAxes[2]], half: new Float64Array(3) }\n\n/** The quaternion of the turn whose columns are the axes `a` (x), `b` (y) and `c` (z). */\nconst quatOfAxes = (a: ArrayLike<number>, b: ArrayLike<number>, c: ArrayLike<number>): [number, number, number, number] => {\n const m00 = a[0]!, m10 = a[1]!, m20 = a[2]!, m01 = b[0]!, m11 = b[1]!, m21 = b[2]!, m02 = c[0]!, m12 = c[1]!, m22 = c[2]!\n const trace = m00 + m11 + m22\n if (trace > 0) {\n const s = 0.5 / Math.sqrt(trace + 1)\n return [(m21 - m12) * s, (m02 - m20) * s, (m10 - m01) * s, 0.25 / s]\n }\n if (m00 > m11 && m00 > m22) {\n const s = 2 * Math.sqrt(1 + m00 - m11 - m22)\n return [0.25 * s, (m01 + m10) / s, (m02 + m20) / s, (m21 - m12) / s]\n }\n if (m11 > m22) {\n const s = 2 * Math.sqrt(1 + m11 - m00 - m22)\n return [(m01 + m10) / s, 0.25 * s, (m12 + m21) / s, (m02 - m20) / s]\n }\n const s = 2 * Math.sqrt(1 + m22 - m00 - m11)\n return [(m02 + m20) / s, (m12 + m21) / s, 0.25 * s, (m10 - m01) / s]\n}\n\n/** How thick (m) a box whose bottom moves by `lean` per metre of thickness may be and stay within `lo`..`hi`, its top spanning `low`..`high` (no thickness when the top does not fit). */\nconst thickWithin = (lean: number, low: number, high: number, lo: number, hi: number): number => {\n if (low < lo || high > hi) return -Infinity\n return lean > 1e-12 ? (hi - high) / lean : lean < -1e-12 ? (low - lo) / -lean : Infinity\n}\n\n/**\n * The blocks under a tile of `cells` cells of side `cell` from (`x0`, `z0`), over its `read` heights (`(cells + 1)^2`, x fastest) and the engine's coarser collision field of\n * them (`step`: every how many corners it is), and the ground around it (`groundAt`, read only past the tile's edges, up to `SOLID_RING`, and its collision field there too).\n */\nexport const buildSolidVolume = (read: Float32Array, cells: number, x0: number, z0: number, cell: number, groundAt: GroundSource, step = 1): SolidVolume => {\n // under the drawn ground and the engine's collision field (every `step`-th corner, `engine-ground-collision`) both, whichever is lower at each corner\n const heights = underBoth(read, cells, step)\n const m = cells + 1\n let low = Infinity\n for (const h of heights) low = Math.min(low, h)\n const bottom = low - SOLID_DEPTH\n const boxes: number[] = []\n // past the edge, under the neighbour's coarse field too, whichever it collides with\n const ring = createGroundRing(heights, cells, x0, z0, cell, groundAt, coarseStep(cells, cell))\n const reachTile = { heights, cells, x0, z0, cell, pyramid: buildLowPyramid(heights, cells, cell), ring }\n const outer = ring.cells * cell\n const loX = x0 - outer, hiX = x0 + cells * cell + outer, loZ = z0 - outer, hiZ = z0 + cells * cell + outer\n const at = (i: number, j: number): number => heights[j * m + i]!\n /** The slopes (per cell) of the plane through the block's corners, into `slopes` (x then z). */\n const slopesOf = (i0: number, j0: number, i1: number, j1: number): void => {\n slopes[0] = (at(i1, j0) - at(i0, j0) + at(i1, j1) - at(i0, j1)) / 2 / (i1 - i0)\n slopes[1] = (at(i0, j1) - at(i0, j0) + at(i1, j1) - at(i1, j0)) / 2 / (j1 - j0)\n }\n\n /** How far the surface rises above the plane through the block's corners lowered to its lowest sample: the block is split while it is more. */\n const planeGap = (i0: number, j0: number, i1: number, j1: number): number => {\n slopesOf(i0, j0, i1, j1)\n const sx = slopes[0]!, sz = slopes[1]!\n let least = Infinity\n let most = -Infinity\n for (let j = j0; j <= j1; j++) {\n for (let i = i0; i <= i1; i++) {\n const above = at(i, j) - (at(i0, j0) + sx * (i - i0) + sz * (j - j0))\n if (above < least) least = above\n if (above > most) most = above\n }\n }\n return most - least\n }\n\n /** A level block: an upright box topped at its lowest ground less `SOLID_MARGIN`. */\n const level = (i0: number, j0: number, i1: number, j1: number, least: number): void => {\n const top = least - SOLID_MARGIN\n boxes.push(x0 + ((i0 + i1) / 2) * cell, (top + bottom) / 2, z0 + ((j0 + j1) / 2) * cell, ((i1 - i0) * cell) / 2, (top - bottom) / 2, ((j1 - j0) * cell) / 2, 0, 0, 0, 1)\n }\n\n /**\n * A sloped block: one box turned to the plane through its corners, its top the rectangle on that plane over the block and a cell past it each way, down to under the\n * solid's bottom, lowered by the most it rises over the ground anywhere (`reachOf`) and `SOLID_MARGIN`. A box that would lean past the ring is made as deep as stays in\n * it (the block's upright box is under it); a box lowered by more than the block's relief is the upright box alone. False when the block should be split instead: its box would not\n * fit the ring, or the ground past the tile lowers it much more than its own.\n */\n const sloped = (i0: number, j0: number, i1: number, j1: number, least: number, most: number): boolean => {\n const span = Math.max(i1 - i0, j1 - j0)\n slopesOf(i0, j0, i1, j1)\n const gx = slopes[0]! / cell\n const gz = slopes[1]! / cell\n const ox = x0 + i0 * cell\n const oz = z0 + j0 * cell\n const base = at(i0, j0)\n // the box's axes, in the scratch the reach reads them from: n the normal of its top, ax along x up the slope, az across both\n const n = unitInto(reachAxes[1]!, -gx, 1, -gz)\n const ax = unitInto(reachAxes[0]!, 1, gx, 0)\n const az = reachAxes[2]!\n az[0] = ax[1]! * n[2]! - ax[2]! * n[1]!\n az[1] = ax[2]! * n[0]! - ax[0]! * n[2]!\n az[2] = ax[0]! * n[1]! - ax[1]! * n[0]!\n const xa = ox, xb = x0 + i1 * cell, za = oz, zb = z0 + j1 * cell\n const cx = (xa + xb) / 2, cz = (za + zb) / 2, cy = base + gx * (cx - ox) + gz * (cz - oz)\n let hx = 0\n let hz = 0\n for (let a = 0; a < 2; a++) {\n const x = a === 0 ? xa : xb\n for (let b = 0; b < 2; b++) {\n const z = b === 0 ? za : zb\n const d0 = x - cx, d1 = base + gx * (x - ox) + gz * (z - oz) - cy, d2 = z - cz\n hx = Math.max(hx, Math.abs(d0 * ax[0]! + d1 * ax[1]! + d2 * ax[2]!))\n hz = Math.max(hz, Math.abs(d0 * az[0]! + d1 * az[1]! + d2 * az[2]!))\n }\n }\n hx += cell\n hz += cell\n let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity, highest = -Infinity\n for (let a = 0; a < 2; a++) {\n const su = a === 0 ? -1 : 1\n for (let b = 0; b < 2; b++) {\n const sw = b === 0 ? -1 : 1\n const qx = cx + su * hx * ax[0] + sw * hz * az[0]\n const qz = cz + su * hx * ax[2] + sw * hz * az[2]\n minX = Math.min(minX, qx)\n maxX = Math.max(maxX, qx)\n minZ = Math.min(minZ, qz)\n maxZ = Math.max(maxZ, qz)\n highest = Math.max(highest, cy + su * hx * ax[1] + sw * hz * az[1])\n }\n }\n // deep enough that its bottom face is under the solid's bottom everywhere (a box made only as deep as its block's upright box let what it pushed out the bottom through:\n // 17 of the 48 boxes of the push-up sweep fell, as with a730b5450's slab), unless its bottom would lean (uphill: by -n per metre of thickness) past the ring\n const deep = (highest - bottom) / n[1]\n const fits = Math.min(thickWithin(-n[0], minX, maxX, loX, hiX), thickWithin(-n[2], minZ, maxZ, loZ, hiZ))\n const thick = Math.max(SOLID_THINNEST, Math.min(deep, fits))\n if (fits < thick) {\n if (span > SOLID_MIN_CELLS) return false\n level(i0, j0, i1, j1, least)\n return true\n }\n const hy = thick / 2\n const centre = reachBox.c\n centre[0] = cx - n[0]! * hy\n centre[1] = cy - n[1]! * hy\n centre[2] = cz - n[2]! * hy\n reachBox.half[0] = hx\n reachBox.half[1] = hy\n reachBox.half[2] = hz\n const reach = reachOf(reachBox, reachTile)\n if (reach.ring > reach.tile + SEAM_SPLIT && span > SOLID_MIN_CELLS) return false\n const drop = SOLID_MARGIN + Math.max(reach.tile, reach.ring)\n // lowered further than the block's own relief, its top would be further under the ground than the upright box's\n if (drop - SOLID_MARGIN >= most - least) {\n level(i0, j0, i1, j1, least)\n return true\n }\n // and under it the block's upright box: what slips between two turned boxes (they part under their tops; a cell's overlap closes only so deep) rests on it, no\n // further under the ground than the block's relief\n level(i0, j0, i1, j1, least)\n const q = quatOfAxes(ax, n, az)\n boxes.push(centre[0]!, centre[1]! - drop, centre[2]!, hx, hy, hz, q[0], q[1], q[2], q[3])\n return true\n }\n\n const fill = (i0: number, j0: number, i1: number, j1: number): void => {\n let least = Infinity\n let most = -Infinity\n for (let j = j0; j <= j1; j++) {\n for (let i = i0; i <= i1; i++) {\n const h = at(i, j)\n if (h < least) least = h\n if (h > most) most = h\n }\n }\n if (most - least <= SOLID_RELIEF) return level(i0, j0, i1, j1, least)\n const span = Math.max(i1 - i0, j1 - j0)\n if ((planeGap(i0, j0, i1, j1) > SOLID_RELIEF && span > SOLID_MIN_CELLS) || !sloped(i0, j0, i1, j1, least, most)) {\n // in halves (a side under two cells stays whole), x's halves first\n const im = i1 - i0 < 2 ? i1 : (i0 + i1) >> 1\n const jm = j1 - j0 < 2 ? j1 : (j0 + j1) >> 1\n for (let a = i0; a < i1; a = im) {\n const b = a === i0 ? im : i1\n for (let d = j0; d < j1; d = jm) {\n const e = d === j0 ? jm : j1\n fill(a, d, b, e)\n if (e === j1) break\n }\n if (b === i1) break\n }\n }\n }\n fill(0, 0, cells, cells)\n return { boxes, ring: ring.read }\n}\n\n/** The same blocks. */\nexport const sameSolid = (a: SolidVolume, b: SolidVolume): boolean => same(a.boxes, b.boxes)\n\n/** The same numbers, in order (plain or typed arrays alike). */\nexport const sameNumbers = (a: ArrayLike<number>, b: ArrayLike<number>): boolean => {\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false\n return true\n}\n\nconst same = sameNumbers\n","import type { HeightPatch } from '@adatechnology/game-terrain'\n\nimport { NO_SOLID, buildSolidVolume } from './engine-ground-solid'\nimport type { SolidVolume } from './engine-ground-solid'\nimport { collisionFieldOf } from './engine-ground-collision'\nimport { holdsStep } from './engine-ground-step'\n\n/**\n * The ground a physics engine stands the pieces on, one tile of `groundAt` at a time: a height field over the cell corners for what is smooth, and solid boxes\n * for the cells a hard step runs through (a crater's rim, a terraced slope) and the cells around them. A box's top is its cell's centre height and its\n * sides are vertical, so a step keeps its edge (within half a cell of where it is) instead of a ramp one cell wide; under the boxes the height field is lowered so\n * it does not ramp up through them. A level tile is one slab, solid below.\n *\n * Why not triangles: the step-keeping triangle mesh this replaces was one-sided (a thin piece pressed half through a triangle fell through for good) and had to be\n * made again, as a new body, for every change, which threw away the engine's contact cache. A height field of the same tile is made in about 0.3 ms and can be\n * swapped on the same body (`EnginePieces`), so the pieces on it keep their contacts.\n *\n * The tile is read at `GROUND_CELL`; the engine collides with every second corner of it, a 5 cm field (`engine-ground-collision`, owner decision 2026-11-17), and the solid\n * under it stays under both.\n */\n\n/** Cells of a tile (m), as Rapier's spike measured good enough for a 4 cm plate. */\nexport const GROUND_CELL = 0.025\n/** How far (m) under the lowest ground around them the step boxes go, and how far the height field drops under them. */\nconst BOX_DEPTH = 0.05\nconst UNDER_BOX = 0.01\n\nexport interface GroundTile {\n /** Corner heights, `(cells + 1)^2`, x fastest: `heights[iz * (cells + 1) + ix]`. Empty when the tile is level. */\n readonly heights: Float32Array\n readonly cells: number\n /** The height field the engine collides with (`engine-ground-collision`): every `cells / collisionCells`-th corner of `heights`, `(collisionCells + 1)^2`. Empty when level. */\n readonly collision: Float32Array\n readonly collisionCells: number\n /** The step boxes: centre x, y, z and half x, y, z, six numbers each (a typed array when the tile came from a worker, `engine-ground-job`). */\n readonly boxes: readonly number[] | Float64Array\n /** The solid under the height field (`engine-ground-solid`); none when the tile is level (a slab is solid already). */\n readonly solid: SolidVolume\n /** The height of a level tile (every sample equal), or null. */\n readonly level: number | null\n /** Every sample read, to tell whether the ground changed since; null for a tile proved level from the terrain's own bounds (`flatTile`), whose samples were never read. */\n readonly samples: Float64Array | null\n /** The terrain's vertices the tile was made from (`readGroundPatch`; its samples are then null): what tells whether the ground changed since. */\n readonly patch?: HeightPatch\n}\n\nconst NO_HEIGHTS = new Float32Array(0)\n/** One cell's nine samples, for `holdsStep`. */\nconst cellSamples = new Float64Array(9)\n\n/** The tile of a level `size` at `level`, laid without a sample read: the caller has proved, from the ground's own data, that every sample there is `level` (to 1e-9, as `shapeGround` calls level). */\nexport const flatTile = (level: number, size: number): GroundTile => ({ heights: NO_HEIGHTS, cells: Math.round(size / GROUND_CELL), collision: NO_HEIGHTS, collisionCells: 0, boxes: [], solid: NO_SOLID, level, samples: null })\n\n/** A rectangle of the ground, world x and z. */\nexport interface GroundRect {\n readonly minX: number\n readonly maxX: number\n readonly minZ: number\n readonly maxZ: number\n}\n\n/**\n * The four series of samples of a tile, one after the other in `samples`: the corners, the cells' centres, the middles of the edges along x and those along z.\n * `ox` and `oz` are where the series sits in a cell (0 or half), `width` and `rows` how many samples it has along x and along z.\n */\nconst seriesOf = (n: number): ReadonlyArray<{ offset: number; width: number; rows: number; ox: number; oz: number }> => {\n const m = n + 1\n return [\n { offset: 0, width: m, rows: m, ox: 0, oz: 0 },\n { offset: m * m, width: n, rows: n, ox: 0.5, oz: 0.5 },\n { offset: m * m + n * n, width: n, rows: m, ox: 0.5, oz: 0 },\n { offset: m * m + n * n + n * m, width: m, rows: n, ox: 0, oz: 0.5 },\n ]\n}\n\n/** The `samples` array of a tile of `n` cells. */\nexport const sampleCount = (n: number): number => (n + 1) * (n + 1) + n * n + 2 * n * (n + 1)\n\n/**\n * The ground over a lattice in one pass: the height at (`xs[i]`, `zs[j]`) into `out[j * xs.length + i]`, to the bit what the tile's `groundAt` answers at each point\n * (`Terrain.heightGrid` is one). A tile reads its 26 000 samples through it instead of a call each.\n */\nexport type GroundGrid = (xs: ArrayLike<number>, zs: ArrayLike<number>, out: Float64Array) => void\n\n// the points a grid read asks for and what it answers, kept between reads (one at a time) so a read does not make them again\nlet seriesX = new Float64Array(0)\nlet seriesZ = new Float64Array(0)\nlet seriesHeights = new Float64Array(0)\n\n/**\n * Reads the ground of the tile at (x0, z0) into `samples`: every sample, or only those a rectangle reaches (a sample a cell outside it is read too, so what the\n * rectangle's edge touches is not left old). True when a sample read differs from the one held. A crater in a corner of a tile asks `groundAt` for the corner.\n * With a `grid` each series is read in one pass over its own points, each the one `groundAt` would be asked for (`x0 + (i + ox) * c`), so the same heights.\n * Not reentrant: the points are module scratch, so neither reader may read a tile in turn.\n */\nexport const readGround = (groundAt: (x: number, z: number) => number, samples: Float64Array, x0: number, z0: number, size: number, rect?: GroundRect, grid?: GroundGrid): boolean => {\n const n = Math.round(size / GROUND_CELL)\n const c = size / n\n let changed = false\n for (const { offset, width, rows, ox, oz } of seriesOf(n)) {\n const i0 = rect ? Math.max(0, Math.floor((rect.minX - x0) / c - ox)) : 0\n const i1 = rect ? Math.min(width - 1, Math.ceil((rect.maxX - x0) / c - ox)) : width - 1\n const j0 = rect ? Math.max(0, Math.floor((rect.minZ - z0) / c - oz)) : 0\n const j1 = rect ? Math.min(rows - 1, Math.ceil((rect.maxZ - z0) / c - oz)) : rows - 1\n if (i0 > i1 || j0 > j1) continue\n if (!grid) {\n for (let j = j0; j <= j1; j++) {\n for (let i = i0; i <= i1; i++) {\n const h = groundAt(x0 + (i + ox) * c, z0 + (j + oz) * c)\n if (samples[offset + j * width + i] !== h) changed = true\n samples[offset + j * width + i] = h\n }\n }\n continue\n }\n const across = i1 - i0 + 1\n const along = j1 - j0 + 1\n if (seriesX.length < across) seriesX = new Float64Array(across)\n if (seriesZ.length < along) seriesZ = new Float64Array(along)\n if (seriesHeights.length < across * along) seriesHeights = new Float64Array(across * along)\n for (let i = 0; i < across; i++) seriesX[i] = x0 + (i0 + i + ox) * c\n for (let j = 0; j < along; j++) seriesZ[j] = z0 + (j0 + j + oz) * c\n grid(seriesX.subarray(0, across), seriesZ.subarray(0, along), seriesHeights)\n for (let j = 0; j < along; j++) {\n const from = j * across\n const to = offset + (j0 + j) * width + i0\n if (!changed) {\n for (let i = 0; i < across; i++) {\n if (samples[to + i] !== seriesHeights[from + i]) {\n changed = true\n break\n }\n }\n }\n samples.set(seriesHeights.subarray(from, from + across), to)\n }\n }\n return changed\n}\n\nexport const buildGroundTile = (groundAt: (x: number, z: number) => number, x0: number, z0: number, size: number, withSolid = true, grid?: GroundGrid): GroundTile => {\n const samples = new Float64Array(sampleCount(Math.round(size / GROUND_CELL)))\n readGround(groundAt, samples, x0, z0, size, undefined, grid)\n return shapeGround(samples, x0, z0, size, withSolid ? groundAt : null)\n}\n\n/**\n * The tile the samples make: level, or its height field, step boxes and (given the ground, which it reads past the tile's edges; else `NO_SOLID`, for a caller that may\n * not need it) the solid under it. Pure of the samples (and that ground), so a tile made from samples patched in place is the one made from all of them read again, but\n * for its collision field near the bound, which keeps the coarse one it had (`wasCoarse`, `collisionFieldOf`).\n */\nexport const shapeGround = (samples: Float64Array, x0: number, z0: number, size: number, solidGround: ((x: number, z: number) => number) | null, wasCoarse = false): GroundTile => {\n const n = Math.round(size / GROUND_CELL)\n const c = size / n\n const m = n + 1\n const [cornerSeries, centreSeries, midXSeries, midZSeries] = seriesOf(n)\n const corners = samples.subarray(cornerSeries!.offset, centreSeries!.offset)\n const centres = samples.subarray(centreSeries!.offset, midXSeries!.offset)\n const midX = samples.subarray(midXSeries!.offset, midZSeries!.offset)\n const midZ = samples.subarray(midZSeries!.offset)\n let low = Infinity\n let high = -Infinity\n for (const h of samples) {\n low = Math.min(low, h)\n high = Math.max(high, h)\n }\n if (high - low < 1e-9) return { heights: new Float32Array(0), cells: n, collision: NO_HEIGHTS, collisionCells: 0, boxes: [], solid: NO_SOLID, level: high, samples }\n const corner = (i: number, j: number): number => corners[j * m + i]\n // a cell whose centre or an edge's middle leaves its corners holds a step; it and the cells around it become boxes\n const mask = new Uint8Array(n * n)\n for (let j = 0; j < n; j++) {\n for (let i = 0; i < n; i++) {\n cellSamples[0] = corner(i, j)\n cellSamples[1] = corner(i + 1, j)\n cellSamples[2] = corner(i, j + 1)\n cellSamples[3] = corner(i + 1, j + 1)\n cellSamples[4] = centres[j * n + i]\n cellSamples[5] = midX[j * n + i]\n cellSamples[6] = midX[(j + 1) * n + i]\n cellSamples[7] = midZ[j * m + i]\n cellSamples[8] = midZ[j * m + i + 1]\n if (!holdsStep(cellSamples)) continue\n for (let dj = -1; dj <= 1; dj++) for (let di = -1; di <= 1; di++) if (i + di >= 0 && j + dj >= 0 && i + di < n && j + dj < n) mask[(j + dj) * n + i + di] = 1\n }\n }\n const heights = new Float32Array(m * m)\n for (let j = 0; j <= n; j++) {\n for (let i = 0; i <= n; i++) {\n // a corner whose four cells are all boxes goes under the lowest of them\n let inside = true\n let least = corner(i, j)\n for (let dj = -1; dj <= 0 && inside; dj++) for (let di = -1; di <= 0; di++) {\n const ii = i + di, jj = j + dj\n if (ii < 0 || jj < 0 || ii >= n || jj >= n || !mask[jj * n + ii]) {\n inside = false\n break\n }\n least = Math.min(least, centres[jj * n + ii], corner(ii, jj), corner(ii + 1, jj), corner(ii, jj + 1), corner(ii + 1, jj + 1))\n }\n heights[j * m + i] = inside ? least - UNDER_BOX : corner(i, j)\n }\n }\n // the boxes: runs along x of masked cells at one height, down to under the lowest ground around them\n const boxes: number[] = []\n for (let j = 0; j < n; j++) {\n let i = 0\n while (i < n) {\n if (!mask[j * n + i]) {\n i++\n continue\n }\n const top = centres[j * n + i]\n let end = i + 1\n while (end < n && mask[j * n + end] && Math.abs(centres[j * n + end] - top) < 0.001) end++\n let bottom = top\n for (let k = Math.max(0, i - 1); k <= Math.min(n, end + 1); k++) for (let jj = Math.max(0, j - 1); jj <= Math.min(n, j + 2); jj++) bottom = Math.min(bottom, corner(k, jj))\n bottom -= BOX_DEPTH\n boxes.push(x0 + ((i + end) / 2) * c, (top + bottom) / 2, z0 + (j + 0.5) * c, ((end - i) * c) / 2, (top - bottom) / 2, c / 2)\n i = end\n }\n }\n const { step, field } = collisionFieldOf(heights, n, c, boxes.length > 0, wasCoarse)\n return { heights, cells: n, collision: field, collisionCells: n / step, boxes, solid: solidGround ? buildSolidVolume(heights, n, x0, z0, c, solidGround, step) : NO_SOLID, level: null, samples }\n}\n","import { cellCoordinate, heightPatchGrid } from '@adatechnology/game-terrain'\nimport type { HeightPatch } from '@adatechnology/game-terrain'\n\nimport { GROUND_CELL, readGround, sampleCount, shapeGround } from './engine-ground'\nimport type { GroundGrid, GroundTile } from './engine-ground'\nimport { SOLID_RING } from './engine-ground-ring'\nimport { NO_SOLID, buildSolidVolume } from './engine-ground-solid'\n\n/**\n * A tile of the engine's ground as plain data, so it can be made off the main thread (`engine-ground-port`): the main thread reads the tile's samples and the band of ground\n * past its edges its solid may read (`readGroundBand`), and the tile is a pure function of those (`computeGroundTile`), the same bits wherever it runs. Nothing here calls back\n * into the host: a worker has no `groundAt`.\n */\n\n/** What a tile is made from: its samples (`readGround`) and the band past its edges (`readGroundBand`), both read on the main thread at the frame it was asked for. */\nexport interface GroundTileJob {\n readonly id: number\n readonly x0: number\n readonly z0: number\n readonly size: number\n /** Whether the tile collided on the coarse field before (`collisionFieldOf`). */\n readonly wasCoarse: boolean\n /** Empty in a patch job (`patch`), whose samples and band are made where the tile is. */\n readonly samples: Float64Array\n readonly band: Float64Array\n /**\n * The terrain's vertices under the tile and its ring (`readGroundPatch`), in place of the samples and the band: about 26 x 26 numbers instead of 60 000. The tile is made from\n * the samples and band the patch gives (`heightPatchGrid`, the terrain's own blend), the same bits as read from the terrain on the main thread.\n */\n readonly patch?: HeightPatch\n}\n\n/** A tile made from a job, as arrays that cross threads; `samples` and `band` are the job's own, handed back for the next job. */\nexport interface GroundTileResult {\n readonly id: number\n readonly cells: number\n readonly collisionCells: number\n readonly level: number | null\n readonly heights: Float32Array\n readonly collision: Float32Array\n readonly boxes: Float64Array\n readonly solid: Float64Array\n readonly ring: Float64Array\n readonly samples: Float64Array\n readonly band: Float64Array\n /** A patch job's vertex heights, handed back for the next job. */\n readonly patch?: Float64Array\n}\n\n/** How many read cells the ring past a tile of `cells` cells of side `cell` is wide (`createGroundRing`). */\nconst ringOf = (cell: number): number => Math.round(SOLID_RING / cell)\n\n/** The length of the band of a tile of `size` m: one height per half cell over the tile and its ring (`GroundSource`). */\nexport const bandLength = (size: number): number => {\n const n = Math.round(size / GROUND_CELL)\n const width = 2 * (n + 2 * ringOf(size / n)) + 1\n return width * width\n}\n\n// the lattice of a band read through the grid, kept between reads (one at a time)\nlet lineX = new Float64Array(0)\nlet lineZ = new Float64Array(0)\nlet sideOut = new Float64Array(0)\n\n/**\n * Reads into `band` the ground past the tile's edges, as far as its solid may read it (`SOLID_RING`) and on the edges themselves: every half cell `(a, b)` with `a` or `b` on or\n * past an edge, at the very point the ring asks `groundAt` for (`x0 + (a / 2) * cell`). Through `grid` in four strips, else a call each. The tile's inside is left as it was.\n */\nexport const readGroundBand = (groundAt: (x: number, z: number) => number, band: Float64Array, x0: number, z0: number, size: number, grid?: GroundGrid): void => {\n const n = Math.round(size / GROUND_CELL)\n const cell = size / n\n const r = ringOf(cell)\n const lo = -2 * r\n const hi = 2 * n + 2 * r\n const width = hi - lo + 1\n const xAt = (a: number): number => x0 + (a / 2) * cell\n const zAt = (b: number): number => z0 + (b / 2) * cell\n if (!grid) {\n for (let b = lo; b <= hi; b++) {\n for (let a = lo; a <= hi; a++) {\n if (a > 0 && a < 2 * n && b > 0 && b < 2 * n) continue\n band[(b - lo) * width + a - lo] = groundAt(xAt(a), zAt(b))\n }\n }\n return\n }\n const strip = 2 * r + 1\n const middle = 2 * n - 1\n if (lineX.length < width) lineX = new Float64Array(width)\n if (lineZ.length < width) lineZ = new Float64Array(width)\n if (sideOut.length < strip * middle) sideOut = new Float64Array(strip * middle)\n for (let a = lo; a <= hi; a++) lineX[a - lo] = xAt(a)\n const xs = lineX.subarray(0, width)\n // the rows under the tile and over it, whole: straight into the band\n for (const from of [lo, 2 * n]) {\n for (let k = 0; k < strip; k++) lineZ[k] = zAt(from + k)\n grid(xs, lineZ.subarray(0, strip), band.subarray((from - lo) * width, (from - lo + strip) * width))\n }\n // the columns left and right of it, between those rows\n for (let k = 0; k < middle; k++) lineZ[k] = zAt(1 + k)\n const zs = lineZ.subarray(0, middle)\n for (const from of [lo, 2 * n]) {\n grid(lineX.subarray(from - lo, from - lo + strip), zs, sideOut)\n for (let k = 0; k < middle; k++) for (let i = 0; i < strip; i++) band[(1 + k - lo) * width + from - lo + i] = sideOut[k * strip + i]!\n }\n}\n\n/** The host's terrain as vertex heights under a rectangle (min x, max x, min z, max z), or null where it cannot (`Terrain.heightPatch` is one); written into `into` when long enough. */\nexport type GroundPatchRead = (minX: number, maxX: number, minZ: number, maxZ: number, into?: Float64Array) => HeightPatch | null\n\n/**\n * The terrain's vertices under the tile at (x0, z0) and its ring, the rectangle every sample and band point lies in (the band's own outermost points, as `readGroundBand` computes\n * them); null where the host has none (a tile crossing the terrain's bounds, where its `baseHeight` answers): that tile is read as before.\n */\nexport const readGroundPatch = (read: GroundPatchRead, x0: number, z0: number, size: number, into?: Float64Array): HeightPatch | null => {\n const n = Math.round(size / GROUND_CELL)\n const cell = size / n\n const r = ringOf(cell)\n const lo = -2 * r\n const hi = 2 * n + 2 * r\n return read(x0 + (lo / 2) * cell, x0 + (hi / 2) * cell, z0 + (lo / 2) * cell, z0 + (hi / 2) * cell, into)\n}\n\n/** The cell of `latticePatchRead`'s ground (m): a terrain's usual one. */\nconst LATTICE_CELL = 0.1\n\n/**\n * A `GroundPatchRead` of any ground as a terrain would hold it: `ground` sampled at the vertices of a `LATTICE_CELL` lattice laid a metre and more around each rectangle asked,\n * the patch found with the terrain's own cell rule (`cellCoordinate`). For the warm job of a patch tile, which has no terrain: whatever the tile size and ring are, its patch\n * covers them, as a real one does.\n */\nexport const latticePatchRead = (ground: (x: number, z: number) => number): GroundPatchRead => (minX, maxX, minZ, maxZ, into) => {\n const originX = Math.floor(minX) - 1\n const originZ = Math.floor(minZ) - 1\n const columns = Math.ceil((maxX - originX) / LATTICE_CELL) + 2\n const rows = Math.ceil((maxZ - originZ) / LATTICE_CELL) + 2\n const column0 = cellCoordinate(minX, originX, columns, LATTICE_CELL) | 0\n const row0 = cellCoordinate(minZ, originZ, rows, LATTICE_CELL) | 0\n const width = (cellCoordinate(maxX, originX, columns, LATTICE_CELL) | 0) + 2 - column0\n const depth = (cellCoordinate(maxZ, originZ, rows, LATTICE_CELL) | 0) + 2 - row0\n const heights = into && into.length >= width * depth ? into : new Float64Array(width * depth)\n for (let j = 0; j < depth; j++) for (let i = 0; i < width; i++) heights[j * width + i] = ground(originX + (column0 + i) * LATTICE_CELL, originZ + (row0 + j) * LATTICE_CELL)\n return { cellSize: LATTICE_CELL, originX, originZ, columns, rows, column0, row0, width, depth, heights }\n}\n\nconst NO_GROUND = (): number => {\n throw new Error('engine-ground-job: a patch job reads its patch only')\n}\n// the patch the grid below reads, and the samples and band a patch job is made into, kept between jobs (one at a time) so a job makes no arrays for them\nlet gridPatch: HeightPatch | null = null\nconst patchGrid: GroundGrid = (xs, zs, out) => heightPatchGrid(gridPatch as HeightPatch, xs, zs, out)\nlet patchSamples = new Float64Array(0)\nlet patchBand = new Float64Array(0)\n\n/** The samples and band of a patch job, read from its patch through the same lattices `readGround` and `readGroundBand` read the terrain at (module scratch: not reentrant). */\nconst groundOfPatch = (job: GroundTileJob, patch: HeightPatch): { samples: Float64Array; band: Float64Array } => {\n const count = sampleCount(Math.round(job.size / GROUND_CELL))\n if (patchSamples.length !== count) patchSamples = new Float64Array(count)\n if (patchBand.length !== bandLength(job.size)) patchBand = new Float64Array(bandLength(job.size))\n gridPatch = patch\n readGround(NO_GROUND, patchSamples, job.x0, job.z0, job.size, undefined, patchGrid)\n readGroundBand(NO_GROUND, patchBand, job.x0, job.z0, job.size, patchGrid)\n gridPatch = null\n return { samples: patchSamples, band: patchBand }\n}\n\n/**\n * The tile a job makes: `shapeGround` of its samples and, under a height field, its solid over the band (both made from its patch first, in a patch job). Pure of the job.\n * Not reentrant: a patch job's samples and band, and `readGround`'s lattice, are module scratch (one job at a time per thread, as a worker and the schedule run them).\n */\nexport const computeGroundTile = (job: GroundTileJob): GroundTileResult => {\n const { samples, band } = job.patch ? groundOfPatch(job, job.patch) : job\n const t = shapeGround(samples, job.x0, job.z0, job.size, null, job.wasCoarse)\n const solid = t.level === null ? buildSolidVolume(t.heights, t.cells, job.x0, job.z0, job.size / t.cells, band, t.cells / t.collisionCells) : NO_SOLID\n return {\n id: job.id, cells: t.cells, collisionCells: t.collisionCells, level: t.level, heights: t.heights, collision: t.collision,\n boxes: Float64Array.from(t.boxes), solid: Float64Array.from(solid.boxes), ring: Float64Array.from(solid.ring), samples: job.samples, band: job.band,\n ...(job.patch ? { patch: job.patch.heights } : {}),\n }\n}\n\n/** Each buffer of the arrays once, none empty (an empty one may be shared, and a buffer transferred twice throws). */\nconst buffersOf = (arrays: ReadonlyArray<Float32Array | Float64Array | undefined>): ArrayBuffer[] => {\n const out: ArrayBuffer[] = []\n for (const array of arrays) {\n const buffer = array?.buffer as ArrayBuffer | undefined\n if (buffer && buffer.byteLength > 0 && !out.includes(buffer)) out.push(buffer)\n }\n return out\n}\n\n/** The buffers a result hands over, each once and none empty (a height field may be its own collision field). */\nexport const transferOf = (r: GroundTileResult): ArrayBuffer[] => buffersOf([r.heights, r.collision, r.boxes, r.solid, r.ring, r.samples, r.band, r.patch])\n\n/** The buffers a job hands over: its samples and band, or its patch. */\nexport const jobTransferOf = (job: GroundTileJob): ArrayBuffer[] => buffersOf([job.samples, job.band, job.patch?.heights])\n\n/** The tile a result stands for, over the samples the main thread keeps for the tile (none for a patch tile, which keeps its patch instead). */\nexport const tileOfResult = (r: GroundTileResult, samples: Float64Array | null, patch?: HeightPatch): GroundTile => ({\n heights: r.heights, cells: r.cells, collision: r.collision, collisionCells: r.collisionCells, boxes: r.boxes,\n solid: r.level === null ? { boxes: r.solid, ring: r.ring } : NO_SOLID, level: r.level, samples, ...(patch ? { patch } : {}),\n})\n","import { isWorkerInputLost } from '@adatechnology/game-contracts'\nimport type { WorkerCoordinator } from '@adatechnology/game-contracts'\nimport type { WorkerLike, WorkerScopeLike } from '@adatechnology/game-shapes'\n\nimport { computeGroundTile, jobTransferOf, transferOf } from './engine-ground-job'\nimport type { GroundTileJob, GroundTileResult } from './engine-ground-job'\nimport { groundTilesKind } from './worker-kinds'\n\n/**\n * Where the engine's ground tiles are made (`RendererOptions.groundWorker`): the main thread posts a job (`GroundTileJob`, plain arrays, transferred) and takes the tile back\n * when it comes. The engine applies a tile exactly `groundWorkerFrames` updates after it asked for it, from the answer if it came, else made on the main thread from the same\n * job: the answer is the same bits either way, so when it comes changes nothing but where the work ran (`GroundSchedule`).\n *\n * - `transfer`: the game's worker coordinator (`createCoordinatorGroundPort`, the `destruction.ground-tiles` kind, CLAUDE.md §14), or a\n * worker of the host's (`createWorkerGroundPort`, over game-shapes' `WorkerLike`); the answer comes whenever its event loop delivers it.\n * - `inline`: this thread, at once when posted (`createInlineGroundPort`): tests, Node.\n * - `none`: never answers and nothing is posted (`createMainThreadGroundPort`): every tile made on the main thread at its frame, the reference the other two match.\n */\nexport interface GroundWorkerPort {\n /** May turn `none` later (a worker that failed): read it at each job. */\n readonly transport: 'transfer' | 'inline' | 'none'\n /** Takes the job's arrays (they may be transferred: not to be read after). */\n postTile(job: GroundTileJob): void\n /** The one handler the answers go to. */\n onTile(handler: (result: GroundTileResult) => void): void\n /** Stops the worker, if any; no answer comes after. */\n dispose(): void\n}\n\n/** The one handler of a port: a port serves one engine, so a second one is an error (it would take the answers of the first). */\nconst oneHandler = (): { set(h: (result: GroundTileResult) => void): void; get(): ((result: GroundTileResult) => void) | null; drop(): void } => {\n let handler: ((result: GroundTileResult) => void) | null = null\n return {\n set: (h) => {\n if (handler) throw new Error('GroundWorkerPort: onTile set twice (a port serves one engine)')\n handler = h\n },\n get: () => handler,\n drop: () => {\n handler = null\n },\n }\n}\n\nexport const createInlineGroundPort = (): GroundWorkerPort => {\n const handler = oneHandler()\n return {\n transport: 'inline',\n postTile: (job) => handler.get()?.(computeGroundTile(job)),\n onTile: handler.set,\n dispose: handler.drop,\n }\n}\n\nexport const createMainThreadGroundPort = (): GroundWorkerPort => {\n const handler = oneHandler()\n return { transport: 'none', postTile: () => undefined, onTile: handler.set, dispose: handler.drop }\n}\n\n/**\n * A worker running `installGroundWorker` (the package's `ground-worker` entry): jobs and answers cross with their buffers transferred; `dispose` terminates it. A worker that\n * fails (`onerror`: its script did not load, it threw) is posted nothing more: the port turns `none` and every tile is made on the main thread at its update, as it would have\n * been anyway (game-shapes' pool fails its jobs the same way).\n */\nexport const createWorkerGroundPort = (worker: WorkerLike): GroundWorkerPort => {\n const handler = oneHandler()\n let failed = false\n worker.onmessage = (event) => handler.get()?.(event.data as GroundTileResult)\n worker.onerror = () => {\n failed = true\n }\n return {\n get transport() {\n return failed ? 'none' : 'transfer'\n },\n postTile: (job) => {\n if (!failed) worker.postMessage(job, jobTransferOf(job))\n },\n onTile: handler.set,\n dispose: () => {\n handler.drop()\n worker.onmessage = null\n worker.onerror = null\n worker.terminate()\n },\n }\n}\n\n/**\n * The tiles through the game's worker coordinator (CLAUDE.md §14): each job is a `destruction.ground-tiles` task the coordinator hands to a\n * worker, awaited (the engine's `GroundSchedule` applies the tile at its update, from the answer if it came, else made here from the same\n * job). A coordinator with no workers is posted nothing (`none`): every tile is made at its update, with no job run twice. The coordinator\n * is the game's: `dispose` lets go of the answers, not of the workers. The job's arrays are transferred (the kind's `transferAwaitedInput`):\n * `GroundSchedule` posts copies from its pool and keeps its own for the fallback. A job lost with its worker (it died holding it) is made here at\n * its update and the next ones still go to the workers (the coordinator replaces a dying worker a few times, then lets it go: `none` when none\n * is left); any other rejection (a worker that cannot run the kind) and nothing more is posted.\n */\nexport const createCoordinatorGroundPort = (workers: WorkerCoordinator): GroundWorkerPort => {\n const handler = oneHandler()\n let disposed = false\n let failed = false\n return {\n get transport() {\n return failed || workers.stats().workers === 0 ? 'none' : 'transfer'\n },\n postTile: (job) => {\n if (disposed || failed || workers.stats().workers === 0) return\n workers.run(groundTilesKind, job).then(\n (result) => {\n if (!disposed) handler.get()?.(result)\n },\n // the tile is made here at its update; a job lost with its worker leaves the next ones to the workers, anything else posts nothing more\n (error: unknown) => {\n if (!isWorkerInputLost(error)) failed = true\n },\n )\n },\n onTile: handler.set,\n dispose: () => {\n disposed = true\n handler.drop()\n },\n }\n}\n\n/** The worker side: each job answered with its tile, every array transferred back (the job's own included, for the main thread's pool). */\nexport const installGroundWorker = (scope: WorkerScopeLike): void => {\n scope.onmessage = (event) => {\n const result = computeGroundTile(event.data as GroundTileJob)\n scope.postMessage(result, transferOf(result))\n }\n}\n","import type { WorkerScopeLike } from '@adatechnology/game-shapes'\n\nimport { installGroundWorker } from './engine-ground-port'\n\n// the worker script a host starts for `createWorkerGroundPort` (dist/ground-worker.js as a module, or dist/ground-worker.global.js as a classic or Blob worker): no three.js here\ninstallGroundWorker(globalThis as unknown as WorkerScopeLike)\n"],"mappings":";;;AMMO,MAAM,iBAAiB,CAAC,GAAW,QAAgB,OAAe,aAA6B,KAAK,IAAI,GAAG,KAAK,IAAI,QAAQ,OAAO,IAAI,UAAU,QAAQ,CAAC;AAG1J,MAAM,eAAe,CAAC,MAAc,KAAa,MAAsB,QAAQ,IAAI,KAAK,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