@adatechnology/game-urban 0.5.2 → 0.5.4

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":["../../src/networks/classes.ts","../../src/networks/codes.ts","../../src/networks/graph.ts","../../src/networks/rules.ts","../../src/networks/layout-rules.ts","../../src/networks/slots.ts","../../src/networks/geometry.ts","../../src/networks/validate-context.ts","../../src/networks/validate-aerial.ts","../../src/networks/validate-buried.ts","../../src/networks/frame.ts","../../src/networks/drop-rules.ts","../../src/networks/validate-drops.ts","../../src/networks/validate-load.ts","../../src/networks/validate-structure.ts","../../src/networks/validate.ts","../../src/pole-distribution.ts","../../src/networks/circuits.ts","../../src/networks/pole-tree.ts","../../src/networks/aerial.ts","../../src/networks/connections.ts","../../src/networks/pole-layout.ts","../../src/networks/reach.ts","../../src/networks/runs.ts","../../src/networks/buried.ts","../../src/networks/chain.ts","../../src/networks/interceptor.ts","../../src/networks/inverts.ts","../../src/networks/line-network.ts","../../src/networks/sewer.ts","../../src/networks/storm.ts","../../src/networks/telecom.ts","../../src/networks/water.ts","../../src/networks/generate.ts","../../src/lamps.ts","../../src/networks/lamps.ts","../../src/pole-hardware.ts"],"sourcesContent":["import type { UtilityNetwork } from '@adatechnology/game-contracts'\n\nimport type { AerialEdgeKind, NetworkClass, NetworkEdgeKind, NetworkKind, NetworkNodeKind } from './types'\n\n/** The network each edge belongs to. A service drop is low voltage: a lot is never linked to the medium voltage. */\nexport const EDGE_NETWORK: Readonly<Record<NetworkEdgeKind, NetworkKind>> = {\n mv_span: 'power_mv',\n lv_span: 'power_lv',\n service_drop: 'power_lv',\n light_feed: 'lighting',\n telecom_span: 'telecom',\n telecom_drop: 'telecom',\n sewer_main: 'sewer',\n sewer_lateral: 'sewer',\n storm_gallery: 'storm',\n storm_lateral: 'storm',\n storm_gutter: 'storm',\n water_main: 'water',\n water_service: 'water',\n}\n\n/** The class the rules read each edge by. */\nexport const EDGE_CLASS: Readonly<Record<NetworkEdgeKind, NetworkClass>> = {\n mv_span: 'power_mv',\n lv_span: 'power_lv',\n service_drop: 'service_drop',\n light_feed: 'street_light',\n telecom_span: 'telecom',\n telecom_drop: 'telecom',\n sewer_main: 'sewer',\n sewer_lateral: 'sewer',\n storm_gallery: 'storm',\n storm_lateral: 'storm',\n storm_gutter: 'storm',\n water_main: 'water',\n water_service: 'water',\n}\n\nconst AERIAL: ReadonlySet<NetworkEdgeKind> = new Set<AerialEdgeKind>(['mv_span', 'lv_span', 'telecom_span', 'service_drop', 'telecom_drop', 'light_feed'])\n\nexport function isAerialEdgeKind(kind: NetworkEdgeKind): kind is AerialEdgeKind {\n return AERIAL.has(kind)\n}\n\n/** The network of a street a lot connection links to: `power` takes the low voltage. */\nexport const CONNECTION_NETWORK: Readonly<Record<UtilityNetwork, NetworkKind>> = {\n power: 'power_lv',\n telecom: 'telecom',\n sewer: 'sewer',\n storm: 'storm',\n water: 'water',\n}\n\n/** Supply networks flow from their sources to the loads; drain networks flow from the houses to their destinations. */\nexport const NETWORK_FLOW: Readonly<Record<NetworkKind, 'supply' | 'drain'>> = {\n power_mv: 'supply',\n power_lv: 'supply',\n lighting: 'supply',\n telecom: 'supply',\n water: 'supply',\n sewer: 'drain',\n storm: 'drain',\n}\n\n/**\n * The nodes a network starts from (supply) or ends at (drain). The low voltage starts at the transformers the medium voltage reaches,\n * and the lighting at the low voltage nodes, so these two are resolved by the graph.\n */\nexport const NETWORK_ENDS: Readonly<Record<NetworkKind, readonly NetworkNodeKind[]>> = {\n power_mv: ['feed'],\n power_lv: ['transformer'],\n lighting: [],\n telecom: ['feed'],\n water: ['reservoir'],\n sewer: ['treatment', 'outfall'],\n storm: ['outfall'],\n}\n","/** Stable codes of what `validateNetworks` finds wrong, as the `STRUCTURAL_VIOLATION` of game-floorplan-structure. */\nexport const NETWORK_VIOLATION = {\n DUPLICATE_ID: 'duplicate_id',\n UNKNOWN_NODE: 'unknown_node',\n NOT_CARRIED: 'not_carried',\n NOT_RADIAL: 'not_radial',\n DISCONNECTED: 'disconnected',\n LOOP_AT_END: 'loop_at_end',\n CONNECTION_IN_PLAN_FRAME: 'connection_in_plan_frame',\n LOT_UNCONNECTED: 'lot_unconnected',\n LOT_CONNECTED_TWICE: 'lot_connected_twice',\n LOT_DECLARED_TWICE: 'lot_declared_twice',\n ORPHAN_CONNECTION: 'orphan_connection',\n CONNECTION_MOVED: 'connection_moved',\n DROP_TOO_LONG: 'drop_too_long',\n DROP_SKEWED: 'drop_skewed',\n DROP_OFF_FRONTAGE: 'drop_off_frontage',\n DROP_OVER_OTHER_LOT: 'drop_over_other_lot',\n POLE_TOO_MANY_DROPS: 'pole_too_many_drops',\n MISSING_SAG: 'missing_sag',\n CLEARANCE: 'clearance',\n MV_OVER_LOT: 'mv_over_lot',\n SPAN_OVER_BUILDING: 'span_over_building',\n SPAN_THROUGH_CROWN: 'span_through_crown',\n MISSING_INVERT: 'missing_invert',\n MISSING_DIAMETER: 'missing_diameter',\n SLOPE: 'slope',\n SLOPE_MISMATCH: 'slope_mismatch',\n COVER: 'cover',\n TOO_DEEP: 'too_deep',\n CROSSING_TOO_CLOSE: 'crossing_too_close',\n CROSSING_ORDER: 'crossing_order',\n LATERAL_TOO_DEEP: 'lateral_too_deep',\n MANHOLE_SPACING: 'manhole_spacing',\n UNKNOWN_TRANSFORMER: 'unknown_transformer',\n TRANSFORMER_OVERLOADED: 'transformer_overloaded',\n LV_CIRCUIT_TOO_LONG: 'lv_circuit_too_long',\n} as const\n\nexport type NetworkViolationCode = (typeof NETWORK_VIOLATION)[keyof typeof NETWORK_VIOLATION]\n\n/** One finding: the id of the node, edge or lot, and the number against its limit when there is one. */\nexport type NetworkViolation = {\n readonly code: NetworkViolationCode\n readonly id: string\n readonly detail?: string\n readonly value?: number\n readonly limit?: number\n}\n","import { EDGE_NETWORK, NETWORK_ENDS, NETWORK_FLOW } from './classes'\nimport type { NetworkEdge, NetworkKind, NetworkNode } from './types'\n\n/** The networks indexed: nodes and edges by id, and the edges in and out of each node. Edges whose ends are missing are kept but link nothing. */\nexport type NetworkGraph = {\n readonly nodes: ReadonlyMap<string, NetworkNode>\n readonly edges: ReadonlyMap<string, NetworkEdge>\n /** Edges leaving a node, of one network or all. */\n outgoing(nodeId: string, network?: NetworkKind): readonly NetworkEdge[]\n /** Edges reaching a node, of one network or all. */\n incoming(nodeId: string, network?: NetworkKind): readonly NetworkEdge[]\n}\n\nconst NONE: readonly NetworkEdge[] = []\n\nconst ofNetwork = (edges: readonly NetworkEdge[] | undefined, network: NetworkKind | undefined): readonly NetworkEdge[] => {\n if (edges === undefined) return NONE\n return network === undefined ? edges : edges.filter((edge) => EDGE_NETWORK[edge.kind] === network)\n}\n\n/** Indexes nodes and edges. The first of two entries with the same id wins (the validator reports the second). */\nexport function buildNetworkGraph(input: { readonly nodes: readonly NetworkNode[]; readonly edges: readonly NetworkEdge[] }): NetworkGraph {\n const nodes = new Map<string, NetworkNode>()\n for (const node of input.nodes) if (!nodes.has(node.id)) nodes.set(node.id, node)\n const edges = new Map<string, NetworkEdge>()\n const out = new Map<string, NetworkEdge[]>()\n const into = new Map<string, NetworkEdge[]>()\n for (const edge of input.edges) {\n if (edges.has(edge.id)) continue\n edges.set(edge.id, edge)\n if (!nodes.has(edge.from) || !nodes.has(edge.to)) continue\n out.set(edge.from, [...(out.get(edge.from) ?? []), edge])\n into.set(edge.to, [...(into.get(edge.to) ?? []), edge])\n }\n return {\n nodes,\n edges,\n outgoing: (nodeId, network) => ofNetwork(out.get(nodeId), network),\n incoming: (nodeId, network) => ofNetwork(into.get(nodeId), network),\n }\n}\n\nfunction sourcesOf(graph: NetworkGraph, network: NetworkKind): string[] {\n if (network === 'lighting') return [...connectedNodes(graph, 'power_lv')]\n const kinds = NETWORK_ENDS[network]\n const ends = [...graph.nodes.values()].filter((node) => kinds.includes(node.kind) && node.carries.includes(network)).map((node) => node.id)\n if (network !== 'power_lv') return ends\n const medium = connectedNodes(graph, 'power_mv')\n return ends.filter((id) => medium.has(id))\n}\n\n/**\n * The nodes linked to their source by the edges of `network`: walked from the sources along the flow (supply), or back from the\n * destinations against it (drain). The low voltage starts only at transformers the medium voltage reaches.\n */\nexport function connectedNodes(graph: NetworkGraph, network: NetworkKind): ReadonlySet<string> {\n const reached = new Set<string>()\n const pending = sourcesOf(graph, network)\n const forward = NETWORK_FLOW[network] === 'supply'\n while (pending.length > 0) {\n const id = pending.pop() as string\n if (reached.has(id)) continue\n reached.add(id)\n const next = forward ? graph.outgoing(id, network).map((edge) => edge.to) : graph.incoming(id, network).map((edge) => edge.from)\n for (const nextId of next) if (!reached.has(nextId)) pending.push(nextId)\n }\n return reached\n}\n\n/** Horizontal length of an edge, metres (0 when an end is missing). */\nexport function edgeLength(graph: NetworkGraph, edge: NetworkEdge): number {\n const from = graph.nodes.get(edge.from)\n const to = graph.nodes.get(edge.to)\n if (from === undefined || to === undefined) return 0\n return Math.hypot(to.at[0] - from.at[0], to.at[2] - from.at[2])\n}\n\n/** The low voltage nodes a transformer feeds, with the length of line (low voltage spans; a service drop adds none) from it to each one. */\nexport function circuitOf(graph: NetworkGraph, transformerId: string): ReadonlyMap<string, number> {\n const distance = new Map<string, number>([[transformerId, 0]])\n const pending = [transformerId]\n while (pending.length > 0) {\n const id = pending.pop() as string\n const base = distance.get(id) ?? 0\n for (const edge of graph.outgoing(id, 'power_lv')) {\n if (distance.has(edge.to)) continue\n distance.set(edge.to, base + (edge.kind === 'lv_span' ? edgeLength(graph, edge) : 0))\n pending.push(edge.to)\n }\n }\n return distance\n}\n","import { deepMerge } from '@adatechnology/game-contracts'\nimport type { DeepPartial } from '@adatechnology/game-contracts'\n\nimport { DEFAULT_NETWORK_LAYOUT } from './layout-rules'\nimport type { NetworkLayoutRules } from './layout-rules'\nimport type { AerialClass, BuriedEdgeKind, NetworkSurface } from './types'\n\n/** Lowest point of a conductor over each surface, metres; `null` = the class does not go there. */\nexport type ClearanceRow = Readonly<Record<NetworkSurface, number | null>>\n\n/** A band of the diversified demand table: up to `consumers` consumers, kVA per consumer at or below the split and above it. */\nexport type DiversityBand = { readonly consumers: number; readonly low: number; readonly high: number }\n\nexport type TransformerRating = { readonly id: string; readonly kva: number }\n\nexport type PowerRules = {\n /** Longest service drop, metres (horizontal). */\n readonly dropMaxLength: number\n /** A drop that crosses the street goes straight across: its horizontal direction at most this far from the street's normal, degrees. */\n readonly dropMaxSkew: number\n /** A drop on the pole's own side comes from a pole in front of the lot: its station at most this far past the lot's frontage, metres. */\n readonly dropFrontageSlack: number\n /** Most service drops one pole holds. */\n readonly dropsPerPole: number\n /** Longest low voltage path from the transformer to its farthest node, each way, metres. */\n readonly lvCircuitMaxLength: number\n /** Highest demand over the rating. */\n readonly maxLoading: number\n readonly transformers: readonly TransformerRating[]\n /** Installed load (kVA) that splits the `low` and `high` columns of the demand table. */\n readonly installedSplitKva: number\n /** By number of consumers, ascending; the last band takes any number above. */\n readonly diversity: readonly DiversityBand[]\n}\n\n/** Cover of a pipe: from the ground down to its top, metres. */\nexport type CoverRange = { readonly min: number; readonly max?: number }\n\nexport type NetworkRules = {\n readonly clearance: Readonly<Record<AerialClass, ClearanceRow>>\n /** Samples along a span when the catenary is checked. */\n readonly catenarySamples: number\n readonly power: PowerRules\n readonly lighting: { readonly lampKva: number }\n readonly telecom: { readonly dropMaxLength: number }\n /** Least slope of each gravity pipe, m/m. */\n readonly minSlope: Readonly<Record<Extract<BuriedEdgeKind, 'sewer_main' | 'sewer_lateral' | 'storm_gallery' | 'storm_lateral' | 'storm_gutter'>, number>>\n readonly cover: Readonly<Record<BuriedEdgeKind, CoverRange>>\n readonly sewer: {\n /** Deepest invert below the ground before a pumping station is needed. */\n readonly maxDepth: number\n /** Cover of a sewer main under a street with a storm gallery (the main passes under the gallery's laterals). */\n readonly coverUnderGallery: number\n /** A storm gallery this close to a sewer main, metres in plan, puts the main under that street's rule. */\n readonly galleryReach: number\n /** Deepest bottom of a sewer lateral where it crosses a storm gallery (it goes over it). */\n readonly lateralOverGallery: number\n /** Longest sewer main between two manholes. */\n readonly manholeSpacing: number\n }\n /** Least vertical gap between two pipes that cross, and which one goes above (lower rank above). */\n readonly crossing: { readonly separation: number; readonly rank: Readonly<Record<BuriedEdgeKind, number>> }\n /** How far a connection node may sit from the point the lot declared, metres. */\n readonly connectionTolerance: number\n /** What `generateNetworks` lays out: spacing, offsets, sags, diameters (the validator reads none of it). */\n readonly layout: NetworkLayoutRules\n}\n\nconst LOW_VOLTAGE: ClearanceRow = { road: 5.5, sidewalk: 4.5, lot: 3.5 }\n\n/** Brazilian practice (NBR 15688, NBR 9649, NBR 12218 and the utilities' sharing rules), with no brand. Every number is patched by `resolveNetworkRules`. */\nexport const DEFAULT_NETWORK_RULES: NetworkRules = {\n clearance: {\n power_mv: { road: 7, sidewalk: 6, lot: null },\n power_lv: LOW_VOLTAGE,\n service_drop: LOW_VOLTAGE,\n street_light: LOW_VOLTAGE,\n telecom: { road: 5, sidewalk: 4.5, lot: 3 },\n },\n catenarySamples: 16,\n power: {\n dropMaxLength: 30,\n dropMaxSkew: 30,\n dropFrontageSlack: 0.5,\n dropsPerPole: 4,\n lvCircuitMaxLength: 200,\n maxLoading: 0.8,\n transformers: [\n { id: 't30', kva: 30 },\n { id: 't45', kva: 45 },\n { id: 't75', kva: 75 },\n { id: 't112', kva: 112.5 },\n ],\n installedSplitKva: 5,\n diversity: [\n { consumers: 5, low: 2, high: 3 },\n { consumers: 15, low: 1.5, high: 2.4 },\n { consumers: 30, low: 1.2, high: 2 },\n { consumers: 60, low: 1, high: 1.7 },\n { consumers: Number.POSITIVE_INFINITY, low: 0.9, high: 1.5 },\n ],\n },\n lighting: { lampKva: 0.15 },\n telecom: { dropMaxLength: 30 },\n minSlope: { sewer_main: 0.005, sewer_lateral: 0.01, storm_gallery: 0.005, storm_lateral: 0.005, storm_gutter: 0.005 },\n cover: {\n water_main: { min: 0.6, max: 0.8 },\n water_service: { min: 0.6, max: 0.8 },\n // the design sets no least cover for the lateral, only that it is buried and passes over a gallery (`sewer.lateralOverGallery`)\n sewer_lateral: { min: 0 },\n storm_lateral: { min: 1, max: 1.2 },\n storm_gallery: { min: 1.2 },\n // the gutter is an open channel at the kerb (diameter 0): its bottom only has to stay at or under the ground\n storm_gutter: { min: 0 },\n sewer_main: { min: 0.9 },\n },\n sewer: { maxDepth: 4.5, coverUnderGallery: 1.8, galleryReach: 3, lateralOverGallery: 0.85, manholeSpacing: 80 },\n crossing: { separation: 0.2, rank: { storm_gutter: 0, water_main: 1, water_service: 1, sewer_lateral: 2, storm_lateral: 3, storm_gallery: 3, sewer_main: 4 } },\n connectionTolerance: 0.01,\n layout: DEFAULT_NETWORK_LAYOUT,\n}\n\n/** The default rules with a game's numbers over them (objects merge, arrays such as the transformers replace). */\nexport function resolveNetworkRules(patch?: DeepPartial<NetworkRules>): NetworkRules {\n return deepMerge(DEFAULT_NETWORK_RULES, patch)\n}\n\n/**\n * kVA of the circuit's consumers by the diversified demand table: the band of their count, the column of each one's installed load. A\n * consumer whose load is not known (a connection without `installedKva`, a lot linked without a meter) counts in the `low` column.\n */\nexport function diversifiedDemand(installedKva: readonly number[], rules: PowerRules): number {\n if (installedKva.length === 0) return 0\n const band = rules.diversity.find((entry) => installedKva.length <= entry.consumers) ?? rules.diversity[rules.diversity.length - 1]\n if (band === undefined) return 0\n return installedKva.reduce((sum, installed) => sum + (installed <= rules.installedSplitKva ? band.low : band.high), 0)\n}\n\n/** The smallest rating whose loading stays within `maxLoading` for this demand, or none. */\nexport function pickTransformer(demandKva: number, rules: PowerRules): TransformerRating | undefined {\n return [...rules.transformers].sort((a, b) => a.kva - b.kva).find((rating) => demandKva <= rating.kva * rules.maxLoading)\n}\n","/** Where a lot takes each network when it declares none (a building of `fillBlock`, a lot whose house has no utilities yet), metres. */\nexport type DefaultConnectionRules = {\n /** The meter post, the water stand and the sewer box stand this far inside the lot's front. */\n readonly frontInset: number\n /** The inspection box stands this far inside the lot's front. */\n readonly sewerInset: number\n /** From the lot's side boundary to the meter post (power and telecom), and to the water stand. */\n readonly meterFromSide: number\n readonly waterFromSide: number\n /** The downspout outlet at the kerb this far from the lot's other side boundary. */\n readonly downspoutFromSide: number\n /** Anchor of the service drop on the meter post over the ground, and of the telecom drop under it. */\n readonly powerHeight: number\n readonly telecomBelowPower: number\n /** Invert of the inspection box outlet under the ground; a lot set back from its street gets a shallower one, never under the least. */\n readonly sewerDepth: number\n readonly sewerLeastDepth: number\n}\n\n/** How the generator lays the networks out: the numbers of a street, not checked by the validator but by the generator's own tests. */\nexport type NetworkLayoutRules = {\n /** Width of the sidewalk on each side of a street. */\n readonly sidewalk: number\n /** A run end this close to the map border is where the line leaves the map (a feed, a reservoir). */\n readonly edgeReach: number\n readonly poles: {\n /** Least and longest span between two poles. */\n readonly spacing: readonly [number, number]\n /** The pole's axis from the kerb, on the service strip; the corner pole as far from the cross street's kerb. */\n readonly curbSetback: number\n /** An end-of-line pole this far inside the end of its run. */\n readonly endInset: number\n /** No two poles closer than this (a pole added to reach a lot keeps it). */\n readonly minGap: number\n /** An intermediate pole at least this far from the edge of a cross street's roadway. */\n readonly crossingClearance: number\n /** A pole looks this far either way (in steps) for a lot boundary near its target, and slides as far to clear a gate. */\n readonly snap: number\n readonly slide: number\n readonly slideStep: number\n }\n /** Sag at mid span of each class, metres. */\n readonly sag: { readonly mv: number; readonly lv: number; readonly telecom: number; readonly drop: number; readonly telecomDrop: number }\n readonly telecom: {\n /** A splice box with its reserve coil every this many spans. */\n readonly spliceEvery: number\n /** Gap between two cables of a bundle, from the top of the band down. */\n readonly cableGap: number\n /** Cables of a bundle, least and most, in a clean district and in the periphery. */\n readonly cables: { readonly clean: readonly [number, number]; readonly periphery: readonly [number, number] }\n }\n /** The periphery: district kinds with telecom bundles and a few illegal hookups (a drop with no meter, counted in its transformer's load). */\n readonly periphery: { readonly kinds: readonly string[]; readonly hookupShare: number }\n /** Added to every least slope and least cover the generator lays, so a pipe never sits on the limit. */\n readonly slopeMargin: number\n readonly coverMargin: number\n readonly sewer: {\n readonly mainDiameter: number\n readonly lateralDiameter: number\n /** The lateral drops into the main from a cleanout this far from the street's axis. */\n readonly dropOffset: number\n /** The interceptor runs along the river this far from its bank. */\n readonly interceptorOffset: number\n }\n readonly storm: {\n /** The gallery runs this far from the street's axis, on the side of the poles. */\n readonly galleryOffset: number\n readonly galleryDiameter: number\n readonly lateralDiameter: number\n /** Longest gap between two inlets along a kerb; one at each corner. */\n readonly inletSpacing: number\n /** An inlet's grate this far from the kerb into the road, and the corner inlet this far from the end of its kerb. */\n readonly inletSetback: number\n readonly inletFromCorner: number\n /** Level of the river's water: an outfall's bottom stays above it. */\n readonly riverLevel: number\n }\n readonly water: {\n readonly mainDiameter: number\n readonly serviceDiameter: number\n /** The main runs under the sidewalk opposite the poles, this share of its width out from the kerb. */\n readonly sidewalkShare: number\n /** A hydrant stands this far from the valve of a crossing, toward the kerb. */\n readonly hydrantOffset: number\n }\n readonly connection: DefaultConnectionRules\n}\n\n/** The defaults of a Brazilian street: 30 to 40 m spans, MV bare on the crossarm, LV multiplexed, sewer to an interceptor along the river. */\nexport const DEFAULT_NETWORK_LAYOUT: NetworkLayoutRules = {\n sidewalk: 2.5,\n edgeReach: 5,\n poles: { spacing: [30, 40], curbSetback: 0.4, endInset: 1, minGap: 3, crossingClearance: 5, snap: 5, slide: 6, slideStep: 0.25 },\n sag: { mv: 0.5, lv: 0.6, telecom: 0.6, drop: 0.2, telecomDrop: 0.15 },\n telecom: { spliceEvery: 4, cableGap: 0.1, cables: { clean: [1, 2], periphery: [3, 5] } },\n periphery: { kinds: ['residential_popular'], hookupShare: 0.1 },\n slopeMargin: 0.0005,\n coverMargin: 0.05,\n sewer: { mainDiameter: 0.15, lateralDiameter: 0.1, dropOffset: 1, interceptorOffset: 2 },\n storm: { galleryOffset: 2, galleryDiameter: 0.6, lateralDiameter: 0.4, inletSpacing: 60, inletSetback: 0.3, inletFromCorner: 1, riverLevel: -4 },\n water: { mainDiameter: 0.075, serviceDiameter: 0.02, sidewalkShare: 1 / 3, hydrantOffset: 0.6 },\n connection: { frontInset: 0.3, sewerInset: 1, meterFromSide: 1, waterFromSide: 1.6, downspoutFromSide: 1, powerHeight: 5.7, telecomBelowPower: 0.6, sewerDepth: 0.6, sewerLeastDepth: 0.3 },\n}\n","import type { PoleDef, PoleSlotBand, PoleSlots } from '../pole-specs'\n\n/** The bands from the top of the pole down. */\nexport const POLE_SLOT_ORDER: readonly PoleSlotBand[] = ['mv', 'transformer', 'lv', 'lighting', 'telecom']\n\n/**\n * Least free gap between the top of a band and the bottom of the band above it, metres: the transformer drum 0.3 m under the crossarm,\n * the first telecom cable 0.4 m under the lamp. A band never enters the one above (gap 0 at least).\n */\nexport const POLE_SLOT_GAPS: Readonly<Record<Exclude<PoleSlotBand, 'mv'>, number>> = { transformer: 0.3, lv: 0, lighting: 0, telecom: 0.4 }\n\n/** The 11 m double-T concrete pole, 1.7 m buried (9.3 m above the ground), with the bands of Brazilian distribution practice. */\nexport const DEFAULT_POLE_SLOTS: PoleSlots = {\n height: 11,\n embedment: 1.7,\n bands: { mv: [9, 9.25], transformer: [7.7, 8.7], lv: [7.1, 7.4], lighting: [6.5, 6.8], telecom: [5.7, 6.1] },\n}\n\nexport type PoleSlotViolation = {\n readonly code: 'slot_out_of_pole' | 'slot_inverted' | 'slot_order'\n readonly band: PoleSlotBand\n readonly value: number\n readonly limit: number\n}\n\n/** Every band inside the pole above the ground, bottom under top, in order and apart by the least gaps. */\nexport function checkPoleSlots(slots: PoleSlots, gaps: Readonly<Record<Exclude<PoleSlotBand, 'mv'>, number>> = POLE_SLOT_GAPS): PoleSlotViolation[] {\n const violations: PoleSlotViolation[] = []\n const above = slots.height - slots.embedment\n for (const band of POLE_SLOT_ORDER) {\n const [bottom, top] = slots.bands[band]\n if (bottom > top) violations.push({ code: 'slot_inverted', band, value: bottom, limit: top })\n if (bottom < 0) violations.push({ code: 'slot_out_of_pole', band, value: bottom, limit: 0 })\n if (top > above) violations.push({ code: 'slot_out_of_pole', band, value: top, limit: above })\n }\n for (let index = 1; index < POLE_SLOT_ORDER.length; index++) {\n const band = POLE_SLOT_ORDER[index] as Exclude<PoleSlotBand, 'mv'>\n const upper = POLE_SLOT_ORDER[index - 1] as PoleSlotBand\n const gap = slots.bands[upper][0] - slots.bands[band][1]\n if (gap < gaps[band]) violations.push({ code: 'slot_order', band, value: gap, limit: gaps[band] })\n }\n return violations\n}\n\nconst isPoleSlots = (value: unknown): value is PoleSlots =>\n typeof value === 'object' && value !== null && 'bands' in value && 'height' in value && 'embedment' in value\n\n/** The slots a pole of the registry declares (a distribution pole), or none. */\nexport function slotsOfPole(pole: PoleDef): PoleSlots | undefined {\n const slots: unknown = 'slots' in pole.spec ? pole.spec.slots : undefined\n return isPoleSlots(slots) ? slots : undefined\n}\n","/** A point on the ground plane: world x, z. */\nexport type PlanPoint = readonly [number, number]\n\n/**\n * Where two segments cross in plan, as the share along each (`[t, u]`, both strictly inside 0..1), or nothing when they do not cross\n * or only touch at an end.\n */\nexport function segmentCrossing(a0: PlanPoint, a1: PlanPoint, b0: PlanPoint, b1: PlanPoint): readonly [number, number] | undefined {\n const rx = a1[0] - a0[0]\n const rz = a1[1] - a0[1]\n const sx = b1[0] - b0[0]\n const sz = b1[1] - b0[1]\n const denominator = rx * sz - rz * sx\n if (Math.abs(denominator) < 1e-12) return undefined\n const qx = b0[0] - a0[0]\n const qz = b0[1] - a0[1]\n const t = (qx * sz - qz * sx) / denominator\n const u = (qx * rz - qz * rx) / denominator\n const inside = (value: number): boolean => value > 1e-9 && value < 1 - 1e-9\n return inside(t) && inside(u) ? [t, u] : undefined\n}\n\n/** Point inside a polygon (even-odd rule). */\nexport function pointInPolygon(point: PlanPoint, outline: readonly PlanPoint[]): boolean {\n let inside = false\n for (let index = 0, previous = outline.length - 1; index < outline.length; previous = index++) {\n const a = outline[index] as PlanPoint\n const b = outline[previous] as PlanPoint\n if (a[1] > point[1] !== b[1] > point[1] && point[0] < ((b[0] - a[0]) * (point[1] - a[1])) / (b[1] - a[1]) + a[0]) inside = !inside\n }\n return inside\n}\n\n/** A segment enters a polygon: an end inside it or a crossing with one of its sides. */\nexport function segmentEntersPolygon(a: PlanPoint, b: PlanPoint, outline: readonly PlanPoint[]): boolean {\n if (outline.length < 3) return false\n if (pointInPolygon(a, outline) || pointInPolygon(b, outline)) return true\n for (let index = 0, previous = outline.length - 1; index < outline.length; previous = index++) {\n if (segmentCrossing(a, b, outline[previous] as PlanPoint, outline[index] as PlanPoint) !== undefined) return true\n }\n return false\n}\n\n/** Share along a segment of the point nearest to `point`, clamped to 0..1. */\nexport function nearestShare(a: PlanPoint, b: PlanPoint, point: PlanPoint): number {\n const dx = b[0] - a[0]\n const dz = b[1] - a[1]\n const length = dx * dx + dz * dz\n if (length === 0) return 0\n return Math.min(1, Math.max(0, ((point[0] - a[0]) * dx + (point[1] - a[1]) * dz) / length))\n}\n\n/** Height of a hanging conductor at share `t` of its span: the chord less a parabola with `sag` at mid span. */\nexport function catenaryHeight(fromY: number, toY: number, sag: number, t: number): number {\n return fromY + (toY - fromY) * t - 4 * sag * t * (1 - t)\n}\n\n/** Shares along a segment where it crosses the sides of a polygon, ascending. */\nexport function polygonCrossings(a: PlanPoint, b: PlanPoint, outline: readonly PlanPoint[]): number[] {\n const shares: number[] = []\n for (let index = 0, previous = outline.length - 1; index < outline.length; previous = index++) {\n const crossing = segmentCrossing(a, b, outline[previous] as PlanPoint, outline[index] as PlanPoint)\n if (crossing !== undefined) shares.push(crossing[0])\n }\n return shares.sort((first, second) => first - second)\n}\n\n/** The range of shares along a segment that lies inside a circle, or none. */\nexport function circleShares(a: PlanPoint, b: PlanPoint, centre: PlanPoint, radius: number): readonly [number, number] | undefined {\n const dx = b[0] - a[0]\n const dz = b[1] - a[1]\n const fx = a[0] - centre[0]\n const fz = a[1] - centre[1]\n const qa = dx * dx + dz * dz\n const qb = 2 * (fx * dx + fz * dz)\n const qc = fx * fx + fz * fz - radius * radius\n if (qa === 0) return qc <= 0 ? [0, 1] : undefined\n const discriminant = qb * qb - 4 * qa * qc\n if (discriminant < 0) return undefined\n const root = Math.sqrt(discriminant)\n const start = Math.max(0, (-qb - root) / (2 * qa))\n const end = Math.min(1, (-qb + root) / (2 * qa))\n return start <= end ? [start, end] : undefined\n}\n","import type { UtilityConnection } from '@adatechnology/game-contracts'\n\nimport type { NetworkViolation } from './codes'\nimport type { LotFrontage } from './drop-rules'\nimport type { NetworkGraph } from './graph'\nimport type { NetworkRules } from './rules'\nimport type { NetworkBuilding, NetworkCrown, NetworkEdge, NetworkNode, NetworkSurface } from './types'\n\n/** What the validator reads besides the networks: the lots' connections, the buildings and trees in the way, the ground. */\nexport type ValidateNetworksOptions = {\n /** Every connection a lot declared; each must be linked once, in `frame: 'world'`. */\n readonly connections?: readonly UtilityConnection[]\n /** Outlines no span may cross (a drop may end over the building of its own lot). */\n readonly buildings?: readonly NetworkBuilding[]\n /** Tree crowns no span may go through (from the scene's plant provider). */\n readonly obstacles?: { readonly crowns?: readonly NetworkCrown[] }\n /** What lies under a point of a span. Default: road everywhere (the strictest clearance a conductor may have). A point with no surface is not checked. */\n readonly surfaceAt?: (x: number, z: number) => NetworkSurface | undefined\n /** Ground level at a point. Default: 0 under a span; along a pipe, the cover levels of its two nodes. */\n readonly groundAt?: (x: number, z: number) => number\n /** The lots' fronts on their streets (`GeneratedNetworks.frontages`): with them the drops are held to the street's practice. */\n readonly frontages?: readonly LotFrontage[]\n}\n\nexport type ValidationContext = {\n readonly graph: NetworkGraph\n readonly rules: NetworkRules\n readonly options: ValidateNetworksOptions\n readonly report: (violation: NetworkViolation) => void\n}\n\n/** The ends of an edge whose nodes both exist, or nothing. */\nexport function edgeEnds(context: ValidationContext, edge: NetworkEdge): readonly [NetworkNode, NetworkNode] | undefined {\n const from = context.graph.nodes.get(edge.from)\n const to = context.graph.nodes.get(edge.to)\n return from === undefined || to === undefined ? undefined : [from, to]\n}\n","import { EDGE_CLASS, isAerialEdgeKind } from './classes'\nimport { NETWORK_VIOLATION } from './codes'\nimport { catenaryHeight, circleShares, pointInPolygon, polygonCrossings, segmentEntersPolygon } from './geometry'\nimport type { PlanPoint } from './geometry'\nimport { edgeLength } from './graph'\nimport type { AerialClass, NetworkBuilding, NetworkEdge, NetworkNode } from './types'\nimport { edgeEnds } from './validate-context'\nimport type { ValidationContext } from './validate-context'\n\ntype Span = { readonly edge: NetworkEdge; readonly from: NetworkNode; readonly to: NetworkNode; readonly sag: number; readonly heights: readonly [number, number] }\n\nconst planOf = (node: NetworkNode): PlanPoint => [node.at[0], node.at[2]]\n\nfunction validateDrop(context: ValidationContext, edge: NetworkEdge): void {\n const limit = edge.kind === 'service_drop' ? context.rules.power.dropMaxLength : edge.kind === 'telecom_drop' ? context.rules.telecom.dropMaxLength : undefined\n if (limit === undefined) return\n const length = edgeLength(context.graph, edge)\n if (length > limit) context.report({ code: NETWORK_VIOLATION.DROP_TOO_LONG, id: edge.id, value: length, limit })\n}\n\n/** The lowest point of the conductor over each sampled surface against the clearance of its class. */\nfunction validateClearance(context: ValidationContext, span: Span): void {\n const row = context.rules.clearance[EDGE_CLASS[span.edge.kind] as AerialClass]\n const samples = Math.max(1, context.rules.catenarySamples)\n const lowest = new Map<'road' | 'sidewalk' | 'lot', number>()\n for (let index = 0; index <= samples; index++) {\n const t = index / samples\n const x = span.from.at[0] + (span.to.at[0] - span.from.at[0]) * t\n const z = span.from.at[2] + (span.to.at[2] - span.from.at[2]) * t\n const surface = context.options.surfaceAt === undefined ? 'road' : context.options.surfaceAt(x, z)\n if (surface === undefined) continue\n const height = catenaryHeight(span.heights[0], span.heights[1], span.sag, t) - (context.options.groundAt?.(x, z) ?? 0)\n lowest.set(surface, Math.min(lowest.get(surface) ?? Number.POSITIVE_INFINITY, height))\n }\n for (const [surface, height] of lowest) {\n const limit = row[surface]\n if (limit === null) context.report({ code: NETWORK_VIOLATION.MV_OVER_LOT, id: span.edge.id, detail: surface })\n else if (height < limit) context.report({ code: NETWORK_VIOLATION.CLEARANCE, id: span.edge.id, detail: surface, value: height, limit })\n }\n}\n\nconst pointAt = (span: Span, t: number): PlanPoint => [span.from.at[0] + (span.to.at[0] - span.from.at[0]) * t, span.from.at[2] + (span.to.at[2] - span.from.at[2]) * t]\n\n/** Lowest and highest conductor over the shares `[start, end]` of a span, sampled. */\nfunction heightRange(context: ValidationContext, span: Span, start: number, end: number): readonly [number, number] {\n const samples = Math.max(1, context.rules.catenarySamples)\n let low = Number.POSITIVE_INFINITY\n let high = Number.NEGATIVE_INFINITY\n for (let index = 0; index <= samples; index++) {\n const y = catenaryHeight(span.heights[0], span.heights[1], span.sag, start + ((end - start) * index) / samples)\n low = Math.min(low, y)\n high = Math.max(high, y)\n }\n return [low, high]\n}\n\n/** The part of a span over a building, as shares, or none: a drop to its own lot may end over the house, but not cross the whole body. */\nfunction overBuilding(span: Span, building: NetworkBuilding): readonly [number, number] | undefined {\n const a = planOf(span.from)\n const b = planOf(span.to)\n const crossings = polygonCrossings(a, b, building.outline)\n const ownLot = span.to.kind === 'connection' && span.to.lot !== undefined && building.lot === span.to.lot\n if (ownLot) return crossings.length >= 2 ? [crossings[0] as number, crossings[crossings.length - 1] as number] : undefined\n if (!segmentEntersPolygon(a, b, building.outline)) return undefined\n const start = pointInPolygon(a, building.outline) ? 0 : (crossings[0] ?? 0)\n const end = pointInPolygon(b, building.outline) ? 1 : (crossings[crossings.length - 1] ?? 1)\n return [start, end]\n}\n\n/** No span passes over a building lower than its roof. */\nfunction validateBuildings(context: ValidationContext, span: Span): void {\n for (const building of context.options.buildings ?? []) {\n const over = overBuilding(span, building)\n if (over === undefined) continue\n const middle = pointAt(span, (over[0] + over[1]) / 2)\n const roof = (context.options.groundAt?.(middle[0], middle[1]) ?? 0) + building.height\n const [low] = heightRange(context, span, over[0], over[1])\n if (low < roof) context.report({ code: NETWORK_VIOLATION.SPAN_OVER_BUILDING, id: span.edge.id, detail: building.id, value: low, limit: roof })\n }\n}\n\n/** No span goes through a crown: the conductor over the part of the span inside the crown's radius stays out of `[bottom, top]`. */\nfunction validateCrowns(context: ValidationContext, span: Span): void {\n for (const crown of context.options.obstacles?.crowns ?? []) {\n const inside = circleShares(planOf(span.from), planOf(span.to), [crown.x, crown.z], crown.radius)\n if (inside === undefined) continue\n const [low, high] = heightRange(context, span, inside[0], inside[1])\n if (low <= crown.top && high >= crown.bottom) context.report({ code: NETWORK_VIOLATION.SPAN_THROUGH_CROWN, id: span.edge.id, detail: `${crown.x},${crown.z}` })\n }\n}\n\n/** Drops within reach; every span with its sag, its clearance by class over road, sidewalk and lot, clear of buildings and crowns. */\nexport function validateAerial(context: ValidationContext): void {\n for (const edge of context.graph.edges.values()) {\n if (!isAerialEdgeKind(edge.kind)) continue\n validateDrop(context, edge)\n const ends = edgeEnds(context, edge)\n if (ends === undefined) continue\n if (edge.sag === undefined) {\n context.report({ code: NETWORK_VIOLATION.MISSING_SAG, id: edge.id })\n continue\n }\n const span: Span = { edge, from: ends[0], to: ends[1], sag: edge.sag, heights: edge.heights ?? [ends[0].at[1], ends[1].at[1]] }\n validateClearance(context, span)\n validateBuildings(context, span)\n validateCrowns(context, span)\n }\n}\n","import { isAerialEdgeKind } from './classes'\nimport { NETWORK_VIOLATION } from './codes'\nimport { nearestShare, segmentCrossing } from './geometry'\nimport type { PlanPoint } from './geometry'\nimport { edgeLength } from './graph'\nimport type { BuriedEdgeKind, NetworkEdge, NetworkNode } from './types'\nimport { edgeEnds } from './validate-context'\nimport type { ValidationContext } from './validate-context'\n\n/** A pipe with everything the rules read: its ends, the inverts at each end and its diameter. */\ntype Pipe = { readonly edge: NetworkEdge; readonly kind: BuriedEdgeKind; readonly from: NetworkNode; readonly to: NetworkNode; readonly inverts: readonly [number, number]; readonly diameter: number }\n\nconst SLOPE_TOLERANCE = 1e-3\n\nconst lerp = (a: number, b: number, t: number): number => a + (b - a) * t\n\nfunction groundAt(context: ValidationContext, pipe: Pipe, t: number): number {\n const x = lerp(pipe.from.at[0], pipe.to.at[0], t)\n const z = lerp(pipe.from.at[2], pipe.to.at[2], t)\n return context.options.groundAt?.(x, z) ?? lerp(pipe.from.at[1], pipe.to.at[1], t)\n}\n\nfunction pipeOf(context: ValidationContext, edge: NetworkEdge): Pipe | undefined {\n if (isAerialEdgeKind(edge.kind)) return undefined\n const ends = edgeEnds(context, edge)\n if (ends === undefined) return undefined\n const inverts = edge.inverts ?? (ends[0].invert !== undefined && ends[1].invert !== undefined ? ([ends[0].invert, ends[1].invert] as const) : undefined)\n if (inverts === undefined) context.report({ code: NETWORK_VIOLATION.MISSING_INVERT, id: edge.id })\n if (edge.diameter === undefined) context.report({ code: NETWORK_VIOLATION.MISSING_DIAMETER, id: edge.id })\n if (inverts === undefined || edge.diameter === undefined) return undefined\n return { edge, kind: edge.kind, from: ends[0], to: ends[1], inverts, diameter: edge.diameter }\n}\n\n/** Gravity pipes fall along the flow by at least the least slope; a declared slope agrees with the inverts. */\nfunction validateSlope(context: ValidationContext, pipe: Pipe): void {\n if (pipe.kind === 'water_main' || pipe.kind === 'water_service') return\n const length = edgeLength(context.graph, pipe.edge)\n if (length === 0) return\n const slope = (pipe.inverts[0] - pipe.inverts[1]) / length\n const limit = context.rules.minSlope[pipe.kind]\n if (slope < limit) context.report({ code: NETWORK_VIOLATION.SLOPE, id: pipe.edge.id, value: slope, limit })\n if (pipe.edge.slope !== undefined && Math.abs(pipe.edge.slope - slope) > SLOPE_TOLERANCE) context.report({ code: NETWORK_VIOLATION.SLOPE_MISMATCH, id: pipe.edge.id, value: pipe.edge.slope, limit: slope })\n}\n\nconst planAt = (pipe: Pipe, t: number): PlanPoint => [lerp(pipe.from.at[0], pipe.to.at[0], t), lerp(pipe.from.at[2], pipe.to.at[2], t)]\n\n/** A storm gallery runs within reach of a sewer main (the same street), at any sampled point of the main. */\nfunction besideGallery(context: ValidationContext, main: Pipe, pipes: readonly Pipe[]): boolean {\n const samples = Math.max(1, context.rules.catenarySamples)\n const reach = context.rules.sewer.galleryReach\n return pipes.some((gallery) => {\n if (gallery.kind !== 'storm_gallery') return false\n const a = planAt(gallery, 0)\n const b = planAt(gallery, 1)\n for (let index = 0; index <= samples; index++) {\n const point = planAt(main, index / samples)\n const nearest = planAt(gallery, nearestShare(a, b, point))\n if (Math.hypot(point[0] - nearest[0], point[1] - nearest[1]) <= reach) return true\n }\n return false\n })\n}\n\n/** Cover from the ground to the top of the pipe within its range, sampled along it; a sewer no deeper than the pumping limit. */\nfunction validateCover(context: ValidationContext, pipe: Pipe, pipes: readonly Pipe[]): void {\n const base = context.rules.cover[pipe.kind]\n const range = pipe.kind === 'sewer_main' && besideGallery(context, pipe, pipes) ? { ...base, min: Math.max(base.min, context.rules.sewer.coverUnderGallery) } : base\n const samples = Math.max(1, context.rules.catenarySamples)\n let least = Number.POSITIVE_INFINITY\n let most = Number.NEGATIVE_INFINITY\n let deepest = Number.NEGATIVE_INFINITY\n for (let index = 0; index <= samples; index++) {\n const t = index / samples\n const ground = groundAt(context, pipe, t)\n const invert = lerp(pipe.inverts[0], pipe.inverts[1], t)\n least = Math.min(least, ground - invert - pipe.diameter)\n most = Math.max(most, ground - invert - pipe.diameter)\n deepest = Math.max(deepest, ground - invert)\n }\n if (least < range.min) context.report({ code: NETWORK_VIOLATION.COVER, id: pipe.edge.id, detail: 'min', value: least, limit: range.min })\n if (range.max !== undefined && most > range.max) context.report({ code: NETWORK_VIOLATION.COVER, id: pipe.edge.id, detail: 'max', value: most, limit: range.max })\n const isSewer = pipe.kind === 'sewer_main' || pipe.kind === 'sewer_lateral'\n if (isSewer && deepest > context.rules.sewer.maxDepth) context.report({ code: NETWORK_VIOLATION.TOO_DEEP, id: pipe.edge.id, value: deepest, limit: context.rules.sewer.maxDepth })\n}\n\nconst shareEnds = (a: NetworkEdge, b: NetworkEdge): boolean => a.from === b.from || a.from === b.to || a.to === b.from || a.to === b.to\n\n/** Two pipes that cross in plan keep the least vertical gap, and the one of lower rank (water, then the sewer lateral, then drainage, then the sewer main) goes above. */\nfunction validateCrossing(context: ValidationContext, a: Pipe, b: Pipe): void {\n if (shareEnds(a.edge, b.edge)) return\n const crossing = segmentCrossing([a.from.at[0], a.from.at[2]], [a.to.at[0], a.to.at[2]], [b.from.at[0], b.from.at[2]], [b.to.at[0], b.to.at[2]])\n if (crossing === undefined) return\n const bottomA = lerp(a.inverts[0], a.inverts[1], crossing[0])\n const bottomB = lerp(b.inverts[0], b.inverts[1], crossing[1])\n const [upper, lower, upperBottom, lowerBottom] = bottomA >= bottomB ? [a, b, bottomA, bottomB] : [b, a, bottomB, bottomA]\n const gap = upperBottom - (lowerBottom + lower.diameter)\n const id = `${a.edge.id}x${b.edge.id}`\n const separation = context.rules.crossing.separation\n if (gap < separation) context.report({ code: NETWORK_VIOLATION.CROSSING_TOO_CLOSE, id, value: gap, limit: separation })\n const rank = context.rules.crossing.rank\n if (rank[upper.kind] > rank[lower.kind]) context.report({ code: NETWORK_VIOLATION.CROSSING_ORDER, id, detail: `${upper.edge.id} above ${lower.edge.id}` })\n const lateral = a.kind === 'sewer_lateral' && b.kind === 'storm_gallery' ? { pipe: a, t: crossing[0], bottom: bottomA } : b.kind === 'sewer_lateral' && a.kind === 'storm_gallery' ? { pipe: b, t: crossing[1], bottom: bottomB } : undefined\n if (lateral === undefined) return\n const depth = groundAt(context, lateral.pipe, lateral.t) - lateral.bottom\n const limit = context.rules.sewer.lateralOverGallery\n if (depth > limit) context.report({ code: NETWORK_VIOLATION.LATERAL_TOO_DEEP, id, value: depth, limit })\n}\n\n/** A sewer main has a manhole at most every `manholeSpacing` metres: its nodes are manholes, so no edge is longer. */\nfunction validateSpacing(context: ValidationContext, pipe: Pipe): void {\n if (pipe.kind !== 'sewer_main') return\n const length = edgeLength(context.graph, pipe.edge)\n if (length > context.rules.sewer.manholeSpacing) context.report({ code: NETWORK_VIOLATION.MANHOLE_SPACING, id: pipe.edge.id, value: length, limit: context.rules.sewer.manholeSpacing })\n}\n\n/** Inverts and diameters known, slopes, covers and depths, and every crossing between two pipes. */\nexport function validateBuried(context: ValidationContext): void {\n const pipes: Pipe[] = []\n for (const edge of context.graph.edges.values()) {\n const pipe = pipeOf(context, edge)\n if (pipe !== undefined) pipes.push(pipe)\n }\n for (const pipe of pipes) {\n validateSlope(context, pipe)\n validateCover(context, pipe, pipes)\n validateSpacing(context, pipe)\n }\n for (let first = 0; first < pipes.length; first++) {\n for (let second = first + 1; second < pipes.length; second++) validateCrossing(context, pipes[first] as Pipe, pipes[second] as Pipe)\n }\n}\n","/** The axis a straight street runs along. */\nexport type RunAxis = 'x' | 'z'\n\n/** A straight street's frame: `u` along it, `v` across it (+z for a street along x, +x for one along z). */\nexport type RunFrame = { readonly along: RunAxis; readonly axis: number }\n\n/** A point of a street's frame in the world. */\nexport function worldOf({ frame, u, v }: { readonly frame: RunFrame; readonly u: number; readonly v: number }): readonly [number, number] {\n return frame.along === 'x' ? [u, frame.axis + v] : [frame.axis + v, u]\n}\n\n/** A world point in a street's frame: the inverse of `worldOf`. */\nexport function frameOf({ frame, x, z }: { readonly frame: RunFrame; readonly x: number; readonly z: number }): readonly [number, number] {\n return frame.along === 'x' ? [x, z - frame.axis] : [z, x - frame.axis]\n}\n\nconst UINT32 = 2 ** 32\n\nexport type HashParams = { readonly seed: number; readonly id: string }\n\n/** FNV-1a of the seed and an id, into [0, 1): what the generator draws (a hookup, a bundle of cables), never the scene's random. */\nexport function hashOf({ seed, id }: HashParams): number {\n let h = 2166136261 ^ (seed >>> 0)\n h = Math.imul(h, 16777619)\n h ^= Math.floor(seed / UINT32) >>> 0\n h = Math.imul(h, 16777619)\n for (let index = 0; index < id.length; index++) {\n h ^= id.charCodeAt(index)\n h = Math.imul(h, 16777619)\n }\n // murmur3's finaliser: ids that differ in their last character land far apart\n h ^= h >>> 16\n h = Math.imul(h, 0x85ebca6b)\n h ^= h >>> 13\n h = Math.imul(h, 0xc2b2ae35)\n h ^= h >>> 16\n return (h >>> 0) / UINT32\n}\n\n/** A whole number in `range` (both ends in) by the hash of the seed and an id. */\nexport function countOf({ seed, id, range }: HashParams & { readonly range: readonly [number, number] }): number {\n const [least, most] = range\n return least + Math.min(most - least, Math.floor(hashOf({ seed, id }) * (most - least + 1)))\n}\n\n/** Two digits from 1: 'pole:main_street:07'. */\nexport const ordinal = (index: number): string => String(index + 1).padStart(2, '0')\n\n/** Points in square cells of `size` metres, to find the near ones without a pass over all of them. */\nexport type PlanBins<T> = { add(x: number, z: number, item: T): void; near(x: number, z: number, radius: number): T[] }\n\nexport function planBins<T>(size: number): PlanBins<T> {\n const cells = new Map<string, T[]>()\n const key = (i: number, k: number): string => `${i},${k}`\n return {\n add(x, z, item) {\n const id = key(Math.floor(x / size), Math.floor(z / size))\n cells.set(id, [...(cells.get(id) ?? []), item])\n },\n near(x, z, radius) {\n const out: T[] = []\n const reach = Math.ceil(radius / size)\n const [ci, ck] = [Math.floor(x / size), Math.floor(z / size)]\n for (let i = ci - reach; i <= ci + reach; i++) for (let k = ck - reach; k <= ck + reach; k++) out.push(...(cells.get(key(i, k)) ?? []))\n return out\n },\n }\n}\n","import type { PlanRect } from '../cities/types'\nimport { frameOf } from './frame'\nimport type { RunFrame } from './frame'\nimport type { PowerRules } from './rules'\n\n/** A lot's front on its street: its rectangle, the street's frame, the side of the street it stands on and its span along the street. */\nexport type LotFrontage = {\n readonly lot: string\n readonly rect: PlanRect\n readonly frame: RunFrame\n /** Half the street's roadway plus its sidewalk: a point farther from the axis is off the street. */\n readonly reach: number\n readonly side: 1 | -1\n readonly span: readonly [number, number]\n}\n\nexport type DropFitParams = {\n readonly frontage: LotFrontage\n readonly pole: { readonly x: number; readonly z: number }\n readonly anchor: readonly [number, number, number]\n readonly rules: Pick<PowerRules, 'dropMaxSkew' | 'dropFrontageSlack'>\n}\n\nexport type DropMisfit = 'skewed' | 'off_frontage'\n\n/**\n * How a drop from a street pole to a lot's anchor breaks the street's practice, or nothing: on the pole's own side the pole stands in front of\n * the lot (its station within the frontage); across the street the drop goes straight over (within `dropMaxSkew` of the street's normal),\n * never along the street. A pole off the street (a service pole inside a lot) is not judged here.\n */\nexport function dropMisfitOf({ frontage, pole, anchor, rules }: DropFitParams): DropMisfit | undefined {\n const [poleU, poleV] = frameOf({ frame: frontage.frame, x: pole.x, z: pole.z })\n if (Math.abs(poleV) > frontage.reach) return undefined\n const [anchorU, anchorV] = frameOf({ frame: frontage.frame, x: anchor[0], z: anchor[2] })\n if (Math.sign(poleV) === frontage.side) {\n const [low, high] = frontage.span\n return poleU >= low - rules.dropFrontageSlack && poleU <= high + rules.dropFrontageSlack ? undefined : 'off_frontage'\n }\n const skew = (Math.atan2(Math.abs(poleU - anchorU), Math.abs(poleV - anchorV)) * 180) / Math.PI\n return skew <= rules.dropMaxSkew ? undefined : 'skewed'\n}\n\nconst inside = (x: number, z: number, rect: PlanRect): boolean => x > rect[0] && x < rect[2] && z > rect[1] && z < rect[3]\n\n/** The first other lot a drop's straight path passes over (sampled every 0.25 m), or none. */\nexport function lotUnderDrop({ from, to, lot, frontages }: { readonly from: readonly [number, number]; readonly to: readonly [number, number]; readonly lot: string; readonly frontages: readonly LotFrontage[] }): string | undefined {\n const steps = Math.max(1, Math.ceil(Math.hypot(to[0] - from[0], to[1] - from[1]) / 0.25))\n for (let index = 0; index <= steps; index++) {\n const t = index / steps\n const [x, z] = [from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t]\n const other = frontages.find((entry) => entry.lot !== lot && inside(x, z, entry.rect))\n if (other) return other.lot\n }\n return undefined\n}\n","import { NETWORK_VIOLATION } from './codes'\nimport { dropMisfitOf, lotUnderDrop } from './drop-rules'\nimport { edgeEnds } from './validate-context'\nimport type { ValidationContext } from './validate-context'\n\n/**\n * The street's practice for drops (with the lots' `frontages`): a drop leaves a pole in front of its lot or goes straight across the street,\n * never along it, and never passes over another lot; no pole holds more than `dropsPerPole` service drops. A drop from a service pole inside a lot\n * is judged only by the lots it passes over.\n */\nexport function validateDrops(context: ValidationContext): void {\n const frontages = context.options.frontages\n const perPole = new Map<string, number>()\n for (const edge of context.graph.edges.values()) {\n if (edge.kind !== 'service_drop' && edge.kind !== 'telecom_drop') continue\n const ends = edgeEnds(context, edge)\n if (!ends) continue\n const [pole, end] = ends\n if (edge.kind === 'service_drop') perPole.set(pole.id, (perPole.get(pole.id) ?? 0) + 1)\n const lot = end.lot\n if (frontages === undefined || lot === undefined) continue\n const frontage = frontages.find((entry) => entry.lot === lot)\n const misfit = frontage && dropMisfitOf({ frontage, pole: { x: pole.at[0], z: pole.at[2] }, anchor: end.at, rules: context.rules.power })\n if (misfit === 'skewed') context.report({ code: NETWORK_VIOLATION.DROP_SKEWED, id: edge.id, limit: context.rules.power.dropMaxSkew })\n if (misfit === 'off_frontage') context.report({ code: NETWORK_VIOLATION.DROP_OFF_FRONTAGE, id: edge.id, detail: pole.id })\n const other = lotUnderDrop({ from: [pole.at[0], pole.at[2]], to: [end.at[0], end.at[2]], lot, frontages })\n if (other !== undefined) context.report({ code: NETWORK_VIOLATION.DROP_OVER_OTHER_LOT, id: edge.id, detail: other })\n }\n for (const [pole, count] of perPole) {\n if (count > context.rules.power.dropsPerPole) context.report({ code: NETWORK_VIOLATION.POLE_TOO_MANY_DROPS, id: pole, value: count, limit: context.rules.power.dropsPerPole })\n }\n}\n","import { NETWORK_VIOLATION } from './codes'\nimport { circuitOf } from './graph'\nimport { diversifiedDemand } from './rules'\nimport type { ValidationContext } from './validate-context'\n\n/** kVA of the low voltage circuit of a transformer: the diversified demand of its consumers plus its street lights. */\nexport function circuitDemand(context: ValidationContext, transformerId: string): number {\n const circuit = circuitOf(context.graph, transformerId)\n const installed = new Map((context.options.connections ?? []).filter((connection) => connection.network === 'power').map((connection) => [connection.lot, connection.installedKva]))\n const consumers: number[] = []\n let lights = 0\n for (const id of circuit.keys()) {\n const node = context.graph.nodes.get(id)\n if (node?.kind === 'connection' && node.lot !== undefined) consumers.push(installed.get(node.lot) ?? 0)\n lights += context.graph.outgoing(id, 'lighting').length\n }\n return diversifiedDemand(consumers, context.rules.power) + lights * context.rules.lighting.lampKva\n}\n\n/** Each transformer has a known rating, its demand within the loading limit, and its circuit no longer than the limit each way. */\nexport function validateLoad(context: ValidationContext): void {\n const power = context.rules.power\n for (const node of context.graph.nodes.values()) {\n if (node.kind !== 'transformer') continue\n const rating = power.transformers.find((entry) => entry.id === node.spec)\n if (rating === undefined) context.report({ code: NETWORK_VIOLATION.UNKNOWN_TRANSFORMER, id: node.id, detail: node.spec ?? 'none' })\n else {\n const loading = circuitDemand(context, node.id) / rating.kva\n if (loading > power.maxLoading) context.report({ code: NETWORK_VIOLATION.TRANSFORMER_OVERLOADED, id: node.id, value: loading, limit: power.maxLoading })\n }\n const longest = Math.max(0, ...circuitOf(context.graph, node.id).values())\n if (longest > power.lvCircuitMaxLength) context.report({ code: NETWORK_VIOLATION.LV_CIRCUIT_TOO_LONG, id: node.id, value: longest, limit: power.lvCircuitMaxLength })\n }\n}\n","import { CONNECTION_NETWORK, EDGE_NETWORK, NETWORK_ENDS, NETWORK_FLOW } from './classes'\nimport { NETWORK_VIOLATION } from './codes'\nimport { connectedNodes } from './graph'\nimport type { NetworkKind, UtilityNetworks } from './types'\nimport type { ValidationContext } from './validate-context'\n\nconst NETWORKS: readonly NetworkKind[] = ['power_mv', 'power_lv', 'lighting', 'telecom', 'sewer', 'storm', 'water']\n\n/** Ids used twice, edges to missing nodes, edges whose ends do not carry their network. */\nexport function validateIds(context: ValidationContext, networks: UtilityNetworks): void {\n const seen = new Set<string>()\n for (const entry of [...networks.nodes, ...networks.edges]) {\n if (seen.has(entry.id)) context.report({ code: NETWORK_VIOLATION.DUPLICATE_ID, id: entry.id })\n seen.add(entry.id)\n }\n for (const edge of context.graph.edges.values()) {\n const network = EDGE_NETWORK[edge.kind]\n for (const end of [edge.from, edge.to]) {\n const node = context.graph.nodes.get(end)\n if (node === undefined) context.report({ code: NETWORK_VIOLATION.UNKNOWN_NODE, id: edge.id, detail: end })\n else if (!node.carries.includes(network)) context.report({ code: NETWORK_VIOLATION.NOT_CARRIED, id: edge.id, detail: `${end} does not carry ${network}` })\n }\n }\n}\n\n/**\n * Each network is a tree tied to its source: a supply node is fed by one edge of a network, a drain node flows out through one, and every\n * node that carries a network is reached from its source (or reaches its destination). A loop or an island is never reached, and a loop\n * through the source itself shows as a source with an edge coming in (or a destination with one going out).\n */\nexport function validateTrees(context: ValidationContext): void {\n for (const network of NETWORKS) {\n const supply = NETWORK_FLOW[network] === 'supply'\n const connected = connectedNodes(context.graph, network)\n for (const node of context.graph.nodes.values()) {\n if (!node.carries.includes(network)) continue\n const links = supply ? context.graph.incoming(node.id, network) : context.graph.outgoing(node.id, network)\n if (links.length > 1) context.report({ code: NETWORK_VIOLATION.NOT_RADIAL, id: node.id, detail: network, value: links.length, limit: 1 })\n if (!connected.has(node.id)) context.report({ code: NETWORK_VIOLATION.DISCONNECTED, id: node.id, detail: network })\n const back = supply ? context.graph.incoming(node.id, network) : context.graph.outgoing(node.id, network)\n if (NETWORK_ENDS[network].includes(node.kind) && back.length > 0) context.report({ code: NETWORK_VIOLATION.LOOP_AT_END, id: node.id, detail: network })\n }\n }\n}\n\n/** Every connection a lot declared is in the world frame, has one connection node on its network, and that node is tied to the source. */\nexport function validateLots(context: ValidationContext): void {\n const connections = context.options.connections ?? []\n const connectedByNetwork = new Map<NetworkKind, ReadonlySet<string>>()\n const nodes = [...context.graph.nodes.values()]\n const declared = new Set<string>()\n for (const connection of connections) {\n const id = `${connection.lot}:${connection.network}`\n if (declared.has(id)) {\n context.report({ code: NETWORK_VIOLATION.LOT_DECLARED_TWICE, id })\n continue\n }\n declared.add(id)\n if (connection.frame !== 'world') {\n context.report({ code: NETWORK_VIOLATION.CONNECTION_IN_PLAN_FRAME, id })\n continue\n }\n const network = CONNECTION_NETWORK[connection.network]\n const matches = nodes.filter((node) => node.kind === 'connection' && node.lot === connection.lot && node.carries.includes(network))\n if (matches.length > 1) context.report({ code: NETWORK_VIOLATION.LOT_CONNECTED_TWICE, id, value: matches.length, limit: 1 })\n const node = matches[0]\n const connected = connectedByNetwork.get(network) ?? connectedNodes(context.graph, network)\n connectedByNetwork.set(network, connected)\n if (node === undefined || !connected.has(node.id)) {\n context.report({ code: NETWORK_VIOLATION.LOT_UNCONNECTED, id, detail: network })\n continue\n }\n const moved = Math.hypot(node.at[0] - connection.at[0], node.at[1] - connection.at[1], node.at[2] - connection.at[2])\n if (moved > context.rules.connectionTolerance) context.report({ code: NETWORK_VIOLATION.CONNECTION_MOVED, id, value: moved, limit: context.rules.connectionTolerance })\n }\n}\n\n/** With the lots' connections given, every connection node answers one of them. */\nexport function validateOrphans(context: ValidationContext): void {\n const connections = context.options.connections\n if (connections === undefined) return\n const declared = new Set(connections.map((connection) => `${connection.lot}:${CONNECTION_NETWORK[connection.network]}`))\n for (const node of context.graph.nodes.values()) {\n if (node.kind !== 'connection') continue\n if (!node.carries.some((network) => declared.has(`${node.lot ?? ''}:${network}`))) context.report({ code: NETWORK_VIOLATION.ORPHAN_CONNECTION, id: node.id })\n }\n}\n","import type { NetworkViolation } from './codes'\nimport { buildNetworkGraph } from './graph'\nimport type { UtilityNetworks } from './types'\nimport { validateAerial } from './validate-aerial'\nimport { validateBuried } from './validate-buried'\nimport { validateDrops } from './validate-drops'\nimport type { ValidateNetworksOptions, ValidationContext } from './validate-context'\nimport { validateLoad } from './validate-load'\nimport { validateIds, validateLots, validateOrphans, validateTrees } from './validate-structure'\n\n/**\n * Everything wrong with the networks, by the rules they carry: ids and links, each network a tree tied to its source, every lot linked once,\n * spans (reach, sag, clearance, buildings, crowns), pipes (slope, cover, depth, crossings) and transformers (loading, circuit length).\n * Pure and in input order: the same networks give the same list.\n */\nexport function validateNetworks(networks: UtilityNetworks, options: ValidateNetworksOptions = {}): NetworkViolation[] {\n const violations: NetworkViolation[] = []\n const context: ValidationContext = { graph: buildNetworkGraph(networks), rules: networks.rules, options, report: (violation) => violations.push(violation) }\n validateIds(context, networks)\n validateTrees(context)\n validateLots(context)\n validateOrphans(context)\n validateAerial(context)\n validateDrops(context)\n validateBuried(context)\n validateLoad(context)\n return violations\n}\n","import { DEFAULT_POLE_SLOTS } from './networks/slots'\nimport type { DistributionSpec } from './pole-specs'\n\n/** The 11 m double-T concrete distribution pole (9.3 m above the ground): the lamp's arm in the street light band, the drum in the transformer band. */\nexport const DISTRIBUTION: DistributionSpec = {\n mast: { radiusTop: 0.12, radiusBottom: 0.22, height: 9.3, color: 0x8a8a84, segments: 4 },\n arm: { reach: 1, y: 6.7, width: 2, height: 0.1, depth: 0.1, color: 0x6a6a66 },\n lamp: { reach: 2, y: 6.55, width: 0.5, height: 0.16, depth: 0.3 },\n lens: { lit: 0xffa040, unlit: 0x3a3a3a },\n light: { color: 0xff9a40, intensity: 1.3, distance: 20, y: 6.4 },\n transformer: { offset: 0.45, y: 7.7, radius: 0.32, height: 1, color: 0x5a5e62, segments: 8 },\n slots: DEFAULT_POLE_SLOTS,\n crossarm: { reach: 0.3, width: 2, height: 0.1, depth: 0.09, color: 0x8c8c86 },\n insulators: { at: [-0.55, 0.35, 1.15], radius: 0.04, color: 0xd8d4c8 },\n bushings: { spread: 0.16, radius: 0.025, height: 0.14, color: 0xa8b0b8 },\n lowVoltage: { out: 0.2, color: 0x5e6064 },\n telecom: { out: 0.18, color: 0x5e6064 },\n guy: { reach: 3, color: 0x7a7c7e },\n}\n","import type { PoleSystem } from './pole-tree'\nimport { diversifiedDemand, pickTransformer } from './rules'\nimport type { NetworkRules } from './rules'\n\n/** Length of the span between two neighbouring poles. */\nexport type SpanOf = (ends: { readonly from: string; readonly to: string }) => number\n\n/** One low voltage circuit: its poles, the pole that carries its transformer (the centre of the circuit), the rating that takes its load. */\nexport type Circuit = { readonly poles: readonly string[]; readonly transformer: string; readonly rating: string; readonly demand: number; readonly over: boolean }\n\nexport type CircuitParams = {\n readonly system: PoleSystem\n /** The installed kVA of each consumer a pole feeds (unknown counts in the lower column). */\n readonly consumers: ReadonlyMap<string, readonly number[]>\n readonly span: SpanOf\n readonly rules: NetworkRules\n /** Poles a transformer may not stand on (a service pole inside a lot: the medium voltage never enters a lot). */\n readonly isService: (pole: string) => boolean\n}\n\ntype Open = { readonly poles: string[]; readonly height: number; readonly diameter: number; readonly installed: number[] }\n\n/**\n * The circuits of a system, cut bottom up on its tree: a pole gathers its children's open circuits, and while the longest line between two\n * of their poles is over twice the circuit limit less one span (the transformer stands on a pole, at most half a span off the middle) or\n * their diversified demand (plus one lamp a pole) is over the largest rating's loading, the child that reaches farthest closes as a circuit\n * of its own (one more transformer). Each circuit's transformer stands on its centre. `over` marks a circuit no cut can bring under the\n * largest rating (one pole's own consumers).\n */\nexport function circuitsOf({ system, consumers, span, rules, isService }: CircuitParams): Circuit[] {\n const power = rules.power\n const capacity = Math.max(...power.transformers.map((rating) => rating.kva)) * power.maxLoading\n const longest = 2 * power.lvCircuitMaxLength - rules.layout.poles.spacing[1]\n const demandOf = (open: Pick<Open, 'poles' | 'installed'>): number => diversifiedDemand(open.installed, power) + open.poles.filter((pole) => !isService(pole)).length * rules.lighting.lampKva\n const closed: Array<Pick<Open, 'poles' | 'installed'>> = []\n const gather = (pole: string): Open => {\n const parts = (system.children.get(pole) ?? []).map((child) => {\n const open = gather(child)\n return { ...open, height: open.height + span({ from: pole, to: child }) }\n })\n parts.sort((a, b) => b.height - a.height)\n const own = (): Open => {\n const heights = parts.map((part) => part.height)\n return {\n poles: [pole, ...parts.flatMap((part) => part.poles)],\n height: Math.max(0, ...heights),\n diameter: Math.max(0, ...parts.map((part) => part.diameter), (heights[0] ?? 0) + (heights[1] ?? 0)),\n installed: [...(consumers.get(pole) ?? []), ...parts.flatMap((part) => part.installed)],\n }\n }\n let open = own()\n while (parts.length > 0 && (open.diameter > longest || demandOf(open) > capacity)) {\n closed.push(parts.shift() as Open)\n open = own()\n }\n return open\n }\n closed.push(gather(system.root))\n return closed.map((open) => {\n const transformer = centreOf({ poles: open.poles, system, span, isService })\n const demand = demandOf(open)\n const rating = pickTransformer(demand, power)\n return { poles: open.poles, transformer, rating: rating?.id ?? power.transformers[power.transformers.length - 1]?.id ?? 'none', demand, over: rating === undefined }\n })\n}\n\nexport type DistancesParams = { readonly poles: readonly string[]; readonly from: string; readonly system: PoleSystem; readonly span: SpanOf }\n\n/** Line length from `from` to every pole of the circuit, along the tree. */\nexport function distancesWithin({ poles, from, system, span }: DistancesParams): Map<string, number> {\n const members = new Set(poles)\n const distance = new Map([[from, 0]])\n const pending = [from]\n while (pending.length > 0) {\n const id = pending.pop() as string\n const up = system.parent.get(id)\n const near = [...(system.children.get(id) ?? []), ...(up === undefined ? [] : [up])].filter((next) => members.has(next) && !distance.has(next))\n for (const next of near) {\n distance.set(next, (distance.get(id) ?? 0) + span({ from: id, to: next }))\n pending.push(next)\n }\n }\n return distance\n}\n\n/** The street pole of a circuit with the shortest longest line to the others (the first in tree order on a tie). */\nfunction centreOf({ poles, system, span, isService }: Omit<DistancesParams, 'from'> & { readonly isService: (pole: string) => boolean }): string {\n let best = poles.find((pole) => !isService(pole)) ?? (poles[0] as string)\n let bestReach = Number.POSITIVE_INFINITY\n for (const pole of poles) {\n if (isService(pole)) continue\n const reach = Math.max(...distancesWithin({ poles, from: pole, system, span }).values())\n if (reach < bestReach - 1e-9) {\n best = pole\n bestReach = reach\n }\n }\n return best\n}\n","import { worldOf } from './frame'\nimport type { PoleStation } from './pole-layout'\nimport type { StreetRun } from './runs'\n\n/** A pole of the networks: its stable id and where it stands. A corner shared by two streets is one pole. */\nexport type NetworkPole = { readonly id: string; readonly station: PoleStation }\n\n/**\n * The poles one feed reaches through the spans, as a tree from the pole nearest the feed: `parent`, `children` and the length of line\n * from the root to each pole. Spans that would close a loop are left out, so every network laid on it is radial.\n */\nexport type PoleSystem = {\n readonly root: string\n /** Where the line enters the map (a run end at the border), on the line of the poles. */\n readonly feed: readonly [number, number]\n /** In order of distance from the root. */\n readonly poles: readonly string[]\n readonly parent: ReadonlyMap<string, string>\n readonly children: ReadonlyMap<string, readonly string[]>\n readonly distance: ReadonlyMap<string, number>\n readonly depth: ReadonlyMap<string, number>\n}\n\nexport type PoleTree = { readonly poles: ReadonlyMap<string, NetworkPole>; readonly systems: readonly PoleSystem[] }\n\nexport type PoleTreeParams = {\n /** Stations of each run in order, and service chains from their street pole: consecutive stations are spans. */\n readonly chains: ReadonlyArray<readonly PoleStation[]>\n readonly sides: ReadonlyMap<string, 1 | -1>\n readonly setback: number\n}\n\nconst planDistance = (a: PoleStation, b: PoleStation): number => Math.hypot(a.x - b.x, a.z - b.z)\nconst spotOf = (station: PoleStation): string => `${Math.round(station.x * 20)},${Math.round(station.z * 20)}`\n\n/** Poles by id (a station two runs share at the same spot kept once) and the spans between consecutive stations of each chain. */\nfunction polesAndSpans(chains: ReadonlyArray<readonly PoleStation[]>): { poles: Map<string, NetworkPole>; spans: Map<string, Set<string>> } {\n const poles = new Map<string, NetworkPole>()\n const bySpot = new Map<string, string>()\n const spans = new Map<string, Set<string>>()\n const link = (a: string, b: string): void => {\n if (a === b) return\n spans.set(a, (spans.get(a) ?? new Set()).add(b))\n spans.set(b, (spans.get(b) ?? new Set()).add(a))\n }\n for (const chain of chains) {\n let previous: string | undefined\n for (const station of chain) {\n const id = bySpot.get(spotOf(station)) ?? station.id\n if (!poles.has(id)) {\n poles.set(id, { id, station })\n bySpot.set(spotOf(station), id)\n }\n if (previous !== undefined) link(previous, id)\n previous = id\n }\n }\n linkCorners(poles, link)\n return { poles, spans }\n}\n\n/** At every crossing, the corner poles of the two streets that do not share a spot are joined by a span across the corner (the nearest pair). */\nfunction linkCorners(poles: ReadonlyMap<string, NetworkPole>, link: (a: string, b: string) => void): void {\n const corners = [...poles.values()].filter((pole) => pole.station.role === 'corner')\n const runs = new Map(corners.map((pole) => [pole.station.run.id, pole.station.run]))\n for (const run of runs.values()) {\n for (const crossing of run.crossings) {\n const near = (pole: NetworkPole, of: StreetRun, at: number, half: number): boolean => pole.station.run.id === of.id && Math.abs(pole.station.u - at) <= half + 2\n const other = runs.get(crossing.run)\n if (other === undefined || other.id < run.id) continue\n const mine = corners.filter((pole) => near(pole, run, crossing.at, crossing.half))\n const theirs = corners.filter((pole) => near(pole, other, run.axis, run.width / 2))\n const pairs = mine.flatMap((a) => theirs.map((b) => [a, b] as const)).sort((p, q) => planDistance(p[0].station, p[1].station) - planDistance(q[0].station, q[1].station) || (p[0].id + p[1].id < q[0].id + q[1].id ? -1 : 1))\n const best = pairs[0]\n if (best !== undefined) link(best[0].id, best[1].id)\n }\n }\n}\n\nfunction feedOf({ runs, sides, setback, fallback }: { readonly runs: readonly StreetRun[]; readonly sides: ReadonlyMap<string, 1 | -1>; readonly setback: number; readonly fallback: NetworkPole }): readonly [number, number] {\n for (const run of runs) {\n const v = (sides.get(run.id) ?? -1) * (run.width / 2 + setback)\n if (run.ends[0] === 'edge') return worldOf({ frame: run, u: run.from, v })\n if (run.ends[1] === 'edge') return worldOf({ frame: run, u: run.to, v })\n }\n return [fallback.station.x, fallback.station.z]\n}\n\n/** Shortest-line tree from the root over the spans (ties by id), so the same poles always give the same tree. Plain O(n²) Dijkstra: a system has tens of poles. */\nfunction treeFrom({ root, poles, spans }: { readonly root: string; readonly poles: ReadonlyMap<string, NetworkPole>; readonly spans: ReadonlyMap<string, ReadonlySet<string>> }): Omit<PoleSystem, 'feed'> {\n const distance = new Map([[root, 0]])\n const parent = new Map<string, string>()\n const done = new Set<string>()\n const order: string[] = []\n for (;;) {\n const open = [...distance.entries()].filter(([id]) => !done.has(id)).sort((a, b) => a[1] - b[1] || (a[0] < b[0] ? -1 : 1))[0]\n if (open === undefined) break\n const [id, base] = open\n done.add(id)\n order.push(id)\n for (const next of [...(spans.get(id) ?? [])].sort()) {\n const length = base + planDistance((poles.get(id) as NetworkPole).station, (poles.get(next) as NetworkPole).station)\n if (done.has(next) || length >= (distance.get(next) ?? Number.POSITIVE_INFINITY)) continue\n distance.set(next, length)\n parent.set(next, id)\n }\n }\n const children = new Map<string, string[]>()\n const depth = new Map<string, number>()\n for (const id of order) {\n const up = parent.get(id)\n depth.set(id, up === undefined ? 0 : (depth.get(up) ?? 0) + 1)\n if (up !== undefined) children.set(up, [...(children.get(up) ?? []), id])\n }\n return { root, poles: order, parent, children, distance, depth }\n}\n\n/** The poles of every run and the systems they make: each fed from the border where one of its runs leaves the map (one per side of a river). */\nexport function poleTreeOf({ chains, sides, setback }: PoleTreeParams): PoleTree {\n const { poles, spans } = polesAndSpans(chains)\n const systems: PoleSystem[] = []\n const seen = new Set<string>()\n for (const pole of poles.values()) {\n if (seen.has(pole.id)) continue\n const members = treeFrom({ root: pole.id, poles, spans }).poles\n for (const id of members) seen.add(id)\n const runs = [...new Map(members.map((id) => (poles.get(id) as NetworkPole).station.run).map((run) => [run.id, run])).values()]\n const feed = feedOf({ runs, sides, setback, fallback: pole })\n const along = (id: string): number => Math.hypot((poles.get(id) as NetworkPole).station.x - feed[0], (poles.get(id) as NetworkPole).station.z - feed[1])\n const root = [...members].filter((id) => (poles.get(id) as NetworkPole).station.role !== 'service').sort((a, b) => along(a) - along(b))[0] ?? pole.id\n systems.push({ ...treeFrom({ root, poles, spans }), feed })\n }\n return { poles, systems }\n}\n\n/** Length of the span between two poles, metres in plan. */\nexport const spanLength = ({ tree, from, to }: { readonly tree: PoleTree; readonly from: string; readonly to: string }): number =>\n planDistance((tree.poles.get(from) as NetworkPole).station, (tree.poles.get(to) as NetworkPole).station)\n","import type { UtilityConnection } from '@adatechnology/game-contracts'\n\nimport type { PoleSlots } from '../pole-specs'\nimport { circuitsOf, distancesWithin } from './circuits'\nimport type { Circuit, SpanOf } from './circuits'\nimport { planBins, worldOf } from './frame'\nimport { spanLength } from './pole-tree'\nimport type { NetworkPole, PoleSystem, PoleTree } from './pole-tree'\nimport type { NetworkRules } from './rules'\nimport type { NetworkEdge, NetworkKind, NetworkNode } from './types'\nimport type { NetworkWarning } from './warnings'\n\n/** What the layers of the generator add to. */\nexport type NetworkSink = { readonly nodes: NetworkNode[]; readonly edges: NetworkEdge[]; readonly warnings: NetworkWarning[] }\n\n/** The fixing heights over the ground, read from the pole's bands. */\nexport type PoleHeights = { readonly mv: number; readonly transformer: number; readonly transformerBottom: number; readonly lv: number; readonly lamp: number; readonly telecom: number }\n\nexport function poleHeightsOf(slots: PoleSlots): PoleHeights {\n const { mv, transformer, lv, lighting, telecom } = slots.bands\n return { mv: mv[1], transformer: (transformer[0] + transformer[1]) / 2, transformerBottom: transformer[0], lv: lv[1] - 0.1, lamp: lighting[0] + 0.1, telecom: telecom[1] }\n}\n\nexport type AerialParams = {\n readonly tree: PoleTree\n readonly connections: readonly UtilityConnection[]\n readonly rules: NetworkRules\n readonly heights: PoleHeights\n /** The distribution pole of the registry: its id and how far its arm hangs the lamp from the mast. */\n readonly pole: { readonly id: string; readonly lampReach: number }\n /** Lots with a drop and no meter (illegal hookups): linked as any other, counted in the load. */\n readonly unmetered: ReadonlySet<string>\n /** The pole each lot's drop leaves from (`reachLots`): in front of the lot or straight across, at most `dropsPerPole` a pole. */\n readonly feeds: ReadonlyMap<string, { readonly x: number; readonly z: number }>\n readonly sink: NetworkSink\n}\n\n/** The poles of a tree in cells, to find the nearest ones to a point. */\nexport function poleFinder(tree: PoleTree): (point: { readonly x: number; readonly z: number; readonly radius: number }) => NetworkPole[] {\n const bins = planBins<NetworkPole>(40)\n for (const pole of tree.poles.values()) bins.add(pole.station.x, pole.station.z, pole)\n const all = [...tree.poles.values()]\n return ({ x, z, radius }) => {\n const near = bins.near(x, z, radius)\n const pool = near.length > 0 ? near : all\n return pool.sort((a, b) => Math.hypot(a.station.x - x, a.station.z - z) - Math.hypot(b.station.x - x, b.station.z - z) || (a.id < b.id ? -1 : 1))\n }\n}\n\n/** The lamp of a pole: on its arm over the road, `lampReach` from the mast toward the street. A service pole inside a lot has none. */\nexport function lampOf({ pole, rules, lampReach }: { readonly pole: NetworkPole; readonly rules: NetworkRules; readonly lampReach: number }): readonly [number, number] | undefined {\n const { run, side, u, role } = pole.station\n if (role === 'service') return undefined\n return worldOf({ frame: run, u, v: side * (run.width / 2 + rules.layout.poles.curbSetback - lampReach) })\n}\n\n/** The pole that stands at a point, or none. */\nexport function poleAt(tree: PoleTree, at: { readonly x: number; readonly z: number } | undefined): NetworkPole | undefined {\n if (at === undefined) return undefined\n return [...tree.poles.values()].find((pole) => Math.hypot(pole.station.x - at.x, pole.station.z - at.z) < 1e-6)\n}\n\n/** Each lot's drop from the pole `reachLots` chose for it (the nearest one in reach when it chose none). */\nfunction dropsOf(params: AerialParams): Map<string, UtilityConnection[]> {\n const find = poleFinder(params.tree)\n const out = new Map<string, UtilityConnection[]>()\n for (const connection of params.connections) {\n const pole = poleAt(params.tree, params.feeds.get(`${connection.lot}:power`)) ?? find({ x: connection.at[0], z: connection.at[2], radius: params.rules.power.dropMaxLength })[0]\n if (pole !== undefined) out.set(pole.id, [...(out.get(pole.id) ?? []), connection])\n }\n return out\n}\n\n/** The circuits of every system, with the poles the medium voltage must reach (the path from the feed to each transformer). */\nexport function powerPlanOf({ params, drops }: { readonly params: AerialParams; readonly drops: ReadonlyMap<string, readonly UtilityConnection[]> }): Array<{ system: PoleSystem; circuits: Circuit[]; medium: Set<string> }> {\n const span: SpanOf = ({ from, to }) => spanLength({ tree: params.tree, from, to })\n const isService = (pole: string): boolean => params.tree.poles.get(pole)?.station.role === 'service'\n return params.tree.systems.map((system) => {\n const consumers = new Map(system.poles.map((pole) => [pole, (drops.get(pole) ?? []).map((connection) => connection.installedKva ?? 0)]))\n const circuits = circuitsOf({ system, consumers, span, rules: params.rules, isService })\n // the medium voltage runs along every street pole of the feeder (a street with poles and no medium voltage reads wrong), and to each transformer\n const medium = new Set(system.poles.filter((pole) => !isService(pole)))\n for (const circuit of circuits) {\n for (let pole: string | undefined = circuit.transformer; pole !== undefined && !medium.has(pole); pole = system.parent.get(pole)) medium.add(pole)\n }\n return { system, circuits, medium }\n })\n}\n\n/** Medium voltage from each feed to the transformers, each circuit's low voltage from its transformer, a lamp on every street pole and a drop to every lot. */\nexport function layPower(params: AerialParams): void {\n const { tree, heights, rules, sink } = params\n const sag = rules.layout.sag\n const drops = dropsOf(params)\n for (const { system, circuits, medium } of powerPlanOf({ params, drops })) {\n const feed = `feed:${system.root}`\n sink.nodes.push({ id: feed, kind: 'feed', at: [system.feed[0], heights.mv, system.feed[1]], carries: ['power_mv'] })\n for (const id of system.poles) {\n const pole = tree.poles.get(id) as NetworkPole\n const lamp = lampOf({ pole, rules, lampReach: params.pole.lampReach })\n const carries: NetworkKind[] = [...(medium.has(id) ? (['power_mv'] as const) : []), 'power_lv', ...(lamp === undefined ? [] : (['lighting'] as const)), 'telecom']\n sink.nodes.push({ id, kind: 'pole', at: [pole.station.x, 0, pole.station.z], carries, spec: params.pole.id, ...(pole.station.role === 'line' || pole.station.role === 'service' ? {} : { guyed: true }) })\n if (medium.has(id)) sink.edges.push({ id: `mv:${id}`, kind: 'mv_span', from: system.parent.get(id) ?? feed, to: id, sag: sag.mv, heights: [heights.mv, heights.mv], conductors: 3 })\n if (lamp === undefined) continue\n sink.nodes.push({ id: `light:${id}`, kind: 'light', at: [lamp[0], heights.lamp, lamp[1]], carries: ['lighting'], spec: 'street_light' })\n sink.edges.push({ id: `light_feed:${id}`, kind: 'light_feed', from: id, to: `light:${id}`, sag: 0, heights: [heights.lv, heights.lamp] })\n }\n for (const circuit of circuits) {\n if (circuit.over) sink.warnings.push({ code: 'transformer_over_capacity', id: `transformer:${circuit.transformer}`, detail: `${circuit.demand.toFixed(1)} kVA` })\n layCircuit({ params, system, circuit })\n }\n }\n for (const [poleId, connections] of drops) {\n for (const connection of connections) {\n const node = `lot:${connection.lot}:power`\n sink.nodes.push({ id: node, kind: 'connection', at: connection.at, carries: ['power_lv'], lot: connection.lot, ...(params.unmetered.has(connection.lot) ? { spec: 'unmetered' } : {}) })\n sink.edges.push({ id: `drop:${connection.lot}`, kind: 'service_drop', from: poleId, to: node, sag: sag.drop, heights: [heights.lv, connection.at[1]], conductors: 2 })\n }\n }\n}\n\n/** The transformer on its pole, fed by the medium voltage, and the low voltage spans out from it over the circuit's poles. */\nfunction layCircuit({ params, system, circuit }: { readonly params: AerialParams; readonly system: PoleSystem; readonly circuit: Circuit }): void {\n const { tree, heights, sink } = params\n const pole = tree.poles.get(circuit.transformer) as NetworkPole\n const id = `transformer:${circuit.transformer}`\n sink.nodes.push({ id, kind: 'transformer', at: [pole.station.x, heights.transformer, pole.station.z], carries: ['power_mv', 'power_lv'], spec: circuit.rating })\n sink.edges.push({ id: `mv:${id}`, kind: 'mv_span', from: circuit.transformer, to: id, sag: 0, heights: [heights.mv, heights.transformer] })\n sink.edges.push({ id: `lv:${circuit.transformer}`, kind: 'lv_span', from: id, to: circuit.transformer, sag: 0, heights: [heights.transformerBottom, heights.lv] })\n const span: SpanOf = ({ from, to }) => spanLength({ tree, from, to })\n const order = [...distancesWithin({ poles: circuit.poles, from: circuit.transformer, system, span }).entries()].sort((a, b) => a[1] - b[1])\n const members = new Set(circuit.poles)\n const reached = new Set([circuit.transformer])\n for (const [from] of order) {\n const up = system.parent.get(from)\n const near = [...(system.children.get(from) ?? []), ...(up === undefined ? [] : [up])].filter((next) => members.has(next) && !reached.has(next))\n for (const next of near) {\n reached.add(next)\n sink.edges.push({ id: `lv:${next}`, kind: 'lv_span', from, to: next, sag: params.rules.layout.sag.lv, heights: [heights.lv, heights.lv], conductors: 4 })\n }\n }\n}\n","import type { UtilityConnection, UtilityNetwork } from '@adatechnology/game-contracts'\n\nimport { worldOf } from './frame'\nimport type { NetworkRules } from './rules'\nimport type { ServedLot } from './runs'\n\nexport type GroundAt = (x: number, z: number) => number\n\n/**\n * Where a lot takes each network when it declares none, from its rectangle and the street it faces: the meter post (power, telecom 0.6 m\n * under it) and the water stand behind the front wall, the inspection box 1 m inside the front, the downspout outlet at the kerb.\n */\nexport function defaultConnectionsOf({ served, rules, groundAt }: { readonly served: ServedLot; readonly rules: NetworkRules; readonly groundAt: GroundAt }): UtilityConnection[] {\n const { run, side, span, front, lot } = served\n const rule = rules.layout.connection\n const within = (u: number): number => Math.min(Math.max(u, span[0]), span[1])\n const centre = (span[0] + span[1]) / 2\n const at = (u: number, v: number, above: number): readonly [number, number, number] => {\n const [x, z] = worldOf({ frame: run, u: within(u), v })\n return [x, groundAt(x, z) + above, z]\n }\n const wall = side * (front + rule.frontInset)\n const sewer = at(centre, side * (front + rule.sewerInset), 0)\n const base = { lot: lot.id, frame: 'world' as const }\n return [\n { ...base, network: 'power', at: at(span[0] + rule.meterFromSide, wall, rule.powerHeight) },\n { ...base, network: 'telecom', at: at(span[0] + rule.meterFromSide, wall, rule.powerHeight - rule.telecomBelowPower) },\n { ...base, network: 'sewer', at: sewer, invert: sewer[1] - sewerDepthOf({ rules, length: front + rule.sewerInset - rules.layout.sewer.dropOffset }) },\n { ...base, network: 'storm', at: at(span[1] - rule.downspoutFromSide, side * (run.width / 2), 0) },\n { ...base, network: 'water', at: at(span[0] + rule.waterFromSide, wall, 0) },\n ]\n}\n\n/**\n * The depth of a lot's inspection box outlet: the usual one, shallower for a lot set back from its street, so its lateral still crosses\n * the gallery within `lateralOverGallery` at its least slope (never under `sewerLeastDepth`).\n */\nfunction sewerDepthOf({ rules, length }: { readonly rules: NetworkRules; readonly length: number }): number {\n const { connection, slopeMargin, coverMargin } = rules.layout\n const fits = rules.sewer.lateralOverGallery - coverMargin - (rules.minSlope.sewer_lateral + slopeMargin) * length\n return Math.max(connection.sewerLeastDepth, Math.min(connection.sewerDepth, fits))\n}\n\n/** The connections of every served lot: the ones a lot declared, and the defaults for the networks it declared none of. */\nexport type LotConnectionsParams = { readonly served: readonly ServedLot[]; readonly declared: readonly UtilityConnection[]; readonly rules: NetworkRules; readonly groundAt: GroundAt }\n\nexport function lotConnectionsOf({ served, declared, rules, groundAt }: LotConnectionsParams): UtilityConnection[] {\n const own = new Map(declared.map((connection) => [`${connection.lot}:${connection.network}`, connection]))\n return served.flatMap((entry) => defaultConnectionsOf({ served: entry, rules, groundAt }).map((fallback) => own.get(`${entry.lot.id}:${fallback.network}`) ?? fallback))\n}\n\n/** The connections of one network. */\nexport const ofNetwork = ({ connections, network }: { readonly connections: readonly UtilityConnection[]; readonly network: UtilityNetwork }): UtilityConnection[] =>\n connections.filter((connection) => connection.network === network)\n","import type { PlanRect } from '../cities/types'\nimport { ordinal, worldOf } from './frame'\nimport type { NetworkLayoutRules } from './layout-rules'\nimport type { RunEnd, ServedLot, StreetRun } from './runs'\nimport type { NetworkWarning } from './warnings'\n\n/** Where a pole stands: its id, its run, its station along it, the world point and its role (corner, end of line, in line, or a service pole inside a lot). */\nexport type PoleStation = {\n readonly id: string\n readonly run: StreetRun\n readonly side: 1 | -1\n readonly u: number\n readonly x: number\n readonly z: number\n readonly role: 'corner' | 'end' | 'line' | 'service'\n}\n\ntype PieceEnd = RunEnd | 'crossing'\ntype Piece = { readonly from: number; readonly to: number; readonly ends: readonly [PieceEnd, PieceEnd] }\n\n/** The sidewalk stretches of a run between the cross streets' roadways. */\nexport function piecesOf(run: StreetRun): Piece[] {\n const out: Piece[] = []\n let start = run.from\n let startEnd: PieceEnd = run.ends[0]\n for (const crossing of run.crossings) {\n out.push({ from: start, to: crossing.at - crossing.half, ends: [startEnd, 'crossing'] })\n start = crossing.at + crossing.half\n startEnd = 'crossing'\n }\n out.push({ from: start, to: run.to, ends: [startEnd, run.ends[1]] })\n return out.filter((piece) => piece.to - piece.from > 1)\n}\n\nexport type PoleLayoutParams = {\n readonly run: StreetRun\n readonly side: 1 | -1\n readonly served: readonly ServedLot[]\n readonly avoid: readonly PlanRect[]\n readonly rules: NetworkLayoutRules\n /** Where something must stand clear of a gate that no free ground could clear is told here. */\n readonly warn: (warning: NetworkWarning) => void\n}\n\ntype Placed = { readonly u: number; readonly role: PoleStation['role'] }\ntype Bounds = { readonly low: number; readonly high: number }\n\nconst inside = (x: number, z: number, rect: PlanRect): boolean => x > rect[0] && x < rect[2] && z > rect[1] && z < rect[3]\n\n/** The pole line of a run: `u` to the world, and whether a station is clear of every `avoid` rectangle. */\nfunction lineOf(params: PoleLayoutParams): { place: (u: number) => readonly [number, number]; isFree: (u: number) => boolean } {\n const lateral = params.side * (params.run.width / 2 + params.rules.poles.curbSetback)\n const place = (u: number): readonly [number, number] => worldOf({ frame: params.run, u, v: lateral })\n return { place, isFree: (u) => !params.avoid.some((rect) => inside(...place(u), rect)) }\n}\n\n/** The nearest free station to `u` within `bounds` (0, then ±step, ±2 steps... up to the slide), or none. */\nfunction slideClear({ u, bounds, isFree, poles }: { readonly u: number; readonly bounds: Bounds; readonly isFree: (u: number) => boolean; readonly poles: NetworkLayoutRules['poles'] }): number | undefined {\n for (let step = 0; step <= poles.slide / poles.slideStep; step++) {\n for (const offset of step === 0 ? [0] : [step * poles.slideStep, -step * poles.slideStep]) {\n const candidate = u + offset\n if (candidate >= bounds.low && candidate <= bounds.high && isFree(candidate)) return candidate\n }\n }\n return undefined\n}\n\n/**\n * The next in-line station after `at`, toward `last`: the lot boundary nearest the even target, slid clear of gates, never beyond the\n * longest span. With no free ground near the target it tries the other boundaries in reach, then any free station in reach; with none, it\n * stands at the target and warns.\n */\nfunction nextStation({ at, last, bounds, boundaries, params }: { readonly at: number; readonly last: number; readonly bounds: Bounds; readonly boundaries: readonly number[]; readonly params: PoleLayoutParams }): number {\n const { poles } = params.rules\n const { isFree } = lineOf(params)\n const target = at + (last - at) / Math.ceil((last - at) / poles.spacing[1])\n const reach: Bounds = { low: Math.max(bounds.low, at + 1), high: Math.min(bounds.high, at + poles.spacing[1]) }\n const inReach = boundaries.filter((u) => u >= reach.low && u <= reach.high).sort((a, b) => Math.abs(a - target) - Math.abs(b - target) || a - b)\n const first = inReach[0] !== undefined && Math.abs(inReach[0] - target) <= poles.snap ? inReach[0] : Math.min(Math.max(target, reach.low), reach.high)\n for (const candidate of [first, ...inReach]) {\n const slid = slideClear({ u: candidate, bounds: reach, isFree, poles })\n if (slid !== undefined) return slid\n }\n for (let u = reach.high; u >= reach.low; u -= poles.slideStep) if (isFree(u)) return u\n params.warn({ code: 'pole_on_avoid', id: `${params.run.id}@${first.toFixed(2)}` })\n return first\n}\n\n/** The stations of one stretch: a corner or end pole at each end, and in-line poles every 30 to 40 m on lot boundaries, clear of gates. */\nfunction piecePoles({ piece, params, boundaries }: { readonly piece: Piece; readonly params: PoleLayoutParams; readonly boundaries: readonly number[] }): Placed[] {\n const { poles } = params.rules\n const { isFree } = lineOf(params)\n // a corner or end pole slides inward off a gate (up to the slide), and warns when it finds no free ground\n const endAt = (end: PieceEnd, at: number, inward: 1 | -1): Placed => {\n const u = at + inward * (end === 'crossing' ? poles.curbSetback : poles.endInset)\n const role = end === 'crossing' ? 'corner' : 'end'\n for (let step = 0; step <= poles.slide / poles.slideStep; step++) {\n const candidate = u + inward * step * poles.slideStep\n if (isFree(candidate)) return { u: candidate, role }\n }\n params.warn({ code: 'pole_on_avoid', id: `${params.run.id}@${u.toFixed(2)}` })\n return { u, role }\n }\n const first = endAt(piece.ends[0], piece.from, 1)\n const last = endAt(piece.ends[1], piece.to, -1)\n if (last.u - first.u < poles.spacing[0] / 4) return [{ u: (first.u + last.u) / 2, role: first.role }]\n const bounds: Bounds = {\n low: piece.ends[0] === 'crossing' ? piece.from + poles.crossingClearance : first.u,\n high: piece.ends[1] === 'crossing' ? piece.to - poles.crossingClearance : last.u,\n }\n const out: Placed[] = [first]\n let at = first.u\n while (last.u - at > poles.spacing[1]) {\n const next = nextStation({ at, last: last.u, bounds, boundaries, params })\n if (next <= at + 1) break\n out.push({ u: next, role: 'line' })\n at = next\n }\n out.push(last)\n return out\n}\n\n/** Every pole station of a run, in order along it: corners at the cross streets, ends at the river and the line ends, in-line poles between. */\nexport function poleStationsOf(params: PoleLayoutParams): PoleStation[] {\n const { run, side } = params\n const boundaries = [...new Set(params.served.filter((entry) => entry.run.id === run.id).flatMap((entry) => [entry.span[0], entry.span[1]]))].sort((a, b) => a - b)\n const { place } = lineOf(params)\n return piecesOf(run)\n .flatMap((piece) => piecePoles({ piece, params, boundaries }))\n .map((station, index) => {\n const [x, z] = place(station.u)\n return { ...station, id: `pole:${run.id}:${ordinal(index)}`, run, side, x, z }\n })\n}\n","import type { UtilityConnection } from '@adatechnology/game-contracts'\n\nimport { frameOf, ordinal } from './frame'\nimport { dropMisfitOf, lotUnderDrop } from './drop-rules'\nimport type { LotFrontage } from './drop-rules'\nimport type { NetworkLayoutRules } from './layout-rules'\nimport type { PowerRules } from './rules'\nimport { piecesOf } from './pole-layout'\nimport type { PoleStation } from './pole-layout'\nimport type { ServedLot, StreetRun } from './runs'\nimport type { NetworkWarning } from './warnings'\n\nexport type ReachParams = {\n /** The stations of each run, in order along it. */\n readonly runs: ReadonlyArray<readonly PoleStation[]>\n /** The points the drops must reach (power and telecom anchors). */\n readonly anchors: readonly UtilityConnection[]\n readonly served: ReadonlyMap<string, ServedLot>\n /** Longest drop, metres. */\n readonly reach: number\n readonly rules: NetworkLayoutRules\n /** Clear of every gate, door and meter post. */\n readonly isFree: (x: number, z: number) => boolean\n /** Where a service pole of a lot may stand: off the roadway and out of every other lot. */\n readonly canServe: (point: { readonly x: number; readonly z: number; readonly lot: string }) => boolean\n readonly warn: (warning: NetworkWarning) => void\n /** The lots' fronts and the drop rules: a power anchor is fed from a pole in front of it or straight across, never over another lot. */\n readonly frontages: ReadonlyMap<string, LotFrontage>\n readonly power: Pick<PowerRules, 'dropMaxSkew' | 'dropFrontageSlack' | 'dropsPerPole'>\n}\n\nexport type Reached = {\n /** The stations of each run with the poles added to reach the lots, renumbered in order. */\n readonly runs: PoleStation[][]\n /** Service poles into a lot set back from its street: each chain starts at the street pole it hangs from. */\n readonly chains: PoleStation[][]\n /** The pole (where it stands) each lot's drop of each network leaves from, by `feedKey`. */\n readonly feeds: ReadonlyMap<string, { readonly x: number; readonly z: number }>\n}\n\n/** The key of a lot's drop of one network in `Reached.feeds`. */\nexport const feedKey = (anchor: Pick<UtilityConnection, 'lot' | 'network'>): string => `${anchor.lot}:${anchor.network}`\n\nconst distance = (station: PoleStation, anchor: UtilityConnection): number => Math.hypot(station.x - anchor.at[0], station.z - anchor.at[2])\n\ntype InLineParams = { readonly run: StreetRun; readonly stations: readonly PoleStation[]; readonly anchor: UtilityConnection; readonly params: ReachParams }\n\n/** An in-line station on the run's pole line at the lot's own station, inside a stretch, on free ground and `minGap` from every pole, or none. */\nfunction inLine({ run, stations, anchor, params }: InLineParams): PoleStation | undefined {\n const { poles } = params.rules\n const [u] = frameOf({ frame: run, x: anchor.at[0], z: anchor.at[2] })\n const side = stations[0]?.side ?? -1\n const lateral = side * (run.width / 2 + poles.curbSetback)\n const clear = (at: number): boolean => stations.every((station) => Math.abs(station.u - at) >= poles.minGap)\n for (const piece of piecesOf(run)) {\n const [low, high] = [piece.from + poles.crossingClearance, piece.to - poles.crossingClearance]\n if (u < piece.from || u > piece.to || high < low) continue\n for (let step = 0; step <= poles.slide / poles.slideStep; step++) {\n for (const offset of step === 0 ? [0] : [step * poles.slideStep, -step * poles.slideStep]) {\n const at = Math.min(Math.max(u + offset, low), high)\n const [x, z] = run.along === 'x' ? [at, run.axis + lateral] : [run.axis + lateral, at]\n if (params.isFree(x, z) && clear(at)) return { id: '', run, side, u: at, x, z, role: 'line' }\n }\n }\n }\n return undefined\n}\n\n/**\n * Service poles from `from` toward the anchor, evenly spaced (`gap / (count + 1)`, never past the anchor), as few as keep each span within\n * the longest and the last drop within reach. Each stands on ground a pole may take (slid along the line up to the slide); with none, the\n * lot is told out of reach and no chain is laid.\n */\nfunction chainTo({ from, anchor, params }: { readonly from: PoleStation; readonly anchor: UtilityConnection; readonly params: ReachParams }): PoleStation[] | undefined {\n const { poles } = params.rules\n const gap = distance(from, anchor)\n const count = Math.max(0, Math.ceil(gap / poles.spacing[1]) - 1, Math.ceil(gap / (params.reach - 1)) - 1)\n const out: PoleStation[] = []\n for (let index = 0; index < count; index++) {\n const even = ((index + 1) * gap) / (count + 1)\n const offsets = [0, ...Array.from({ length: Math.floor(poles.slide / poles.slideStep) }, (_, step) => [(step + 1) * poles.slideStep, -(step + 1) * poles.slideStep]).flat()]\n const spot = offsets.map((offset) => Math.min(Math.max(even + offset, 1), gap - 1) / gap).map((share) => ({ x: from.x + (anchor.at[0] - from.x) * share, z: from.z + (anchor.at[2] - from.z) * share })).find((point) => params.isFree(point.x, point.z) && params.canServe({ ...point, lot: anchor.lot }))\n if (spot === undefined) {\n params.warn({ code: 'lot_out_of_reach', id: anchor.lot, detail: `${gap.toFixed(1)} m` })\n return undefined\n }\n out.push({ ...from, id: `pole:${from.run.id}:lot:${anchor.lot}:${ordinal(index)}`, x: spot.x, z: spot.z, role: 'service' })\n }\n return out\n}\n\n/** Whether a pole may feed the anchor: in reach, in front of the lot or straight across, over no other lot. */\nexport function feedsAnchor({ station, anchor, params }: { readonly station: { readonly x: number; readonly z: number }; readonly anchor: UtilityConnection; readonly params: Pick<ReachParams, 'reach' | 'frontages' | 'power'> }): boolean {\n if (Math.hypot(station.x - anchor.at[0], station.z - anchor.at[2]) > params.reach - 1e-6) return false\n const frontage = params.frontages.get(anchor.lot)\n if (!frontage) return true\n if (dropMisfitOf({ frontage, pole: station, anchor: anchor.at, rules: params.power }) !== undefined) return false\n return lotUnderDrop({ from: [station.x, station.z], to: [anchor.at[0], anchor.at[2]], lot: anchor.lot, frontages: [...params.frontages.values()] }) === undefined\n}\n\n/**\n * Poles added where a lot's anchor has no pole to feed it (design §4): the nearest pole in front of the lot or straight across the street with\n * room for one more drop (`dropsPerPole`); with none, an in-line pole on its street at the lot's station, and when the lot stands farther back\n * than a drop, service poles into it from that pole.\n */\nexport function reachLots(params: ReachParams): Reached {\n const runs = params.runs.map((stations) => [...stations])\n const chains: PoleStation[][] = []\n const feeds = new Map<string, PoleStation>()\n const load = new Map<PoleStation, number>()\n const all = (): PoleStation[] => [...runs.flat(), ...chains.flat()]\n const take = (anchor: UtilityConnection, station: PoleStation): void => {\n feeds.set(feedKey(anchor), station)\n if (anchor.network === 'power') load.set(station, (load.get(station) ?? 0) + 1)\n }\n const free = (station: PoleStation): boolean => (load.get(station) ?? 0) < params.power.dropsPerPole\n // power first, so a telecom drop can leave the pole its lot's power drop leaves\n const anchors = [...params.anchors].sort((a, b) => (a.network === 'power' ? 0 : 1) - (b.network === 'power' ? 0 : 1))\n for (const anchor of anchors) {\n const isPower = anchor.network === 'power'\n const fits = (station: PoleStation): boolean => feedsAnchor({ station, anchor, params }) && (!isPower || free(station))\n const power = feeds.get(`${anchor.lot}:power`)\n const nearest = power !== undefined && !isPower && fits(power) ? power : all().filter(fits).sort((a, b) => distance(a, anchor) - distance(b, anchor))[0]\n if (nearest) {\n take(anchor, nearest)\n continue\n }\n const served = params.served.get(anchor.lot)\n const stations = runs.find((entry) => entry[0]?.run.id === served?.run.id)\n if (served === undefined || stations === undefined) continue\n const added = inLine({ run: served.run, stations, anchor, params })\n if (added !== undefined) stations.push(added)\n stations.sort((a, b) => a.u - b.u)\n const from = added ?? [...stations].sort((a, b) => distance(a, anchor) - distance(b, anchor))[0]\n if (from === undefined) continue\n if (distance(from, anchor) <= params.reach - 1e-6) {\n if (!fits(from)) params.warn({ code: 'drop_off_practice', id: anchor.lot, detail: 'no pole in front of the lot or straight across the street' })\n take(anchor, from)\n continue\n }\n const chain = chainTo({ from, anchor, params })\n if (chain === undefined) continue\n chains.push([from, ...chain])\n take(anchor, chain[chain.length - 1] ?? from)\n }\n const renumbered = runs.map((stations) => stations.map((station, index) => ({ ...station, id: `pole:${station.run.id}:${ordinal(index)}` })))\n return { runs: renumbered, chains, feeds: new Map([...feeds].map(([lot, station]) => [lot, { x: station.x, z: station.z }])) }\n}\n","import type { CityPlanInput, PlanLine, PlanRect } from '../cities/types'\nimport { frameOf } from './frame'\nimport type { RunAxis } from './frame'\n\n/** How a run of street ends: at the map border (the line leaves the map), at a river bank, or where the line itself ends. */\nexport type RunEnd = 'edge' | 'river' | 'line_end'\n\n/** Another run crossing this one: `at` is its axis along this run, `half` the half width of its roadway. */\nexport type RunCrossing = { readonly run: string; readonly at: number; readonly half: number }\n\n/** A straight stretch of street between two river banks or line ends, in its own frame (`u` along, `v` across). */\nexport type StreetRun = {\n readonly id: string\n readonly line: string\n readonly along: RunAxis\n /** z of a street along x, x of one along z. */\n readonly axis: number\n readonly width: number\n readonly from: number\n readonly to: number\n readonly ends: readonly [RunEnd, RunEnd]\n readonly crossings: readonly RunCrossing[]\n}\n\n/** A lot of the site: its id and its rectangle on the plan. */\nexport type NetworkLot = { readonly id: string; readonly rect: PlanRect }\n\n/** A lot and the run it faces: the side of the street, its span along the run and the distance from the axis to its front. */\nexport type ServedLot = { readonly lot: NetworkLot; readonly run: StreetRun; readonly side: 1 | -1; readonly span: readonly [number, number]; readonly front: number }\n\nconst isStreet = (line: PlanLine): boolean => line.kind === 'street' || line.kind === 'avenue'\n\ntype Segment = { readonly line: PlanLine; readonly along: RunAxis; readonly axis: number; readonly from: number; readonly to: number }\n\nfunction segmentsOf(line: PlanLine): Segment[] {\n const out: Segment[] = []\n for (let index = 1; index < line.points.length; index++) {\n const [a, b] = [line.points[index - 1], line.points[index]]\n if (a === undefined || b === undefined) continue\n if (Math.abs(a[1] - b[1]) < 1e-9) out.push({ line, along: 'x', axis: a[1], from: Math.min(a[0], b[0]), to: Math.max(a[0], b[0]) })\n else if (Math.abs(a[0] - b[0]) < 1e-9) out.push({ line, along: 'z', axis: a[0], from: Math.min(a[1], b[1]), to: Math.max(a[1], b[1]) })\n else throw new Error(`networks: the line \"${line.id}\" has a stretch that is not along x or z; the generator lays straight streets only`)\n }\n return out\n}\n\n/** The river bands a road band of `segment` meets, as intervals along it. */\nfunction riverCuts({ segment, rivers }: { readonly segment: Segment; readonly rivers: readonly Segment[] }): Array<readonly [number, number]> {\n const half = segment.line.width / 2\n return rivers.flatMap((river) => {\n const riverHalf = river.line.width / 2\n if (river.along === segment.along) return []\n const across = river.axis\n const reaches = segment.axis + half > river.from && segment.axis - half < river.to\n return reaches && across + riverHalf > segment.from && across - riverHalf < segment.to ? [[across - riverHalf, across + riverHalf] as const] : []\n })\n}\n\n/**\n * The runs of every street of the plan, cut at the rivers, with their crossings. Ids are the line's, with `_<n>` when a line makes more\n * than one. A run end within `edgeReach` of the map border is where the line leaves the map.\n */\nexport function streetRunsOf({ plan, edgeReach }: { readonly plan: CityPlanInput; readonly edgeReach: number }): StreetRun[] {\n const lines = plan.lines ?? []\n const [width, depth] = plan.size ?? [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY]\n const rivers = lines.filter((line) => line.kind === 'river').flatMap(segmentsOf)\n const isEdge = (along: RunAxis, at: number): boolean => Math.abs(at) >= (along === 'x' ? width : depth) / 2 - edgeReach\n const bare = lines.filter(isStreet).flatMap((line) => {\n const pieces = segmentsOf(line).flatMap((segment) => {\n const cuts = riverCuts({ segment, rivers }).sort((a, b) => a[0] - b[0])\n const out: Array<Omit<StreetRun, 'id' | 'crossings'>> = []\n let start = segment.from\n let startEnd: RunEnd = isEdge(segment.along, segment.from) ? 'edge' : 'line_end'\n for (const [cutFrom, cutTo] of cuts) {\n if (cutFrom > start) out.push({ line: line.id, along: segment.along, axis: segment.axis, width: line.width, from: start, to: cutFrom, ends: [startEnd, 'river'] })\n start = Math.max(start, cutTo)\n startEnd = 'river'\n }\n if (segment.to > start) out.push({ line: line.id, along: segment.along, axis: segment.axis, width: line.width, from: start, to: segment.to, ends: [startEnd, isEdge(segment.along, segment.to) ? 'edge' : 'line_end'] })\n return out\n })\n return pieces.map((piece, index) => ({ ...piece, id: pieces.length > 1 ? `${line.id}_${index}` : line.id }))\n })\n return bare.map((run) => ({ ...run, crossings: crossingsOf({ run, runs: bare }) }))\n}\n\n/**\n * The runs whose roadway this run meets: a street that crosses it, and a street it ends at or that ends at it (a T junction), so no pole\n * stands inside another street's roadway and the end at a T is a corner.\n */\nfunction crossingsOf({ run, runs }: { readonly run: Omit<StreetRun, 'crossings'>; readonly runs: ReadonlyArray<Omit<StreetRun, 'crossings'>> }): RunCrossing[] {\n return runs\n .filter((other) => other.along !== run.along && other.axis + other.width / 2 > run.from && other.axis - other.width / 2 < run.to)\n .filter((other) => other.from <= run.axis + run.width / 2 && other.to >= run.axis - run.width / 2)\n .map((other) => ({ run: other.id, at: other.axis, half: other.width / 2 }))\n .sort((a, b) => a.at - b.at)\n}\n\n/** Distance from a lot's rectangle to a run's axis segment, and the lot in the run's frame. */\nfunction servedBy({ lot, run }: { readonly lot: NetworkLot; readonly run: StreetRun }): ServedLot & { readonly distance: number } {\n const [x0, z0, x1, z1] = lot.rect\n const [ua, va] = frameOf({ frame: run, x: x0, z: z0 })\n const [ub, vb] = frameOf({ frame: run, x: x1, z: z1 })\n const [u0, u1, v0, v1] = [Math.min(ua, ub), Math.max(ua, ub), Math.min(va, vb), Math.max(va, vb)]\n const side: 1 | -1 = v0 + v1 >= 0 ? 1 : -1\n const front = side > 0 ? Math.max(0, v0) : Math.max(0, -v1)\n const du = Math.max(0, run.from - u1, u0 - run.to)\n return { lot, run, side, span: [u0, u1], front, distance: Math.hypot(du, front) }\n}\n\n/** Each lot and the run it faces: the nearest (the first of the plan on a tie). */\nexport function servedLotsOf({ lots, runs }: { readonly lots: readonly NetworkLot[]; readonly runs: readonly StreetRun[] }): ServedLot[] {\n return lots.flatMap((lot) => {\n let best: (ServedLot & { readonly distance: number }) | undefined\n for (const run of runs) {\n const candidate = servedBy({ lot, run })\n if (best === undefined || candidate.distance < best.distance - 1e-9) best = candidate\n }\n if (best === undefined) return []\n const { distance: _distance, ...served } = best\n return [served]\n })\n}\n\n/** The side of each run its poles stand on: the one with more lots; on a tie the north (−z) or west (−x) side. */\nexport function poleSidesOf({ runs, served }: { readonly runs: readonly StreetRun[]; readonly served: readonly ServedLot[] }): ReadonlyMap<string, 1 | -1> {\n return new Map(\n runs.map((run) => {\n const own = served.filter((entry) => entry.run.id === run.id)\n const plus = own.filter((entry) => entry.side > 0).length\n return [run.id, plus > own.length - plus ? 1 : -1] as const\n }),\n )\n}\n","import type { PlanLine } from '../cities/types'\nimport type { NetworkSink } from './aerial'\nimport type { ChainNode } from './chain'\nimport type { GroundAt } from './connections'\nimport type { GravityPipe, LaidPipe } from './inverts'\nimport type { NetworkRules } from './rules'\nimport type { ServedLot, StreetRun } from './runs'\nimport type { NetworkEdge } from './types'\n\n/** What every buried network reads: the runs and their pole sides, the lots, the rules, the ground and the rivers. */\nexport type BuriedContext = {\n readonly runs: readonly StreetRun[]\n readonly sides: ReadonlyMap<string, 1 | -1>\n readonly served: ReadonlyMap<string, ServedLot>\n readonly rules: NetworkRules\n readonly groundAt: GroundAt\n readonly rivers: readonly PlanLine[]\n /** Half the map's width and depth: where a line without a river leaves the map. */\n readonly border: readonly [number, number]\n readonly sink: NetworkSink\n}\n\nexport type OnRun = { readonly context: BuriedContext; readonly run: StreetRun }\n\nconst sideOf = ({ context, run }: OnRun): 1 | -1 => context.sides.get(run.id) ?? -1\n\n/** The storm gallery runs beside the axis on the side of the poles; the water main under the sidewalk on the other side (they never cross a lateral together). */\nexport const galleryOffset = (on: OnRun): number => sideOf(on) * on.context.rules.layout.storm.galleryOffset\nexport function waterOffset(on: OnRun): number {\n const { sidewalk, water } = on.context.rules.layout\n return -sideOf(on) * (on.run.width / 2 + sidewalk * water.sidewalkShare)\n}\n\n/** A line reaches a cross line this far past its own run (a street ending at another). */\nexport const reachOf = (context: BuriedContext): number => Math.max(0, ...context.runs.map((run) => run.width / 2)) + context.rules.layout.sidewalk\n\nexport type TopParams = { readonly context: BuriedContext; readonly x: number; readonly z: number; readonly cover: number; readonly diameter: number }\n\n/** The highest invert a pipe of `diameter` may have at a point under its least cover (plus the margin). */\nexport function topOf({ context, x, z, cover, diameter }: TopParams): number {\n return context.groundAt(x, z) - cover - context.rules.layout.coverMargin - diameter\n}\n\n/** The mains of a set of chains, consecutive nodes in the direction of the flow. */\nexport function pipesOf({ chains, diameter, slope }: { readonly chains: readonly ChainNode[][]; readonly diameter: number; readonly slope: number }): GravityPipe[] {\n return chains.flatMap((chain) =>\n chain.slice(1).map((node, index) => {\n const from = chain[index] as ChainNode\n return { from: from.id, to: node.id, a: [from.x, from.z] as const, b: [node.x, node.z] as const, diameter, slope }\n }),\n )\n}\n\n/** Laid pipes of a set of edges (for a main that must pass under them), by the inverts of their nodes or their own. */\nexport function laidOf({ edges, sink }: { readonly edges: readonly NetworkEdge[]; readonly sink: NetworkSink }): LaidPipe[] {\n const nodes = new Map(sink.nodes.map((node) => [node.id, node]))\n return edges.flatMap((edge) => {\n const [from, to] = [nodes.get(edge.from), nodes.get(edge.to)]\n const inverts = edge.inverts ?? (from?.invert !== undefined && to?.invert !== undefined ? ([from.invert, to.invert] as const) : undefined)\n return from === undefined || to === undefined || inverts === undefined ? [] : [{ a: [from.at[0], from.at[2]] as const, b: [to.at[0], to.at[2]] as const, inverts }]\n })\n}\n\n/** Unique nodes of chains: a vertex shared by two segments is one node. */\nexport function chainNodes(chains: readonly ChainNode[][]): ChainNode[] {\n return [...new Map(chains.flat().map((node) => [node.id, node])).values()]\n}\n","import { ordinal, worldOf } from './frame'\nimport type { LineNetwork, LineSegment } from './line-network'\nimport type { StreetRun } from './runs'\n\n/** A point a branch joins a main at (a lateral's saddle, a service's tee): its run, its station along it and a key to find it again. */\nexport type ChainStop = { readonly key: string; readonly run: StreetRun; readonly u: number }\n\n/** A node of a main along a segment: a vertex of the line, a joint where a stop branches off, or a manhole that keeps the spacing. */\nexport type ChainNode = { readonly id: string; readonly x: number; readonly z: number; readonly role: 'vertex' | 'stop' | 'spaced' }\n\nexport type ChainParams = {\n readonly line: LineNetwork\n readonly prefix: string\n readonly offset: (run: StreetRun) => number\n readonly stops: readonly ChainStop[]\n /** Longest gap between two nodes that are not stops (manholes); none = no spacing. */\n readonly spacing?: number\n}\n\n/**\n * Every segment of a line as a chain of nodes in the direction of the flow, with the stops of its run inserted at their stations and\n * spaced nodes so no two non-stop nodes are farther apart than `spacing`. `joints` tells which node each stop landed on.\n */\nexport function chainsOf(params: ChainParams): { chains: ChainNode[][]; joints: Map<string, string> } {\n const joints = new Map<string, string>()\n const chains = params.line.segments.map((segment, index) => chainOf({ segment, index, params, joints }))\n return { chains, joints }\n}\n\nfunction chainOf({ segment, index, params, joints }: { readonly segment: LineSegment; readonly index: number; readonly params: ChainParams; readonly joints: Map<string, string> }): ChainNode[] {\n const { run, ua, ub } = segment\n const [low, high] = [Math.min(ua, ub), Math.max(ua, ub)]\n const place = (u: number): readonly [number, number] => worldOf({ frame: run, u, v: params.offset(run) })\n const vertex = (id: string): ChainNode => {\n const found = params.line.vertices.get(id)\n return { id, x: found?.x ?? 0, z: found?.z ?? 0, role: 'vertex' }\n }\n const points: Array<{ u: number; node: ChainNode }> = []\n for (const stop of params.stops) {\n if (stop.run.id !== run.id || stop.u < low - 1e-6 || stop.u > high + 1e-6 || joints.has(stop.key)) continue\n if (Math.abs(stop.u - ua) < 0.05) joints.set(stop.key, segment.from)\n else if (Math.abs(stop.u - ub) < 0.05) joints.set(stop.key, segment.to)\n else {\n const [x, z] = place(stop.u)\n const id = `${params.prefix}:${stop.key}`\n points.push({ u: stop.u, node: { id, x, z, role: 'stop' } })\n joints.set(stop.key, id)\n }\n }\n if (params.spacing !== undefined) {\n const parts = Math.ceil((high - low) / params.spacing - 1e-9)\n for (let part = 1; part < parts; part++) {\n const u = low + ((high - low) * part) / parts\n const [x, z] = place(u)\n points.push({ u, node: { id: `${params.prefix}:${run.id}:${ordinal(index)}:${ordinal(part - 1)}`, x, z, role: 'spaced' } })\n }\n }\n const direction = ub >= ua ? 1 : -1\n points.sort((a, b) => (a.u - b.u) * direction)\n return [vertex(segment.from), ...points.map((point) => point.node), vertex(segment.to)]\n}\n","import type { PlanLine } from '../cities/types'\nimport { ordinal } from './frame'\nimport type { LineVertex } from './line-network'\n\n/** A stretch of the interceptor, from upstream to downstream. */\nexport type InterceptorLink = { readonly from: string; readonly to: string }\n\nexport type Interceptor = {\n readonly nodes: ReadonlyArray<{ readonly id: string; readonly x: number; readonly z: number; readonly kind: 'manhole' | 'treatment' }>\n readonly links: readonly InterceptorLink[]\n}\n\n/** The river segment nearest a point, along x or z, and where it ends downstream (its last point). */\nfunction riverOf({ rivers, x, z }: { readonly rivers: readonly PlanLine[]; readonly x: number; readonly z: number }): { along: 'x' | 'z'; end: number } | undefined {\n let best: { along: 'x' | 'z'; end: number; distance: number } | undefined\n for (const river of rivers) {\n const last = river.points[river.points.length - 1]\n const before = river.points[river.points.length - 2]\n if (last === undefined || before === undefined) continue\n const along = Math.abs(last[0] - before[0]) < 1e-9 ? 'z' : 'x'\n const distance = along === 'z' ? Math.abs(x - last[0]) : Math.abs(z - last[1])\n if (best === undefined || distance < best.distance) best = { along, end: along === 'z' ? last[1] : last[0], distance }\n }\n return best\n}\n\n/**\n * The interceptors along the river banks: the mains of each bank reach the bank at their outlets (`outlets`), and one interceptor per\n * bank line runs from the farthest upstream of them along the river to where it leaves the map, at a treatment node; manholes at most\n * `spacing` apart. Outlets on the same bank line join the same interceptor.\n */\nexport type InterceptorParams = {\n /** Where the mains leave their streets: the river ends, else the one end of a line with no river. */\n readonly outlets: readonly LineVertex[]\n readonly rivers: readonly PlanLine[]\n readonly spacing: number\n /** Half the map's width and depth. */\n readonly border: readonly [number, number]\n}\n\nexport function interceptorsOf({ outlets, rivers, spacing, border }: InterceptorParams): Interceptor {\n const lines = new Map<string, { along: 'x' | 'z'; at: number; end: number; outlets: LineVertex[] }>()\n for (const outlet of outlets) {\n const river = outlet.end === 'river' ? riverOf({ rivers, x: outlet.x, z: outlet.z }) : undefined\n if (river === undefined) {\n const way = outlet.outward ?? [1, 0]\n const along = way[0] !== 0 ? 'x' : 'z'\n const end = way[0] !== 0 ? Math.max(Math.abs(outlet.x) + 1, border[0]) * Math.sign(way[0]) : Math.max(Math.abs(outlet.z) + 1, border[1]) * Math.sign(way[1])\n const at = along === 'x' ? outlet.z : outlet.x\n lines.set(`${along}:${at.toFixed(3)}:${outlet.id}`, { along: along === 'x' ? 'x' : 'z', at, end, outlets: [outlet] })\n continue\n }\n const at = river.along === 'z' ? outlet.x : outlet.z\n const key = `${river.along}:${at.toFixed(3)}`\n const line = lines.get(key) ?? { along: river.along, at, end: river.end, outlets: [] }\n line.outlets.push(outlet)\n lines.set(key, line)\n }\n const nodes: Array<Interceptor['nodes'][number]> = []\n const links: InterceptorLink[] = []\n ;[...lines.values()].forEach((line, lineIndex) => {\n const station = (vertex: { x: number; z: number }): number => (line.along === 'z' ? vertex.z : vertex.x)\n const downstream = (position: number): number => -Math.abs(line.end - position)\n const ordered = [...line.outlets].sort((a, b) => downstream(station(a)) - downstream(station(b)))\n const treatment = `sewer:treatment:${ordinal(lineIndex)}`\n const point = (position: number): { x: number; z: number } => (line.along === 'z' ? { x: line.at, z: position } : { x: position, z: line.at })\n nodes.push({ id: treatment, ...point(line.end), kind: 'treatment' })\n const stops = [...ordered.map((vertex) => ({ id: vertex.id, position: station(vertex) })), { id: treatment, position: line.end }]\n for (let index = 1; index < stops.length; index++) {\n const [from, to] = [stops[index - 1], stops[index]] as [{ id: string; position: number }, { id: string; position: number }]\n const parts = Math.max(1, Math.ceil(Math.abs(to.position - from.position) / spacing - 1e-9))\n let previous = from.id\n for (let part = 1; part < parts; part++) {\n const id = `sewer:interceptor:${ordinal(lineIndex)}:${ordinal(index - 1)}:${ordinal(part - 1)}`\n nodes.push({ id, ...point(from.position + ((to.position - from.position) * part) / parts), kind: 'manhole' })\n links.push({ from: previous, to: id })\n previous = id\n }\n links.push({ from: previous, to: to.id })\n }\n })\n return { nodes, links }\n}\n","import { segmentCrossing } from './geometry'\nimport type { PlanPoint } from './geometry'\n\n/** A pipe of a gravity main between two nodes, in the direction of the flow. */\nexport type GravityPipe = { readonly from: string; readonly to: string; readonly a: PlanPoint; readonly b: PlanPoint; readonly diameter: number; readonly slope: number }\n\n/** A pipe already laid, by its plan ends and the bottoms there: the main must pass under it. */\nexport type LaidPipe = { readonly a: PlanPoint; readonly b: PlanPoint; readonly inverts: readonly [number, number] }\n\nexport type DrainParams = {\n readonly pipes: readonly GravityPipe[]\n /** The highest invert each node may have: under its least cover. */\n readonly top: ReadonlyMap<string, number>\n /** The lowest invert each node may have (the deepest a sewer goes, an outfall above the river): a pipe that would reach under it is lifted at its upper node. */\n readonly floor?: ReadonlyMap<string, number>\n /** Pipes of other networks the mains must pass under by `separation`. */\n readonly above?: readonly LaidPipe[]\n readonly separation?: number\n}\n\n/** The inverts of the nodes, and the lifts: a node whose outgoing pipe starts again near the ground (a pumping station), with that start. */\nexport type DrainInverts = { readonly inverts: ReadonlyMap<string, number>; readonly lifts: ReadonlyMap<string, number> }\n\nconst length = (pipe: GravityPipe): number => Math.hypot(pipe.b[0] - pipe.a[0], pipe.b[1] - pipe.a[1])\n\ntype PassParams = { readonly pipes: readonly GravityPipe[]; readonly top: ReadonlyMap<string, number>; readonly floor: ReadonlyMap<string, number> }\n\n/** Inverts down the flow: each node at most its top, every pipe falling at its slope from the highest it can start, lifted where it would go under the floor. */\nfunction pass({ pipes, top, floor }: PassParams): { inverts: Map<string, number>; lifts: Map<string, number> } {\n const incoming = new Map<string, GravityPipe[]>()\n const pending = new Map<string, number>()\n for (const pipe of pipes) {\n incoming.set(pipe.to, [...(incoming.get(pipe.to) ?? []), pipe])\n pending.set(pipe.to, (pending.get(pipe.to) ?? 0) + 1)\n if (!pending.has(pipe.from)) pending.set(pipe.from, 0)\n }\n const inverts = new Map<string, number>()\n const lifts = new Map<string, number>()\n const ready = [...pending.entries()].filter(([, count]) => count === 0).map(([id]) => id).sort()\n const outgoing = new Map(pipes.map((pipe) => [pipe.from, pipe]))\n while (ready.length > 0) {\n const id = ready.shift() as string\n const lowest = floor.get(id) ?? Number.NEGATIVE_INFINITY\n const fromAbove = (incoming.get(id) ?? []).map((pipe) => {\n const reach = (lifts.get(pipe.from) ?? inverts.get(pipe.from) ?? 0) - pipe.slope * length(pipe)\n if (reach >= lowest - 1e-9 || lifts.has(pipe.from)) return reach\n lifts.set(pipe.from, top.get(pipe.from) ?? 0)\n return (lifts.get(pipe.from) ?? 0) - pipe.slope * length(pipe)\n })\n inverts.set(id, Math.min(top.get(id) ?? Number.POSITIVE_INFINITY, ...fromAbove))\n const next = outgoing.get(id)\n if (next === undefined) continue\n const left = (pending.get(next.to) ?? 1) - 1\n pending.set(next.to, left)\n if (left === 0) ready.push(next.to)\n }\n return { inverts, lifts }\n}\n\n/** For each main, the laid pipes whose plan boxes meet its own (found once, by cells of 20 m). */\nfunction crossingCandidates({ pipes, above }: { readonly pipes: readonly GravityPipe[]; readonly above: readonly LaidPipe[] }): Map<GravityPipe, LaidPipe[]> {\n const size = 20\n const cells = new Map<string, LaidPipe[]>()\n const cellsOf = (a: PlanPoint, b: PlanPoint): string[] => {\n const out: string[] = []\n for (let i = Math.floor(Math.min(a[0], b[0]) / size); i <= Math.floor(Math.max(a[0], b[0]) / size); i++) {\n for (let k = Math.floor(Math.min(a[1], b[1]) / size); k <= Math.floor(Math.max(a[1], b[1]) / size); k++) out.push(`${i},${k}`)\n }\n return out\n }\n for (const laid of above) for (const cell of cellsOf(laid.a, laid.b)) cells.set(cell, [...(cells.get(cell) ?? []), laid])\n return new Map(pipes.map((pipe) => [pipe, [...new Set(cellsOf(pipe.a, pipe.b).flatMap((cell) => cells.get(cell) ?? []))]]))\n}\n\n/**\n * The inverts of a tree of gravity mains: from the heads down, at the least slope, never above the least cover nor under the floor (a lift\n * there); then, where a main crosses a pipe laid above it, the upper end of that main is lowered until it passes `separation` under it, and the\n * flow is laid again from there.\n */\nexport function solveDrainInverts({ pipes, top, floor = new Map(), above = [], separation = 0 }: DrainParams): DrainInverts {\n const caps = new Map(top)\n const candidates = crossingCandidates({ pipes, above })\n let result = pass({ pipes, top: caps, floor })\n for (let round = 0; round < 16; round++) {\n let lowered = false\n for (const pipe of pipes) {\n for (const laid of candidates.get(pipe) ?? []) {\n const crossing = segmentCrossing(pipe.a, pipe.b, laid.a, laid.b)\n if (crossing === undefined) continue\n const need = laid.inverts[0] + (laid.inverts[1] - laid.inverts[0]) * crossing[1] - separation - pipe.diameter\n const from = result.lifts.get(pipe.from) ?? result.inverts.get(pipe.from) ?? 0\n const to = result.inverts.get(pipe.to) ?? 0\n if (from + (to - from) * crossing[0] <= need + 1e-9) continue\n // the pipe falls from its upper node, so starting it under the crossing is enough\n caps.set(pipe.from, Math.min(caps.get(pipe.from) ?? Number.POSITIVE_INFINITY, need - 1e-3))\n lowered = true\n }\n }\n if (!lowered) return result\n result = pass({ pipes, top: caps, floor })\n }\n return result\n}\n","import { ordinal, worldOf } from './frame'\nimport type { RunEnd, StreetRun } from './runs'\n\n/** A key point of a buried line: a run end, a crossing of two runs' lines, or the middle of a stretch that closes a loop. */\nexport type LineVertex = {\n readonly id: string\n readonly x: number\n readonly z: number\n readonly role: 'end' | 'crossing' | 'split'\n readonly end?: RunEnd\n /** An end: the way out of its run, as a unit step in plan (where the line would go on past the map). */\n readonly outward?: readonly [number, number]\n}\n\n/** A stretch of line on one run between two vertices, in the direction of the flow. `ua`, `ub` are the stations of `from` and `to`. */\nexport type LineSegment = { readonly run: StreetRun; readonly from: string; readonly to: string; readonly ua: number; readonly ub: number }\n\nexport type LineNetwork = { readonly vertices: ReadonlyMap<string, LineVertex>; readonly segments: readonly LineSegment[]; readonly roots: readonly string[] }\n\nexport type LineParams = {\n readonly prefix: string\n readonly runs: readonly StreetRun[]\n /** Distance of the line from the axis of each run (+ to +z or +x). */\n readonly offset: (run: StreetRun) => number\n /** A line stops this far before the river bank (the sewer's interceptor runs there). */\n readonly riverInset: number\n /** A line reaches a cross line this far past its own run's end (a street that ends at another). */\n readonly reach: number\n /** Drain lines flow to their roots (the river ends), supply lines from them (the border ends). */\n readonly flow: 'drain' | 'supply'\n}\n\ntype Station = { readonly u: number; readonly vertex: LineVertex }\n\nfunction stationsOf({ run, params }: { readonly run: StreetRun; readonly params: LineParams }): Station[] {\n const place = (u: number): readonly [number, number] => worldOf({ frame: run, u, v: params.offset(run) })\n const out: Station[] = []\n const position = run.axis + params.offset(run)\n for (const other of params.runs) {\n if (other.along === run.along) continue\n const u = other.axis + params.offset(other)\n if (u < run.from - params.reach || u > run.to + params.reach || position < other.from - params.reach || position > other.to + params.reach) continue\n const [x, z] = place(u)\n out.push({ u, vertex: { id: `${params.prefix}:x:${[run.id, other.id].sort().join(':')}`, x, z, role: 'crossing' } })\n }\n const ends: Array<readonly [number, RunEnd, string, 1 | -1]> = [\n [run.ends[0] === 'river' ? run.from + params.riverInset : run.from, run.ends[0], 'start', -1],\n [run.ends[1] === 'river' ? run.to - params.riverInset : run.to, run.ends[1], 'end', 1],\n ]\n for (const [u, end, name, way] of ends) {\n if (out.some((station) => Math.abs(station.u - u) < 0.5)) continue\n const [x, z] = place(u)\n const outward: readonly [number, number] = run.along === 'x' ? [way, 0] : [0, way]\n out.push({ u, vertex: { id: `${params.prefix}:${run.id}:${name}`, x, z, role: 'end', end, outward } })\n }\n return out.sort((a, b) => a.u - b.u)\n}\n\ntype Link = { readonly run: StreetRun; readonly a: Station; readonly b: Station }\n\n/** The lines of every run joined at their crossings, as a tree toward (drain) or from (supply) the roots; a stretch that would close a loop is split in its middle. */\nexport function lineNetworkOf(params: LineParams): LineNetwork {\n const vertices = new Map<string, LineVertex>()\n const links: Link[] = []\n for (const run of params.runs) {\n const stations = stationsOf({ run, params })\n for (const station of stations) if (!vertices.has(station.vertex.id)) vertices.set(station.vertex.id, station.vertex)\n for (let index = 1; index < stations.length; index++) links.push({ run, a: stations[index - 1] as Station, b: stations[index] as Station })\n }\n const roots = rootsOf({ vertices, links, flow: params.flow })\n const parent = shortestTree({ roots, links })\n const segments: LineSegment[] = []\n let splits = 0\n for (const link of links) {\n const [a, b] = [link.a.vertex.id, link.b.vertex.id]\n const toward = (from: Station, to: Station): LineSegment =>\n params.flow === 'drain' ? { run: link.run, from: from.vertex.id, to: to.vertex.id, ua: from.u, ub: to.u } : { run: link.run, from: to.vertex.id, to: from.vertex.id, ua: to.u, ub: from.u }\n if (parent.get(a) === b) segments.push(toward(link.a, link.b))\n else if (parent.get(b) === a) segments.push(toward(link.b, link.a))\n else {\n const u = (link.a.u + link.b.u) / 2\n const [x, z] = worldOf({ frame: link.run, u, v: params.offset(link.run) })\n const middle: Station = { u, vertex: { id: `${params.prefix}:${link.run.id}:split:${ordinal(splits++)}`, x, z, role: 'split' } }\n vertices.set(middle.vertex.id, middle.vertex)\n segments.push(toward(middle, link.a), toward(middle, link.b))\n }\n }\n return { vertices, segments, roots }\n}\n\ntype Graph = { readonly vertices: ReadonlyMap<string, LineVertex>; readonly links: readonly Link[] }\n\nfunction componentsOf({ vertices, links }: Graph): string[][] {\n const near = new Map<string, string[]>()\n for (const link of links) {\n near.set(link.a.vertex.id, [...(near.get(link.a.vertex.id) ?? []), link.b.vertex.id])\n near.set(link.b.vertex.id, [...(near.get(link.b.vertex.id) ?? []), link.a.vertex.id])\n }\n const seen = new Set<string>()\n const out: string[][] = []\n for (const id of vertices.keys()) {\n if (seen.has(id)) continue\n const group: string[] = []\n const pending = [id]\n while (pending.length > 0) {\n const next = pending.pop() as string\n if (seen.has(next)) continue\n seen.add(next)\n group.push(next)\n pending.push(...(near.get(next) ?? []))\n }\n out.push(group)\n }\n return out\n}\n\n/** Drain: every river end of a group (else its first border end, else its first vertex); supply: the first border end of a group (else its first vertex). */\nfunction rootsOf({ vertices, links, flow }: Graph & { readonly flow: 'drain' | 'supply' }): string[] {\n return componentsOf({ vertices, links }).flatMap((group) => {\n const ends = (end: RunEnd): string[] => group.filter((id) => vertices.get(id)?.end === end)\n const river = flow === 'drain' ? ends('river') : []\n if (river.length > 0) return river\n return [ends('edge')[0] ?? (group[0] as string)]\n })\n}\n\n/** Each vertex's next vertex toward its nearest root, by line length (ties by id). */\nfunction shortestTree({ roots, links }: { readonly roots: readonly string[]; readonly links: readonly Link[] }): Map<string, string> {\n const near = new Map<string, Array<readonly [Station, Station]>>()\n for (const link of links) {\n near.set(link.a.vertex.id, [...(near.get(link.a.vertex.id) ?? []), [link.a, link.b]])\n near.set(link.b.vertex.id, [...(near.get(link.b.vertex.id) ?? []), [link.b, link.a]])\n }\n const distance = new Map(roots.map((root) => [root, 0]))\n const parent = new Map<string, string>()\n const done = new Set<string>()\n for (;;) {\n const open = [...distance.entries()].filter(([id]) => !done.has(id)).sort((a, b) => a[1] - b[1] || (a[0] < b[0] ? -1 : 1))[0]\n if (open === undefined) return parent\n const [id, base] = open\n done.add(id)\n for (const [here, there] of near.get(id) ?? []) {\n if (done.has(there.vertex.id)) continue\n const length = base + Math.abs(there.u - here.u)\n if (length >= (distance.get(there.vertex.id) ?? Number.POSITIVE_INFINITY)) continue\n distance.set(there.vertex.id, length)\n parent.set(there.vertex.id, id)\n }\n }\n}\n","import type { UtilityConnection } from '@adatechnology/game-contracts'\n\nimport { chainNodes, laidOf, pipesOf, reachOf, topOf, waterOffset } from './buried'\nimport type { BuriedContext } from './buried'\nimport { chainsOf } from './chain'\nimport type { ChainNode, ChainStop } from './chain'\nimport { frameOf, worldOf } from './frame'\nimport { interceptorsOf } from './interceptor'\nimport { solveDrainInverts } from './inverts'\nimport type { GravityPipe } from './inverts'\nimport { lineNetworkOf } from './line-network'\nimport type { LineVertex } from './line-network'\nimport type { NetworkEdge, NetworkNode } from './types'\n\ntype Lateral = { readonly connection: UtilityConnection; readonly drop: NetworkNode; readonly key: string; readonly u: number }\ntype OnLot = { readonly context: BuriedContext; readonly connection: UtilityConnection }\n\n/**\n * The drop of a lot's lateral: a cleanout `dropOffset` from the axis on the lot's side. The lateral falls to it at its least slope, and\n * deeper where it must pass under the water main (on the side opposite the poles); on the side of the poles it stays shallow over the gallery.\n */\nfunction lateralOf({ context, connection }: OnLot): Lateral | undefined {\n const served = context.served.get(connection.lot)\n if (served === undefined || connection.invert === undefined) return undefined\n const { run, side } = served\n const { sewer, slopeMargin, water, coverMargin } = context.rules.layout\n const [u, v] = frameOf({ frame: run, x: connection.at[0], z: connection.at[2] })\n const length = Math.abs(v) - sewer.dropOffset\n let fall = (context.rules.minSlope.sewer_lateral + slopeMargin) * length\n const main = waterOffset({ context, run })\n if (Math.sign(main) === side && Math.abs(main) < Math.abs(v) && Math.abs(main) > sewer.dropOffset) {\n const share = (Math.abs(v) - Math.abs(main)) / length\n const [x, z] = worldOf({ frame: run, u, v: main })\n const need = topOf({ context, x, z, cover: context.rules.cover.water_main.min, diameter: water.mainDiameter }) - context.rules.crossing.separation - sewer.lateralDiameter - coverMargin\n fall = Math.max(fall, (connection.invert - need) / share)\n }\n const [x, z] = worldOf({ frame: run, u, v: side * sewer.dropOffset })\n const id = `sewer:drop:${connection.lot}`\n return { connection, u, key: `saddle:${connection.lot}`, drop: { id, kind: 'cleanout', at: [x, context.groundAt(x, z), z], invert: connection.invert - fall, carries: ['sewer'], spec: 'drop' } }\n}\n\ntype Kinds = { readonly roots: ReadonlySet<string>; readonly heads: ReadonlySet<string>; readonly lifts: ReadonlyMap<string, number>; readonly treatments: ReadonlySet<string> }\n\nfunction kindOf({ node, kinds }: { readonly node: ChainNode; readonly kinds: Kinds }): Pick<NetworkNode, 'kind' | 'spec'> {\n if (kinds.treatments.has(node.id)) return { kind: 'treatment', spec: 'treatment_plant' }\n if (kinds.lifts.has(node.id)) return { kind: 'pumping_station', spec: 'lift' }\n if (node.role === 'stop') return { kind: 'splice', spec: 'saddle' }\n if (kinds.heads.has(node.id) && !kinds.roots.has(node.id)) return { kind: 'cleanout', spec: 'terminal' }\n return { kind: 'manhole', spec: 'pv_600' }\n}\n\n/** The mains of the streets and the interceptors, with each node's place. */\nfunction mainsOf({ context, laterals }: { readonly context: BuriedContext; readonly laterals: readonly Lateral[] }) {\n const { rules } = context\n const { sewer, slopeMargin } = rules.layout\n const line = lineNetworkOf({ prefix: 'sewer', runs: context.runs, offset: () => 0, riverInset: sewer.interceptorOffset, reach: reachOf(context), flow: 'drain' })\n const stops: ChainStop[] = laterals.flatMap((lateral) => {\n const served = context.served.get(lateral.connection.lot)\n return served === undefined ? [] : [{ key: lateral.key, run: served.run, u: lateral.u }]\n })\n const { chains, joints } = chainsOf({ line, prefix: 'sewer', offset: () => 0, stops, spacing: rules.sewer.manholeSpacing })\n const outlets = line.roots.flatMap((id) => [line.vertices.get(id)].filter((vertex): vertex is LineVertex => vertex !== undefined))\n const interceptor = interceptorsOf({ outlets, rivers: context.rivers, spacing: rules.sewer.manholeSpacing, border: context.border })\n const slope = rules.minSlope.sewer_main + slopeMargin\n const nodes: ChainNode[] = [...chainNodes(chains), ...interceptor.nodes.map((node) => ({ id: node.id, x: node.x, z: node.z, role: 'vertex' as const }))]\n const where = new Map(nodes.map((node) => [node.id, node]))\n const pipes: GravityPipe[] = [\n ...pipesOf({ chains, diameter: sewer.mainDiameter, slope }),\n ...interceptor.links.map((link) => {\n const [a, b] = [where.get(link.from), where.get(link.to)]\n return { from: link.from, to: link.to, a: [a?.x ?? 0, a?.z ?? 0] as const, b: [b?.x ?? 0, b?.z ?? 0] as const, diameter: sewer.mainDiameter, slope }\n }),\n ]\n const treatments = new Set(interceptor.nodes.filter((node) => node.kind === 'treatment').map((node) => node.id))\n return { line, nodes, where, pipes, joints, treatments }\n}\n\n/**\n * The sewer: a DN 150 main under the axis of every street, falling to the river bank (a cleanout at each dry head, a manhole at every\n * crossing and at most 80 m apart), an interceptor along each bank to a treatment node where the river leaves the map (with no river, from\n * the line's end to the border); a pumping station where a main would go deeper than the rules allow; every lot's lateral from its\n * inspection box over the gallery (or under the water main) down to a saddle on the main. The mains pass under `above`.\n */\nexport function laySewer({ context, connections, above }: { readonly context: BuriedContext; readonly connections: readonly UtilityConnection[]; readonly above: readonly NetworkEdge[] }): void {\n const { rules, sink } = context\n const { sewer, slopeMargin, coverMargin } = rules.layout\n const laterals = connections.flatMap((connection) => lateralOf({ context, connection }) ?? [])\n const { line, nodes, where, pipes, joints, treatments } = mainsOf({ context, laterals })\n const top = new Map(nodes.map((node) => [node.id, topOf({ context, x: node.x, z: node.z, cover: rules.sewer.coverUnderGallery, diameter: sewer.mainDiameter })]))\n const floor = new Map(nodes.map((node) => [node.id, context.groundAt(node.x, node.z) - rules.sewer.maxDepth + coverMargin]))\n for (const lateral of laterals) {\n const joint = joints.get(lateral.key) as string\n const target = where.get(joint)\n const length = target === undefined ? 0 : Math.hypot(target.x - lateral.drop.at[0], target.z - lateral.drop.at[2])\n const highest = (lateral.drop.invert ?? 0) - (rules.minSlope.sewer_lateral + slopeMargin) * length - sewer.mainDiameter\n top.set(joint, Math.min(top.get(joint) ?? Number.POSITIVE_INFINITY, highest))\n }\n const { inverts, lifts } = solveDrainInverts({ pipes, top, floor, above: laidOf({ edges: above, sink }), separation: rules.crossing.separation + coverMargin })\n const fed = new Set(pipes.map((pipe) => pipe.to))\n const heads = new Set(pipes.filter((pipe) => !fed.has(pipe.from)).map((pipe) => pipe.from))\n const kinds: Kinds = { roots: new Set(line.roots), heads, lifts, treatments }\n for (const node of nodes) {\n const ground = context.groundAt(node.x, node.z)\n sink.nodes.push({ id: node.id, ...kindOf({ node, kinds }), at: [node.x, ground, node.z], invert: inverts.get(node.id) ?? ground, carries: ['sewer'] })\n }\n for (const pipe of pipes) {\n const lift = lifts.get(pipe.from)\n sink.edges.push({ id: `${pipe.from}>${pipe.to}`, kind: 'sewer_main', from: pipe.from, to: pipe.to, diameter: sewer.mainDiameter, ...(lift === undefined ? {} : { inverts: [lift, inverts.get(pipe.to) ?? 0] as const }) })\n }\n for (const lateral of laterals) {\n const { connection, drop } = lateral\n const joint = joints.get(lateral.key) as string\n const lot = `lot:${connection.lot}:sewer`\n sink.nodes.push({ id: lot, kind: 'connection', at: connection.at, invert: connection.invert, carries: ['sewer'], lot: connection.lot }, drop)\n sink.edges.push({ id: `sewer:lateral:${connection.lot}`, kind: 'sewer_lateral', from: lot, to: drop.id, diameter: sewer.lateralDiameter })\n sink.edges.push({ id: `${drop.id}>${joint}`, kind: 'sewer_lateral', from: drop.id, to: joint, diameter: sewer.lateralDiameter, inverts: [drop.invert ?? 0, (inverts.get(joint) ?? 0) + sewer.mainDiameter] })\n }\n}\n","import type { UtilityConnection } from '@adatechnology/game-contracts'\n\nimport { chainNodes, galleryOffset, pipesOf, reachOf, topOf } from './buried'\nimport type { BuriedContext } from './buried'\nimport { chainsOf } from './chain'\nimport type { ChainStop } from './chain'\nimport { frameOf, ordinal, worldOf } from './frame'\nimport { solveDrainInverts } from './inverts'\nimport { lineNetworkOf } from './line-network'\nimport { piecesOf } from './pole-layout'\nimport type { StreetRun } from './runs'\nimport type { NetworkEdge, NetworkNode } from './types'\n\ntype Inlet = { readonly id: string; readonly key: string; readonly run: StreetRun; readonly curb: 1 | -1; readonly u: number; readonly node: NetworkNode }\n\n/** Inlets on both kerbs of every stretch: one at each corner (or end) and at most `inletSpacing` apart between. */\nfunction inletsOf(context: BuriedContext): Inlet[] {\n const { storm, coverMargin } = context.rules.layout\n const depth = context.rules.cover.storm_lateral.min + coverMargin + storm.lateralDiameter\n return context.runs.flatMap((run) =>\n piecesOf(run).flatMap((piece, pieceIndex) =>\n ([-1, 1] as const).flatMap((curb) => {\n const [from, to] = [piece.from + storm.inletFromCorner, piece.to - storm.inletFromCorner]\n const gaps = Math.max(1, Math.ceil((to - from) / storm.inletSpacing - 1e-9))\n return Array.from({ length: gaps + 1 }, (_, index): Inlet => {\n const u = from + ((to - from) * index) / gaps\n const [x, z] = worldOf({ frame: run, u, v: curb * (run.width / 2 - storm.inletSetback) })\n const key = `inlet:${run.id}:${curb > 0 ? 'plus' : 'minus'}:${ordinal(pieceIndex)}:${ordinal(index)}`\n const ground = context.groundAt(x, z)\n return { id: `storm:${key}`, key, run, curb, u, node: { id: `storm:${key}`, kind: 'inlet', at: [x, ground, z], invert: ground - depth, carries: ['storm'], spec: 'grated_inlet' } }\n })\n }),\n ),\n )\n}\n\n/**\n * The drainage: a gallery beside the axis of every street on the side of the poles, to a headwall on the river bank (else the border), its\n * bottom above the river (a lift where the gallery would reach under it); inlets on both kerbs with a lateral each to the gallery, and every\n * lot's downspout outlet down the gutter to the nearest inlet of its kerb. Returns the edges laid, for the sewer that passes under them.\n */\nexport function layStorm({ context, connections }: { readonly context: BuriedContext; readonly connections: readonly UtilityConnection[] }): NetworkEdge[] {\n const { rules, sink } = context\n const { storm, slopeMargin, coverMargin } = rules.layout\n const offset = (run: StreetRun): number => galleryOffset({ context, run })\n const line = lineNetworkOf({ prefix: 'storm', runs: context.runs, offset, riverInset: 0, reach: reachOf(context), flow: 'drain' })\n const inlets = inletsOf(context)\n const stops: ChainStop[] = inlets.map((inlet) => ({ key: inlet.key, run: inlet.run, u: inlet.u }))\n const { chains, joints } = chainsOf({ line, prefix: 'storm:gallery', offset, stops, spacing: rules.sewer.manholeSpacing })\n const nodes = chainNodes(chains)\n const where = new Map(nodes.map((node) => [node.id, node]))\n const top = new Map(nodes.map((node) => [node.id, topOf({ context, x: node.x, z: node.z, cover: rules.cover.storm_gallery.min, diameter: storm.galleryDiameter })]))\n const roots = new Set(line.roots)\n // a gallery no deeper than a sewer main can pass under it and still run to its next manhole within the deepest a sewer goes; an outfall above the river\n const sewerRun = (rules.minSlope.sewer_main + slopeMargin) * rules.sewer.manholeSpacing\n const deepest = rules.sewer.maxDepth - rules.layout.sewer.mainDiameter - rules.crossing.separation - 3 * coverMargin - sewerRun\n const floor = new Map(nodes.map((node) => [node.id, Math.max(context.groundAt(node.x, node.z) - deepest, roots.has(node.id) ? storm.riverLevel + coverMargin : Number.NEGATIVE_INFINITY)]))\n const laterals = inlets.map((inlet) => {\n const joint = joints.get(inlet.key) as string\n const target = where.get(joint)\n const length = target === undefined ? 0 : Math.hypot(target.x - inlet.node.at[0], target.z - inlet.node.at[2])\n const end = (inlet.node.invert ?? 0) - (rules.minSlope.storm_lateral + slopeMargin) * length\n top.set(joint, Math.min(top.get(joint) ?? Number.POSITIVE_INFINITY, end))\n return { inlet, joint, end }\n })\n const pipes = pipesOf({ chains, diameter: storm.galleryDiameter, slope: rules.minSlope.storm_gallery + slopeMargin })\n const { inverts, lifts } = solveDrainInverts({ pipes, top, floor })\n for (const node of nodes) {\n const ground = context.groundAt(node.x, node.z)\n const kind = roots.has(node.id) ? ({ kind: 'outfall', spec: 'headwall' } as const) : lifts.has(node.id) ? ({ kind: 'pumping_station', spec: 'storm_lift' } as const) : ({ kind: 'manhole', spec: 'gallery_box' } as const)\n sink.nodes.push({ id: node.id, ...kind, at: [node.x, ground, node.z], invert: inverts.get(node.id) ?? ground, carries: ['storm'] })\n }\n const edges: NetworkEdge[] = pipes.map((pipe) => {\n const lift = lifts.get(pipe.from)\n return { id: `${pipe.from}>${pipe.to}`, kind: 'storm_gallery', from: pipe.from, to: pipe.to, diameter: storm.galleryDiameter, ...(lift === undefined ? {} : { inverts: [lift, inverts.get(pipe.to) ?? 0] as const }) }\n })\n for (const { inlet, joint, end } of laterals) {\n sink.nodes.push(inlet.node)\n edges.push({ id: `storm:lateral:${inlet.key}`, kind: 'storm_lateral', from: inlet.id, to: joint, diameter: storm.lateralDiameter, inverts: [inlet.node.invert ?? 0, end] })\n }\n edges.push(...gutters({ context, connections, inlets }))\n sink.edges.push(...edges)\n return edges\n}\n\n/** Each lot's downspout outlet at the kerb, down the gutter to the nearest inlet of the same kerb of its street. */\nfunction gutters({ context, connections, inlets }: { readonly context: BuriedContext; readonly connections: readonly UtilityConnection[]; readonly inlets: readonly Inlet[] }): NetworkEdge[] {\n const slope = context.rules.minSlope.storm_gutter + context.rules.layout.slopeMargin\n return connections.flatMap((connection) => {\n const served = context.served.get(connection.lot)\n if (served === undefined) return []\n const [u] = frameOf({ frame: served.run, x: connection.at[0], z: connection.at[2] })\n const own = inlets.filter((inlet) => inlet.run.id === served.run.id && inlet.curb === served.side)\n const inlet = [...own].sort((a, b) => Math.abs(a.u - u) - Math.abs(b.u - u))[0]\n if (inlet === undefined) return []\n const node = `lot:${connection.lot}:storm`\n context.sink.nodes.push({ id: node, kind: 'connection', at: connection.at, carries: ['storm'], lot: connection.lot })\n const length = Math.hypot(inlet.node.at[0] - connection.at[0], inlet.node.at[2] - connection.at[2])\n return [{ id: `storm:gutter:${connection.lot}`, kind: 'storm_gutter', from: node, to: inlet.id, diameter: 0, inverts: [connection.at[1], inlet.node.at[1] - slope * length] } satisfies NetworkEdge]\n })\n}\n","import type { UtilityConnection } from '@adatechnology/game-contracts'\n\nimport { poleAt, poleFinder } from './aerial'\nimport type { NetworkSink, PoleHeights } from './aerial'\nimport { countOf } from './frame'\nimport type { NetworkPole, PoleTree } from './pole-tree'\nimport type { NetworkRules } from './rules'\n\nexport type TelecomParams = {\n readonly tree: PoleTree\n readonly connections: readonly UtilityConnection[]\n readonly rules: NetworkRules\n readonly heights: PoleHeights\n readonly seed: number\n /** The periphery (a bundle of 3 to 5 cables) or a clean district (1 or 2), at a point. */\n readonly isPeriphery: (x: number, z: number) => boolean\n /** The pole each lot's power drop leaves from: its telecom drop leaves the same pole. */\n readonly feeds: ReadonlyMap<string, { readonly x: number; readonly z: number }>\n readonly sink: NetworkSink\n}\n\n/** Cables of the bundle that reaches a pole: one draw per run, by the hash of the seed and the run (the same street keeps its bundle). */\nexport function cablesAt({ pole, rules, seed, isPeriphery }: Pick<TelecomParams, 'rules' | 'seed' | 'isPeriphery'> & { readonly pole: NetworkPole }): number {\n const { cables } = rules.layout.telecom\n return countOf({ seed, id: `telecom:${pole.station.run.id}`, range: isPeriphery(pole.station.x, pole.station.z) ? cables.periphery : cables.clean })\n}\n\n/**\n * The telecom bundle over every system's poles from its feed, on the top cable of the telecom band, with a splice box and reserve coil\n * every few spans (on the span into the pole, near it), and a drop from the nearest pole to every lot.\n */\nexport function layTelecom(params: TelecomParams): void {\n const { tree, heights, rules, sink } = params\n const { sag, telecom } = rules.layout\n for (const system of tree.systems) {\n const feed = `feed:telecom:${system.root}`\n sink.nodes.push({ id: feed, kind: 'feed', at: [system.feed[0], heights.telecom, system.feed[1]], carries: ['telecom'] })\n for (const id of system.poles) {\n const pole = tree.poles.get(id) as NetworkPole\n const up = system.parent.get(id)\n const conductors = cablesAt({ pole, rules, seed: params.seed, isPeriphery: params.isPeriphery })\n const depth = system.depth.get(id) ?? 0\n if (up === undefined || depth % telecom.spliceEvery !== 0) {\n sink.edges.push({ id: `telecom:${id}`, kind: 'telecom_span', from: up ?? feed, to: id, sag: sag.telecom, heights: [heights.telecom, heights.telecom], conductors })\n continue\n }\n const parent = tree.poles.get(up) as NetworkPole\n const length = Math.hypot(parent.station.x - pole.station.x, parent.station.z - pole.station.z)\n const share = Math.min(0.5, 0.6 / Math.max(length, 1e-9))\n const splice = `splice:${id}`\n const at: readonly [number, number, number] = [pole.station.x + (parent.station.x - pole.station.x) * share, heights.telecom, pole.station.z + (parent.station.z - pole.station.z) * share]\n sink.nodes.push({ id: splice, kind: 'splice', at, carries: ['telecom'], spec: 'splice_reserve' })\n sink.edges.push({ id: `telecom:${splice}`, kind: 'telecom_span', from: up, to: splice, sag: sag.telecom, heights: [heights.telecom, heights.telecom], conductors })\n sink.edges.push({ id: `telecom:${id}`, kind: 'telecom_span', from: splice, to: id, sag: 0, heights: [heights.telecom, heights.telecom], conductors })\n }\n }\n const find = poleFinder(tree)\n for (const connection of params.connections) {\n const pole = poleAt(tree, params.feeds.get(`${connection.lot}:telecom`)) ?? find({ x: connection.at[0], z: connection.at[2], radius: rules.telecom.dropMaxLength })[0]\n if (pole === undefined) continue\n const node = `lot:${connection.lot}:telecom`\n sink.nodes.push({ id: node, kind: 'connection', at: connection.at, carries: ['telecom'], lot: connection.lot })\n sink.edges.push({ id: `telecom_drop:${connection.lot}`, kind: 'telecom_drop', from: pole.id, to: node, sag: sag.telecomDrop, heights: [heights.telecom, connection.at[1]], conductors: 1 })\n }\n}\n","import type { UtilityConnection } from '@adatechnology/game-contracts'\n\nimport { chainNodes, pipesOf, reachOf, topOf, waterOffset } from './buried'\nimport type { BuriedContext } from './buried'\nimport { chainsOf } from './chain'\nimport type { ChainNode, ChainStop } from './chain'\nimport { frameOf } from './frame'\nimport { lineNetworkOf } from './line-network'\nimport type { LineVertex } from './line-network'\nimport type { StreetRun } from './runs'\nimport type { NetworkNode } from './types'\n\n/** Kind and spec of a node of the main: the reservoir at the border, a valve at every crossing and dead end, a tee where a service leaves. */\nfunction kindOf({ node, vertex, roots }: { readonly node: ChainNode; readonly vertex: LineVertex | undefined; readonly roots: ReadonlySet<string> }): Pick<NetworkNode, 'kind' | 'spec'> {\n if (roots.has(node.id)) return { kind: 'reservoir', spec: 'reservoir' }\n if (node.role === 'stop') return { kind: 'splice', spec: 'tee' }\n return { kind: 'valve', spec: vertex?.role === 'crossing' ? 'gate_valve' : 'end_valve' }\n}\n\n/**\n * The water: a main under the sidewalk opposite the poles on every street, from a reservoir where the line enters the map (one per side of\n * a river), a valve and a hydrant at every crossing, and a service from a tee on the main to every lot's meter stand.\n */\nexport function layWater({ context, connections }: { readonly context: BuriedContext; readonly connections: readonly UtilityConnection[] }): void {\n const { rules, sink } = context\n const { water } = rules.layout\n const offset = (run: StreetRun): number => waterOffset({ context, run })\n const line = lineNetworkOf({ prefix: 'water', runs: context.runs, offset, riverInset: 0, reach: reachOf(context), flow: 'supply' })\n const stops: ChainStop[] = connections.flatMap((connection) => {\n const served = context.served.get(connection.lot)\n if (served === undefined) return []\n return [{ key: `tee:${connection.lot}`, run: served.run, u: frameOf({ frame: served.run, x: connection.at[0], z: connection.at[2] })[0] }]\n })\n const { chains, joints } = chainsOf({ line, prefix: 'water', offset, stops })\n const roots = new Set(line.roots)\n for (const node of chainNodes(chains)) {\n const ground = context.groundAt(node.x, node.z)\n sink.nodes.push({ id: node.id, ...kindOf({ node, vertex: line.vertices.get(node.id), roots }), at: [node.x, ground, node.z], invert: topOf({ context, x: node.x, z: node.z, cover: rules.cover.water_main.min, diameter: water.mainDiameter }), carries: ['water'] })\n }\n for (const pipe of pipesOf({ chains, diameter: water.mainDiameter, slope: 0 })) sink.edges.push({ id: `${pipe.from}>${pipe.to}`, kind: 'water_main', from: pipe.from, to: pipe.to, diameter: water.mainDiameter })\n for (const vertex of line.vertices.values()) if (vertex.role === 'crossing') layHydrant({ context, vertex })\n for (const connection of connections) {\n const tee = joints.get(`tee:${connection.lot}`)\n if (tee === undefined) continue\n const node = `lot:${connection.lot}:water`\n const invert = topOf({ context, x: connection.at[0], z: connection.at[2], cover: rules.cover.water_service.min, diameter: water.serviceDiameter })\n sink.nodes.push({ id: node, kind: 'connection', at: connection.at, invert, carries: ['water'], lot: connection.lot })\n sink.edges.push({ id: `water:service:${connection.lot}`, kind: 'water_service', from: tee, to: node, diameter: water.serviceDiameter })\n }\n}\n\n/** A pillar hydrant beside the valve of a crossing, on the sidewalk away from the cross street's roadway. */\nfunction layHydrant({ context, vertex }: { readonly context: BuriedContext; readonly vertex: LineVertex }): void {\n const { water } = context.rules.layout\n const run = context.runs.find((candidate) => {\n const [, v] = frameOf({ frame: candidate, x: vertex.x, z: vertex.z })\n return Math.abs(v - waterOffset({ context, run: candidate })) < 1e-6\n })\n if (run === undefined) return\n const cross = context.runs.find((candidate) => candidate.along !== run.along && Math.abs((run.along === 'x' ? vertex.x : vertex.z) - candidate.axis - waterOffset({ context, run: candidate })) < 1e-6)\n const away = cross === undefined ? 1 : Math.sign(waterOffset({ context, run: cross })) || 1\n const [x, z] = run.along === 'x' ? [vertex.x + away * water.hydrantOffset, vertex.z] : [vertex.x, vertex.z + away * water.hydrantOffset]\n const id = `water:hydrant:${vertex.id.slice('water:'.length)}`\n const ground = context.groundAt(x, z)\n context.sink.nodes.push({ id, kind: 'hydrant', at: [x, ground, z], invert: topOf({ context, x, z, cover: context.rules.cover.water_main.min, diameter: water.mainDiameter }), carries: ['water'], spec: 'pillar_hydrant' })\n context.sink.edges.push({ id: `${vertex.id}>${id}`, kind: 'water_main', from: vertex.id, to: id, diameter: water.mainDiameter })\n}\n","import type { DeepPartial, UtilityConnection } from '@adatechnology/game-contracts'\n\nimport type { CityPlanInput, PlanRect } from '../cities/types'\nimport { DISTRIBUTION } from '../pole-distribution'\nimport type { DistributionSpec } from '../pole-specs'\nimport { layPower, poleHeightsOf } from './aerial'\nimport type { NetworkSink } from './aerial'\nimport type { BuriedContext } from './buried'\nimport { lotConnectionsOf, ofNetwork } from './connections'\nimport type { LotFrontage } from './drop-rules'\nimport type { GroundAt } from './connections'\nimport { frameOf, hashOf } from './frame'\nimport { poleStationsOf } from './pole-layout'\nimport { poleTreeOf } from './pole-tree'\nimport { reachLots } from './reach'\nimport { resolveNetworkRules } from './rules'\nimport type { NetworkRules } from './rules'\nimport { poleSidesOf, servedLotsOf, streetRunsOf } from './runs'\nimport type { NetworkLot, ServedLot, StreetRun } from './runs'\nimport { laySewer } from './sewer'\nimport { layStorm } from './storm'\nimport { layTelecom } from './telecom'\nimport type { NetworkSurface, UtilityNetworks } from './types'\nimport type { NetworkWarning } from './warnings'\nimport { layWater } from './water'\n\nexport type GenerateNetworksParams = {\n readonly plan: CityPlanInput\n /** The lots of the site; each takes the networks from the street it faces. */\n readonly lots: readonly NetworkLot[]\n /** What the lots declared (`frame: 'world'`); a lot that declared none of a network gets the default point from its rectangle. */\n readonly connections?: readonly UtilityConnection[]\n /** A game's numbers over the defaults. */\n readonly rules?: DeepPartial<NetworkRules>\n /** Draws (illegal hookups, telecom bundles) come from the hash of the seed and an id, never from a scene's random. */\n readonly seed: number\n /** Ground no pole may stand on: the front of every gate and door, the meter posts. */\n readonly avoid?: readonly PlanRect[]\n /** Ground level at a point. Default 0 (the flat ground of a levelled city). */\n readonly groundAt?: GroundAt\n /** The distribution pole of the registry: its bands and its lamp's reach are read from its spec. Default `concrete_distribution`. */\n readonly pole?: { readonly id: string; readonly spec: DistributionSpec }\n}\n\nexport type GeneratedNetworks = {\n readonly networks: UtilityNetworks\n /** Every connection the networks link (the declared ones and the defaults), for `validateNetworks`. */\n readonly connections: readonly UtilityConnection[]\n /** Road, sidewalk or lot under a point, from the plan's streets: the `surfaceAt` of `validateNetworks`. */\n readonly surfaceAt: (x: number, z: number) => NetworkSurface\n /** The front of every lot on its street: the `frontages` of `validateNetworks` (the drop rules). */\n readonly frontages: readonly LotFrontage[]\n /** What the generator laid against its own rules because nothing else fit (empty for a plan it can lay). */\n readonly warnings: readonly NetworkWarning[]\n}\n\n/** What lies under a point: the roadway or the sidewalk of a street of the plan, else a lot. */\nexport function surfaceOf({ runs, sidewalk }: { readonly runs: readonly StreetRun[]; readonly sidewalk: number }): (x: number, z: number) => NetworkSurface {\n return (x, z) => {\n let surface: NetworkSurface = 'lot'\n for (const run of runs) {\n const [u, v] = frameOf({ frame: run, x, z })\n if (u < run.from || u > run.to) continue\n if (Math.abs(v) < run.width / 2) return 'road'\n if (Math.abs(v) < run.width / 2 + sidewalk) surface = 'sidewalk'\n }\n return surface\n }\n}\n\n/** Whether a point is in a district of the periphery (the last district of the plan that holds it decides). */\nfunction peripheryOf({ plan, kinds }: { readonly plan: CityPlanInput; readonly kinds: readonly string[] }): (x: number, z: number) => boolean {\n const districts = [...(plan.districts ?? [])].reverse()\n return (x, z) => {\n const holder = districts.find((district) => x >= district.rect[0] && x <= district.rect[2] && z >= district.rect[1] && z <= district.rect[3])\n return holder !== undefined && kinds.includes(holder.kind)\n }\n}\n\ntype Layout = { readonly rules: NetworkRules; readonly runs: readonly StreetRun[]; readonly served: readonly ServedLot[]; readonly sides: ReadonlyMap<string, 1 | -1>; readonly connections: UtilityConnection[] }\n\n/** The poles of every run, with the ones added to reach far lots, as a tree per feed. */\nfunction polesOf({ params, layout, sink }: { readonly params: GenerateNetworksParams; readonly layout: Layout; readonly sink: NetworkSink }) {\n const { rules, runs, served, sides } = layout\n const avoid = params.avoid ?? []\n const warn = (warning: NetworkWarning): void => void sink.warnings.push(warning)\n const stations = runs.map((run) => poleStationsOf({ run, side: sides.get(run.id) ?? -1, served, avoid, rules: rules.layout, warn }))\n const anchors = layout.connections.filter((connection) => connection.network === 'power' || connection.network === 'telecom')\n const isFree = (x: number, z: number): boolean => !avoid.some((rect) => x > rect[0] && x < rect[2] && z > rect[1] && z < rect[3])\n const surface = surfaceOf({ runs, sidewalk: rules.layout.sidewalk })\n const inside = (x: number, z: number, rect: PlanRect): boolean => x > rect[0] && x < rect[2] && z > rect[1] && z < rect[3]\n const canServe = ({ x, z, lot }: { readonly x: number; readonly z: number; readonly lot: string }): boolean =>\n surface(x, z) !== 'road' && !params.lots.some((other) => other.id !== lot && inside(x, z, other.rect))\n const reach = Math.min(rules.power.dropMaxLength, rules.telecom.dropMaxLength)\n const frontages = new Map(frontagesOf({ served, sidewalk: rules.layout.sidewalk }).map((frontage) => [frontage.lot, frontage]))\n const reached = reachLots({ runs: stations, anchors, served: new Map(served.map((entry) => [entry.lot.id, entry])), reach, rules: rules.layout, isFree, canServe, warn, frontages, power: rules.power })\n return { tree: poleTreeOf({ chains: [...reached.runs, ...reached.chains], sides, setback: rules.layout.poles.curbSetback }), feeds: reached.feeds }\n}\n\n/** The front of every lot on its street, for the drop rules (`validateNetworks`' `frontages`). */\nexport function frontagesOf({ served, sidewalk }: { readonly served: readonly ServedLot[]; readonly sidewalk: number }): LotFrontage[] {\n return served.map((entry) => ({ lot: entry.lot.id, rect: entry.lot.rect, frame: { along: entry.run.along, axis: entry.run.axis }, reach: entry.run.width / 2 + sidewalk, side: entry.side, span: entry.span }))\n}\n\n/**\n * The utility networks of a district from its city plan and the site's lots, as data: power (medium voltage from a feed where the trunk\n * leaves the map, transformers sized by the diversified demand, low voltage, a drop to every lot), a lamp on every street pole, telecom, sewer\n * to an interceptor along the river, drainage to headwalls on the bank, water from a reservoir at the border. Pure: the same input gives the same bytes.\n */\nexport function generateNetworks(params: GenerateNetworksParams): GeneratedNetworks {\n const rules = resolveNetworkRules(params.rules)\n const groundAt = params.groundAt ?? ((): number => 0)\n const runs = streetRunsOf({ plan: params.plan, edgeReach: rules.layout.edgeReach })\n const served = servedLotsOf({ lots: params.lots, runs })\n const sides = poleSidesOf({ runs, served })\n const connections = lotConnectionsOf({ served, declared: params.connections ?? [], rules, groundAt })\n const sink: NetworkSink = { nodes: [], edges: [], warnings: [] }\n const { tree, feeds } = polesOf({ params, layout: { rules, runs, served, sides, connections }, sink })\n const pole = params.pole ?? { id: 'concrete_distribution', spec: DISTRIBUTION }\n const heights = poleHeightsOf(pole.spec.slots)\n const isPeriphery = peripheryOf({ plan: params.plan, kinds: rules.layout.periphery.kinds })\n const unmetered = new Set(\n served\n .filter(({ lot }) => isPeriphery((lot.rect[0] + lot.rect[2]) / 2, (lot.rect[1] + lot.rect[3]) / 2) && hashOf({ seed: params.seed, id: `hookup:${lot.id}` }) < rules.layout.periphery.hookupShare)\n .map((entry) => entry.lot.id),\n )\n layPower({ tree, connections: ofNetwork({ connections, network: 'power' }), rules, heights, pole: { id: pole.id, lampReach: pole.spec.lamp.reach }, unmetered, feeds, sink })\n layTelecom({ tree, connections: ofNetwork({ connections, network: 'telecom' }), rules, heights, seed: params.seed, isPeriphery, feeds, sink })\n const [width, depth] = params.plan.size ?? [0, 0]\n const rivers = (params.plan.lines ?? []).filter((line) => line.kind === 'river')\n const context: BuriedContext = { runs, sides, served: new Map(served.map((entry) => [entry.lot.id, entry])), rules, groundAt, rivers, border: [width / 2, depth / 2], sink }\n const storm = layStorm({ context, connections: ofNetwork({ connections, network: 'storm' }) })\n layWater({ context, connections: ofNetwork({ connections, network: 'water' }) })\n laySewer({ context, connections: ofNetwork({ connections, network: 'sewer' }), above: storm })\n const networks: UtilityNetworks = { nodes: sink.nodes, edges: sink.edges, seed: params.seed, rules }\n return { networks, connections, surfaceAt: surfaceOf({ runs, sidewalk: rules.layout.sidewalk }), frontages: frontagesOf({ served, sidewalk: rules.layout.sidewalk }), warnings: sink.warnings }\n}\n","/** How the lamps of a street are kept: `lit` is the share of lamps that work, `flicker` the share of all lamps that work badly (a part of `lit`). The rest are burnt out. */\nexport type LampShares = { readonly lit: number; readonly flicker: number }\n\n/** One lamp: `on` for `PoleOptions.on`, `flicker` for `PoleOptions.flicker`. */\nexport type LampState = { readonly on: boolean; readonly flicker: boolean }\n\nexport type LampStateParams = { readonly seed: number; readonly x: number; readonly z: number; readonly shares: LampShares }\n\nconst UINT32 = 2 ** 32\n/** Salt of the flicker phase, so it is not the same roll as the lamp's state. */\nconst PHASE_SALT = 0x5f3759df\n\n/** The seed's 64 bits, as two 32-bit words: a large or fractional seed keeps every bit (no `| 0` truncation). */\nconst SEED_BITS = new DataView(new ArrayBuffer(8))\n\n/** FNV-1a of the seed and the spot (centimetres), into [0, 1). */\nconst hashLamp = (seed: number, x: number, z: number): number => {\n SEED_BITS.setFloat64(0, seed)\n let h = 2166136261\n for (const value of [SEED_BITS.getUint32(0), SEED_BITS.getUint32(4), Math.round(x * 100), Math.round(z * 100)]) {\n h ^= value & 0xffff\n h = Math.imul(h, 16777619)\n h ^= (value >>> 16) & 0xffff\n h = Math.imul(h, 16777619)\n }\n return (h >>> 0) / UINT32\n}\n\n/** The phase (radians, [0, 2π)) a failing lamp at `x, z` flickers on: its lens and its light share it. A drawer may round it: game-urban-three rounds it to 4 groups, so about a quarter of the failing lamps blink in step. */\nexport const flickerPhaseOf = (x: number, z: number): number => hashLamp(PHASE_SALT, x, z) * 2 * Math.PI\n\n/** Throws when the shares are not `0 <= flicker <= lit <= 1`. */\nexport function assertLampShares(shares: LampShares): void {\n const { lit, flicker } = shares\n if (!(lit >= 0 && lit <= 1)) throw new RangeError(`lamp shares: lit must be in [0, 1], got ${lit}`)\n if (!(flicker >= 0 && flicker <= lit)) throw new RangeError(`lamp shares: flicker must be in [0, lit], got ${flicker}`)\n}\n\n/**\n * Whether the lamp standing at `x, z` works, flickers or is burnt out, by a hash of the seed and the spot: the same street with the same seed keeps the same dead and failing lamps,\n * and the choice does not draw from the builder's random, so the scene around it keeps its draw order.\n */\nexport function lampStateOf({ seed, x, z, shares }: LampStateParams): LampState {\n assertLampShares(shares)\n const roll = hashLamp(seed, x, z)\n if (roll >= shares.lit) return { on: false, flicker: false }\n return { on: true, flicker: roll >= shares.lit - shares.flicker }\n}\n","import { flickerPhaseOf, lampStateOf } from '../lamps'\nimport type { LampShares, LampState } from '../lamps'\nimport type { UtilityNetworks } from './types'\n\n/** A street light of the network with the state of its lamp: `pole` is the pole its `light_feed` comes from. */\nexport type NetworkLamp = LampState & { readonly id: string; readonly pole: string; readonly at: readonly [number, number, number]; readonly flickerPhase?: number }\n\nexport type NetworkLampsParams = {\n readonly networks: UtilityNetworks\n /** The share of lamps that work and the share that flicker (the rest are burnt out). */\n readonly shares: LampShares\n /** By day every lamp is off. */\n readonly isNight: boolean\n}\n\n/**\n * Every `light` node with its lamp's state, `lampStateOf` by the network's seed and the node's place (the same draw a pole of the scene had), and\n * a failing lamp's flicker phase (`flickerPhaseOf`). A lamp is on at night when its state says so; the transformer that feeds it is T2.8f.\n */\nexport function networkLampsOf({ networks, shares, isNight }: NetworkLampsParams): NetworkLamp[] {\n const feeds = new Map(networks.edges.filter((edge) => edge.kind === 'light_feed').map((edge) => [edge.to, edge.from]))\n return networks.nodes\n .filter((node) => node.kind === 'light')\n .map((node): NetworkLamp => {\n const [x, , z] = node.at\n const state = isNight ? lampStateOf({ seed: networks.seed, x, z, shares }) : { on: false, flicker: false }\n return { id: node.id, pole: feeds.get(node.id) ?? '', at: node.at, ...state, ...(state.flicker ? { flickerPhase: flickerPhaseOf(x, z) } : {}) }\n })\n}\n","import { poleHeightsOf } from './networks/aerial'\nimport type { DistributionSpec } from './pole-specs'\n\n/** A point of a pole in its own frame: `x` toward the road (where the lamp hangs), `y` up from the ground, `z` along the line. */\nexport type PolePoint = readonly [number, number, number]\n\n/** What a piece of a distribution pole is, so a drawing can keep what another already draws (the single arm draws `arm`, `lamp` and the tank). */\nexport type HardwareRole = 'crossarm' | 'insulator' | 'lv_clamp' | 'telecom_clamp' | 'bracket' | 'bushing' | 'arm' | 'lamp' | 'tank'\n\n/** A box of the pole in its frame: `y` is the base, as the builder's boxes. */\nexport type HardwareBox = { readonly role: HardwareRole; readonly x: number; readonly y: number; readonly z: number; readonly width: number; readonly height: number; readonly depth: number; readonly color: number }\n/** An upright cylinder (the transformer tank): `y` is the base. */\nexport type HardwareCylinder = { readonly role: 'tank'; readonly x: number; readonly y: number; readonly z: number; readonly radius: number; readonly height: number; readonly color: number; readonly segments: number }\n\n/** Where each conductor is fixed on the pole, in its frame. */\nexport type PoleAttachments = {\n /** The three medium-voltage phases, on the tops of the pin insulators. */\n readonly mv: readonly PolePoint[]\n /** The low-voltage multiplexed cable in its suspension clamp. */\n readonly lv: PolePoint\n /** One clamp per telecom cable, the first on top. */\n readonly telecom: readonly PolePoint[]\n /** The transformer: its three bushing tops (medium voltage in) and the side of its tank the low voltage leaves from. */\n readonly transformer?: { readonly mv: readonly PolePoint[]; readonly lv: PolePoint }\n /** The guy wire's eye, under the crossarm. */\n readonly guy: PolePoint\n}\n\n/** The pieces and fixing points of a distribution pole. The lens is apart: its colour is the lamp's state. */\nexport type PoleHardware = { readonly boxes: readonly HardwareBox[]; readonly cylinders: readonly HardwareCylinder[]; readonly lens?: HardwareBox; readonly attachments: PoleAttachments }\n\nexport type PoleHardwareOptions = {\n /** The pole carries the medium voltage (its crossarm and insulators). */\n readonly mv: boolean\n /** A transformer hangs on it. */\n readonly transformer: boolean\n /** Its street light (arm, luminaire, lens). */\n readonly lamp: boolean\n /** Telecom cables fixed on it, `cableGap` apart (the network's `rules.layout.telecom.cableGap`). */\n readonly cables: number\n readonly cableGap: number\n}\n\n/** Least free gap between two pieces that touch (CLAUDE.md §13). */\nconst GAP = 0.002\n\n/** The crossarm and its three pin insulators, the top of each insulator in the medium-voltage band's top. */\nfunction mediumVoltage(spec: DistributionSpec): { boxes: HardwareBox[]; mv: PolePoint[] } {\n const { crossarm, insulators, slots } = spec\n const [bottom, top] = slots.bands.mv\n const pin = top - bottom - crossarm.height - GAP\n const boxes: HardwareBox[] = [{ role: 'crossarm', x: crossarm.reach, y: bottom, z: 0, width: crossarm.width, height: crossarm.height, depth: crossarm.depth, color: crossarm.color }]\n for (const x of insulators.at) boxes.push({ role: 'insulator', x, y: bottom + crossarm.height + GAP, z: 0, width: insulators.radius * 2, height: pin, depth: insulators.radius * 2, color: insulators.color })\n return { boxes, mv: insulators.at.map((x): PolePoint => [x, top, 0]) }\n}\n\n/** The tank on its bracket on the field side, under the crossarm, with three bushings on its lid. */\nfunction transformerOf(spec: DistributionSpec): { boxes: HardwareBox[]; tank: HardwareCylinder; points: NonNullable<PoleAttachments['transformer']> } {\n const t = spec.transformer\n const x = -t.offset\n const tank: HardwareCylinder = { role: 'tank', x, y: t.y, z: 0, radius: t.radius, height: t.height, color: t.color, segments: t.segments }\n const { bushings } = spec\n const lid = t.y + t.height + GAP\n const zs = [-bushings.spread, 0, bushings.spread]\n const boxes: HardwareBox[] = [\n { role: 'bracket', x: x / 2, y: t.y + t.height * 0.6, z: 0, width: t.offset, height: 0.08, depth: 0.1, color: spec.lowVoltage.color },\n ...zs.map((z): HardwareBox => ({ role: 'bushing', x, y: lid, z, width: bushings.radius * 2, height: bushings.height, depth: bushings.radius * 2, color: bushings.color })),\n ]\n return { boxes, tank, points: { mv: zs.map((z): PolePoint => [x, lid + bushings.height, z]), lv: [x + t.radius, t.y + t.height * 0.3, 0] } }\n}\n\n/** The arm over the road, the luminaire at its end and the lens under the luminaire (2 mm apart). */\nfunction lampOf(spec: DistributionSpec): { boxes: HardwareBox[]; lens: HardwareBox } {\n const { arm, lamp } = spec\n const lensHeight = 0.03\n return {\n boxes: [\n { role: 'arm', x: arm.reach, y: arm.y, z: 0, width: arm.width, height: arm.height, depth: arm.depth, color: arm.color },\n { role: 'lamp', x: lamp.reach, y: lamp.y, z: 0, width: lamp.width, height: lamp.height, depth: lamp.depth, color: arm.color },\n ],\n lens: { role: 'lamp', x: lamp.reach, y: lamp.y - lensHeight - GAP, z: 0, width: lamp.width * 0.8, height: lensHeight, depth: lamp.depth * 0.8, color: spec.lens.unlit },\n }\n}\n\n/**\n * The hardware of a distribution pole in its own frame, every fixing height read from its bands (`slots`) as the network generator reads them:\n * the crossarm with its pin insulators at the medium voltage, the transformer under it, the low-voltage cable's suspension clamp on the field\n * side, the street light's arm over the road, and one telecom clamp per cable under the lamp. Pure; the drawing places and instances it.\n */\nexport function distributionHardwareOf(spec: DistributionSpec, o: PoleHardwareOptions): PoleHardware {\n const heights = poleHeightsOf(spec.slots)\n const boxes: HardwareBox[] = []\n const cylinders: HardwareCylinder[] = []\n const mv = mediumVoltage(spec)\n if (o.mv || o.transformer) boxes.push(...mv.boxes)\n const lvAt: PolePoint = [-spec.lowVoltage.out, heights.lv, 0]\n boxes.push({ role: 'lv_clamp', x: -spec.lowVoltage.out / 2 - spec.mast.radiusTop / 2, y: heights.lv - 0.06, z: 0, width: spec.lowVoltage.out - spec.mast.radiusTop + 0.06, height: 0.12, depth: 0.08, color: spec.lowVoltage.color })\n const { telecom } = spec\n const cables = Math.max(o.cables, 0)\n const telecomAt = Array.from({ length: cables }, (_, index): PolePoint => [-telecom.out, heights.telecom - index * o.cableGap, 0])\n if (cables > 0) {\n const bottom = heights.telecom - (cables - 1) * o.cableGap - 0.05\n boxes.push({ role: 'telecom_clamp', x: -telecom.out / 2 - spec.mast.radiusTop / 2, y: bottom, z: 0, width: telecom.out - spec.mast.radiusTop + 0.04, height: heights.telecom + 0.05 - bottom, depth: 0.06, color: telecom.color })\n }\n const transformer = o.transformer ? transformerOf(spec) : undefined\n if (transformer) {\n boxes.push(...transformer.boxes)\n cylinders.push(transformer.tank)\n }\n const lamp = o.lamp ? lampOf(spec) : undefined\n if (lamp) boxes.push(...lamp.boxes)\n const attachments: PoleAttachments = { mv: mv.mv, lv: lvAt, telecom: telecomAt, guy: [0, spec.slots.bands.mv[0] - 0.15, 0], ...(transformer ? { transformer: transformer.points } : {}) }\n return { boxes, cylinders, ...(lamp ? { lens: lamp.lens } : {}), attachments }\n}\n"],"mappings":";AAKO,IAAM,eAA+D;AAAA,EAC1E,SAAS;AAAA,EACT,SAAS;AAAA,EACT,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,eAAe;AAAA,EACf,eAAe;AAAA,EACf,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,eAAe;AACjB;AAGO,IAAM,aAA8D;AAAA,EACzE,SAAS;AAAA,EACT,SAAS;AAAA,EACT,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,eAAe;AAAA,EACf,eAAe;AAAA,EACf,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,eAAe;AACjB;AAEA,IAAM,SAAuC,oBAAI,IAAoB,CAAC,WAAW,WAAW,gBAAgB,g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AY,IAAI;AAAA,EACjC;AACA,QAAM,OAAO,EAAE,OAAOA,QAAO,IAAI,IAAI;AACrC,MAAI,KAAM,OAAM,KAAK,GAAG,KAAK,KAAK;AAClC,QAAM,cAA+B,EAAE,IAAI,GAAG,IAAI,IAAI,MAAM,SAAS,WAAW,KAAK,CAAC,GAAG,KAAK,MAAM,MAAM,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,GAAI,cAAc,EAAE,aAAa,YAAY,OAAO,IAAI,CAAC,EAAG;AACxL,SAAO,EAAE,OAAO,WAAW,GAAI,OAAO,EAAE,MAAM,KAAK,KAAK,IAAI,CAAC,GAAI,YAAY;AAC/E;","names":["distance","inside","length","length","inside","length","node","open","distance","distance","id","length","groundAt","length","ofNetwork","inside","at","distance","at","distance","id","length","length","x","z","length","inlet","length","kindOf","inside","groundAt","ofNetwork","UINT32","lampOf"]}
1
+ {"version":3,"sources":["../../src/networks/classes.ts","../../src/networks/codes.ts","../../src/networks/graph.ts","../../src/networks/rules.ts","../../src/networks/layout-rules.ts","../../src/networks/slots.ts","../../src/networks/geometry.ts","../../src/networks/validate-context.ts","../../src/networks/validate-aerial.ts","../../src/networks/validate-buried.ts","../../src/networks/frame.ts","../../src/networks/drop-rules.ts","../../src/networks/validate-drops.ts","../../src/networks/validate-load.ts","../../src/networks/validate-surface.ts","../../src/networks/validate-structure.ts","../../src/networks/validate.ts","../../src/pole-distribution.ts","../../src/networks/circuits.ts","../../src/networks/pole-tree.ts","../../src/networks/aerial.ts","../../src/networks/connections.ts","../../src/networks/pole-layout.ts","../../src/networks/reach.ts","../../src/networks/runs.ts","../../src/networks/buried.ts","../../src/networks/chain.ts","../../src/networks/interceptor.ts","../../src/networks/inverts.ts","../../src/networks/line-network.ts","../../src/networks/sewer.ts","../../src/networks/storm.ts","../../src/networks/telecom.ts","../../src/networks/water.ts","../../src/networks/generate.ts","../../src/lamps.ts","../../src/networks/lamps.ts","../../src/pole-hardware.ts","../../src/networks/surface.ts","../../src/networks/pipes.ts","../../src/networks/breach.ts","../../src/networks/cover.ts","../../src/networks/leaks.ts"],"sourcesContent":["import type { UtilityNetwork } from '@adatechnology/game-contracts'\n\nimport type { AerialEdgeKind, NetworkClass, NetworkEdgeKind, NetworkKind, NetworkNodeKind } from './types'\n\n/** The network each edge belongs to. A service drop is low voltage: a lot is never linked to the medium voltage. */\nexport const EDGE_NETWORK: Readonly<Record<NetworkEdgeKind, NetworkKind>> = {\n mv_span: 'power_mv',\n lv_span: 'power_lv',\n service_drop: 'power_lv',\n light_feed: 'lighting',\n telecom_span: 'telecom',\n telecom_drop: 'telecom',\n sewer_main: 'sewer',\n sewer_lateral: 'sewer',\n storm_gallery: 'storm',\n storm_lateral: 'storm',\n storm_gutter: 'storm',\n water_main: 'water',\n water_service: 'water',\n}\n\n/** The class the rules read each edge by. */\nexport const EDGE_CLASS: Readonly<Record<NetworkEdgeKind, NetworkClass>> = {\n mv_span: 'power_mv',\n lv_span: 'power_lv',\n service_drop: 'service_drop',\n light_feed: 'street_light',\n telecom_span: 'telecom',\n telecom_drop: 'telecom',\n sewer_main: 'sewer',\n sewer_lateral: 'sewer',\n storm_gallery: 'storm',\n storm_lateral: 'storm',\n storm_gutter: 'storm',\n water_main: 'water',\n water_service: 'water',\n}\n\nconst AERIAL: ReadonlySet<NetworkEdgeKind> = new Set<AerialEdgeKind>(['mv_span', 'lv_span', 'telecom_span', 'service_drop', 'telecom_drop', 'light_feed'])\n\nexport function isAerialEdgeKind(kind: NetworkEdgeKind): kind is AerialEdgeKind {\n return AERIAL.has(kind)\n}\n\n/** The network of a street a lot connection links to: `power` takes the low voltage. */\nexport const CONNECTION_NETWORK: Readonly<Record<UtilityNetwork, NetworkKind>> = {\n power: 'power_lv',\n telecom: 'telecom',\n sewer: 'sewer',\n storm: 'storm',\n water: 'water',\n}\n\n/** Supply networks flow from their sources to the loads; drain networks flow from the houses to their destinations. */\nexport const NETWORK_FLOW: Readonly<Record<NetworkKind, 'supply' | 'drain'>> = {\n power_mv: 'supply',\n power_lv: 'supply',\n lighting: 'supply',\n telecom: 'supply',\n water: 'supply',\n sewer: 'drain',\n storm: 'drain',\n}\n\n/**\n * The nodes a network starts from (supply) or ends at (drain). The low voltage starts at the transformers the medium voltage reaches,\n * and the lighting at the low voltage nodes, so these two are resolved by the graph.\n */\nexport const NETWORK_ENDS: Readonly<Record<NetworkKind, readonly NetworkNodeKind[]>> = {\n power_mv: ['feed'],\n power_lv: ['transformer'],\n lighting: [],\n telecom: ['feed'],\n water: ['reservoir'],\n sewer: ['treatment', 'outfall'],\n storm: ['outfall'],\n}\n","/** Stable codes of what `validateNetworks` finds wrong, as the `STRUCTURAL_VIOLATION` of game-floorplan-structure. */\nexport const NETWORK_VIOLATION = {\n DUPLICATE_ID: 'duplicate_id',\n UNKNOWN_NODE: 'unknown_node',\n NOT_CARRIED: 'not_carried',\n NOT_RADIAL: 'not_radial',\n DISCONNECTED: 'disconnected',\n LOOP_AT_END: 'loop_at_end',\n CONNECTION_IN_PLAN_FRAME: 'connection_in_plan_frame',\n LOT_UNCONNECTED: 'lot_unconnected',\n LOT_CONNECTED_TWICE: 'lot_connected_twice',\n LOT_DECLARED_TWICE: 'lot_declared_twice',\n ORPHAN_CONNECTION: 'orphan_connection',\n CONNECTION_MOVED: 'connection_moved',\n DROP_TOO_LONG: 'drop_too_long',\n DROP_SKEWED: 'drop_skewed',\n DROP_OFF_FRONTAGE: 'drop_off_frontage',\n DROP_OVER_OTHER_LOT: 'drop_over_other_lot',\n POLE_TOO_MANY_DROPS: 'pole_too_many_drops',\n MISSING_SAG: 'missing_sag',\n CLEARANCE: 'clearance',\n MV_OVER_LOT: 'mv_over_lot',\n SPAN_OVER_BUILDING: 'span_over_building',\n SPAN_THROUGH_CROWN: 'span_through_crown',\n MISSING_INVERT: 'missing_invert',\n MISSING_DIAMETER: 'missing_diameter',\n SLOPE: 'slope',\n SLOPE_MISMATCH: 'slope_mismatch',\n COVER: 'cover',\n TOO_DEEP: 'too_deep',\n CROSSING_TOO_CLOSE: 'crossing_too_close',\n CROSSING_ORDER: 'crossing_order',\n LATERAL_TOO_DEEP: 'lateral_too_deep',\n MANHOLE_SPACING: 'manhole_spacing',\n PV_MISSING: 'pv_missing',\n INLET_SPACING: 'inlet_spacing',\n INLET_AT_CORNER: 'inlet_at_corner',\n BRANCH_SKEWED: 'branch_skewed',\n UNKNOWN_TRANSFORMER: 'unknown_transformer',\n TRANSFORMER_OVERLOADED: 'transformer_overloaded',\n LV_CIRCUIT_TOO_LONG: 'lv_circuit_too_long',\n} as const\n\nexport type NetworkViolationCode = (typeof NETWORK_VIOLATION)[keyof typeof NETWORK_VIOLATION]\n\n/** One finding: the id of the node, edge or lot, and the number against its limit when there is one. */\nexport type NetworkViolation = {\n readonly code: NetworkViolationCode\n readonly id: string\n readonly detail?: string\n readonly value?: number\n readonly limit?: number\n}\n","import { EDGE_NETWORK, NETWORK_ENDS, NETWORK_FLOW } from './classes'\nimport type { NetworkEdge, NetworkKind, NetworkNode } from './types'\n\n/** The networks indexed: nodes and edges by id, and the edges in and out of each node. Edges whose ends are missing are kept but link nothing. */\nexport type NetworkGraph = {\n readonly nodes: ReadonlyMap<string, NetworkNode>\n readonly edges: ReadonlyMap<string, NetworkEdge>\n /** Edges leaving a node, of one network or all. */\n outgoing(nodeId: string, network?: NetworkKind): readonly NetworkEdge[]\n /** Edges reaching a node, of one network or all. */\n incoming(nodeId: string, network?: NetworkKind): readonly NetworkEdge[]\n}\n\nconst NONE: readonly NetworkEdge[] = []\n\nconst ofNetwork = (edges: readonly NetworkEdge[] | undefined, network: NetworkKind | undefined): readonly NetworkEdge[] => {\n if (edges === undefined) return NONE\n return network === undefined ? edges : edges.filter((edge) => EDGE_NETWORK[edge.kind] === network)\n}\n\n/** Indexes nodes and edges. The first of two entries with the same id wins (the validator reports the second). */\nexport function buildNetworkGraph(input: { readonly nodes: readonly NetworkNode[]; readonly edges: readonly NetworkEdge[] }): NetworkGraph {\n const nodes = new Map<string, NetworkNode>()\n for (const node of input.nodes) if (!nodes.has(node.id)) nodes.set(node.id, node)\n const edges = new Map<string, NetworkEdge>()\n const out = new Map<string, NetworkEdge[]>()\n const into = new Map<string, NetworkEdge[]>()\n for (const edge of input.edges) {\n if (edges.has(edge.id)) continue\n edges.set(edge.id, edge)\n if (!nodes.has(edge.from) || !nodes.has(edge.to)) continue\n out.set(edge.from, [...(out.get(edge.from) ?? []), edge])\n into.set(edge.to, [...(into.get(edge.to) ?? []), edge])\n }\n return {\n nodes,\n edges,\n outgoing: (nodeId, network) => ofNetwork(out.get(nodeId), network),\n incoming: (nodeId, network) => ofNetwork(into.get(nodeId), network),\n }\n}\n\nfunction sourcesOf(graph: NetworkGraph, network: NetworkKind): string[] {\n if (network === 'lighting') return [...connectedNodes(graph, 'power_lv')]\n const kinds = NETWORK_ENDS[network]\n const ends = [...graph.nodes.values()].filter((node) => kinds.includes(node.kind) && node.carries.includes(network)).map((node) => node.id)\n if (network !== 'power_lv') return ends\n const medium = connectedNodes(graph, 'power_mv')\n return ends.filter((id) => medium.has(id))\n}\n\n/**\n * The nodes linked to their source by the edges of `network`: walked from the sources along the flow (supply), or back from the\n * destinations against it (drain). The low voltage starts only at transformers the medium voltage reaches.\n */\nexport function connectedNodes(graph: NetworkGraph, network: NetworkKind): ReadonlySet<string> {\n const reached = new Set<string>()\n const pending = sourcesOf(graph, network)\n const forward = NETWORK_FLOW[network] === 'supply'\n while (pending.length > 0) {\n const id = pending.pop() as string\n if (reached.has(id)) continue\n reached.add(id)\n const next = forward ? graph.outgoing(id, network).map((edge) => edge.to) : graph.incoming(id, network).map((edge) => edge.from)\n for (const nextId of next) if (!reached.has(nextId)) pending.push(nextId)\n }\n return reached\n}\n\n/** Horizontal length of an edge, metres (0 when an end is missing). */\nexport function edgeLength(graph: NetworkGraph, edge: NetworkEdge): number {\n const from = graph.nodes.get(edge.from)\n const to = graph.nodes.get(edge.to)\n if (from === undefined || to === undefined) return 0\n return Math.hypot(to.at[0] - from.at[0], to.at[2] - from.at[2])\n}\n\n/** The low voltage nodes a transformer feeds, with the length of line (low voltage spans; a service drop adds none) from it to each one. */\nexport function circuitOf(graph: NetworkGraph, transformerId: string): ReadonlyMap<string, number> {\n const distance = new Map<string, number>([[transformerId, 0]])\n const pending = [transformerId]\n while (pending.length > 0) {\n const id = pending.pop() as string\n const base = distance.get(id) ?? 0\n for (const edge of graph.outgoing(id, 'power_lv')) {\n if (distance.has(edge.to)) continue\n distance.set(edge.to, base + (edge.kind === 'lv_span' ? edgeLength(graph, edge) : 0))\n pending.push(edge.to)\n }\n }\n return distance\n}\n","import { deepMerge } from '@adatechnology/game-contracts'\nimport type { DeepPartial } from '@adatechnology/game-contracts'\n\nimport { DEFAULT_NETWORK_LAYOUT } from './layout-rules'\nimport type { NetworkLayoutRules } from './layout-rules'\nimport type { AerialClass, BuriedEdgeKind, NetworkSurface } from './types'\n\n/** Lowest point of a conductor over each surface, metres; `null` = the class does not go there. */\nexport type ClearanceRow = Readonly<Record<NetworkSurface, number | null>>\n\n/** A band of the diversified demand table: up to `consumers` consumers, kVA per consumer at or below the split and above it. */\nexport type DiversityBand = { readonly consumers: number; readonly low: number; readonly high: number }\n\nexport type TransformerRating = { readonly id: string; readonly kva: number }\n\nexport type PowerRules = {\n /** Longest service drop, metres (horizontal). */\n readonly dropMaxLength: number\n /** A drop that crosses the street goes straight across: its horizontal direction at most this far from the street's normal, degrees. */\n readonly dropMaxSkew: number\n /** A drop on the pole's own side comes from a pole in front of the lot: its station at most this far past the lot's frontage, metres. */\n readonly dropFrontageSlack: number\n /** Most service drops one pole holds. */\n readonly dropsPerPole: number\n /** Longest low voltage path from the transformer to its farthest node, each way, metres. */\n readonly lvCircuitMaxLength: number\n /** Highest demand over the rating. */\n readonly maxLoading: number\n readonly transformers: readonly TransformerRating[]\n /** Installed load (kVA) that splits the `low` and `high` columns of the demand table. */\n readonly installedSplitKva: number\n /** By number of consumers, ascending; the last band takes any number above. */\n readonly diversity: readonly DiversityBand[]\n}\n\n/** Cover of a pipe: from the ground down to its top, metres. */\nexport type CoverRange = { readonly min: number; readonly max?: number }\n\nexport type NetworkRules = {\n readonly clearance: Readonly<Record<AerialClass, ClearanceRow>>\n /** Samples along a span when the catenary is checked. */\n readonly catenarySamples: number\n readonly power: PowerRules\n readonly lighting: { readonly lampKva: number }\n readonly telecom: { readonly dropMaxLength: number }\n /** Least slope of each gravity pipe, m/m. */\n readonly minSlope: Readonly<Record<Extract<BuriedEdgeKind, 'sewer_main' | 'sewer_lateral' | 'storm_gallery' | 'storm_lateral' | 'storm_gutter'>, number>>\n readonly cover: Readonly<Record<BuriedEdgeKind, CoverRange>>\n readonly sewer: {\n /** Deepest invert below the ground before a pumping station is needed. */\n readonly maxDepth: number\n /** Cover of a sewer main under a street with a storm gallery (the main passes under the gallery's laterals). */\n readonly coverUnderGallery: number\n /** A storm gallery this close to a sewer main, metres in plan, puts the main under that street's rule. */\n readonly galleryReach: number\n /** Deepest bottom of a sewer lateral where it crosses a storm gallery (it goes over it). */\n readonly lateralOverGallery: number\n /** Longest sewer main between two manholes. */\n readonly manholeSpacing: number\n /** A pipe that turns more than this, degrees, or meets two others, is a manhole (a PV). */\n readonly turnTolerance: number\n /** A house lateral leaves the street's main at a right angle, within this many degrees. */\n readonly branchMaxSkew: number\n }\n readonly storm: {\n /** Longest gap between two inlets of a kerb, metres. */\n readonly inletSpacing: number\n /** Each corner of a crossing has an inlet within this distance of the crossing's gallery box, metres. */\n readonly cornerReach: number\n }\n /** Least vertical gap between two pipes that cross, and which one goes above (lower rank above). */\n readonly crossing: { readonly separation: number; readonly rank: Readonly<Record<BuriedEdgeKind, number>> }\n /** How far a connection node may sit from the point the lot declared, metres. */\n readonly connectionTolerance: number\n /** What `generateNetworks` lays out: spacing, offsets, sags, diameters (the validator reads none of it). */\n readonly layout: NetworkLayoutRules\n}\n\nconst LOW_VOLTAGE: ClearanceRow = { road: 5.5, sidewalk: 4.5, lot: 3.5 }\n\n/** Brazilian practice (NBR 15688, NBR 9649, NBR 12218 and the utilities' sharing rules), with no brand. Every number is patched by `resolveNetworkRules`. */\nexport const DEFAULT_NETWORK_RULES: NetworkRules = {\n clearance: {\n power_mv: { road: 7, sidewalk: 6, lot: null },\n power_lv: LOW_VOLTAGE,\n service_drop: LOW_VOLTAGE,\n street_light: LOW_VOLTAGE,\n telecom: { road: 5, sidewalk: 4.5, lot: 3 },\n },\n catenarySamples: 16,\n power: {\n dropMaxLength: 30,\n dropMaxSkew: 30,\n dropFrontageSlack: 0.5,\n dropsPerPole: 4,\n lvCircuitMaxLength: 200,\n maxLoading: 0.8,\n transformers: [\n { id: 't30', kva: 30 },\n { id: 't45', kva: 45 },\n { id: 't75', kva: 75 },\n { id: 't112', kva: 112.5 },\n ],\n installedSplitKva: 5,\n diversity: [\n { consumers: 5, low: 2, high: 3 },\n { consumers: 15, low: 1.5, high: 2.4 },\n { consumers: 30, low: 1.2, high: 2 },\n { consumers: 60, low: 1, high: 1.7 },\n { consumers: Number.POSITIVE_INFINITY, low: 0.9, high: 1.5 },\n ],\n },\n lighting: { lampKva: 0.15 },\n telecom: { dropMaxLength: 30 },\n minSlope: { sewer_main: 0.005, sewer_lateral: 0.01, storm_gallery: 0.005, storm_lateral: 0.005, storm_gutter: 0.005 },\n cover: {\n water_main: { min: 0.6, max: 0.8 },\n water_service: { min: 0.6, max: 0.8 },\n // the design sets no least cover for the lateral, only that it is buried and passes over a gallery (`sewer.lateralOverGallery`)\n sewer_lateral: { min: 0 },\n storm_lateral: { min: 1, max: 1.2 },\n storm_gallery: { min: 1.2 },\n // the gutter is an open channel at the kerb (diameter 0): its bottom only has to stay at or under the ground\n storm_gutter: { min: 0 },\n sewer_main: { min: 0.9 },\n },\n sewer: { maxDepth: 4.5, coverUnderGallery: 1.8, galleryReach: 3, lateralOverGallery: 0.85, manholeSpacing: 80, turnTolerance: 5, branchMaxSkew: 5 },\n storm: { inletSpacing: 60, cornerReach: 15 },\n crossing: { separation: 0.2, rank: { storm_gutter: 0, water_main: 1, water_service: 1, sewer_lateral: 2, storm_lateral: 3, storm_gallery: 3, sewer_main: 4 } },\n connectionTolerance: 0.01,\n layout: DEFAULT_NETWORK_LAYOUT,\n}\n\n/** The default rules with a game's numbers over them (objects merge, arrays such as the transformers replace). */\nexport function resolveNetworkRules(patch?: DeepPartial<NetworkRules>): NetworkRules {\n return deepMerge(DEFAULT_NETWORK_RULES, patch)\n}\n\n/**\n * kVA of the circuit's consumers by the diversified demand table: the band of their count, the column of each one's installed load. A\n * consumer whose load is not known (a connection without `installedKva`, a lot linked without a meter) counts in the `low` column.\n */\nexport function diversifiedDemand(installedKva: readonly number[], rules: PowerRules): number {\n if (installedKva.length === 0) return 0\n const band = rules.diversity.find((entry) => installedKva.length <= entry.consumers) ?? rules.diversity[rules.diversity.length - 1]\n if (band === undefined) return 0\n return installedKva.reduce((sum, installed) => sum + (installed <= rules.installedSplitKva ? band.low : band.high), 0)\n}\n\n/** The smallest rating whose loading stays within `maxLoading` for this demand, or none. */\nexport function pickTransformer(demandKva: number, rules: PowerRules): TransformerRating | undefined {\n return [...rules.transformers].sort((a, b) => a.kva - b.kva).find((rating) => demandKva <= rating.kva * rules.maxLoading)\n}\n","/** Where a lot takes each network when it declares none (a building of `fillBlock`, a lot whose house has no utilities yet), metres. */\nexport type DefaultConnectionRules = {\n /** The meter post, the water stand and the sewer box stand this far inside the lot's front. */\n readonly frontInset: number\n /** The inspection box stands this far inside the lot's front. */\n readonly sewerInset: number\n /** From the lot's side boundary to the meter post (power and telecom), and to the water stand. */\n readonly meterFromSide: number\n readonly waterFromSide: number\n /** The downspout outlet at the kerb this far from the lot's other side boundary. */\n readonly downspoutFromSide: number\n /** Anchor of the service drop on the meter post over the ground, and of the telecom drop under it. */\n readonly powerHeight: number\n readonly telecomBelowPower: number\n /** Invert of the inspection box outlet under the ground; a lot set back from its street gets a shallower one, never under the least. */\n readonly sewerDepth: number\n readonly sewerLeastDepth: number\n}\n\n/** How the generator lays the networks out: the numbers of a street, not checked by the validator but by the generator's own tests. */\nexport type NetworkLayoutRules = {\n /** Width of the sidewalk on each side of a street. */\n readonly sidewalk: number\n /** A run end this close to the map border is where the line leaves the map (a feed, a reservoir). */\n readonly edgeReach: number\n readonly poles: {\n /** Least and longest span between two poles. */\n readonly spacing: readonly [number, number]\n /** The pole's axis from the kerb, on the service strip; the corner pole as far from the cross street's kerb. */\n readonly curbSetback: number\n /** An end-of-line pole this far inside the end of its run. */\n readonly endInset: number\n /** No two poles closer than this (a pole added to reach a lot keeps it). */\n readonly minGap: number\n /** An intermediate pole at least this far from the edge of a cross street's roadway. */\n readonly crossingClearance: number\n /** A pole looks this far either way (in steps) for a lot boundary near its target, and slides as far to clear a gate. */\n readonly snap: number\n readonly slide: number\n readonly slideStep: number\n }\n /** Sag at mid span of each class, metres. */\n readonly sag: { readonly mv: number; readonly lv: number; readonly telecom: number; readonly drop: number; readonly telecomDrop: number }\n readonly telecom: {\n /** A splice box with its reserve coil every this many spans. */\n readonly spliceEvery: number\n /** Gap between two cables of a bundle, from the top of the band down. */\n readonly cableGap: number\n /** Cables of a bundle, least and most, in a clean district and in the periphery. */\n readonly cables: { readonly clean: readonly [number, number]; readonly periphery: readonly [number, number] }\n }\n /** The periphery: district kinds with telecom bundles and a few illegal hookups (a drop with no meter, counted in its transformer's load). */\n readonly periphery: { readonly kinds: readonly string[]; readonly hookupShare: number }\n /** Added to every least slope and least cover the generator lays, so a pipe never sits on the limit. */\n readonly slopeMargin: number\n readonly coverMargin: number\n readonly sewer: {\n readonly mainDiameter: number\n readonly lateralDiameter: number\n /** The lateral drops into the main from a cleanout this far from the street's axis. */\n readonly dropOffset: number\n /** The interceptor runs along the river this far from its bank. */\n readonly interceptorOffset: number\n }\n readonly storm: {\n /** The gallery runs this far from the street's axis, on the side of the poles. */\n readonly galleryOffset: number\n readonly galleryDiameter: number\n readonly lateralDiameter: number\n /** Longest gap between two inlets along a kerb; one at each corner. */\n readonly inletSpacing: number\n /** An inlet's grate this far from the kerb into the road, and the corner inlet this far from the end of its kerb. */\n readonly inletSetback: number\n readonly inletFromCorner: number\n /** Level of the river's water: an outfall's bottom stays above it. */\n readonly riverLevel: number\n }\n readonly water: {\n readonly mainDiameter: number\n readonly serviceDiameter: number\n /** The main runs under the sidewalk opposite the poles, this share of its width out from the kerb. */\n readonly sidewalkShare: number\n /** A hydrant stands this far from the valve of a crossing, toward the kerb. */\n readonly hydrantOffset: number\n }\n readonly connection: DefaultConnectionRules\n}\n\n/** The defaults of a Brazilian street: 30 to 40 m spans, MV bare on the crossarm, LV multiplexed, sewer to an interceptor along the river. */\nexport const DEFAULT_NETWORK_LAYOUT: NetworkLayoutRules = {\n sidewalk: 2.5,\n edgeReach: 5,\n poles: { spacing: [30, 40], curbSetback: 0.4, endInset: 1, minGap: 3, crossingClearance: 5, snap: 5, slide: 6, slideStep: 0.25 },\n sag: { mv: 0.5, lv: 0.6, telecom: 0.6, drop: 0.2, telecomDrop: 0.15 },\n telecom: { spliceEvery: 4, cableGap: 0.1, cables: { clean: [1, 2], periphery: [3, 5] } },\n periphery: { kinds: ['residential_popular'], hookupShare: 0.1 },\n slopeMargin: 0.0005,\n coverMargin: 0.05,\n sewer: { mainDiameter: 0.15, lateralDiameter: 0.1, dropOffset: 1, interceptorOffset: 2 },\n storm: { galleryOffset: 2, galleryDiameter: 0.6, lateralDiameter: 0.4, inletSpacing: 60, inletSetback: 0.3, inletFromCorner: 1, riverLevel: -4 },\n water: { mainDiameter: 0.075, serviceDiameter: 0.02, sidewalkShare: 1 / 3, hydrantOffset: 0.6 },\n connection: { frontInset: 0.3, sewerInset: 1, meterFromSide: 1, waterFromSide: 1.6, downspoutFromSide: 1, powerHeight: 5.7, telecomBelowPower: 0.6, sewerDepth: 0.6, sewerLeastDepth: 0.3 },\n}\n","import type { PoleDef, PoleSlotBand, PoleSlots } from '../pole-specs'\n\n/** The bands from the top of the pole down. */\nexport const POLE_SLOT_ORDER: readonly PoleSlotBand[] = ['mv', 'transformer', 'lv', 'lighting', 'telecom']\n\n/**\n * Least free gap between the top of a band and the bottom of the band above it, metres: the transformer drum 0.3 m under the crossarm,\n * the first telecom cable 0.4 m under the lamp. A band never enters the one above (gap 0 at least).\n */\nexport const POLE_SLOT_GAPS: Readonly<Record<Exclude<PoleSlotBand, 'mv'>, number>> = { transformer: 0.3, lv: 0, lighting: 0, telecom: 0.4 }\n\n/** The 11 m double-T concrete pole, 1.7 m buried (9.3 m above the ground), with the bands of Brazilian distribution practice. */\nexport const DEFAULT_POLE_SLOTS: PoleSlots = {\n height: 11,\n embedment: 1.7,\n bands: { mv: [9, 9.25], transformer: [7.7, 8.7], lv: [7.1, 7.4], lighting: [6.5, 6.8], telecom: [5.7, 6.1] },\n}\n\nexport type PoleSlotViolation = {\n readonly code: 'slot_out_of_pole' | 'slot_inverted' | 'slot_order'\n readonly band: PoleSlotBand\n readonly value: number\n readonly limit: number\n}\n\n/** Every band inside the pole above the ground, bottom under top, in order and apart by the least gaps. */\nexport function checkPoleSlots(slots: PoleSlots, gaps: Readonly<Record<Exclude<PoleSlotBand, 'mv'>, number>> = POLE_SLOT_GAPS): PoleSlotViolation[] {\n const violations: PoleSlotViolation[] = []\n const above = slots.height - slots.embedment\n for (const band of POLE_SLOT_ORDER) {\n const [bottom, top] = slots.bands[band]\n if (bottom > top) violations.push({ code: 'slot_inverted', band, value: bottom, limit: top })\n if (bottom < 0) violations.push({ code: 'slot_out_of_pole', band, value: bottom, limit: 0 })\n if (top > above) violations.push({ code: 'slot_out_of_pole', band, value: top, limit: above })\n }\n for (let index = 1; index < POLE_SLOT_ORDER.length; index++) {\n const band = POLE_SLOT_ORDER[index] as Exclude<PoleSlotBand, 'mv'>\n const upper = POLE_SLOT_ORDER[index - 1] as PoleSlotBand\n const gap = slots.bands[upper][0] - slots.bands[band][1]\n if (gap < gaps[band]) violations.push({ code: 'slot_order', band, value: gap, limit: gaps[band] })\n }\n return violations\n}\n\nconst isPoleSlots = (value: unknown): value is PoleSlots =>\n typeof value === 'object' && value !== null && 'bands' in value && 'height' in value && 'embedment' in value\n\n/** The slots a pole of the registry declares (a distribution pole), or none. */\nexport function slotsOfPole(pole: PoleDef): PoleSlots | undefined {\n const slots: unknown = 'slots' in pole.spec ? pole.spec.slots : undefined\n return isPoleSlots(slots) ? slots : undefined\n}\n","/** A point on the ground plane: world x, z. */\nexport type PlanPoint = readonly [number, number]\n\n/**\n * Where two segments cross in plan, as the share along each (`[t, u]`, both strictly inside 0..1), or nothing when they do not cross\n * or only touch at an end.\n */\nexport function segmentCrossing(a0: PlanPoint, a1: PlanPoint, b0: PlanPoint, b1: PlanPoint): readonly [number, number] | undefined {\n const rx = a1[0] - a0[0]\n const rz = a1[1] - a0[1]\n const sx = b1[0] - b0[0]\n const sz = b1[1] - b0[1]\n const denominator = rx * sz - rz * sx\n if (Math.abs(denominator) < 1e-12) return undefined\n const qx = b0[0] - a0[0]\n const qz = b0[1] - a0[1]\n const t = (qx * sz - qz * sx) / denominator\n const u = (qx * rz - qz * rx) / denominator\n const inside = (value: number): boolean => value > 1e-9 && value < 1 - 1e-9\n return inside(t) && inside(u) ? [t, u] : undefined\n}\n\n/** Point inside a polygon (even-odd rule). */\nexport function pointInPolygon(point: PlanPoint, outline: readonly PlanPoint[]): boolean {\n let inside = false\n for (let index = 0, previous = outline.length - 1; index < outline.length; previous = index++) {\n const a = outline[index] as PlanPoint\n const b = outline[previous] as PlanPoint\n if (a[1] > point[1] !== b[1] > point[1] && point[0] < ((b[0] - a[0]) * (point[1] - a[1])) / (b[1] - a[1]) + a[0]) inside = !inside\n }\n return inside\n}\n\n/** A segment enters a polygon: an end inside it or a crossing with one of its sides. */\nexport function segmentEntersPolygon(a: PlanPoint, b: PlanPoint, outline: readonly PlanPoint[]): boolean {\n if (outline.length < 3) return false\n if (pointInPolygon(a, outline) || pointInPolygon(b, outline)) return true\n for (let index = 0, previous = outline.length - 1; index < outline.length; previous = index++) {\n if (segmentCrossing(a, b, outline[previous] as PlanPoint, outline[index] as PlanPoint) !== undefined) return true\n }\n return false\n}\n\n/** Share along a segment of the point nearest to `point`, clamped to 0..1. */\nexport function nearestShare(a: PlanPoint, b: PlanPoint, point: PlanPoint): number {\n const dx = b[0] - a[0]\n const dz = b[1] - a[1]\n const length = dx * dx + dz * dz\n if (length === 0) return 0\n return Math.min(1, Math.max(0, ((point[0] - a[0]) * dx + (point[1] - a[1]) * dz) / length))\n}\n\n/** Height of a hanging conductor at share `t` of its span: the chord less a parabola with `sag` at mid span. */\nexport function catenaryHeight(fromY: number, toY: number, sag: number, t: number): number {\n return fromY + (toY - fromY) * t - 4 * sag * t * (1 - t)\n}\n\n/** Shares along a segment where it crosses the sides of a polygon, ascending. */\nexport function polygonCrossings(a: PlanPoint, b: PlanPoint, outline: readonly PlanPoint[]): number[] {\n const shares: number[] = []\n for (let index = 0, previous = outline.length - 1; index < outline.length; previous = index++) {\n const crossing = segmentCrossing(a, b, outline[previous] as PlanPoint, outline[index] as PlanPoint)\n if (crossing !== undefined) shares.push(crossing[0])\n }\n return shares.sort((first, second) => first - second)\n}\n\n/** The range of shares along a segment that lies inside a circle, or none. */\nexport function circleShares(a: PlanPoint, b: PlanPoint, centre: PlanPoint, radius: number): readonly [number, number] | undefined {\n const dx = b[0] - a[0]\n const dz = b[1] - a[1]\n const fx = a[0] - centre[0]\n const fz = a[1] - centre[1]\n const qa = dx * dx + dz * dz\n const qb = 2 * (fx * dx + fz * dz)\n const qc = fx * fx + fz * fz - radius * radius\n if (qa === 0) return qc <= 0 ? [0, 1] : undefined\n const discriminant = qb * qb - 4 * qa * qc\n if (discriminant < 0) return undefined\n const root = Math.sqrt(discriminant)\n const start = Math.max(0, (-qb - root) / (2 * qa))\n const end = Math.min(1, (-qb + root) / (2 * qa))\n return start <= end ? [start, end] : undefined\n}\n","import type { UtilityConnection } from '@adatechnology/game-contracts'\n\nimport type { NetworkViolation } from './codes'\nimport type { LotFrontage } from './drop-rules'\nimport type { NetworkGraph } from './graph'\nimport type { NetworkRules } from './rules'\nimport type { NetworkBuilding, NetworkCrown, NetworkEdge, NetworkNode, NetworkSurface } from './types'\n\n/** What the validator reads besides the networks: the lots' connections, the buildings and trees in the way, the ground. */\nexport type ValidateNetworksOptions = {\n /** Every connection a lot declared; each must be linked once, in `frame: 'world'`. */\n readonly connections?: readonly UtilityConnection[]\n /** Outlines no span may cross (a drop may end over the building of its own lot). */\n readonly buildings?: readonly NetworkBuilding[]\n /** Tree crowns no span may go through (from the scene's plant provider). */\n readonly obstacles?: { readonly crowns?: readonly NetworkCrown[] }\n /** What lies under a point of a span. Default: road everywhere (the strictest clearance a conductor may have). A point with no surface is not checked. */\n readonly surfaceAt?: (x: number, z: number) => NetworkSurface | undefined\n /** Ground level at a point. Default: 0 under a span; along a pipe, the cover levels of its two nodes. */\n readonly groundAt?: (x: number, z: number) => number\n /** The lots' fronts on their streets (`GeneratedNetworks.frontages`): with them the drops are held to the street's practice. */\n readonly frontages?: readonly LotFrontage[]\n}\n\nexport type ValidationContext = {\n readonly graph: NetworkGraph\n readonly rules: NetworkRules\n readonly options: ValidateNetworksOptions\n readonly report: (violation: NetworkViolation) => void\n}\n\n/** The ends of an edge whose nodes both exist, or nothing. */\nexport function edgeEnds(context: ValidationContext, edge: NetworkEdge): readonly [NetworkNode, NetworkNode] | undefined {\n const from = context.graph.nodes.get(edge.from)\n const to = context.graph.nodes.get(edge.to)\n return from === undefined || to === undefined ? undefined : [from, to]\n}\n","import { EDGE_CLASS, isAerialEdgeKind } from './classes'\nimport { NETWORK_VIOLATION } from './codes'\nimport { catenaryHeight, circleShares, pointInPolygon, polygonCrossings, segmentEntersPolygon } from './geometry'\nimport type { PlanPoint } from './geometry'\nimport { edgeLength } from './graph'\nimport type { AerialClass, NetworkBuilding, NetworkEdge, NetworkNode } from './types'\nimport { edgeEnds } from './validate-context'\nimport type { ValidationContext } from './validate-context'\n\ntype Span = { readonly edge: NetworkEdge; readonly from: NetworkNode; readonly to: NetworkNode; readonly sag: number; readonly heights: readonly [number, number] }\n\nconst planOf = (node: NetworkNode): PlanPoint => [node.at[0], node.at[2]]\n\nfunction validateDrop(context: ValidationContext, edge: NetworkEdge): void {\n const limit = edge.kind === 'service_drop' ? context.rules.power.dropMaxLength : edge.kind === 'telecom_drop' ? context.rules.telecom.dropMaxLength : undefined\n if (limit === undefined) return\n const length = edgeLength(context.graph, edge)\n if (length > limit) context.report({ code: NETWORK_VIOLATION.DROP_TOO_LONG, id: edge.id, value: length, limit })\n}\n\n/** The lowest point of the conductor over each sampled surface against the clearance of its class. */\nfunction validateClearance(context: ValidationContext, span: Span): void {\n const row = context.rules.clearance[EDGE_CLASS[span.edge.kind] as AerialClass]\n const samples = Math.max(1, context.rules.catenarySamples)\n const lowest = new Map<'road' | 'sidewalk' | 'lot', number>()\n for (let index = 0; index <= samples; index++) {\n const t = index / samples\n const x = span.from.at[0] + (span.to.at[0] - span.from.at[0]) * t\n const z = span.from.at[2] + (span.to.at[2] - span.from.at[2]) * t\n const surface = context.options.surfaceAt === undefined ? 'road' : context.options.surfaceAt(x, z)\n if (surface === undefined) continue\n const height = catenaryHeight(span.heights[0], span.heights[1], span.sag, t) - (context.options.groundAt?.(x, z) ?? 0)\n lowest.set(surface, Math.min(lowest.get(surface) ?? Number.POSITIVE_INFINITY, height))\n }\n for (const [surface, height] of lowest) {\n const limit = row[surface]\n if (limit === null) context.report({ code: NETWORK_VIOLATION.MV_OVER_LOT, id: span.edge.id, detail: surface })\n else if (height < limit) context.report({ code: NETWORK_VIOLATION.CLEARANCE, id: span.edge.id, detail: surface, value: height, limit })\n }\n}\n\nconst pointAt = (span: Span, t: number): PlanPoint => [span.from.at[0] + (span.to.at[0] - span.from.at[0]) * t, span.from.at[2] + (span.to.at[2] - span.from.at[2]) * t]\n\n/** Lowest and highest conductor over the shares `[start, end]` of a span, sampled. */\nfunction heightRange(context: ValidationContext, span: Span, start: number, end: number): readonly [number, number] {\n const samples = Math.max(1, context.rules.catenarySamples)\n let low = Number.POSITIVE_INFINITY\n let high = Number.NEGATIVE_INFINITY\n for (let index = 0; index <= samples; index++) {\n const y = catenaryHeight(span.heights[0], span.heights[1], span.sag, start + ((end - start) * index) / samples)\n low = Math.min(low, y)\n high = Math.max(high, y)\n }\n return [low, high]\n}\n\n/** The part of a span over a building, as shares, or none: a drop to its own lot may end over the house, but not cross the whole body. */\nfunction overBuilding(span: Span, building: NetworkBuilding): readonly [number, number] | undefined {\n const a = planOf(span.from)\n const b = planOf(span.to)\n const crossings = polygonCrossings(a, b, building.outline)\n const ownLot = span.to.kind === 'connection' && span.to.lot !== undefined && building.lot === span.to.lot\n if (ownLot) return crossings.length >= 2 ? [crossings[0] as number, crossings[crossings.length - 1] as number] : undefined\n if (!segmentEntersPolygon(a, b, building.outline)) return undefined\n const start = pointInPolygon(a, building.outline) ? 0 : (crossings[0] ?? 0)\n const end = pointInPolygon(b, building.outline) ? 1 : (crossings[crossings.length - 1] ?? 1)\n return [start, end]\n}\n\n/** No span passes over a building lower than its roof. */\nfunction validateBuildings(context: ValidationContext, span: Span): void {\n for (const building of context.options.buildings ?? []) {\n const over = overBuilding(span, building)\n if (over === undefined) continue\n const middle = pointAt(span, (over[0] + over[1]) / 2)\n const roof = (context.options.groundAt?.(middle[0], middle[1]) ?? 0) + building.height\n const [low] = heightRange(context, span, over[0], over[1])\n if (low < roof) context.report({ code: NETWORK_VIOLATION.SPAN_OVER_BUILDING, id: span.edge.id, detail: building.id, value: low, limit: roof })\n }\n}\n\n/** No span goes through a crown: the conductor over the part of the span inside the crown's radius stays out of `[bottom, top]`. */\nfunction validateCrowns(context: ValidationContext, span: Span): void {\n for (const crown of context.options.obstacles?.crowns ?? []) {\n const inside = circleShares(planOf(span.from), planOf(span.to), [crown.x, crown.z], crown.radius)\n if (inside === undefined) continue\n const [low, high] = heightRange(context, span, inside[0], inside[1])\n if (low <= crown.top && high >= crown.bottom) context.report({ code: NETWORK_VIOLATION.SPAN_THROUGH_CROWN, id: span.edge.id, detail: `${crown.x},${crown.z}` })\n }\n}\n\n/** Drops within reach; every span with its sag, its clearance by class over road, sidewalk and lot, clear of buildings and crowns. */\nexport function validateAerial(context: ValidationContext): void {\n for (const edge of context.graph.edges.values()) {\n if (!isAerialEdgeKind(edge.kind)) continue\n validateDrop(context, edge)\n const ends = edgeEnds(context, edge)\n if (ends === undefined) continue\n if (edge.sag === undefined) {\n context.report({ code: NETWORK_VIOLATION.MISSING_SAG, id: edge.id })\n continue\n }\n const span: Span = { edge, from: ends[0], to: ends[1], sag: edge.sag, heights: edge.heights ?? [ends[0].at[1], ends[1].at[1]] }\n validateClearance(context, span)\n validateBuildings(context, span)\n validateCrowns(context, span)\n }\n}\n","import { isAerialEdgeKind } from './classes'\nimport { NETWORK_VIOLATION } from './codes'\nimport { nearestShare, segmentCrossing } from './geometry'\nimport type { PlanPoint } from './geometry'\nimport { edgeLength } from './graph'\nimport type { BuriedEdgeKind, NetworkEdge, NetworkNode } from './types'\nimport { edgeEnds } from './validate-context'\nimport type { ValidationContext } from './validate-context'\n\n/** A pipe with everything the rules read: its ends, the inverts at each end and its diameter. */\ntype Pipe = { readonly edge: NetworkEdge; readonly kind: BuriedEdgeKind; readonly from: NetworkNode; readonly to: NetworkNode; readonly inverts: readonly [number, number]; readonly diameter: number }\n\nconst SLOPE_TOLERANCE = 1e-3\n\nconst lerp = (a: number, b: number, t: number): number => a + (b - a) * t\n\nfunction groundAt(context: ValidationContext, pipe: Pipe, t: number): number {\n const x = lerp(pipe.from.at[0], pipe.to.at[0], t)\n const z = lerp(pipe.from.at[2], pipe.to.at[2], t)\n return context.options.groundAt?.(x, z) ?? lerp(pipe.from.at[1], pipe.to.at[1], t)\n}\n\nfunction pipeOf(context: ValidationContext, edge: NetworkEdge): Pipe | undefined {\n if (isAerialEdgeKind(edge.kind)) return undefined\n const ends = edgeEnds(context, edge)\n if (ends === undefined) return undefined\n const inverts = edge.inverts ?? (ends[0].invert !== undefined && ends[1].invert !== undefined ? ([ends[0].invert, ends[1].invert] as const) : undefined)\n if (inverts === undefined) context.report({ code: NETWORK_VIOLATION.MISSING_INVERT, id: edge.id })\n if (edge.diameter === undefined) context.report({ code: NETWORK_VIOLATION.MISSING_DIAMETER, id: edge.id })\n if (inverts === undefined || edge.diameter === undefined) return undefined\n return { edge, kind: edge.kind, from: ends[0], to: ends[1], inverts, diameter: edge.diameter }\n}\n\n/** Gravity pipes fall along the flow by at least the least slope; a declared slope agrees with the inverts. */\nfunction validateSlope(context: ValidationContext, pipe: Pipe): void {\n if (pipe.kind === 'water_main' || pipe.kind === 'water_service') return\n const length = edgeLength(context.graph, pipe.edge)\n if (length === 0) return\n const slope = (pipe.inverts[0] - pipe.inverts[1]) / length\n const limit = context.rules.minSlope[pipe.kind]\n if (slope < limit) context.report({ code: NETWORK_VIOLATION.SLOPE, id: pipe.edge.id, value: slope, limit })\n if (pipe.edge.slope !== undefined && Math.abs(pipe.edge.slope - slope) > SLOPE_TOLERANCE) context.report({ code: NETWORK_VIOLATION.SLOPE_MISMATCH, id: pipe.edge.id, value: pipe.edge.slope, limit: slope })\n}\n\nconst planAt = (pipe: Pipe, t: number): PlanPoint => [lerp(pipe.from.at[0], pipe.to.at[0], t), lerp(pipe.from.at[2], pipe.to.at[2], t)]\n\n/** A storm gallery runs within reach of a sewer main (the same street), at any sampled point of the main. */\nfunction besideGallery(context: ValidationContext, main: Pipe, pipes: readonly Pipe[]): boolean {\n const samples = Math.max(1, context.rules.catenarySamples)\n const reach = context.rules.sewer.galleryReach\n return pipes.some((gallery) => {\n if (gallery.kind !== 'storm_gallery') return false\n const a = planAt(gallery, 0)\n const b = planAt(gallery, 1)\n for (let index = 0; index <= samples; index++) {\n const point = planAt(main, index / samples)\n const nearest = planAt(gallery, nearestShare(a, b, point))\n if (Math.hypot(point[0] - nearest[0], point[1] - nearest[1]) <= reach) return true\n }\n return false\n })\n}\n\n/** Cover from the ground to the top of the pipe within its range, sampled along it; a sewer no deeper than the pumping limit. */\nfunction validateCover(context: ValidationContext, pipe: Pipe, pipes: readonly Pipe[]): void {\n const base = context.rules.cover[pipe.kind]\n const range = pipe.kind === 'sewer_main' && besideGallery(context, pipe, pipes) ? { ...base, min: Math.max(base.min, context.rules.sewer.coverUnderGallery) } : base\n const samples = Math.max(1, context.rules.catenarySamples)\n let least = Number.POSITIVE_INFINITY\n let most = Number.NEGATIVE_INFINITY\n let deepest = Number.NEGATIVE_INFINITY\n for (let index = 0; index <= samples; index++) {\n const t = index / samples\n const ground = groundAt(context, pipe, t)\n const invert = lerp(pipe.inverts[0], pipe.inverts[1], t)\n least = Math.min(least, ground - invert - pipe.diameter)\n most = Math.max(most, ground - invert - pipe.diameter)\n deepest = Math.max(deepest, ground - invert)\n }\n if (least < range.min) context.report({ code: NETWORK_VIOLATION.COVER, id: pipe.edge.id, detail: 'min', value: least, limit: range.min })\n if (range.max !== undefined && most > range.max) context.report({ code: NETWORK_VIOLATION.COVER, id: pipe.edge.id, detail: 'max', value: most, limit: range.max })\n const isSewer = pipe.kind === 'sewer_main' || pipe.kind === 'sewer_lateral'\n if (isSewer && deepest > context.rules.sewer.maxDepth) context.report({ code: NETWORK_VIOLATION.TOO_DEEP, id: pipe.edge.id, value: deepest, limit: context.rules.sewer.maxDepth })\n}\n\nconst shareEnds = (a: NetworkEdge, b: NetworkEdge): boolean => a.from === b.from || a.from === b.to || a.to === b.from || a.to === b.to\n\n/** Two pipes that cross in plan keep the least vertical gap, and the one of lower rank (water, then the sewer lateral, then drainage, then the sewer main) goes above. */\nfunction validateCrossing(context: ValidationContext, a: Pipe, b: Pipe): void {\n if (shareEnds(a.edge, b.edge)) return\n const crossing = segmentCrossing([a.from.at[0], a.from.at[2]], [a.to.at[0], a.to.at[2]], [b.from.at[0], b.from.at[2]], [b.to.at[0], b.to.at[2]])\n if (crossing === undefined) return\n const bottomA = lerp(a.inverts[0], a.inverts[1], crossing[0])\n const bottomB = lerp(b.inverts[0], b.inverts[1], crossing[1])\n const [upper, lower, upperBottom, lowerBottom] = bottomA >= bottomB ? [a, b, bottomA, bottomB] : [b, a, bottomB, bottomA]\n const gap = upperBottom - (lowerBottom + lower.diameter)\n const id = `${a.edge.id}x${b.edge.id}`\n const separation = context.rules.crossing.separation\n if (gap < separation) context.report({ code: NETWORK_VIOLATION.CROSSING_TOO_CLOSE, id, value: gap, limit: separation })\n const rank = context.rules.crossing.rank\n if (rank[upper.kind] > rank[lower.kind]) context.report({ code: NETWORK_VIOLATION.CROSSING_ORDER, id, detail: `${upper.edge.id} above ${lower.edge.id}` })\n const lateral = a.kind === 'sewer_lateral' && b.kind === 'storm_gallery' ? { pipe: a, t: crossing[0], bottom: bottomA } : b.kind === 'sewer_lateral' && a.kind === 'storm_gallery' ? { pipe: b, t: crossing[1], bottom: bottomB } : undefined\n if (lateral === undefined) return\n const depth = groundAt(context, lateral.pipe, lateral.t) - lateral.bottom\n const limit = context.rules.sewer.lateralOverGallery\n if (depth > limit) context.report({ code: NETWORK_VIOLATION.LATERAL_TOO_DEEP, id, value: depth, limit })\n}\n\n/** A sewer main has a manhole at most every `manholeSpacing` metres: its nodes are manholes, so no edge is longer. */\nfunction validateSpacing(context: ValidationContext, pipe: Pipe): void {\n if (pipe.kind !== 'sewer_main') return\n const length = edgeLength(context.graph, pipe.edge)\n if (length > context.rules.sewer.manholeSpacing) context.report({ code: NETWORK_VIOLATION.MANHOLE_SPACING, id: pipe.edge.id, value: length, limit: context.rules.sewer.manholeSpacing })\n}\n\n/** Inverts and diameters known, slopes, covers and depths, and every crossing between two pipes. */\nexport function validateBuried(context: ValidationContext): void {\n const pipes: Pipe[] = []\n for (const edge of context.graph.edges.values()) {\n const pipe = pipeOf(context, edge)\n if (pipe !== undefined) pipes.push(pipe)\n }\n for (const pipe of pipes) {\n validateSlope(context, pipe)\n validateCover(context, pipe, pipes)\n validateSpacing(context, pipe)\n }\n for (let first = 0; first < pipes.length; first++) {\n for (let second = first + 1; second < pipes.length; second++) validateCrossing(context, pipes[first] as Pipe, pipes[second] as Pipe)\n }\n}\n","/** The axis a straight street runs along. */\nexport type RunAxis = 'x' | 'z'\n\n/** A straight street's frame: `u` along it, `v` across it (+z for a street along x, +x for one along z). */\nexport type RunFrame = { readonly along: RunAxis; readonly axis: number }\n\n/** A point of a street's frame in the world. */\nexport function worldOf({ frame, u, v }: { readonly frame: RunFrame; readonly u: number; readonly v: number }): readonly [number, number] {\n return frame.along === 'x' ? [u, frame.axis + v] : [frame.axis + v, u]\n}\n\n/** A world point in a street's frame: the inverse of `worldOf`. */\nexport function frameOf({ frame, x, z }: { readonly frame: RunFrame; readonly x: number; readonly z: number }): readonly [number, number] {\n return frame.along === 'x' ? [x, z - frame.axis] : [z, x - frame.axis]\n}\n\nconst UINT32 = 2 ** 32\n\nexport type HashParams = { readonly seed: number; readonly id: string }\n\n/** FNV-1a of the seed and an id, into [0, 1): what the generator draws (a hookup, a bundle of cables), never the scene's random. */\nexport function hashOf({ seed, id }: HashParams): number {\n let h = 2166136261 ^ (seed >>> 0)\n h = Math.imul(h, 16777619)\n h ^= Math.floor(seed / UINT32) >>> 0\n h = Math.imul(h, 16777619)\n for (let index = 0; index < id.length; index++) {\n h ^= id.charCodeAt(index)\n h = Math.imul(h, 16777619)\n }\n // murmur3's finaliser: ids that differ in their last character land far apart\n h ^= h >>> 16\n h = Math.imul(h, 0x85ebca6b)\n h ^= h >>> 13\n h = Math.imul(h, 0xc2b2ae35)\n h ^= h >>> 16\n return (h >>> 0) / UINT32\n}\n\n/** A whole number in `range` (both ends in) by the hash of the seed and an id. */\nexport function countOf({ seed, id, range }: HashParams & { readonly range: readonly [number, number] }): number {\n const [least, most] = range\n return least + Math.min(most - least, Math.floor(hashOf({ seed, id }) * (most - least + 1)))\n}\n\n/** Two digits from 1: 'pole:main_street:07'. */\nexport const ordinal = (index: number): string => String(index + 1).padStart(2, '0')\n\n/** Points in square cells of `size` metres, to find the near ones without a pass over all of them. */\nexport type PlanBins<T> = { add(x: number, z: number, item: T): void; near(x: number, z: number, radius: number): T[] }\n\nexport function planBins<T>(size: number): PlanBins<T> {\n const cells = new Map<string, T[]>()\n const key = (i: number, k: number): string => `${i},${k}`\n return {\n add(x, z, item) {\n const id = key(Math.floor(x / size), Math.floor(z / size))\n cells.set(id, [...(cells.get(id) ?? []), item])\n },\n near(x, z, radius) {\n const out: T[] = []\n const reach = Math.ceil(radius / size)\n const [ci, ck] = [Math.floor(x / size), Math.floor(z / size)]\n for (let i = ci - reach; i <= ci + reach; i++) for (let k = ck - reach; k <= ck + reach; k++) out.push(...(cells.get(key(i, k)) ?? []))\n return out\n },\n }\n}\n","import type { PlanRect } from '../cities/types'\nimport { frameOf } from './frame'\nimport type { RunFrame } from './frame'\nimport type { PowerRules } from './rules'\n\n/** A lot's front on its street: its rectangle, the street's frame, the side of the street it stands on and its span along the street. */\nexport type LotFrontage = {\n readonly lot: string\n readonly rect: PlanRect\n readonly frame: RunFrame\n /** Half the street's roadway plus its sidewalk: a point farther from the axis is off the street. */\n readonly reach: number\n readonly side: 1 | -1\n readonly span: readonly [number, number]\n}\n\nexport type DropFitParams = {\n readonly frontage: LotFrontage\n readonly pole: { readonly x: number; readonly z: number }\n readonly anchor: readonly [number, number, number]\n readonly rules: Pick<PowerRules, 'dropMaxSkew' | 'dropFrontageSlack'>\n}\n\nexport type DropMisfit = 'skewed' | 'off_frontage'\n\n/**\n * How a drop from a street pole to a lot's anchor breaks the street's practice, or nothing: on the pole's own side the pole stands in front of\n * the lot (its station within the frontage); across the street the drop goes straight over (within `dropMaxSkew` of the street's normal),\n * never along the street. A pole off the street (a service pole inside a lot) is not judged here.\n */\nexport function dropMisfitOf({ frontage, pole, anchor, rules }: DropFitParams): DropMisfit | undefined {\n const [poleU, poleV] = frameOf({ frame: frontage.frame, x: pole.x, z: pole.z })\n if (Math.abs(poleV) > frontage.reach) return undefined\n const [anchorU, anchorV] = frameOf({ frame: frontage.frame, x: anchor[0], z: anchor[2] })\n if (Math.sign(poleV) === frontage.side) {\n const [low, high] = frontage.span\n return poleU >= low - rules.dropFrontageSlack && poleU <= high + rules.dropFrontageSlack ? undefined : 'off_frontage'\n }\n const skew = (Math.atan2(Math.abs(poleU - anchorU), Math.abs(poleV - anchorV)) * 180) / Math.PI\n return skew <= rules.dropMaxSkew ? undefined : 'skewed'\n}\n\nconst inside = (x: number, z: number, rect: PlanRect): boolean => x > rect[0] && x < rect[2] && z > rect[1] && z < rect[3]\n\n/** The first other lot a drop's straight path passes over (sampled every 0.25 m), or none. */\nexport function lotUnderDrop({ from, to, lot, frontages }: { readonly from: readonly [number, number]; readonly to: readonly [number, number]; readonly lot: string; readonly frontages: readonly LotFrontage[] }): string | undefined {\n const steps = Math.max(1, Math.ceil(Math.hypot(to[0] - from[0], to[1] - from[1]) / 0.25))\n for (let index = 0; index <= steps; index++) {\n const t = index / steps\n const [x, z] = [from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t]\n const other = frontages.find((entry) => entry.lot !== lot && inside(x, z, entry.rect))\n if (other) return other.lot\n }\n return undefined\n}\n","import { NETWORK_VIOLATION } from './codes'\nimport { dropMisfitOf, lotUnderDrop } from './drop-rules'\nimport { edgeEnds } from './validate-context'\nimport type { ValidationContext } from './validate-context'\n\n/**\n * The street's practice for drops (with the lots' `frontages`): a drop leaves a pole in front of its lot or goes straight across the street,\n * never along it, and never passes over another lot; no pole holds more than `dropsPerPole` service drops. A drop from a service pole inside a lot\n * is judged only by the lots it passes over.\n */\nexport function validateDrops(context: ValidationContext): void {\n const frontages = context.options.frontages\n const perPole = new Map<string, number>()\n for (const edge of context.graph.edges.values()) {\n if (edge.kind !== 'service_drop' && edge.kind !== 'telecom_drop') continue\n const ends = edgeEnds(context, edge)\n if (!ends) continue\n const [pole, end] = ends\n if (edge.kind === 'service_drop') perPole.set(pole.id, (perPole.get(pole.id) ?? 0) + 1)\n const lot = end.lot\n if (frontages === undefined || lot === undefined) continue\n const frontage = frontages.find((entry) => entry.lot === lot)\n const misfit = frontage && dropMisfitOf({ frontage, pole: { x: pole.at[0], z: pole.at[2] }, anchor: end.at, rules: context.rules.power })\n if (misfit === 'skewed') context.report({ code: NETWORK_VIOLATION.DROP_SKEWED, id: edge.id, limit: context.rules.power.dropMaxSkew })\n if (misfit === 'off_frontage') context.report({ code: NETWORK_VIOLATION.DROP_OFF_FRONTAGE, id: edge.id, detail: pole.id })\n const other = lotUnderDrop({ from: [pole.at[0], pole.at[2]], to: [end.at[0], end.at[2]], lot, frontages })\n if (other !== undefined) context.report({ code: NETWORK_VIOLATION.DROP_OVER_OTHER_LOT, id: edge.id, detail: other })\n }\n for (const [pole, count] of perPole) {\n if (count > context.rules.power.dropsPerPole) context.report({ code: NETWORK_VIOLATION.POLE_TOO_MANY_DROPS, id: pole, value: count, limit: context.rules.power.dropsPerPole })\n }\n}\n","import { NETWORK_VIOLATION } from './codes'\nimport { circuitOf } from './graph'\nimport { diversifiedDemand } from './rules'\nimport type { ValidationContext } from './validate-context'\n\n/** kVA of the low voltage circuit of a transformer: the diversified demand of its consumers plus its street lights. */\nexport function circuitDemand(context: ValidationContext, transformerId: string): number {\n const circuit = circuitOf(context.graph, transformerId)\n const installed = new Map((context.options.connections ?? []).filter((connection) => connection.network === 'power').map((connection) => [connection.lot, connection.installedKva]))\n const consumers: number[] = []\n let lights = 0\n for (const id of circuit.keys()) {\n const node = context.graph.nodes.get(id)\n if (node?.kind === 'connection' && node.lot !== undefined) consumers.push(installed.get(node.lot) ?? 0)\n lights += context.graph.outgoing(id, 'lighting').length\n }\n return diversifiedDemand(consumers, context.rules.power) + lights * context.rules.lighting.lampKva\n}\n\n/** Each transformer has a known rating, its demand within the loading limit, and its circuit no longer than the limit each way. */\nexport function validateLoad(context: ValidationContext): void {\n const power = context.rules.power\n for (const node of context.graph.nodes.values()) {\n if (node.kind !== 'transformer') continue\n const rating = power.transformers.find((entry) => entry.id === node.spec)\n if (rating === undefined) context.report({ code: NETWORK_VIOLATION.UNKNOWN_TRANSFORMER, id: node.id, detail: node.spec ?? 'none' })\n else {\n const loading = circuitDemand(context, node.id) / rating.kva\n if (loading > power.maxLoading) context.report({ code: NETWORK_VIOLATION.TRANSFORMER_OVERLOADED, id: node.id, value: loading, limit: power.maxLoading })\n }\n const longest = Math.max(0, ...circuitOf(context.graph, node.id).values())\n if (longest > power.lvCircuitMaxLength) context.report({ code: NETWORK_VIOLATION.LV_CIRCUIT_TOO_LONG, id: node.id, value: longest, limit: power.lvCircuitMaxLength })\n }\n}\n","import { NETWORK_VIOLATION } from './codes'\nimport type { NetworkGraph } from './graph'\nimport type { NetworkEdge, NetworkNode, NetworkNodeKind } from './types'\nimport type { ValidationContext } from './validate-context'\n\ntype Direction = readonly [number, number]\ntype Main = { readonly edge: NetworkEdge; readonly away: Direction }\n\nconst MAIN_KINDS: ReadonlySet<string> = new Set(['sewer_main', 'storm_gallery'])\n/** The nodes a main may meet other pipes at, or turn at: a pit with a cover over it. */\nconst PIT_KINDS: ReadonlySet<NetworkNodeKind> = new Set(['manhole', 'pumping_station', 'treatment', 'outfall'])\nconst DEGREES = Math.PI / 180\n\nfunction unit(dx: number, dz: number): Direction {\n const length = Math.hypot(dx, dz)\n return length === 0 ? [0, 0] : [dx / length, dz / length]\n}\n\n/** The mains (sewer mains and storm galleries) that meet at a node, each with the direction it leaves in; one of no length (two saddles on one spot) joins nothing. */\nfunction mainsAt(graph: NetworkGraph, node: NetworkNode): Main[] {\n const leaving = graph.outgoing(node.id).filter((edge) => MAIN_KINDS.has(edge.kind)).map((edge) => ({ edge, other: graph.nodes.get(edge.to) }))\n const reaching = graph.incoming(node.id).filter((edge) => MAIN_KINDS.has(edge.kind)).map((edge) => ({ edge, other: graph.nodes.get(edge.from) }))\n return [...leaving, ...reaching].flatMap(({ edge, other }) => (other === undefined || (other.at[0] === node.at[0] && other.at[2] === node.at[2]) ? [] : [{ edge, away: unit(other.at[0] - node.at[0], other.at[2] - node.at[2]) }]))\n}\n\n/** A PV (a pit with a cover) at every crossing and every change of direction of a main: a node where three mains meet, or two that do not run straight on. */\nfunction validatePits(context: ValidationContext): void {\n const tolerance = Math.cos((180 - context.rules.sewer.turnTolerance) * DEGREES)\n for (const node of context.graph.nodes.values()) {\n if (PIT_KINDS.has(node.kind)) continue\n const mains = mainsAt(context.graph, node)\n const [first, second] = mains\n const meets = mains.length >= 3\n const turns = mains.length === 2 && first !== undefined && second !== undefined && first.away[0] * second.away[0] + first.away[1] * second.away[1] > tolerance\n if (meets || turns) context.report({ code: NETWORK_VIOLATION.PV_MISSING, id: node.id, detail: meets ? 'crossing' : 'turn' })\n }\n}\n\n/** The kerb an inlet is on: its id without the ordinal of the inlet along the stretch (`storm:inlet:main_street:plus:02:03` is of `...:02`). */\nconst kerbOf = (id: string): string => id.slice(0, id.lastIndexOf(':'))\n\n/** At most `inletSpacing` between two inlets of a kerb's stretch. */\nfunction validateInletSpacing(context: ValidationContext, inlets: readonly NetworkNode[]): void {\n const kerbs = new Map<string, NetworkNode[]>()\n for (const inlet of inlets) kerbs.set(kerbOf(inlet.id), [...(kerbs.get(kerbOf(inlet.id)) ?? []), inlet])\n const limit = context.rules.storm.inletSpacing\n for (const kerb of kerbs.values()) {\n const alongX = Math.max(...kerb.map((inlet) => inlet.at[0])) - Math.min(...kerb.map((inlet) => inlet.at[0])) >= Math.max(...kerb.map((inlet) => inlet.at[2])) - Math.min(...kerb.map((inlet) => inlet.at[2]))\n const ordered = [...kerb].sort((a, b) => (alongX ? a.at[0] - b.at[0] : a.at[2] - b.at[2]))\n ordered.slice(1).forEach((inlet, index) => {\n const previous = ordered[index] as NetworkNode\n const gap = Math.hypot(inlet.at[0] - previous.at[0], inlet.at[2] - previous.at[2])\n if (gap > limit + 1e-6) context.report({ code: NETWORK_VIOLATION.INLET_SPACING, id: inlet.id, value: gap, limit })\n })\n }\n}\n\n/** The corners of a crossing of galleries: where the box has an arm in `+x` or `-x` and one in `+z` or `-z`, there is a corner between them. */\nfunction cornersOf(mains: readonly Main[]): Array<readonly [number, number]> {\n const signs = (axis: 0 | 1): number[] => [...new Set(mains.filter((main) => Math.abs(main.away[axis]) > 0.7).map((main) => Math.sign(main.away[axis])))]\n return signs(0).flatMap((x) => signs(1).map((z): readonly [number, number] => [x, z]))\n}\n\n/** Every corner of a crossing has an inlet at the kerb's end: one within `cornerReach` of the gallery box, on the corner's side. */\nfunction validateInletCorners(context: ValidationContext, inlets: readonly NetworkNode[]): void {\n const reach = context.rules.storm.cornerReach\n for (const node of context.graph.nodes.values()) {\n if (node.kind !== 'manhole' || !node.carries.includes('storm')) continue\n const mains = mainsAt(context.graph, node)\n if (mains.length < 3) continue\n for (const [x, z] of cornersOf(mains)) {\n const found = inlets.some((inlet) => Math.sign(inlet.at[0] - node.at[0]) === x && Math.sign(inlet.at[2] - node.at[2]) === z && Math.hypot(inlet.at[0] - node.at[0], inlet.at[2] - node.at[2]) <= reach)\n if (!found) context.report({ code: NETWORK_VIOLATION.INLET_AT_CORNER, id: node.id, detail: `${x > 0 ? '+' : '-'}x${z > 0 ? '+' : '-'}z`, limit: reach })\n }\n }\n}\n\n/** The direction of the street at the end of a lateral: that of the main it reaches, found through the cleanout when the lateral reaches one. */\nfunction streetAt(graph: NetworkGraph, nodeId: string, seen: ReadonlySet<string> = new Set()): Direction | undefined {\n const node = graph.nodes.get(nodeId)\n if (node === undefined || seen.has(nodeId)) return undefined\n const [main] = mainsAt(graph, node)\n if (main !== undefined) return main.away\n const onward = graph.outgoing(nodeId).find((edge) => edge.kind === 'sewer_lateral' || edge.kind === 'storm_lateral')\n return onward === undefined ? undefined : streetAt(graph, onward.to, new Set([...seen, nodeId]))\n}\n\n/** A house lateral and an inlet's lateral meet the street at a right angle, within `branchMaxSkew`. */\nfunction validateBranches(context: ValidationContext): void {\n const limit = context.rules.sewer.branchMaxSkew\n for (const edge of context.graph.edges.values()) {\n if (edge.kind !== 'sewer_lateral' && edge.kind !== 'storm_lateral') continue\n const from = context.graph.nodes.get(edge.from)\n const to = context.graph.nodes.get(edge.to)\n const street = streetAt(context.graph, edge.to)\n if (from === undefined || to === undefined || street === undefined) continue\n const branch = unit(to.at[0] - from.at[0], to.at[2] - from.at[2])\n if (branch[0] === 0 && branch[1] === 0) continue\n const skew = Math.abs(90 - Math.acos(Math.min(1, Math.abs(branch[0] * street[0] + branch[1] * street[1]))) / DEGREES)\n if (skew > limit) context.report({ code: NETWORK_VIOLATION.BRANCH_SKEWED, id: edge.id, value: skew, limit })\n }\n}\n\n/** What the plan of a street asks of the pipes under it: PVs where mains meet or turn, inlets along each kerb and at each corner, branches square to the street. */\nexport function validateSurface(context: ValidationContext): void {\n const inlets = [...context.graph.nodes.values()].filter((node) => node.kind === 'inlet')\n validatePits(context)\n validateInletSpacing(context, inlets)\n validateInletCorners(context, inlets)\n validateBranches(context)\n}\n","import { CONNECTION_NETWORK, EDGE_NETWORK, NETWORK_ENDS, NETWORK_FLOW } from './classes'\nimport { NETWORK_VIOLATION } from './codes'\nimport { connectedNodes } from './graph'\nimport type { NetworkKind, UtilityNetworks } from './types'\nimport type { ValidationContext } from './validate-context'\n\nconst NETWORKS: readonly NetworkKind[] = ['power_mv', 'power_lv', 'lighting', 'telecom', 'sewer', 'storm', 'water']\n\n/** Ids used twice, edges to missing nodes, edges whose ends do not carry their network. */\nexport function validateIds(context: ValidationContext, networks: UtilityNetworks): void {\n const seen = new Set<string>()\n for (const entry of [...networks.nodes, ...networks.edges]) {\n if (seen.has(entry.id)) context.report({ code: NETWORK_VIOLATION.DUPLICATE_ID, id: entry.id })\n seen.add(entry.id)\n }\n for (const edge of context.graph.edges.values()) {\n const network = EDGE_NETWORK[edge.kind]\n for (const end of [edge.from, edge.to]) {\n const node = context.graph.nodes.get(end)\n if (node === undefined) context.report({ code: NETWORK_VIOLATION.UNKNOWN_NODE, id: edge.id, detail: end })\n else if (!node.carries.includes(network)) context.report({ code: NETWORK_VIOLATION.NOT_CARRIED, id: edge.id, detail: `${end} does not carry ${network}` })\n }\n }\n}\n\n/**\n * Each network is a tree tied to its source: a supply node is fed by one edge of a network, a drain node flows out through one, and every\n * node that carries a network is reached from its source (or reaches its destination). A loop or an island is never reached, and a loop\n * through the source itself shows as a source with an edge coming in (or a destination with one going out).\n */\nexport function validateTrees(context: ValidationContext): void {\n for (const network of NETWORKS) {\n const supply = NETWORK_FLOW[network] === 'supply'\n const connected = connectedNodes(context.graph, network)\n for (const node of context.graph.nodes.values()) {\n if (!node.carries.includes(network)) continue\n const links = supply ? context.graph.incoming(node.id, network) : context.graph.outgoing(node.id, network)\n if (links.length > 1) context.report({ code: NETWORK_VIOLATION.NOT_RADIAL, id: node.id, detail: network, value: links.length, limit: 1 })\n if (!connected.has(node.id)) context.report({ code: NETWORK_VIOLATION.DISCONNECTED, id: node.id, detail: network })\n const back = supply ? context.graph.incoming(node.id, network) : context.graph.outgoing(node.id, network)\n if (NETWORK_ENDS[network].includes(node.kind) && back.length > 0) context.report({ code: NETWORK_VIOLATION.LOOP_AT_END, id: node.id, detail: network })\n }\n }\n}\n\n/** Every connection a lot declared is in the world frame, has one connection node on its network, and that node is tied to the source. */\nexport function validateLots(context: ValidationContext): void {\n const connections = context.options.connections ?? []\n const connectedByNetwork = new Map<NetworkKind, ReadonlySet<string>>()\n const nodes = [...context.graph.nodes.values()]\n const declared = new Set<string>()\n for (const connection of connections) {\n const id = `${connection.lot}:${connection.network}`\n if (declared.has(id)) {\n context.report({ code: NETWORK_VIOLATION.LOT_DECLARED_TWICE, id })\n continue\n }\n declared.add(id)\n if (connection.frame !== 'world') {\n context.report({ code: NETWORK_VIOLATION.CONNECTION_IN_PLAN_FRAME, id })\n continue\n }\n const network = CONNECTION_NETWORK[connection.network]\n const matches = nodes.filter((node) => node.kind === 'connection' && node.lot === connection.lot && node.carries.includes(network))\n if (matches.length > 1) context.report({ code: NETWORK_VIOLATION.LOT_CONNECTED_TWICE, id, value: matches.length, limit: 1 })\n const node = matches[0]\n const connected = connectedByNetwork.get(network) ?? connectedNodes(context.graph, network)\n connectedByNetwork.set(network, connected)\n if (node === undefined || !connected.has(node.id)) {\n context.report({ code: NETWORK_VIOLATION.LOT_UNCONNECTED, id, detail: network })\n continue\n }\n const moved = Math.hypot(node.at[0] - connection.at[0], node.at[1] - connection.at[1], node.at[2] - connection.at[2])\n if (moved > context.rules.connectionTolerance) context.report({ code: NETWORK_VIOLATION.CONNECTION_MOVED, id, value: moved, limit: context.rules.connectionTolerance })\n }\n}\n\n/** With the lots' connections given, every connection node answers one of them. */\nexport function validateOrphans(context: ValidationContext): void {\n const connections = context.options.connections\n if (connections === undefined) return\n const declared = new Set(connections.map((connection) => `${connection.lot}:${CONNECTION_NETWORK[connection.network]}`))\n for (const node of context.graph.nodes.values()) {\n if (node.kind !== 'connection') continue\n if (!node.carries.some((network) => declared.has(`${node.lot ?? ''}:${network}`))) context.report({ code: NETWORK_VIOLATION.ORPHAN_CONNECTION, id: node.id })\n }\n}\n","import type { NetworkViolation } from './codes'\nimport { buildNetworkGraph } from './graph'\nimport type { UtilityNetworks } from './types'\nimport { validateAerial } from './validate-aerial'\nimport { validateBuried } from './validate-buried'\nimport { validateDrops } from './validate-drops'\nimport type { ValidateNetworksOptions, ValidationContext } from './validate-context'\nimport { validateLoad } from './validate-load'\nimport { validateSurface } from './validate-surface'\nimport { validateIds, validateLots, validateOrphans, validateTrees } from './validate-structure'\n\n/**\n * Everything wrong with the networks, by the rules they carry: ids and links, each network a tree tied to its source, every lot linked once,\n * spans (reach, sag, clearance, buildings, crowns), pipes (slope, cover, depth, crossings) and transformers (loading, circuit length).\n * Pure and in input order: the same networks give the same list.\n */\nexport function validateNetworks(networks: UtilityNetworks, options: ValidateNetworksOptions = {}): NetworkViolation[] {\n const violations: NetworkViolation[] = []\n const context: ValidationContext = { graph: buildNetworkGraph(networks), rules: networks.rules, options, report: (violation) => violations.push(violation) }\n validateIds(context, networks)\n validateTrees(context)\n validateLots(context)\n validateOrphans(context)\n validateAerial(context)\n validateDrops(context)\n validateBuried(context)\n validateSurface(context)\n validateLoad(context)\n return violations\n}\n","import { DEFAULT_POLE_SLOTS } from './networks/slots'\nimport type { DistributionSpec } from './pole-specs'\n\n/** The 11 m double-T concrete distribution pole (9.3 m above the ground): the lamp's arm in the street light band, the drum in the transformer band. */\nexport const DISTRIBUTION: DistributionSpec = {\n mast: { radiusTop: 0.12, radiusBottom: 0.22, height: 9.3, color: 0x8a8a84, segments: 4 },\n arm: { reach: 1, y: 6.7, width: 2, height: 0.1, depth: 0.1, color: 0x6a6a66 },\n lamp: { reach: 2, y: 6.55, width: 0.5, height: 0.16, depth: 0.3 },\n lens: { lit: 0xffa040, unlit: 0x3a3a3a },\n light: { color: 0xff9a40, intensity: 1.3, distance: 20, y: 6.4 },\n transformer: { offset: 0.45, y: 7.7, radius: 0.32, height: 1, color: 0x5a5e62, segments: 8 },\n slots: DEFAULT_POLE_SLOTS,\n crossarm: { reach: 0.3, width: 2, height: 0.1, depth: 0.09, color: 0x8c8c86 },\n insulators: { at: [-0.55, 0.35, 1.15], radius: 0.04, color: 0xd8d4c8 },\n bushings: { spread: 0.16, radius: 0.025, height: 0.14, color: 0xa8b0b8 },\n lowVoltage: { out: 0.2, color: 0x5e6064 },\n telecom: { out: 0.18, color: 0x5e6064 },\n guy: { reach: 3, color: 0x7a7c7e },\n}\n","import type { PoleSystem } from './pole-tree'\nimport { diversifiedDemand, pickTransformer } from './rules'\nimport type { NetworkRules } from './rules'\n\n/** Length of the span between two neighbouring poles. */\nexport type SpanOf = (ends: { readonly from: string; readonly to: string }) => number\n\n/** One low voltage circuit: its poles, the pole that carries its transformer (the centre of the circuit), the rating that takes its load. */\nexport type Circuit = { readonly poles: readonly string[]; readonly transformer: string; readonly rating: string; readonly demand: number; readonly over: boolean }\n\nexport type CircuitParams = {\n readonly system: PoleSystem\n /** The installed kVA of each consumer a pole feeds (unknown counts in the lower column). */\n readonly consumers: ReadonlyMap<string, readonly number[]>\n readonly span: SpanOf\n readonly rules: NetworkRules\n /** Poles a transformer may not stand on (a service pole inside a lot: the medium voltage never enters a lot). */\n readonly isService: (pole: string) => boolean\n}\n\ntype Open = { readonly poles: string[]; readonly height: number; readonly diameter: number; readonly installed: number[] }\n\n/**\n * The circuits of a system, cut bottom up on its tree: a pole gathers its children's open circuits, and while the longest line between two\n * of their poles is over twice the circuit limit less one span (the transformer stands on a pole, at most half a span off the middle) or\n * their diversified demand (plus one lamp a pole) is over the largest rating's loading, the child that reaches farthest closes as a circuit\n * of its own (one more transformer). Each circuit's transformer stands on its centre. `over` marks a circuit no cut can bring under the\n * largest rating (one pole's own consumers).\n */\nexport function circuitsOf({ system, consumers, span, rules, isService }: CircuitParams): Circuit[] {\n const power = rules.power\n const capacity = Math.max(...power.transformers.map((rating) => rating.kva)) * power.maxLoading\n const longest = 2 * power.lvCircuitMaxLength - rules.layout.poles.spacing[1]\n const demandOf = (open: Pick<Open, 'poles' | 'installed'>): number => diversifiedDemand(open.installed, power) + open.poles.filter((pole) => !isService(pole)).length * rules.lighting.lampKva\n const closed: Array<Pick<Open, 'poles' | 'installed'>> = []\n const gather = (pole: string): Open => {\n const parts = (system.children.get(pole) ?? []).map((child) => {\n const open = gather(child)\n return { ...open, height: open.height + span({ from: pole, to: child }) }\n })\n parts.sort((a, b) => b.height - a.height)\n const own = (): Open => {\n const heights = parts.map((part) => part.height)\n return {\n poles: [pole, ...parts.flatMap((part) => part.poles)],\n height: Math.max(0, ...heights),\n diameter: Math.max(0, ...parts.map((part) => part.diameter), (heights[0] ?? 0) + (heights[1] ?? 0)),\n installed: [...(consumers.get(pole) ?? []), ...parts.flatMap((part) => part.installed)],\n }\n }\n let open = own()\n while (parts.length > 0 && (open.diameter > longest || demandOf(open) > capacity)) {\n closed.push(parts.shift() as Open)\n open = own()\n }\n return open\n }\n closed.push(gather(system.root))\n return closed.map((open) => {\n const transformer = centreOf({ poles: open.poles, system, span, isService })\n const demand = demandOf(open)\n const rating = pickTransformer(demand, power)\n return { poles: open.poles, transformer, rating: rating?.id ?? power.transformers[power.transformers.length - 1]?.id ?? 'none', demand, over: rating === undefined }\n })\n}\n\nexport type DistancesParams = { readonly poles: readonly string[]; readonly from: string; readonly system: PoleSystem; readonly span: SpanOf }\n\n/** Line length from `from` to every pole of the circuit, along the tree. */\nexport function distancesWithin({ poles, from, system, span }: DistancesParams): Map<string, number> {\n const members = new Set(poles)\n const distance = new Map([[from, 0]])\n const pending = [from]\n while (pending.length > 0) {\n const id = pending.pop() as string\n const up = system.parent.get(id)\n const near = [...(system.children.get(id) ?? []), ...(up === undefined ? [] : [up])].filter((next) => members.has(next) && !distance.has(next))\n for (const next of near) {\n distance.set(next, (distance.get(id) ?? 0) + span({ from: id, to: next }))\n pending.push(next)\n }\n }\n return distance\n}\n\n/** The street pole of a circuit with the shortest longest line to the others (the first in tree order on a tie). */\nfunction centreOf({ poles, system, span, isService }: Omit<DistancesParams, 'from'> & { readonly isService: (pole: string) => boolean }): string {\n let best = poles.find((pole) => !isService(pole)) ?? (poles[0] as string)\n let bestReach = Number.POSITIVE_INFINITY\n for (const pole of poles) {\n if (isService(pole)) continue\n const reach = Math.max(...distancesWithin({ poles, from: pole, system, span }).values())\n if (reach < bestReach - 1e-9) {\n best = pole\n bestReach = reach\n }\n }\n return best\n}\n","import { worldOf } from './frame'\nimport type { PoleStation } from './pole-layout'\nimport type { StreetRun } from './runs'\n\n/** A pole of the networks: its stable id and where it stands. A corner shared by two streets is one pole. */\nexport type NetworkPole = { readonly id: string; readonly station: PoleStation }\n\n/**\n * The poles one feed reaches through the spans, as a tree from the pole nearest the feed: `parent`, `children` and the length of line\n * from the root to each pole. Spans that would close a loop are left out, so every network laid on it is radial.\n */\nexport type PoleSystem = {\n readonly root: string\n /** Where the line enters the map (a run end at the border), on the line of the poles. */\n readonly feed: readonly [number, number]\n /** In order of distance from the root. */\n readonly poles: readonly string[]\n readonly parent: ReadonlyMap<string, string>\n readonly children: ReadonlyMap<string, readonly string[]>\n readonly distance: ReadonlyMap<string, number>\n readonly depth: ReadonlyMap<string, number>\n}\n\nexport type PoleTree = { readonly poles: ReadonlyMap<string, NetworkPole>; readonly systems: readonly PoleSystem[] }\n\nexport type PoleTreeParams = {\n /** Stations of each run in order, and service chains from their street pole: consecutive stations are spans. */\n readonly chains: ReadonlyArray<readonly PoleStation[]>\n readonly sides: ReadonlyMap<string, 1 | -1>\n readonly setback: number\n}\n\nconst planDistance = (a: PoleStation, b: PoleStation): number => Math.hypot(a.x - b.x, a.z - b.z)\nconst spotOf = (station: PoleStation): string => `${Math.round(station.x * 20)},${Math.round(station.z * 20)}`\n\n/** Poles by id (a station two runs share at the same spot kept once) and the spans between consecutive stations of each chain. */\nfunction polesAndSpans(chains: ReadonlyArray<readonly PoleStation[]>): { poles: Map<string, NetworkPole>; spans: Map<string, Set<string>> } {\n const poles = new Map<string, NetworkPole>()\n const bySpot = new Map<string, string>()\n const spans = new Map<string, Set<string>>()\n const link = (a: string, b: string): void => {\n if (a === b) return\n spans.set(a, (spans.get(a) ?? new Set()).add(b))\n spans.set(b, (spans.get(b) ?? new Set()).add(a))\n }\n for (const chain of chains) {\n let previous: string | undefined\n for (const station of chain) {\n const id = bySpot.get(spotOf(station)) ?? station.id\n if (!poles.has(id)) {\n poles.set(id, { id, station })\n bySpot.set(spotOf(station), id)\n }\n if (previous !== undefined) link(previous, id)\n previous = id\n }\n }\n linkCorners(poles, link)\n return { poles, spans }\n}\n\n/** At every crossing, the corner poles of the two streets that do not share a spot are joined by a span across the corner (the nearest pair). */\nfunction linkCorners(poles: ReadonlyMap<string, NetworkPole>, link: (a: string, b: string) => void): void {\n const corners = [...poles.values()].filter((pole) => pole.station.role === 'corner')\n const runs = new Map(corners.map((pole) => [pole.station.run.id, pole.station.run]))\n for (const run of runs.values()) {\n for (const crossing of run.crossings) {\n const near = (pole: NetworkPole, of: StreetRun, at: number, half: number): boolean => pole.station.run.id === of.id && Math.abs(pole.station.u - at) <= half + 2\n const other = runs.get(crossing.run)\n if (other === undefined || other.id < run.id) continue\n const mine = corners.filter((pole) => near(pole, run, crossing.at, crossing.half))\n const theirs = corners.filter((pole) => near(pole, other, run.axis, run.width / 2))\n const pairs = mine.flatMap((a) => theirs.map((b) => [a, b] as const)).sort((p, q) => planDistance(p[0].station, p[1].station) - planDistance(q[0].station, q[1].station) || (p[0].id + p[1].id < q[0].id + q[1].id ? -1 : 1))\n const best = pairs[0]\n if (best !== undefined) link(best[0].id, best[1].id)\n }\n }\n}\n\nfunction feedOf({ runs, sides, setback, fallback }: { readonly runs: readonly StreetRun[]; readonly sides: ReadonlyMap<string, 1 | -1>; readonly setback: number; readonly fallback: NetworkPole }): readonly [number, number] {\n for (const run of runs) {\n const v = (sides.get(run.id) ?? -1) * (run.width / 2 + setback)\n if (run.ends[0] === 'edge') return worldOf({ frame: run, u: run.from, v })\n if (run.ends[1] === 'edge') return worldOf({ frame: run, u: run.to, v })\n }\n return [fallback.station.x, fallback.station.z]\n}\n\n/** Shortest-line tree from the root over the spans (ties by id), so the same poles always give the same tree. Plain O(n²) Dijkstra: a system has tens of poles. */\nfunction treeFrom({ root, poles, spans }: { readonly root: string; readonly poles: ReadonlyMap<string, NetworkPole>; readonly spans: ReadonlyMap<string, ReadonlySet<string>> }): Omit<PoleSystem, 'feed'> {\n const distance = new Map([[root, 0]])\n const parent = new Map<string, string>()\n const done = new Set<string>()\n const order: string[] = []\n for (;;) {\n const open = [...distance.entries()].filter(([id]) => !done.has(id)).sort((a, b) => a[1] - b[1] || (a[0] < b[0] ? -1 : 1))[0]\n if (open === undefined) break\n const [id, base] = open\n done.add(id)\n order.push(id)\n for (const next of [...(spans.get(id) ?? [])].sort()) {\n const length = base + planDistance((poles.get(id) as NetworkPole).station, (poles.get(next) as NetworkPole).station)\n if (done.has(next) || length >= (distance.get(next) ?? Number.POSITIVE_INFINITY)) continue\n distance.set(next, length)\n parent.set(next, id)\n }\n }\n const children = new Map<string, string[]>()\n const depth = new Map<string, number>()\n for (const id of order) {\n const up = parent.get(id)\n depth.set(id, up === undefined ? 0 : (depth.get(up) ?? 0) + 1)\n if (up !== undefined) children.set(up, [...(children.get(up) ?? []), id])\n }\n return { root, poles: order, parent, children, distance, depth }\n}\n\n/** The poles of every run and the systems they make: each fed from the border where one of its runs leaves the map (one per side of a river). */\nexport function poleTreeOf({ chains, sides, setback }: PoleTreeParams): PoleTree {\n const { poles, spans } = polesAndSpans(chains)\n const systems: PoleSystem[] = []\n const seen = new Set<string>()\n for (const pole of poles.values()) {\n if (seen.has(pole.id)) continue\n const members = treeFrom({ root: pole.id, poles, spans }).poles\n for (const id of members) seen.add(id)\n const runs = [...new Map(members.map((id) => (poles.get(id) as NetworkPole).station.run).map((run) => [run.id, run])).values()]\n const feed = feedOf({ runs, sides, setback, fallback: pole })\n const along = (id: string): number => Math.hypot((poles.get(id) as NetworkPole).station.x - feed[0], (poles.get(id) as NetworkPole).station.z - feed[1])\n const root = [...members].filter((id) => (poles.get(id) as NetworkPole).station.role !== 'service').sort((a, b) => along(a) - along(b))[0] ?? pole.id\n systems.push({ ...treeFrom({ root, poles, spans }), feed })\n }\n return { poles, systems }\n}\n\n/** Length of the span between two poles, metres in plan. */\nexport const spanLength = ({ tree, from, to }: { readonly tree: PoleTree; readonly from: string; readonly to: string }): number =>\n planDistance((tree.poles.get(from) as NetworkPole).station, (tree.poles.get(to) as NetworkPole).station)\n","import type { UtilityConnection } from '@adatechnology/game-contracts'\n\nimport type { PoleSlots } from '../pole-specs'\nimport { circuitsOf, distancesWithin } from './circuits'\nimport type { Circuit, SpanOf } from './circuits'\nimport { planBins, worldOf } from './frame'\nimport { spanLength } from './pole-tree'\nimport type { NetworkPole, PoleSystem, PoleTree } from './pole-tree'\nimport type { NetworkRules } from './rules'\nimport type { NetworkEdge, NetworkKind, NetworkNode } from './types'\nimport type { NetworkWarning } from './warnings'\n\n/** What the layers of the generator add to. */\nexport type NetworkSink = { readonly nodes: NetworkNode[]; readonly edges: NetworkEdge[]; readonly warnings: NetworkWarning[] }\n\n/** The fixing heights over the ground, read from the pole's bands. */\nexport type PoleHeights = { readonly mv: number; readonly transformer: number; readonly transformerBottom: number; readonly lv: number; readonly lamp: number; readonly telecom: number }\n\nexport function poleHeightsOf(slots: PoleSlots): PoleHeights {\n const { mv, transformer, lv, lighting, telecom } = slots.bands\n return { mv: mv[1], transformer: (transformer[0] + transformer[1]) / 2, transformerBottom: transformer[0], lv: lv[1] - 0.1, lamp: lighting[0] + 0.1, telecom: telecom[1] }\n}\n\nexport type AerialParams = {\n readonly tree: PoleTree\n readonly connections: readonly UtilityConnection[]\n readonly rules: NetworkRules\n readonly heights: PoleHeights\n /** The distribution pole of the registry: its id and how far its arm hangs the lamp from the mast. */\n readonly pole: { readonly id: string; readonly lampReach: number }\n /** Lots with a drop and no meter (illegal hookups): linked as any other, counted in the load. */\n readonly unmetered: ReadonlySet<string>\n /** The pole each lot's drop leaves from (`reachLots`): in front of the lot or straight across, at most `dropsPerPole` a pole. */\n readonly feeds: ReadonlyMap<string, { readonly x: number; readonly z: number }>\n readonly sink: NetworkSink\n}\n\n/** The poles of a tree in cells, to find the nearest ones to a point. */\nexport function poleFinder(tree: PoleTree): (point: { readonly x: number; readonly z: number; readonly radius: number }) => NetworkPole[] {\n const bins = planBins<NetworkPole>(40)\n for (const pole of tree.poles.values()) bins.add(pole.station.x, pole.station.z, pole)\n const all = [...tree.poles.values()]\n return ({ x, z, radius }) => {\n const near = bins.near(x, z, radius)\n const pool = near.length > 0 ? near : all\n return pool.sort((a, b) => Math.hypot(a.station.x - x, a.station.z - z) - Math.hypot(b.station.x - x, b.station.z - z) || (a.id < b.id ? -1 : 1))\n }\n}\n\n/** The lamp of a pole: on its arm over the road, `lampReach` from the mast toward the street. A service pole inside a lot has none. */\nexport function lampOf({ pole, rules, lampReach }: { readonly pole: NetworkPole; readonly rules: NetworkRules; readonly lampReach: number }): readonly [number, number] | undefined {\n const { run, side, u, role } = pole.station\n if (role === 'service') return undefined\n return worldOf({ frame: run, u, v: side * (run.width / 2 + rules.layout.poles.curbSetback - lampReach) })\n}\n\n/** The pole that stands at a point, or none. */\nexport function poleAt(tree: PoleTree, at: { readonly x: number; readonly z: number } | undefined): NetworkPole | undefined {\n if (at === undefined) return undefined\n return [...tree.poles.values()].find((pole) => Math.hypot(pole.station.x - at.x, pole.station.z - at.z) < 1e-6)\n}\n\n/** Each lot's drop from the pole `reachLots` chose for it (the nearest one in reach when it chose none). */\nfunction dropsOf(params: AerialParams): Map<string, UtilityConnection[]> {\n const find = poleFinder(params.tree)\n const out = new Map<string, UtilityConnection[]>()\n for (const connection of params.connections) {\n const pole = poleAt(params.tree, params.feeds.get(`${connection.lot}:power`)) ?? find({ x: connection.at[0], z: connection.at[2], radius: params.rules.power.dropMaxLength })[0]\n if (pole !== undefined) out.set(pole.id, [...(out.get(pole.id) ?? []), connection])\n }\n return out\n}\n\n/** The circuits of every system, with the poles the medium voltage must reach (the path from the feed to each transformer). */\nexport function powerPlanOf({ params, drops }: { readonly params: AerialParams; readonly drops: ReadonlyMap<string, readonly UtilityConnection[]> }): Array<{ system: PoleSystem; circuits: Circuit[]; medium: Set<string> }> {\n const span: SpanOf = ({ from, to }) => spanLength({ tree: params.tree, from, to })\n const isService = (pole: string): boolean => params.tree.poles.get(pole)?.station.role === 'service'\n return params.tree.systems.map((system) => {\n const consumers = new Map(system.poles.map((pole) => [pole, (drops.get(pole) ?? []).map((connection) => connection.installedKva ?? 0)]))\n const circuits = circuitsOf({ system, consumers, span, rules: params.rules, isService })\n // the medium voltage runs along every street pole of the feeder (a street with poles and no medium voltage reads wrong), and to each transformer\n const medium = new Set(system.poles.filter((pole) => !isService(pole)))\n for (const circuit of circuits) {\n for (let pole: string | undefined = circuit.transformer; pole !== undefined && !medium.has(pole); pole = system.parent.get(pole)) medium.add(pole)\n }\n return { system, circuits, medium }\n })\n}\n\n/** Medium voltage from each feed to the transformers, each circuit's low voltage from its transformer, a lamp on every street pole and a drop to every lot. */\nexport function layPower(params: AerialParams): void {\n const { tree, heights, rules, sink } = params\n const sag = rules.layout.sag\n const drops = dropsOf(params)\n for (const { system, circuits, medium } of powerPlanOf({ params, drops })) {\n const feed = `feed:${system.root}`\n sink.nodes.push({ id: feed, kind: 'feed', at: [system.feed[0], heights.mv, system.feed[1]], carries: ['power_mv'] })\n for (const id of system.poles) {\n const pole = tree.poles.get(id) as NetworkPole\n const lamp = lampOf({ pole, rules, lampReach: params.pole.lampReach })\n const carries: NetworkKind[] = [...(medium.has(id) ? (['power_mv'] as const) : []), 'power_lv', ...(lamp === undefined ? [] : (['lighting'] as const)), 'telecom']\n sink.nodes.push({ id, kind: 'pole', at: [pole.station.x, 0, pole.station.z], carries, spec: params.pole.id, ...(pole.station.role === 'line' || pole.station.role === 'service' ? {} : { guyed: true }) })\n if (medium.has(id)) sink.edges.push({ id: `mv:${id}`, kind: 'mv_span', from: system.parent.get(id) ?? feed, to: id, sag: sag.mv, heights: [heights.mv, heights.mv], conductors: 3 })\n if (lamp === undefined) continue\n sink.nodes.push({ id: `light:${id}`, kind: 'light', at: [lamp[0], heights.lamp, lamp[1]], carries: ['lighting'], spec: 'street_light' })\n sink.edges.push({ id: `light_feed:${id}`, kind: 'light_feed', from: id, to: `light:${id}`, sag: 0, heights: [heights.lv, heights.lamp] })\n }\n for (const circuit of circuits) {\n if (circuit.over) sink.warnings.push({ code: 'transformer_over_capacity', id: `transformer:${circuit.transformer}`, detail: `${circuit.demand.toFixed(1)} kVA` })\n layCircuit({ params, system, circuit })\n }\n }\n for (const [poleId, connections] of drops) {\n for (const connection of connections) {\n const node = `lot:${connection.lot}:power`\n sink.nodes.push({ id: node, kind: 'connection', at: connection.at, carries: ['power_lv'], lot: connection.lot, ...(params.unmetered.has(connection.lot) ? { spec: 'unmetered' } : {}) })\n sink.edges.push({ id: `drop:${connection.lot}`, kind: 'service_drop', from: poleId, to: node, sag: sag.drop, heights: [heights.lv, connection.at[1]], conductors: 2 })\n }\n }\n}\n\n/** The transformer on its pole, fed by the medium voltage, and the low voltage spans out from it over the circuit's poles. */\nfunction layCircuit({ params, system, circuit }: { readonly params: AerialParams; readonly system: PoleSystem; readonly circuit: Circuit }): void {\n const { tree, heights, sink } = params\n const pole = tree.poles.get(circuit.transformer) as NetworkPole\n const id = `transformer:${circuit.transformer}`\n sink.nodes.push({ id, kind: 'transformer', at: [pole.station.x, heights.transformer, pole.station.z], carries: ['power_mv', 'power_lv'], spec: circuit.rating })\n sink.edges.push({ id: `mv:${id}`, kind: 'mv_span', from: circuit.transformer, to: id, sag: 0, heights: [heights.mv, heights.transformer] })\n sink.edges.push({ id: `lv:${circuit.transformer}`, kind: 'lv_span', from: id, to: circuit.transformer, sag: 0, heights: [heights.transformerBottom, heights.lv] })\n const span: SpanOf = ({ from, to }) => spanLength({ tree, from, to })\n const order = [...distancesWithin({ poles: circuit.poles, from: circuit.transformer, system, span }).entries()].sort((a, b) => a[1] - b[1])\n const members = new Set(circuit.poles)\n const reached = new Set([circuit.transformer])\n for (const [from] of order) {\n const up = system.parent.get(from)\n const near = [...(system.children.get(from) ?? []), ...(up === undefined ? [] : [up])].filter((next) => members.has(next) && !reached.has(next))\n for (const next of near) {\n reached.add(next)\n sink.edges.push({ id: `lv:${next}`, kind: 'lv_span', from, to: next, sag: params.rules.layout.sag.lv, heights: [heights.lv, heights.lv], conductors: 4 })\n }\n }\n}\n","import type { UtilityConnection, UtilityNetwork } from '@adatechnology/game-contracts'\n\nimport { worldOf } from './frame'\nimport type { NetworkRules } from './rules'\nimport type { ServedLot } from './runs'\n\nexport type GroundAt = (x: number, z: number) => number\n\n/**\n * Where a lot takes each network when it declares none, from its rectangle and the street it faces: the meter post (power, telecom 0.6 m\n * under it) and the water stand behind the front wall, the inspection box 1 m inside the front, the downspout outlet at the kerb.\n */\nexport function defaultConnectionsOf({ served, rules, groundAt }: { readonly served: ServedLot; readonly rules: NetworkRules; readonly groundAt: GroundAt }): UtilityConnection[] {\n const { run, side, span, front, lot } = served\n const rule = rules.layout.connection\n const within = (u: number): number => Math.min(Math.max(u, span[0]), span[1])\n const centre = (span[0] + span[1]) / 2\n const at = (u: number, v: number, above: number): readonly [number, number, number] => {\n const [x, z] = worldOf({ frame: run, u: within(u), v })\n return [x, groundAt(x, z) + above, z]\n }\n const wall = side * (front + rule.frontInset)\n const sewer = at(centre, side * (front + rule.sewerInset), 0)\n const base = { lot: lot.id, frame: 'world' as const }\n return [\n { ...base, network: 'power', at: at(span[0] + rule.meterFromSide, wall, rule.powerHeight) },\n { ...base, network: 'telecom', at: at(span[0] + rule.meterFromSide, wall, rule.powerHeight - rule.telecomBelowPower) },\n { ...base, network: 'sewer', at: sewer, invert: sewer[1] - sewerDepthOf({ rules, length: front + rule.sewerInset - rules.layout.sewer.dropOffset }) },\n { ...base, network: 'storm', at: at(span[1] - rule.downspoutFromSide, side * (run.width / 2), 0) },\n { ...base, network: 'water', at: at(span[0] + rule.waterFromSide, wall, 0) },\n ]\n}\n\n/**\n * The depth of a lot's inspection box outlet: the usual one, shallower for a lot set back from its street, so its lateral still crosses\n * the gallery within `lateralOverGallery` at its least slope (never under `sewerLeastDepth`).\n */\nfunction sewerDepthOf({ rules, length }: { readonly rules: NetworkRules; readonly length: number }): number {\n const { connection, slopeMargin, coverMargin } = rules.layout\n const fits = rules.sewer.lateralOverGallery - coverMargin - (rules.minSlope.sewer_lateral + slopeMargin) * length\n return Math.max(connection.sewerLeastDepth, Math.min(connection.sewerDepth, fits))\n}\n\n/** The connections of every served lot: the ones a lot declared, and the defaults for the networks it declared none of. */\nexport type LotConnectionsParams = { readonly served: readonly ServedLot[]; readonly declared: readonly UtilityConnection[]; readonly rules: NetworkRules; readonly groundAt: GroundAt }\n\nexport function lotConnectionsOf({ served, declared, rules, groundAt }: LotConnectionsParams): UtilityConnection[] {\n const own = new Map(declared.map((connection) => [`${connection.lot}:${connection.network}`, connection]))\n return served.flatMap((entry) => defaultConnectionsOf({ served: entry, rules, groundAt }).map((fallback) => own.get(`${entry.lot.id}:${fallback.network}`) ?? fallback))\n}\n\n/** The connections of one network. */\nexport const ofNetwork = ({ connections, network }: { readonly connections: readonly UtilityConnection[]; readonly network: UtilityNetwork }): UtilityConnection[] =>\n connections.filter((connection) => connection.network === network)\n","import type { PlanRect } from '../cities/types'\nimport { ordinal, worldOf } from './frame'\nimport type { NetworkLayoutRules } from './layout-rules'\nimport type { RunEnd, ServedLot, StreetRun } from './runs'\nimport type { NetworkWarning } from './warnings'\n\n/** Where a pole stands: its id, its run, its station along it, the world point and its role (corner, end of line, in line, or a service pole inside a lot). */\nexport type PoleStation = {\n readonly id: string\n readonly run: StreetRun\n readonly side: 1 | -1\n readonly u: number\n readonly x: number\n readonly z: number\n readonly role: 'corner' | 'end' | 'line' | 'service'\n}\n\ntype PieceEnd = RunEnd | 'crossing'\ntype Piece = { readonly from: number; readonly to: number; readonly ends: readonly [PieceEnd, PieceEnd] }\n\n/** The sidewalk stretches of a run between the cross streets' roadways. */\nexport function piecesOf(run: StreetRun): Piece[] {\n const out: Piece[] = []\n let start = run.from\n let startEnd: PieceEnd = run.ends[0]\n for (const crossing of run.crossings) {\n out.push({ from: start, to: crossing.at - crossing.half, ends: [startEnd, 'crossing'] })\n start = crossing.at + crossing.half\n startEnd = 'crossing'\n }\n out.push({ from: start, to: run.to, ends: [startEnd, run.ends[1]] })\n return out.filter((piece) => piece.to - piece.from > 1)\n}\n\nexport type PoleLayoutParams = {\n readonly run: StreetRun\n readonly side: 1 | -1\n readonly served: readonly ServedLot[]\n readonly avoid: readonly PlanRect[]\n readonly rules: NetworkLayoutRules\n /** Where something must stand clear of a gate that no free ground could clear is told here. */\n readonly warn: (warning: NetworkWarning) => void\n}\n\ntype Placed = { readonly u: number; readonly role: PoleStation['role'] }\ntype Bounds = { readonly low: number; readonly high: number }\n\nconst inside = (x: number, z: number, rect: PlanRect): boolean => x > rect[0] && x < rect[2] && z > rect[1] && z < rect[3]\n\n/** The pole line of a run: `u` to the world, and whether a station is clear of every `avoid` rectangle. */\nfunction lineOf(params: PoleLayoutParams): { place: (u: number) => readonly [number, number]; isFree: (u: number) => boolean } {\n const lateral = params.side * (params.run.width / 2 + params.rules.poles.curbSetback)\n const place = (u: number): readonly [number, number] => worldOf({ frame: params.run, u, v: lateral })\n return { place, isFree: (u) => !params.avoid.some((rect) => inside(...place(u), rect)) }\n}\n\n/** The nearest free station to `u` within `bounds` (0, then ±step, ±2 steps... up to the slide), or none. */\nfunction slideClear({ u, bounds, isFree, poles }: { readonly u: number; readonly bounds: Bounds; readonly isFree: (u: number) => boolean; readonly poles: NetworkLayoutRules['poles'] }): number | undefined {\n for (let step = 0; step <= poles.slide / poles.slideStep; step++) {\n for (const offset of step === 0 ? [0] : [step * poles.slideStep, -step * poles.slideStep]) {\n const candidate = u + offset\n if (candidate >= bounds.low && candidate <= bounds.high && isFree(candidate)) return candidate\n }\n }\n return undefined\n}\n\n/**\n * The next in-line station after `at`, toward `last`: the lot boundary nearest the even target, slid clear of gates, never beyond the\n * longest span. With no free ground near the target it tries the other boundaries in reach, then any free station in reach; with none, it\n * stands at the target and warns.\n */\nfunction nextStation({ at, last, bounds, boundaries, params }: { readonly at: number; readonly last: number; readonly bounds: Bounds; readonly boundaries: readonly number[]; readonly params: PoleLayoutParams }): number {\n const { poles } = params.rules\n const { isFree } = lineOf(params)\n const target = at + (last - at) / Math.ceil((last - at) / poles.spacing[1])\n const reach: Bounds = { low: Math.max(bounds.low, at + 1), high: Math.min(bounds.high, at + poles.spacing[1]) }\n const inReach = boundaries.filter((u) => u >= reach.low && u <= reach.high).sort((a, b) => Math.abs(a - target) - Math.abs(b - target) || a - b)\n const first = inReach[0] !== undefined && Math.abs(inReach[0] - target) <= poles.snap ? inReach[0] : Math.min(Math.max(target, reach.low), reach.high)\n for (const candidate of [first, ...inReach]) {\n const slid = slideClear({ u: candidate, bounds: reach, isFree, poles })\n if (slid !== undefined) return slid\n }\n for (let u = reach.high; u >= reach.low; u -= poles.slideStep) if (isFree(u)) return u\n params.warn({ code: 'pole_on_avoid', id: `${params.run.id}@${first.toFixed(2)}` })\n return first\n}\n\n/** The stations of one stretch: a corner or end pole at each end, and in-line poles every 30 to 40 m on lot boundaries, clear of gates. */\nfunction piecePoles({ piece, params, boundaries }: { readonly piece: Piece; readonly params: PoleLayoutParams; readonly boundaries: readonly number[] }): Placed[] {\n const { poles } = params.rules\n const { isFree } = lineOf(params)\n // a corner or end pole slides inward off a gate (up to the slide), and warns when it finds no free ground\n const endAt = (end: PieceEnd, at: number, inward: 1 | -1): Placed => {\n const u = at + inward * (end === 'crossing' ? poles.curbSetback : poles.endInset)\n const role = end === 'crossing' ? 'corner' : 'end'\n for (let step = 0; step <= poles.slide / poles.slideStep; step++) {\n const candidate = u + inward * step * poles.slideStep\n if (isFree(candidate)) return { u: candidate, role }\n }\n params.warn({ code: 'pole_on_avoid', id: `${params.run.id}@${u.toFixed(2)}` })\n return { u, role }\n }\n const first = endAt(piece.ends[0], piece.from, 1)\n const last = endAt(piece.ends[1], piece.to, -1)\n if (last.u - first.u < poles.spacing[0] / 4) return [{ u: (first.u + last.u) / 2, role: first.role }]\n const bounds: Bounds = {\n low: piece.ends[0] === 'crossing' ? piece.from + poles.crossingClearance : first.u,\n high: piece.ends[1] === 'crossing' ? piece.to - poles.crossingClearance : last.u,\n }\n const out: Placed[] = [first]\n let at = first.u\n while (last.u - at > poles.spacing[1]) {\n const next = nextStation({ at, last: last.u, bounds, boundaries, params })\n if (next <= at + 1) break\n out.push({ u: next, role: 'line' })\n at = next\n }\n out.push(last)\n return out\n}\n\n/** Every pole station of a run, in order along it: corners at the cross streets, ends at the river and the line ends, in-line poles between. */\nexport function poleStationsOf(params: PoleLayoutParams): PoleStation[] {\n const { run, side } = params\n const boundaries = [...new Set(params.served.filter((entry) => entry.run.id === run.id).flatMap((entry) => [entry.span[0], entry.span[1]]))].sort((a, b) => a - b)\n const { place } = lineOf(params)\n return piecesOf(run)\n .flatMap((piece) => piecePoles({ piece, params, boundaries }))\n .map((station, index) => {\n const [x, z] = place(station.u)\n return { ...station, id: `pole:${run.id}:${ordinal(index)}`, run, side, x, z }\n })\n}\n","import type { UtilityConnection } from '@adatechnology/game-contracts'\n\nimport { frameOf, ordinal } from './frame'\nimport { dropMisfitOf, lotUnderDrop } from './drop-rules'\nimport type { LotFrontage } from './drop-rules'\nimport type { NetworkLayoutRules } from './layout-rules'\nimport type { PowerRules } from './rules'\nimport { piecesOf } from './pole-layout'\nimport type { PoleStation } from './pole-layout'\nimport type { ServedLot, StreetRun } from './runs'\nimport type { NetworkWarning } from './warnings'\n\nexport type ReachParams = {\n /** The stations of each run, in order along it. */\n readonly runs: ReadonlyArray<readonly PoleStation[]>\n /** The points the drops must reach (power and telecom anchors). */\n readonly anchors: readonly UtilityConnection[]\n readonly served: ReadonlyMap<string, ServedLot>\n /** Longest drop, metres. */\n readonly reach: number\n readonly rules: NetworkLayoutRules\n /** Clear of every gate, door and meter post. */\n readonly isFree: (x: number, z: number) => boolean\n /** Where a service pole of a lot may stand: off the roadway and out of every other lot. */\n readonly canServe: (point: { readonly x: number; readonly z: number; readonly lot: string }) => boolean\n readonly warn: (warning: NetworkWarning) => void\n /** The lots' fronts and the drop rules: a power anchor is fed from a pole in front of it or straight across, never over another lot. */\n readonly frontages: ReadonlyMap<string, LotFrontage>\n readonly power: Pick<PowerRules, 'dropMaxSkew' | 'dropFrontageSlack' | 'dropsPerPole'>\n}\n\nexport type Reached = {\n /** The stations of each run with the poles added to reach the lots, renumbered in order. */\n readonly runs: PoleStation[][]\n /** Service poles into a lot set back from its street: each chain starts at the street pole it hangs from. */\n readonly chains: PoleStation[][]\n /** The pole (where it stands) each lot's drop of each network leaves from, by `feedKey`. */\n readonly feeds: ReadonlyMap<string, { readonly x: number; readonly z: number }>\n}\n\n/** The key of a lot's drop of one network in `Reached.feeds`. */\nexport const feedKey = (anchor: Pick<UtilityConnection, 'lot' | 'network'>): string => `${anchor.lot}:${anchor.network}`\n\nconst distance = (station: PoleStation, anchor: UtilityConnection): number => Math.hypot(station.x - anchor.at[0], station.z - anchor.at[2])\n\ntype InLineParams = { readonly run: StreetRun; readonly stations: readonly PoleStation[]; readonly anchor: UtilityConnection; readonly params: ReachParams }\n\n/** An in-line station on the run's pole line at the lot's own station, inside a stretch, on free ground and `minGap` from every pole, or none. */\nfunction inLine({ run, stations, anchor, params }: InLineParams): PoleStation | undefined {\n const { poles } = params.rules\n const [u] = frameOf({ frame: run, x: anchor.at[0], z: anchor.at[2] })\n const side = stations[0]?.side ?? -1\n const lateral = side * (run.width / 2 + poles.curbSetback)\n const clear = (at: number): boolean => stations.every((station) => Math.abs(station.u - at) >= poles.minGap)\n for (const piece of piecesOf(run)) {\n const [low, high] = [piece.from + poles.crossingClearance, piece.to - poles.crossingClearance]\n if (u < piece.from || u > piece.to || high < low) continue\n for (let step = 0; step <= poles.slide / poles.slideStep; step++) {\n for (const offset of step === 0 ? [0] : [step * poles.slideStep, -step * poles.slideStep]) {\n const at = Math.min(Math.max(u + offset, low), high)\n const [x, z] = run.along === 'x' ? [at, run.axis + lateral] : [run.axis + lateral, at]\n if (params.isFree(x, z) && clear(at)) return { id: '', run, side, u: at, x, z, role: 'line' }\n }\n }\n }\n return undefined\n}\n\n/**\n * Service poles from `from` toward the anchor, evenly spaced (`gap / (count + 1)`, never past the anchor), as few as keep each span within\n * the longest and the last drop within reach. Each stands on ground a pole may take (slid along the line up to the slide); with none, the\n * lot is told out of reach and no chain is laid.\n */\nfunction chainTo({ from, anchor, params }: { readonly from: PoleStation; readonly anchor: UtilityConnection; readonly params: ReachParams }): PoleStation[] | undefined {\n const { poles } = params.rules\n const gap = distance(from, anchor)\n const count = Math.max(0, Math.ceil(gap / poles.spacing[1]) - 1, Math.ceil(gap / (params.reach - 1)) - 1)\n const out: PoleStation[] = []\n for (let index = 0; index < count; index++) {\n const even = ((index + 1) * gap) / (count + 1)\n const offsets = [0, ...Array.from({ length: Math.floor(poles.slide / poles.slideStep) }, (_, step) => [(step + 1) * poles.slideStep, -(step + 1) * poles.slideStep]).flat()]\n const spot = offsets.map((offset) => Math.min(Math.max(even + offset, 1), gap - 1) / gap).map((share) => ({ x: from.x + (anchor.at[0] - from.x) * share, z: from.z + (anchor.at[2] - from.z) * share })).find((point) => params.isFree(point.x, point.z) && params.canServe({ ...point, lot: anchor.lot }))\n if (spot === undefined) {\n params.warn({ code: 'lot_out_of_reach', id: anchor.lot, detail: `${gap.toFixed(1)} m` })\n return undefined\n }\n out.push({ ...from, id: `pole:${from.run.id}:lot:${anchor.lot}:${ordinal(index)}`, x: spot.x, z: spot.z, role: 'service' })\n }\n return out\n}\n\n/** Whether a pole may feed the anchor: in reach, in front of the lot or straight across, over no other lot. */\nexport function feedsAnchor({ station, anchor, params }: { readonly station: { readonly x: number; readonly z: number }; readonly anchor: UtilityConnection; readonly params: Pick<ReachParams, 'reach' | 'frontages' | 'power'> }): boolean {\n if (Math.hypot(station.x - anchor.at[0], station.z - anchor.at[2]) > params.reach - 1e-6) return false\n const frontage = params.frontages.get(anchor.lot)\n if (!frontage) return true\n if (dropMisfitOf({ frontage, pole: station, anchor: anchor.at, rules: params.power }) !== undefined) return false\n return lotUnderDrop({ from: [station.x, station.z], to: [anchor.at[0], anchor.at[2]], lot: anchor.lot, frontages: [...params.frontages.values()] }) === undefined\n}\n\n/**\n * Poles added where a lot's anchor has no pole to feed it (design §4): the nearest pole in front of the lot or straight across the street with\n * room for one more drop (`dropsPerPole`); with none, an in-line pole on its street at the lot's station, and when the lot stands farther back\n * than a drop, service poles into it from that pole.\n */\nexport function reachLots(params: ReachParams): Reached {\n const runs = params.runs.map((stations) => [...stations])\n const chains: PoleStation[][] = []\n const feeds = new Map<string, PoleStation>()\n const load = new Map<PoleStation, number>()\n const all = (): PoleStation[] => [...runs.flat(), ...chains.flat()]\n const take = (anchor: UtilityConnection, station: PoleStation): void => {\n feeds.set(feedKey(anchor), station)\n if (anchor.network === 'power') load.set(station, (load.get(station) ?? 0) + 1)\n }\n const free = (station: PoleStation): boolean => (load.get(station) ?? 0) < params.power.dropsPerPole\n // power first, so a telecom drop can leave the pole its lot's power drop leaves\n const anchors = [...params.anchors].sort((a, b) => (a.network === 'power' ? 0 : 1) - (b.network === 'power' ? 0 : 1))\n for (const anchor of anchors) {\n const isPower = anchor.network === 'power'\n const fits = (station: PoleStation): boolean => feedsAnchor({ station, anchor, params }) && (!isPower || free(station))\n const power = feeds.get(`${anchor.lot}:power`)\n const nearest = power !== undefined && !isPower && fits(power) ? power : all().filter(fits).sort((a, b) => distance(a, anchor) - distance(b, anchor))[0]\n if (nearest) {\n take(anchor, nearest)\n continue\n }\n const served = params.served.get(anchor.lot)\n const stations = runs.find((entry) => entry[0]?.run.id === served?.run.id)\n if (served === undefined || stations === undefined) continue\n const added = inLine({ run: served.run, stations, anchor, params })\n if (added !== undefined) stations.push(added)\n stations.sort((a, b) => a.u - b.u)\n const from = added ?? [...stations].sort((a, b) => distance(a, anchor) - distance(b, anchor))[0]\n if (from === undefined) continue\n if (distance(from, anchor) <= params.reach - 1e-6) {\n if (!fits(from)) params.warn({ code: 'drop_off_practice', id: anchor.lot, detail: 'no pole in front of the lot or straight across the street' })\n take(anchor, from)\n continue\n }\n const chain = chainTo({ from, anchor, params })\n if (chain === undefined) continue\n chains.push([from, ...chain])\n take(anchor, chain[chain.length - 1] ?? from)\n }\n const renumbered = runs.map((stations) => stations.map((station, index) => ({ ...station, id: `pole:${station.run.id}:${ordinal(index)}` })))\n return { runs: renumbered, chains, feeds: new Map([...feeds].map(([lot, station]) => [lot, { x: station.x, z: station.z }])) }\n}\n","import type { CityPlanInput, PlanLine, PlanRect } from '../cities/types'\nimport { frameOf } from './frame'\nimport type { RunAxis } from './frame'\n\n/** How a run of street ends: at the map border (the line leaves the map), at a river bank, or where the line itself ends. */\nexport type RunEnd = 'edge' | 'river' | 'line_end'\n\n/** Another run crossing this one: `at` is its axis along this run, `half` the half width of its roadway. */\nexport type RunCrossing = { readonly run: string; readonly at: number; readonly half: number }\n\n/** A straight stretch of street between two river banks or line ends, in its own frame (`u` along, `v` across). */\nexport type StreetRun = {\n readonly id: string\n readonly line: string\n readonly along: RunAxis\n /** z of a street along x, x of one along z. */\n readonly axis: number\n readonly width: number\n readonly from: number\n readonly to: number\n readonly ends: readonly [RunEnd, RunEnd]\n readonly crossings: readonly RunCrossing[]\n}\n\n/** A lot of the site: its id and its rectangle on the plan. */\nexport type NetworkLot = { readonly id: string; readonly rect: PlanRect }\n\n/** A lot and the run it faces: the side of the street, its span along the run and the distance from the axis to its front. */\nexport type ServedLot = { readonly lot: NetworkLot; readonly run: StreetRun; readonly side: 1 | -1; readonly span: readonly [number, number]; readonly front: number }\n\nconst isStreet = (line: PlanLine): boolean => line.kind === 'street' || line.kind === 'avenue'\n\ntype Segment = { readonly line: PlanLine; readonly along: RunAxis; readonly axis: number; readonly from: number; readonly to: number }\n\nfunction segmentsOf(line: PlanLine): Segment[] {\n const out: Segment[] = []\n for (let index = 1; index < line.points.length; index++) {\n const [a, b] = [line.points[index - 1], line.points[index]]\n if (a === undefined || b === undefined) continue\n if (Math.abs(a[1] - b[1]) < 1e-9) out.push({ line, along: 'x', axis: a[1], from: Math.min(a[0], b[0]), to: Math.max(a[0], b[0]) })\n else if (Math.abs(a[0] - b[0]) < 1e-9) out.push({ line, along: 'z', axis: a[0], from: Math.min(a[1], b[1]), to: Math.max(a[1], b[1]) })\n else throw new Error(`networks: the line \"${line.id}\" has a stretch that is not along x or z; the generator lays straight streets only`)\n }\n return out\n}\n\n/** The river bands a road band of `segment` meets, as intervals along it. */\nfunction riverCuts({ segment, rivers }: { readonly segment: Segment; readonly rivers: readonly Segment[] }): Array<readonly [number, number]> {\n const half = segment.line.width / 2\n return rivers.flatMap((river) => {\n const riverHalf = river.line.width / 2\n if (river.along === segment.along) return []\n const across = river.axis\n const reaches = segment.axis + half > river.from && segment.axis - half < river.to\n return reaches && across + riverHalf > segment.from && across - riverHalf < segment.to ? [[across - riverHalf, across + riverHalf] as const] : []\n })\n}\n\n/**\n * The runs of every street of the plan, cut at the rivers, with their crossings. Ids are the line's, with `_<n>` when a line makes more\n * than one. A run end within `edgeReach` of the map border is where the line leaves the map.\n */\nexport function streetRunsOf({ plan, edgeReach }: { readonly plan: CityPlanInput; readonly edgeReach: number }): StreetRun[] {\n const lines = plan.lines ?? []\n const [width, depth] = plan.size ?? [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY]\n const rivers = lines.filter((line) => line.kind === 'river').flatMap(segmentsOf)\n const isEdge = (along: RunAxis, at: number): boolean => Math.abs(at) >= (along === 'x' ? width : depth) / 2 - edgeReach\n const bare = lines.filter(isStreet).flatMap((line) => {\n const pieces = segmentsOf(line).flatMap((segment) => {\n const cuts = riverCuts({ segment, rivers }).sort((a, b) => a[0] - b[0])\n const out: Array<Omit<StreetRun, 'id' | 'crossings'>> = []\n let start = segment.from\n let startEnd: RunEnd = isEdge(segment.along, segment.from) ? 'edge' : 'line_end'\n for (const [cutFrom, cutTo] of cuts) {\n if (cutFrom > start) out.push({ line: line.id, along: segment.along, axis: segment.axis, width: line.width, from: start, to: cutFrom, ends: [startEnd, 'river'] })\n start = Math.max(start, cutTo)\n startEnd = 'river'\n }\n if (segment.to > start) out.push({ line: line.id, along: segment.along, axis: segment.axis, width: line.width, from: start, to: segment.to, ends: [startEnd, isEdge(segment.along, segment.to) ? 'edge' : 'line_end'] })\n return out\n })\n return pieces.map((piece, index) => ({ ...piece, id: pieces.length > 1 ? `${line.id}_${index}` : line.id }))\n })\n return bare.map((run) => ({ ...run, crossings: crossingsOf({ run, runs: bare }) }))\n}\n\n/**\n * The runs whose roadway this run meets: a street that crosses it, and a street it ends at or that ends at it (a T junction), so no pole\n * stands inside another street's roadway and the end at a T is a corner.\n */\nfunction crossingsOf({ run, runs }: { readonly run: Omit<StreetRun, 'crossings'>; readonly runs: ReadonlyArray<Omit<StreetRun, 'crossings'>> }): RunCrossing[] {\n return runs\n .filter((other) => other.along !== run.along && other.axis + other.width / 2 > run.from && other.axis - other.width / 2 < run.to)\n .filter((other) => other.from <= run.axis + run.width / 2 && other.to >= run.axis - run.width / 2)\n .map((other) => ({ run: other.id, at: other.axis, half: other.width / 2 }))\n .sort((a, b) => a.at - b.at)\n}\n\n/** Distance from a lot's rectangle to a run's axis segment, and the lot in the run's frame. */\nfunction servedBy({ lot, run }: { readonly lot: NetworkLot; readonly run: StreetRun }): ServedLot & { readonly distance: number } {\n const [x0, z0, x1, z1] = lot.rect\n const [ua, va] = frameOf({ frame: run, x: x0, z: z0 })\n const [ub, vb] = frameOf({ frame: run, x: x1, z: z1 })\n const [u0, u1, v0, v1] = [Math.min(ua, ub), Math.max(ua, ub), Math.min(va, vb), Math.max(va, vb)]\n const side: 1 | -1 = v0 + v1 >= 0 ? 1 : -1\n const front = side > 0 ? Math.max(0, v0) : Math.max(0, -v1)\n const du = Math.max(0, run.from - u1, u0 - run.to)\n return { lot, run, side, span: [u0, u1], front, distance: Math.hypot(du, front) }\n}\n\n/** Each lot and the run it faces: the nearest (the first of the plan on a tie). */\nexport function servedLotsOf({ lots, runs }: { readonly lots: readonly NetworkLot[]; readonly runs: readonly StreetRun[] }): ServedLot[] {\n return lots.flatMap((lot) => {\n let best: (ServedLot & { readonly distance: number }) | undefined\n for (const run of runs) {\n const candidate = servedBy({ lot, run })\n if (best === undefined || candidate.distance < best.distance - 1e-9) best = candidate\n }\n if (best === undefined) return []\n const { distance: _distance, ...served } = best\n return [served]\n })\n}\n\n/** The side of each run its poles stand on: the one with more lots; on a tie the north (−z) or west (−x) side. */\nexport function poleSidesOf({ runs, served }: { readonly runs: readonly StreetRun[]; readonly served: readonly ServedLot[] }): ReadonlyMap<string, 1 | -1> {\n return new Map(\n runs.map((run) => {\n const own = served.filter((entry) => entry.run.id === run.id)\n const plus = own.filter((entry) => entry.side > 0).length\n return [run.id, plus > own.length - plus ? 1 : -1] as const\n }),\n )\n}\n","import type { PlanLine } from '../cities/types'\nimport type { NetworkSink } from './aerial'\nimport type { ChainNode } from './chain'\nimport type { GroundAt } from './connections'\nimport type { GravityPipe, LaidPipe } from './inverts'\nimport type { NetworkRules } from './rules'\nimport type { ServedLot, StreetRun } from './runs'\nimport type { NetworkEdge } from './types'\n\n/** What every buried network reads: the runs and their pole sides, the lots, the rules, the ground and the rivers. */\nexport type BuriedContext = {\n readonly runs: readonly StreetRun[]\n readonly sides: ReadonlyMap<string, 1 | -1>\n readonly served: ReadonlyMap<string, ServedLot>\n readonly rules: NetworkRules\n readonly groundAt: GroundAt\n readonly rivers: readonly PlanLine[]\n /** Half the map's width and depth: where a line without a river leaves the map. */\n readonly border: readonly [number, number]\n readonly sink: NetworkSink\n}\n\nexport type OnRun = { readonly context: BuriedContext; readonly run: StreetRun }\n\nconst sideOf = ({ context, run }: OnRun): 1 | -1 => context.sides.get(run.id) ?? -1\n\n/** The storm gallery runs beside the axis on the side of the poles; the water main under the sidewalk on the other side (they never cross a lateral together). */\nexport const galleryOffset = (on: OnRun): number => sideOf(on) * on.context.rules.layout.storm.galleryOffset\nexport function waterOffset(on: OnRun): number {\n const { sidewalk, water } = on.context.rules.layout\n return -sideOf(on) * (on.run.width / 2 + sidewalk * water.sidewalkShare)\n}\n\n/** A line reaches a cross line this far past its own run (a street ending at another). */\nexport const reachOf = (context: BuriedContext): number => Math.max(0, ...context.runs.map((run) => run.width / 2)) + context.rules.layout.sidewalk\n\nexport type TopParams = { readonly context: BuriedContext; readonly x: number; readonly z: number; readonly cover: number; readonly diameter: number }\n\n/** The highest invert a pipe of `diameter` may have at a point under its least cover (plus the margin). */\nexport function topOf({ context, x, z, cover, diameter }: TopParams): number {\n return context.groundAt(x, z) - cover - context.rules.layout.coverMargin - diameter\n}\n\n/** The mains of a set of chains, consecutive nodes in the direction of the flow. */\nexport function pipesOf({ chains, diameter, slope }: { readonly chains: readonly ChainNode[][]; readonly diameter: number; readonly slope: number }): GravityPipe[] {\n return chains.flatMap((chain) =>\n chain.slice(1).map((node, index) => {\n const from = chain[index] as ChainNode\n return { from: from.id, to: node.id, a: [from.x, from.z] as const, b: [node.x, node.z] as const, diameter, slope }\n }),\n )\n}\n\n/** Laid pipes of a set of edges (for a main that must pass under them), by the inverts of their nodes or their own. */\nexport function laidOf({ edges, sink }: { readonly edges: readonly NetworkEdge[]; readonly sink: NetworkSink }): LaidPipe[] {\n const nodes = new Map(sink.nodes.map((node) => [node.id, node]))\n return edges.flatMap((edge) => {\n const [from, to] = [nodes.get(edge.from), nodes.get(edge.to)]\n const inverts = edge.inverts ?? (from?.invert !== undefined && to?.invert !== undefined ? ([from.invert, to.invert] as const) : undefined)\n return from === undefined || to === undefined || inverts === undefined ? [] : [{ a: [from.at[0], from.at[2]] as const, b: [to.at[0], to.at[2]] as const, inverts }]\n })\n}\n\n/** Unique nodes of chains: a vertex shared by two segments is one node. */\nexport function chainNodes(chains: readonly ChainNode[][]): ChainNode[] {\n return [...new Map(chains.flat().map((node) => [node.id, node])).values()]\n}\n","import { ordinal, worldOf } from './frame'\nimport type { LineNetwork, LineSegment } from './line-network'\nimport type { StreetRun } from './runs'\n\n/** A point a branch joins a main at (a lateral's saddle, a service's tee): its run, its station along it and a key to find it again. */\nexport type ChainStop = { readonly key: string; readonly run: StreetRun; readonly u: number }\n\n/** A node of a main along a segment: a vertex of the line, a joint where a stop branches off, or a manhole that keeps the spacing. */\nexport type ChainNode = { readonly id: string; readonly x: number; readonly z: number; readonly role: 'vertex' | 'stop' | 'spaced' }\n\nexport type ChainParams = {\n readonly line: LineNetwork\n readonly prefix: string\n readonly offset: (run: StreetRun) => number\n readonly stops: readonly ChainStop[]\n /** Longest gap between two nodes that are not stops (manholes); none = no spacing. */\n readonly spacing?: number\n}\n\n/**\n * Every segment of a line as a chain of nodes in the direction of the flow, with the stops of its run inserted at their stations and\n * spaced nodes so no two non-stop nodes are farther apart than `spacing`. `joints` tells which node each stop landed on.\n */\nexport function chainsOf(params: ChainParams): { chains: ChainNode[][]; joints: Map<string, string> } {\n const joints = new Map<string, string>()\n const chains = params.line.segments.map((segment, index) => chainOf({ segment, index, params, joints }))\n return { chains, joints }\n}\n\nfunction chainOf({ segment, index, params, joints }: { readonly segment: LineSegment; readonly index: number; readonly params: ChainParams; readonly joints: Map<string, string> }): ChainNode[] {\n const { run, ua, ub } = segment\n const [low, high] = [Math.min(ua, ub), Math.max(ua, ub)]\n const place = (u: number): readonly [number, number] => worldOf({ frame: run, u, v: params.offset(run) })\n const vertex = (id: string): ChainNode => {\n const found = params.line.vertices.get(id)\n return { id, x: found?.x ?? 0, z: found?.z ?? 0, role: 'vertex' }\n }\n const points: Array<{ u: number; node: ChainNode }> = []\n for (const stop of params.stops) {\n if (stop.run.id !== run.id || stop.u < low - 1e-6 || stop.u > high + 1e-6 || joints.has(stop.key)) continue\n if (Math.abs(stop.u - ua) < 0.05) joints.set(stop.key, segment.from)\n else if (Math.abs(stop.u - ub) < 0.05) joints.set(stop.key, segment.to)\n else {\n const [x, z] = place(stop.u)\n const id = `${params.prefix}:${stop.key}`\n points.push({ u: stop.u, node: { id, x, z, role: 'stop' } })\n joints.set(stop.key, id)\n }\n }\n if (params.spacing !== undefined) {\n const parts = Math.ceil((high - low) / params.spacing - 1e-9)\n for (let part = 1; part < parts; part++) {\n const u = low + ((high - low) * part) / parts\n const [x, z] = place(u)\n points.push({ u, node: { id: `${params.prefix}:${run.id}:${ordinal(index)}:${ordinal(part - 1)}`, x, z, role: 'spaced' } })\n }\n }\n const direction = ub >= ua ? 1 : -1\n points.sort((a, b) => (a.u - b.u) * direction)\n return [vertex(segment.from), ...points.map((point) => point.node), vertex(segment.to)]\n}\n","import type { PlanLine } from '../cities/types'\nimport { ordinal } from './frame'\nimport type { LineVertex } from './line-network'\n\n/** A stretch of the interceptor, from upstream to downstream. */\nexport type InterceptorLink = { readonly from: string; readonly to: string }\n\nexport type Interceptor = {\n readonly nodes: ReadonlyArray<{ readonly id: string; readonly x: number; readonly z: number; readonly kind: 'manhole' | 'treatment' }>\n readonly links: readonly InterceptorLink[]\n}\n\n/** The river segment nearest a point, along x or z, and where it ends downstream (its last point). */\nfunction riverOf({ rivers, x, z }: { readonly rivers: readonly PlanLine[]; readonly x: number; readonly z: number }): { along: 'x' | 'z'; end: number } | undefined {\n let best: { along: 'x' | 'z'; end: number; distance: number } | undefined\n for (const river of rivers) {\n const last = river.points[river.points.length - 1]\n const before = river.points[river.points.length - 2]\n if (last === undefined || before === undefined) continue\n const along = Math.abs(last[0] - before[0]) < 1e-9 ? 'z' : 'x'\n const distance = along === 'z' ? Math.abs(x - last[0]) : Math.abs(z - last[1])\n if (best === undefined || distance < best.distance) best = { along, end: along === 'z' ? last[1] : last[0], distance }\n }\n return best\n}\n\n/**\n * The interceptors along the river banks: the mains of each bank reach the bank at their outlets (`outlets`), and one interceptor per\n * bank line runs from the farthest upstream of them along the river to where it leaves the map, at a treatment node; manholes at most\n * `spacing` apart. Outlets on the same bank line join the same interceptor.\n */\nexport type InterceptorParams = {\n /** Where the mains leave their streets: the river ends, else the one end of a line with no river. */\n readonly outlets: readonly LineVertex[]\n readonly rivers: readonly PlanLine[]\n readonly spacing: number\n /** Half the map's width and depth. */\n readonly border: readonly [number, number]\n}\n\nexport function interceptorsOf({ outlets, rivers, spacing, border }: InterceptorParams): Interceptor {\n const lines = new Map<string, { along: 'x' | 'z'; at: number; end: number; outlets: LineVertex[] }>()\n for (const outlet of outlets) {\n const river = outlet.end === 'river' ? riverOf({ rivers, x: outlet.x, z: outlet.z }) : undefined\n if (river === undefined) {\n const way = outlet.outward ?? [1, 0]\n const along = way[0] !== 0 ? 'x' : 'z'\n const end = way[0] !== 0 ? Math.max(Math.abs(outlet.x) + 1, border[0]) * Math.sign(way[0]) : Math.max(Math.abs(outlet.z) + 1, border[1]) * Math.sign(way[1])\n const at = along === 'x' ? outlet.z : outlet.x\n lines.set(`${along}:${at.toFixed(3)}:${outlet.id}`, { along: along === 'x' ? 'x' : 'z', at, end, outlets: [outlet] })\n continue\n }\n const at = river.along === 'z' ? outlet.x : outlet.z\n const key = `${river.along}:${at.toFixed(3)}`\n const line = lines.get(key) ?? { along: river.along, at, end: river.end, outlets: [] }\n line.outlets.push(outlet)\n lines.set(key, line)\n }\n const nodes: Array<Interceptor['nodes'][number]> = []\n const links: InterceptorLink[] = []\n ;[...lines.values()].forEach((line, lineIndex) => {\n const station = (vertex: { x: number; z: number }): number => (line.along === 'z' ? vertex.z : vertex.x)\n const downstream = (position: number): number => -Math.abs(line.end - position)\n const ordered = [...line.outlets].sort((a, b) => downstream(station(a)) - downstream(station(b)))\n const treatment = `sewer:treatment:${ordinal(lineIndex)}`\n const point = (position: number): { x: number; z: number } => (line.along === 'z' ? { x: line.at, z: position } : { x: position, z: line.at })\n nodes.push({ id: treatment, ...point(line.end), kind: 'treatment' })\n const stops = [...ordered.map((vertex) => ({ id: vertex.id, position: station(vertex) })), { id: treatment, position: line.end }]\n for (let index = 1; index < stops.length; index++) {\n const [from, to] = [stops[index - 1], stops[index]] as [{ id: string; position: number }, { id: string; position: number }]\n const parts = Math.max(1, Math.ceil(Math.abs(to.position - from.position) / spacing - 1e-9))\n let previous = from.id\n for (let part = 1; part < parts; part++) {\n const id = `sewer:interceptor:${ordinal(lineIndex)}:${ordinal(index - 1)}:${ordinal(part - 1)}`\n nodes.push({ id, ...point(from.position + ((to.position - from.position) * part) / parts), kind: 'manhole' })\n links.push({ from: previous, to: id })\n previous = id\n }\n links.push({ from: previous, to: to.id })\n }\n })\n return { nodes, links }\n}\n","import { segmentCrossing } from './geometry'\nimport type { PlanPoint } from './geometry'\n\n/** A pipe of a gravity main between two nodes, in the direction of the flow. */\nexport type GravityPipe = { readonly from: string; readonly to: string; readonly a: PlanPoint; readonly b: PlanPoint; readonly diameter: number; readonly slope: number }\n\n/** A pipe already laid, by its plan ends and the bottoms there: the main must pass under it. */\nexport type LaidPipe = { readonly a: PlanPoint; readonly b: PlanPoint; readonly inverts: readonly [number, number] }\n\nexport type DrainParams = {\n readonly pipes: readonly GravityPipe[]\n /** The highest invert each node may have: under its least cover. */\n readonly top: ReadonlyMap<string, number>\n /** The lowest invert each node may have (the deepest a sewer goes, an outfall above the river): a pipe that would reach under it is lifted at its upper node. */\n readonly floor?: ReadonlyMap<string, number>\n /** Pipes of other networks the mains must pass under by `separation`. */\n readonly above?: readonly LaidPipe[]\n readonly separation?: number\n}\n\n/** The inverts of the nodes, and the lifts: a node whose outgoing pipe starts again near the ground (a pumping station), with that start. */\nexport type DrainInverts = { readonly inverts: ReadonlyMap<string, number>; readonly lifts: ReadonlyMap<string, number> }\n\nconst length = (pipe: GravityPipe): number => Math.hypot(pipe.b[0] - pipe.a[0], pipe.b[1] - pipe.a[1])\n\ntype PassParams = { readonly pipes: readonly GravityPipe[]; readonly top: ReadonlyMap<string, number>; readonly floor: ReadonlyMap<string, number> }\n\n/** Inverts down the flow: each node at most its top, every pipe falling at its slope from the highest it can start, lifted where it would go under the floor. */\nfunction pass({ pipes, top, floor }: PassParams): { inverts: Map<string, number>; lifts: Map<string, number> } {\n const incoming = new Map<string, GravityPipe[]>()\n const pending = new Map<string, number>()\n for (const pipe of pipes) {\n incoming.set(pipe.to, [...(incoming.get(pipe.to) ?? []), pipe])\n pending.set(pipe.to, (pending.get(pipe.to) ?? 0) + 1)\n if (!pending.has(pipe.from)) pending.set(pipe.from, 0)\n }\n const inverts = new Map<string, number>()\n const lifts = new Map<string, number>()\n const ready = [...pending.entries()].filter(([, count]) => count === 0).map(([id]) => id).sort()\n const outgoing = new Map(pipes.map((pipe) => [pipe.from, pipe]))\n while (ready.length > 0) {\n const id = ready.shift() as string\n const lowest = floor.get(id) ?? Number.NEGATIVE_INFINITY\n const fromAbove = (incoming.get(id) ?? []).map((pipe) => {\n const reach = (lifts.get(pipe.from) ?? inverts.get(pipe.from) ?? 0) - pipe.slope * length(pipe)\n if (reach >= lowest - 1e-9 || lifts.has(pipe.from)) return reach\n lifts.set(pipe.from, top.get(pipe.from) ?? 0)\n return (lifts.get(pipe.from) ?? 0) - pipe.slope * length(pipe)\n })\n inverts.set(id, Math.min(top.get(id) ?? Number.POSITIVE_INFINITY, ...fromAbove))\n const next = outgoing.get(id)\n if (next === undefined) continue\n const left = (pending.get(next.to) ?? 1) - 1\n pending.set(next.to, left)\n if (left === 0) ready.push(next.to)\n }\n return { inverts, lifts }\n}\n\n/** For each main, the laid pipes whose plan boxes meet its own (found once, by cells of 20 m). */\nfunction crossingCandidates({ pipes, above }: { readonly pipes: readonly GravityPipe[]; readonly above: readonly LaidPipe[] }): Map<GravityPipe, LaidPipe[]> {\n const size = 20\n const cells = new Map<string, LaidPipe[]>()\n const cellsOf = (a: PlanPoint, b: PlanPoint): string[] => {\n const out: string[] = []\n for (let i = Math.floor(Math.min(a[0], b[0]) / size); i <= Math.floor(Math.max(a[0], b[0]) / size); i++) {\n for (let k = Math.floor(Math.min(a[1], b[1]) / size); k <= Math.floor(Math.max(a[1], b[1]) / size); k++) out.push(`${i},${k}`)\n }\n return out\n }\n for (const laid of above) for (const cell of cellsOf(laid.a, laid.b)) cells.set(cell, [...(cells.get(cell) ?? []), laid])\n return new Map(pipes.map((pipe) => [pipe, [...new Set(cellsOf(pipe.a, pipe.b).flatMap((cell) => cells.get(cell) ?? []))]]))\n}\n\n/**\n * The inverts of a tree of gravity mains: from the heads down, at the least slope, never above the least cover nor under the floor (a lift\n * there); then, where a main crosses a pipe laid above it, the upper end of that main is lowered until it passes `separation` under it, and the\n * flow is laid again from there.\n */\nexport function solveDrainInverts({ pipes, top, floor = new Map(), above = [], separation = 0 }: DrainParams): DrainInverts {\n const caps = new Map(top)\n const candidates = crossingCandidates({ pipes, above })\n let result = pass({ pipes, top: caps, floor })\n for (let round = 0; round < 16; round++) {\n let lowered = false\n for (const pipe of pipes) {\n for (const laid of candidates.get(pipe) ?? []) {\n const crossing = segmentCrossing(pipe.a, pipe.b, laid.a, laid.b)\n if (crossing === undefined) continue\n const need = laid.inverts[0] + (laid.inverts[1] - laid.inverts[0]) * crossing[1] - separation - pipe.diameter\n const from = result.lifts.get(pipe.from) ?? result.inverts.get(pipe.from) ?? 0\n const to = result.inverts.get(pipe.to) ?? 0\n if (from + (to - from) * crossing[0] <= need + 1e-9) continue\n // the pipe falls from its upper node, so starting it under the crossing is enough\n caps.set(pipe.from, Math.min(caps.get(pipe.from) ?? Number.POSITIVE_INFINITY, need - 1e-3))\n lowered = true\n }\n }\n if (!lowered) return result\n result = pass({ pipes, top: caps, floor })\n }\n return result\n}\n","import { ordinal, worldOf } from './frame'\nimport type { RunEnd, StreetRun } from './runs'\n\n/** A key point of a buried line: a run end, a crossing of two runs' lines, or the middle of a stretch that closes a loop. */\nexport type LineVertex = {\n readonly id: string\n readonly x: number\n readonly z: number\n readonly role: 'end' | 'crossing' | 'split'\n readonly end?: RunEnd\n /** An end: the way out of its run, as a unit step in plan (where the line would go on past the map). */\n readonly outward?: readonly [number, number]\n}\n\n/** A stretch of line on one run between two vertices, in the direction of the flow. `ua`, `ub` are the stations of `from` and `to`. */\nexport type LineSegment = { readonly run: StreetRun; readonly from: string; readonly to: string; readonly ua: number; readonly ub: number }\n\nexport type LineNetwork = { readonly vertices: ReadonlyMap<string, LineVertex>; readonly segments: readonly LineSegment[]; readonly roots: readonly string[] }\n\nexport type LineParams = {\n readonly prefix: string\n readonly runs: readonly StreetRun[]\n /** Distance of the line from the axis of each run (+ to +z or +x). */\n readonly offset: (run: StreetRun) => number\n /** A line stops this far before the river bank (the sewer's interceptor runs there). */\n readonly riverInset: number\n /** A line reaches a cross line this far past its own run's end (a street that ends at another). */\n readonly reach: number\n /** Drain lines flow to their roots (the river ends), supply lines from them (the border ends). */\n readonly flow: 'drain' | 'supply'\n}\n\ntype Station = { readonly u: number; readonly vertex: LineVertex }\n\nfunction stationsOf({ run, params }: { readonly run: StreetRun; readonly params: LineParams }): Station[] {\n const place = (u: number): readonly [number, number] => worldOf({ frame: run, u, v: params.offset(run) })\n const out: Station[] = []\n const position = run.axis + params.offset(run)\n for (const other of params.runs) {\n if (other.along === run.along) continue\n const u = other.axis + params.offset(other)\n if (u < run.from - params.reach || u > run.to + params.reach || position < other.from - params.reach || position > other.to + params.reach) continue\n const [x, z] = place(u)\n out.push({ u, vertex: { id: `${params.prefix}:x:${[run.id, other.id].sort().join(':')}`, x, z, role: 'crossing' } })\n }\n const ends: Array<readonly [number, RunEnd, string, 1 | -1]> = [\n [run.ends[0] === 'river' ? run.from + params.riverInset : run.from, run.ends[0], 'start', -1],\n [run.ends[1] === 'river' ? run.to - params.riverInset : run.to, run.ends[1], 'end', 1],\n ]\n for (const [u, end, name, way] of ends) {\n if (out.some((station) => Math.abs(station.u - u) < 0.5)) continue\n const [x, z] = place(u)\n const outward: readonly [number, number] = run.along === 'x' ? [way, 0] : [0, way]\n out.push({ u, vertex: { id: `${params.prefix}:${run.id}:${name}`, x, z, role: 'end', end, outward } })\n }\n return out.sort((a, b) => a.u - b.u)\n}\n\ntype Link = { readonly run: StreetRun; readonly a: Station; readonly b: Station }\n\n/** The lines of every run joined at their crossings, as a tree toward (drain) or from (supply) the roots; a stretch that would close a loop is split in its middle. */\nexport function lineNetworkOf(params: LineParams): LineNetwork {\n const vertices = new Map<string, LineVertex>()\n const links: Link[] = []\n for (const run of params.runs) {\n const stations = stationsOf({ run, params })\n for (const station of stations) if (!vertices.has(station.vertex.id)) vertices.set(station.vertex.id, station.vertex)\n for (let index = 1; index < stations.length; index++) links.push({ run, a: stations[index - 1] as Station, b: stations[index] as Station })\n }\n const roots = rootsOf({ vertices, links, flow: params.flow })\n const parent = shortestTree({ roots, links })\n const segments: LineSegment[] = []\n let splits = 0\n for (const link of links) {\n const [a, b] = [link.a.vertex.id, link.b.vertex.id]\n const toward = (from: Station, to: Station): LineSegment =>\n params.flow === 'drain' ? { run: link.run, from: from.vertex.id, to: to.vertex.id, ua: from.u, ub: to.u } : { run: link.run, from: to.vertex.id, to: from.vertex.id, ua: to.u, ub: from.u }\n if (parent.get(a) === b) segments.push(toward(link.a, link.b))\n else if (parent.get(b) === a) segments.push(toward(link.b, link.a))\n else {\n const u = (link.a.u + link.b.u) / 2\n const [x, z] = worldOf({ frame: link.run, u, v: params.offset(link.run) })\n const middle: Station = { u, vertex: { id: `${params.prefix}:${link.run.id}:split:${ordinal(splits++)}`, x, z, role: 'split' } }\n vertices.set(middle.vertex.id, middle.vertex)\n segments.push(toward(middle, link.a), toward(middle, link.b))\n }\n }\n return { vertices, segments, roots }\n}\n\ntype Graph = { readonly vertices: ReadonlyMap<string, LineVertex>; readonly links: readonly Link[] }\n\nfunction componentsOf({ vertices, links }: Graph): string[][] {\n const near = new Map<string, string[]>()\n for (const link of links) {\n near.set(link.a.vertex.id, [...(near.get(link.a.vertex.id) ?? []), link.b.vertex.id])\n near.set(link.b.vertex.id, [...(near.get(link.b.vertex.id) ?? []), link.a.vertex.id])\n }\n const seen = new Set<string>()\n const out: string[][] = []\n for (const id of vertices.keys()) {\n if (seen.has(id)) continue\n const group: string[] = []\n const pending = [id]\n while (pending.length > 0) {\n const next = pending.pop() as string\n if (seen.has(next)) continue\n seen.add(next)\n group.push(next)\n pending.push(...(near.get(next) ?? []))\n }\n out.push(group)\n }\n return out\n}\n\n/** Drain: every river end of a group (else its first border end, else its first vertex); supply: the first border end of a group (else its first vertex). */\nfunction rootsOf({ vertices, links, flow }: Graph & { readonly flow: 'drain' | 'supply' }): string[] {\n return componentsOf({ vertices, links }).flatMap((group) => {\n const ends = (end: RunEnd): string[] => group.filter((id) => vertices.get(id)?.end === end)\n const river = flow === 'drain' ? ends('river') : []\n if (river.length > 0) return river\n return [ends('edge')[0] ?? (group[0] as string)]\n })\n}\n\n/** Each vertex's next vertex toward its nearest root, by line length (ties by id). */\nfunction shortestTree({ roots, links }: { readonly roots: readonly string[]; readonly links: readonly Link[] }): Map<string, string> {\n const near = new Map<string, Array<readonly [Station, Station]>>()\n for (const link of links) {\n near.set(link.a.vertex.id, [...(near.get(link.a.vertex.id) ?? []), [link.a, link.b]])\n near.set(link.b.vertex.id, [...(near.get(link.b.vertex.id) ?? []), [link.b, link.a]])\n }\n const distance = new Map(roots.map((root) => [root, 0]))\n const parent = new Map<string, string>()\n const done = new Set<string>()\n for (;;) {\n const open = [...distance.entries()].filter(([id]) => !done.has(id)).sort((a, b) => a[1] - b[1] || (a[0] < b[0] ? -1 : 1))[0]\n if (open === undefined) return parent\n const [id, base] = open\n done.add(id)\n for (const [here, there] of near.get(id) ?? []) {\n if (done.has(there.vertex.id)) continue\n const length = base + Math.abs(there.u - here.u)\n if (length >= (distance.get(there.vertex.id) ?? Number.POSITIVE_INFINITY)) continue\n distance.set(there.vertex.id, length)\n parent.set(there.vertex.id, id)\n }\n }\n}\n","import type { UtilityConnection } from '@adatechnology/game-contracts'\n\nimport { chainNodes, laidOf, pipesOf, reachOf, topOf, waterOffset } from './buried'\nimport type { BuriedContext } from './buried'\nimport { chainsOf } from './chain'\nimport type { ChainNode, ChainStop } from './chain'\nimport { frameOf, worldOf } from './frame'\nimport { interceptorsOf } from './interceptor'\nimport { solveDrainInverts } from './inverts'\nimport type { GravityPipe } from './inverts'\nimport { lineNetworkOf } from './line-network'\nimport type { LineVertex } from './line-network'\nimport type { NetworkEdge, NetworkNode } from './types'\n\ntype Lateral = { readonly connection: UtilityConnection; readonly drop: NetworkNode; readonly key: string; readonly u: number }\ntype OnLot = { readonly context: BuriedContext; readonly connection: UtilityConnection }\n\n/**\n * The drop of a lot's lateral: a cleanout `dropOffset` from the axis on the lot's side. The lateral falls to it at its least slope, and\n * deeper where it must pass under the water main (on the side opposite the poles); on the side of the poles it stays shallow over the gallery.\n */\nfunction lateralOf({ context, connection }: OnLot): Lateral | undefined {\n const served = context.served.get(connection.lot)\n if (served === undefined || connection.invert === undefined) return undefined\n const { run, side } = served\n const { sewer, slopeMargin, water, coverMargin } = context.rules.layout\n const [u, v] = frameOf({ frame: run, x: connection.at[0], z: connection.at[2] })\n const length = Math.abs(v) - sewer.dropOffset\n let fall = (context.rules.minSlope.sewer_lateral + slopeMargin) * length\n const main = waterOffset({ context, run })\n if (Math.sign(main) === side && Math.abs(main) < Math.abs(v) && Math.abs(main) > sewer.dropOffset) {\n const share = (Math.abs(v) - Math.abs(main)) / length\n const [x, z] = worldOf({ frame: run, u, v: main })\n const need = topOf({ context, x, z, cover: context.rules.cover.water_main.min, diameter: water.mainDiameter }) - context.rules.crossing.separation - sewer.lateralDiameter - coverMargin\n fall = Math.max(fall, (connection.invert - need) / share)\n }\n const [x, z] = worldOf({ frame: run, u, v: side * sewer.dropOffset })\n const id = `sewer:drop:${connection.lot}`\n return { connection, u, key: `saddle:${connection.lot}`, drop: { id, kind: 'cleanout', at: [x, context.groundAt(x, z), z], invert: connection.invert - fall, carries: ['sewer'], spec: 'drop' } }\n}\n\ntype Kinds = { readonly roots: ReadonlySet<string>; readonly heads: ReadonlySet<string>; readonly lifts: ReadonlyMap<string, number>; readonly treatments: ReadonlySet<string> }\n\nfunction kindOf({ node, kinds }: { readonly node: ChainNode; readonly kinds: Kinds }): Pick<NetworkNode, 'kind' | 'spec'> {\n if (kinds.treatments.has(node.id)) return { kind: 'treatment', spec: 'treatment_plant' }\n if (kinds.lifts.has(node.id)) return { kind: 'pumping_station', spec: 'lift' }\n if (node.role === 'stop') return { kind: 'splice', spec: 'saddle' }\n if (kinds.heads.has(node.id) && !kinds.roots.has(node.id)) return { kind: 'cleanout', spec: 'terminal' }\n return { kind: 'manhole', spec: 'pv_600' }\n}\n\n/** The mains of the streets and the interceptors, with each node's place. */\nfunction mainsOf({ context, laterals }: { readonly context: BuriedContext; readonly laterals: readonly Lateral[] }) {\n const { rules } = context\n const { sewer, slopeMargin } = rules.layout\n const line = lineNetworkOf({ prefix: 'sewer', runs: context.runs, offset: () => 0, riverInset: sewer.interceptorOffset, reach: reachOf(context), flow: 'drain' })\n const stops: ChainStop[] = laterals.flatMap((lateral) => {\n const served = context.served.get(lateral.connection.lot)\n return served === undefined ? [] : [{ key: lateral.key, run: served.run, u: lateral.u }]\n })\n const { chains, joints } = chainsOf({ line, prefix: 'sewer', offset: () => 0, stops, spacing: rules.sewer.manholeSpacing })\n const outlets = line.roots.flatMap((id) => [line.vertices.get(id)].filter((vertex): vertex is LineVertex => vertex !== undefined))\n const interceptor = interceptorsOf({ outlets, rivers: context.rivers, spacing: rules.sewer.manholeSpacing, border: context.border })\n const slope = rules.minSlope.sewer_main + slopeMargin\n const nodes: ChainNode[] = [...chainNodes(chains), ...interceptor.nodes.map((node) => ({ id: node.id, x: node.x, z: node.z, role: 'vertex' as const }))]\n const where = new Map(nodes.map((node) => [node.id, node]))\n const pipes: GravityPipe[] = [\n ...pipesOf({ chains, diameter: sewer.mainDiameter, slope }),\n ...interceptor.links.map((link) => {\n const [a, b] = [where.get(link.from), where.get(link.to)]\n return { from: link.from, to: link.to, a: [a?.x ?? 0, a?.z ?? 0] as const, b: [b?.x ?? 0, b?.z ?? 0] as const, diameter: sewer.mainDiameter, slope }\n }),\n ]\n const treatments = new Set(interceptor.nodes.filter((node) => node.kind === 'treatment').map((node) => node.id))\n return { line, nodes, where, pipes, joints, treatments }\n}\n\n/**\n * The sewer: a DN 150 main under the axis of every street, falling to the river bank (a cleanout at each dry head, a manhole at every\n * crossing and at most 80 m apart), an interceptor along each bank to a treatment node where the river leaves the map (with no river, from\n * the line's end to the border); a pumping station where a main would go deeper than the rules allow; every lot's lateral from its\n * inspection box over the gallery (or under the water main) down to a saddle on the main. The mains pass under `above`.\n */\nexport function laySewer({ context, connections, above }: { readonly context: BuriedContext; readonly connections: readonly UtilityConnection[]; readonly above: readonly NetworkEdge[] }): void {\n const { rules, sink } = context\n const { sewer, slopeMargin, coverMargin } = rules.layout\n const laterals = connections.flatMap((connection) => lateralOf({ context, connection }) ?? [])\n const { line, nodes, where, pipes, joints, treatments } = mainsOf({ context, laterals })\n const top = new Map(nodes.map((node) => [node.id, topOf({ context, x: node.x, z: node.z, cover: rules.sewer.coverUnderGallery, diameter: sewer.mainDiameter })]))\n const floor = new Map(nodes.map((node) => [node.id, context.groundAt(node.x, node.z) - rules.sewer.maxDepth + coverMargin]))\n for (const lateral of laterals) {\n const joint = joints.get(lateral.key) as string\n const target = where.get(joint)\n const length = target === undefined ? 0 : Math.hypot(target.x - lateral.drop.at[0], target.z - lateral.drop.at[2])\n const highest = (lateral.drop.invert ?? 0) - (rules.minSlope.sewer_lateral + slopeMargin) * length - sewer.mainDiameter\n top.set(joint, Math.min(top.get(joint) ?? Number.POSITIVE_INFINITY, highest))\n }\n const { inverts, lifts } = solveDrainInverts({ pipes, top, floor, above: laidOf({ edges: above, sink }), separation: rules.crossing.separation + coverMargin })\n const fed = new Set(pipes.map((pipe) => pipe.to))\n const heads = new Set(pipes.filter((pipe) => !fed.has(pipe.from)).map((pipe) => pipe.from))\n const kinds: Kinds = { roots: new Set(line.roots), heads, lifts, treatments }\n for (const node of nodes) {\n const ground = context.groundAt(node.x, node.z)\n sink.nodes.push({ id: node.id, ...kindOf({ node, kinds }), at: [node.x, ground, node.z], invert: inverts.get(node.id) ?? ground, carries: ['sewer'] })\n }\n for (const pipe of pipes) {\n const lift = lifts.get(pipe.from)\n sink.edges.push({ id: `${pipe.from}>${pipe.to}`, kind: 'sewer_main', from: pipe.from, to: pipe.to, diameter: sewer.mainDiameter, ...(lift === undefined ? {} : { inverts: [lift, inverts.get(pipe.to) ?? 0] as const }) })\n }\n for (const lateral of laterals) {\n const { connection, drop } = lateral\n const joint = joints.get(lateral.key) as string\n const lot = `lot:${connection.lot}:sewer`\n sink.nodes.push({ id: lot, kind: 'connection', at: connection.at, invert: connection.invert, carries: ['sewer'], lot: connection.lot }, drop)\n sink.edges.push({ id: `sewer:lateral:${connection.lot}`, kind: 'sewer_lateral', from: lot, to: drop.id, diameter: sewer.lateralDiameter })\n sink.edges.push({ id: `${drop.id}>${joint}`, kind: 'sewer_lateral', from: drop.id, to: joint, diameter: sewer.lateralDiameter, inverts: [drop.invert ?? 0, (inverts.get(joint) ?? 0) + sewer.mainDiameter] })\n }\n}\n","import type { UtilityConnection } from '@adatechnology/game-contracts'\n\nimport { chainNodes, galleryOffset, pipesOf, reachOf, topOf } from './buried'\nimport type { BuriedContext } from './buried'\nimport { chainsOf } from './chain'\nimport type { ChainStop } from './chain'\nimport { frameOf, ordinal, worldOf } from './frame'\nimport { solveDrainInverts } from './inverts'\nimport { lineNetworkOf } from './line-network'\nimport { piecesOf } from './pole-layout'\nimport type { StreetRun } from './runs'\nimport type { NetworkEdge, NetworkNode } from './types'\n\ntype Inlet = { readonly id: string; readonly key: string; readonly run: StreetRun; readonly curb: 1 | -1; readonly u: number; readonly node: NetworkNode }\n\n/** Inlets on both kerbs of every stretch: one at each corner (or end) and at most `inletSpacing` apart between. */\nfunction inletsOf(context: BuriedContext): Inlet[] {\n const { storm, coverMargin } = context.rules.layout\n const depth = context.rules.cover.storm_lateral.min + coverMargin + storm.lateralDiameter\n return context.runs.flatMap((run) =>\n piecesOf(run).flatMap((piece, pieceIndex) =>\n ([-1, 1] as const).flatMap((curb) => {\n const [from, to] = [piece.from + storm.inletFromCorner, piece.to - storm.inletFromCorner]\n const gaps = Math.max(1, Math.ceil((to - from) / storm.inletSpacing - 1e-9))\n return Array.from({ length: gaps + 1 }, (_, index): Inlet => {\n const u = from + ((to - from) * index) / gaps\n const [x, z] = worldOf({ frame: run, u, v: curb * (run.width / 2 - storm.inletSetback) })\n const key = `inlet:${run.id}:${curb > 0 ? 'plus' : 'minus'}:${ordinal(pieceIndex)}:${ordinal(index)}`\n const ground = context.groundAt(x, z)\n return { id: `storm:${key}`, key, run, curb, u, node: { id: `storm:${key}`, kind: 'inlet', at: [x, ground, z], invert: ground - depth, carries: ['storm'], spec: 'grated_inlet' } }\n })\n }),\n ),\n )\n}\n\n/**\n * The drainage: a gallery beside the axis of every street on the side of the poles, to a headwall on the river bank (else the border), its\n * bottom above the river (a lift where the gallery would reach under it); inlets on both kerbs with a lateral each to the gallery, and every\n * lot's downspout outlet down the gutter to the nearest inlet of its kerb. Returns the edges laid, for the sewer that passes under them.\n */\nexport function layStorm({ context, connections }: { readonly context: BuriedContext; readonly connections: readonly UtilityConnection[] }): NetworkEdge[] {\n const { rules, sink } = context\n const { storm, slopeMargin, coverMargin } = rules.layout\n const offset = (run: StreetRun): number => galleryOffset({ context, run })\n const line = lineNetworkOf({ prefix: 'storm', runs: context.runs, offset, riverInset: 0, reach: reachOf(context), flow: 'drain' })\n const inlets = inletsOf(context)\n const stops: ChainStop[] = inlets.map((inlet) => ({ key: inlet.key, run: inlet.run, u: inlet.u }))\n const { chains, joints } = chainsOf({ line, prefix: 'storm:gallery', offset, stops, spacing: rules.sewer.manholeSpacing })\n const nodes = chainNodes(chains)\n const where = new Map(nodes.map((node) => [node.id, node]))\n const top = new Map(nodes.map((node) => [node.id, topOf({ context, x: node.x, z: node.z, cover: rules.cover.storm_gallery.min, diameter: storm.galleryDiameter })]))\n const roots = new Set(line.roots)\n // a gallery no deeper than a sewer main can pass under it and still run to its next manhole within the deepest a sewer goes; an outfall above the river\n const sewerRun = (rules.minSlope.sewer_main + slopeMargin) * rules.sewer.manholeSpacing\n const deepest = rules.sewer.maxDepth - rules.layout.sewer.mainDiameter - rules.crossing.separation - 3 * coverMargin - sewerRun\n const floor = new Map(nodes.map((node) => [node.id, Math.max(context.groundAt(node.x, node.z) - deepest, roots.has(node.id) ? storm.riverLevel + coverMargin : Number.NEGATIVE_INFINITY)]))\n const laterals = inlets.map((inlet) => {\n const joint = joints.get(inlet.key) as string\n const target = where.get(joint)\n const length = target === undefined ? 0 : Math.hypot(target.x - inlet.node.at[0], target.z - inlet.node.at[2])\n const end = (inlet.node.invert ?? 0) - (rules.minSlope.storm_lateral + slopeMargin) * length\n top.set(joint, Math.min(top.get(joint) ?? Number.POSITIVE_INFINITY, end))\n return { inlet, joint, end }\n })\n const pipes = pipesOf({ chains, diameter: storm.galleryDiameter, slope: rules.minSlope.storm_gallery + slopeMargin })\n const { inverts, lifts } = solveDrainInverts({ pipes, top, floor })\n for (const node of nodes) {\n const ground = context.groundAt(node.x, node.z)\n const kind = roots.has(node.id) ? ({ kind: 'outfall', spec: 'headwall' } as const) : lifts.has(node.id) ? ({ kind: 'pumping_station', spec: 'storm_lift' } as const) : ({ kind: 'manhole', spec: 'gallery_box' } as const)\n sink.nodes.push({ id: node.id, ...kind, at: [node.x, ground, node.z], invert: inverts.get(node.id) ?? ground, carries: ['storm'] })\n }\n const edges: NetworkEdge[] = pipes.map((pipe) => {\n const lift = lifts.get(pipe.from)\n return { id: `${pipe.from}>${pipe.to}`, kind: 'storm_gallery', from: pipe.from, to: pipe.to, diameter: storm.galleryDiameter, ...(lift === undefined ? {} : { inverts: [lift, inverts.get(pipe.to) ?? 0] as const }) }\n })\n for (const { inlet, joint, end } of laterals) {\n sink.nodes.push(inlet.node)\n edges.push({ id: `storm:lateral:${inlet.key}`, kind: 'storm_lateral', from: inlet.id, to: joint, diameter: storm.lateralDiameter, inverts: [inlet.node.invert ?? 0, end] })\n }\n edges.push(...gutters({ context, connections, inlets }))\n sink.edges.push(...edges)\n return edges\n}\n\n/** Each lot's downspout outlet at the kerb, down the gutter to the nearest inlet of the same kerb of its street. */\nfunction gutters({ context, connections, inlets }: { readonly context: BuriedContext; readonly connections: readonly UtilityConnection[]; readonly inlets: readonly Inlet[] }): NetworkEdge[] {\n const slope = context.rules.minSlope.storm_gutter + context.rules.layout.slopeMargin\n return connections.flatMap((connection) => {\n const served = context.served.get(connection.lot)\n if (served === undefined) return []\n const [u] = frameOf({ frame: served.run, x: connection.at[0], z: connection.at[2] })\n const own = inlets.filter((inlet) => inlet.run.id === served.run.id && inlet.curb === served.side)\n const inlet = [...own].sort((a, b) => Math.abs(a.u - u) - Math.abs(b.u - u))[0]\n if (inlet === undefined) return []\n const node = `lot:${connection.lot}:storm`\n context.sink.nodes.push({ id: node, kind: 'connection', at: connection.at, carries: ['storm'], lot: connection.lot })\n const length = Math.hypot(inlet.node.at[0] - connection.at[0], inlet.node.at[2] - connection.at[2])\n return [{ id: `storm:gutter:${connection.lot}`, kind: 'storm_gutter', from: node, to: inlet.id, diameter: 0, inverts: [connection.at[1], inlet.node.at[1] - slope * length] } satisfies NetworkEdge]\n })\n}\n","import type { UtilityConnection } from '@adatechnology/game-contracts'\n\nimport { poleAt, poleFinder } from './aerial'\nimport type { NetworkSink, PoleHeights } from './aerial'\nimport { countOf } from './frame'\nimport type { NetworkPole, PoleTree } from './pole-tree'\nimport type { NetworkRules } from './rules'\n\nexport type TelecomParams = {\n readonly tree: PoleTree\n readonly connections: readonly UtilityConnection[]\n readonly rules: NetworkRules\n readonly heights: PoleHeights\n readonly seed: number\n /** The periphery (a bundle of 3 to 5 cables) or a clean district (1 or 2), at a point. */\n readonly isPeriphery: (x: number, z: number) => boolean\n /** The pole each lot's power drop leaves from: its telecom drop leaves the same pole. */\n readonly feeds: ReadonlyMap<string, { readonly x: number; readonly z: number }>\n readonly sink: NetworkSink\n}\n\n/** Cables of the bundle that reaches a pole: one draw per run, by the hash of the seed and the run (the same street keeps its bundle). */\nexport function cablesAt({ pole, rules, seed, isPeriphery }: Pick<TelecomParams, 'rules' | 'seed' | 'isPeriphery'> & { readonly pole: NetworkPole }): number {\n const { cables } = rules.layout.telecom\n return countOf({ seed, id: `telecom:${pole.station.run.id}`, range: isPeriphery(pole.station.x, pole.station.z) ? cables.periphery : cables.clean })\n}\n\n/**\n * The telecom bundle over every system's poles from its feed, on the top cable of the telecom band, with a splice box and reserve coil\n * every few spans (on the span into the pole, near it), and a drop from the nearest pole to every lot.\n */\nexport function layTelecom(params: TelecomParams): void {\n const { tree, heights, rules, sink } = params\n const { sag, telecom } = rules.layout\n for (const system of tree.systems) {\n const feed = `feed:telecom:${system.root}`\n sink.nodes.push({ id: feed, kind: 'feed', at: [system.feed[0], heights.telecom, system.feed[1]], carries: ['telecom'] })\n for (const id of system.poles) {\n const pole = tree.poles.get(id) as NetworkPole\n const up = system.parent.get(id)\n const conductors = cablesAt({ pole, rules, seed: params.seed, isPeriphery: params.isPeriphery })\n const depth = system.depth.get(id) ?? 0\n if (up === undefined || depth % telecom.spliceEvery !== 0) {\n sink.edges.push({ id: `telecom:${id}`, kind: 'telecom_span', from: up ?? feed, to: id, sag: sag.telecom, heights: [heights.telecom, heights.telecom], conductors })\n continue\n }\n const parent = tree.poles.get(up) as NetworkPole\n const length = Math.hypot(parent.station.x - pole.station.x, parent.station.z - pole.station.z)\n const share = Math.min(0.5, 0.6 / Math.max(length, 1e-9))\n const splice = `splice:${id}`\n const at: readonly [number, number, number] = [pole.station.x + (parent.station.x - pole.station.x) * share, heights.telecom, pole.station.z + (parent.station.z - pole.station.z) * share]\n sink.nodes.push({ id: splice, kind: 'splice', at, carries: ['telecom'], spec: 'splice_reserve' })\n sink.edges.push({ id: `telecom:${splice}`, kind: 'telecom_span', from: up, to: splice, sag: sag.telecom, heights: [heights.telecom, heights.telecom], conductors })\n sink.edges.push({ id: `telecom:${id}`, kind: 'telecom_span', from: splice, to: id, sag: 0, heights: [heights.telecom, heights.telecom], conductors })\n }\n }\n const find = poleFinder(tree)\n for (const connection of params.connections) {\n const pole = poleAt(tree, params.feeds.get(`${connection.lot}:telecom`)) ?? find({ x: connection.at[0], z: connection.at[2], radius: rules.telecom.dropMaxLength })[0]\n if (pole === undefined) continue\n const node = `lot:${connection.lot}:telecom`\n sink.nodes.push({ id: node, kind: 'connection', at: connection.at, carries: ['telecom'], lot: connection.lot })\n sink.edges.push({ id: `telecom_drop:${connection.lot}`, kind: 'telecom_drop', from: pole.id, to: node, sag: sag.telecomDrop, heights: [heights.telecom, connection.at[1]], conductors: 1 })\n }\n}\n","import type { UtilityConnection } from '@adatechnology/game-contracts'\n\nimport { chainNodes, pipesOf, reachOf, topOf, waterOffset } from './buried'\nimport type { BuriedContext } from './buried'\nimport { chainsOf } from './chain'\nimport type { ChainNode, ChainStop } from './chain'\nimport { frameOf } from './frame'\nimport { lineNetworkOf } from './line-network'\nimport type { LineVertex } from './line-network'\nimport type { StreetRun } from './runs'\nimport type { NetworkNode } from './types'\n\n/** Kind and spec of a node of the main: the reservoir at the border, a valve at every crossing and dead end, a tee where a service leaves. */\nfunction kindOf({ node, vertex, roots }: { readonly node: ChainNode; readonly vertex: LineVertex | undefined; readonly roots: ReadonlySet<string> }): Pick<NetworkNode, 'kind' | 'spec'> {\n if (roots.has(node.id)) return { kind: 'reservoir', spec: 'reservoir' }\n if (node.role === 'stop') return { kind: 'splice', spec: 'tee' }\n return { kind: 'valve', spec: vertex?.role === 'crossing' ? 'gate_valve' : 'end_valve' }\n}\n\n/**\n * The water: a main under the sidewalk opposite the poles on every street, from a reservoir where the line enters the map (one per side of\n * a river), a valve and a hydrant at every crossing, and a service from a tee on the main to every lot's meter stand.\n */\nexport function layWater({ context, connections }: { readonly context: BuriedContext; readonly connections: readonly UtilityConnection[] }): void {\n const { rules, sink } = context\n const { water } = rules.layout\n const offset = (run: StreetRun): number => waterOffset({ context, run })\n const line = lineNetworkOf({ prefix: 'water', runs: context.runs, offset, riverInset: 0, reach: reachOf(context), flow: 'supply' })\n const stops: ChainStop[] = connections.flatMap((connection) => {\n const served = context.served.get(connection.lot)\n if (served === undefined) return []\n return [{ key: `tee:${connection.lot}`, run: served.run, u: frameOf({ frame: served.run, x: connection.at[0], z: connection.at[2] })[0] }]\n })\n const { chains, joints } = chainsOf({ line, prefix: 'water', offset, stops })\n const roots = new Set(line.roots)\n for (const node of chainNodes(chains)) {\n const ground = context.groundAt(node.x, node.z)\n sink.nodes.push({ id: node.id, ...kindOf({ node, vertex: line.vertices.get(node.id), roots }), at: [node.x, ground, node.z], invert: topOf({ context, x: node.x, z: node.z, cover: rules.cover.water_main.min, diameter: water.mainDiameter }), carries: ['water'] })\n }\n for (const pipe of pipesOf({ chains, diameter: water.mainDiameter, slope: 0 })) sink.edges.push({ id: `${pipe.from}>${pipe.to}`, kind: 'water_main', from: pipe.from, to: pipe.to, diameter: water.mainDiameter })\n for (const vertex of line.vertices.values()) if (vertex.role === 'crossing') layHydrant({ context, vertex })\n for (const connection of connections) {\n const tee = joints.get(`tee:${connection.lot}`)\n if (tee === undefined) continue\n const node = `lot:${connection.lot}:water`\n const invert = topOf({ context, x: connection.at[0], z: connection.at[2], cover: rules.cover.water_service.min, diameter: water.serviceDiameter })\n sink.nodes.push({ id: node, kind: 'connection', at: connection.at, invert, carries: ['water'], lot: connection.lot })\n sink.edges.push({ id: `water:service:${connection.lot}`, kind: 'water_service', from: tee, to: node, diameter: water.serviceDiameter })\n }\n}\n\n/** A pillar hydrant beside the valve of a crossing, on the sidewalk away from the cross street's roadway. */\nfunction layHydrant({ context, vertex }: { readonly context: BuriedContext; readonly vertex: LineVertex }): void {\n const { water } = context.rules.layout\n const run = context.runs.find((candidate) => {\n const [, v] = frameOf({ frame: candidate, x: vertex.x, z: vertex.z })\n return Math.abs(v - waterOffset({ context, run: candidate })) < 1e-6\n })\n if (run === undefined) return\n const cross = context.runs.find((candidate) => candidate.along !== run.along && Math.abs((run.along === 'x' ? vertex.x : vertex.z) - candidate.axis - waterOffset({ context, run: candidate })) < 1e-6)\n const away = cross === undefined ? 1 : Math.sign(waterOffset({ context, run: cross })) || 1\n const [x, z] = run.along === 'x' ? [vertex.x + away * water.hydrantOffset, vertex.z] : [vertex.x, vertex.z + away * water.hydrantOffset]\n const id = `water:hydrant:${vertex.id.slice('water:'.length)}`\n const ground = context.groundAt(x, z)\n context.sink.nodes.push({ id, kind: 'hydrant', at: [x, ground, z], invert: topOf({ context, x, z, cover: context.rules.cover.water_main.min, diameter: water.mainDiameter }), carries: ['water'], spec: 'pillar_hydrant' })\n context.sink.edges.push({ id: `${vertex.id}>${id}`, kind: 'water_main', from: vertex.id, to: id, diameter: water.mainDiameter })\n}\n","import type { DeepPartial, UtilityConnection } from '@adatechnology/game-contracts'\n\nimport type { CityPlanInput, PlanRect } from '../cities/types'\nimport { DISTRIBUTION } from '../pole-distribution'\nimport type { DistributionSpec } from '../pole-specs'\nimport { layPower, poleHeightsOf } from './aerial'\nimport type { NetworkSink } from './aerial'\nimport type { BuriedContext } from './buried'\nimport { lotConnectionsOf, ofNetwork } from './connections'\nimport type { LotFrontage } from './drop-rules'\nimport type { GroundAt } from './connections'\nimport { frameOf, hashOf } from './frame'\nimport { poleStationsOf } from './pole-layout'\nimport { poleTreeOf } from './pole-tree'\nimport { reachLots } from './reach'\nimport { resolveNetworkRules } from './rules'\nimport type { NetworkRules } from './rules'\nimport { poleSidesOf, servedLotsOf, streetRunsOf } from './runs'\nimport type { NetworkLot, ServedLot, StreetRun } from './runs'\nimport { laySewer } from './sewer'\nimport { layStorm } from './storm'\nimport { layTelecom } from './telecom'\nimport type { NetworkSurface, UtilityNetworks } from './types'\nimport type { NetworkWarning } from './warnings'\nimport { layWater } from './water'\n\nexport type GenerateNetworksParams = {\n readonly plan: CityPlanInput\n /** The lots of the site; each takes the networks from the street it faces. */\n readonly lots: readonly NetworkLot[]\n /** What the lots declared (`frame: 'world'`); a lot that declared none of a network gets the default point from its rectangle. */\n readonly connections?: readonly UtilityConnection[]\n /** A game's numbers over the defaults. */\n readonly rules?: DeepPartial<NetworkRules>\n /** Draws (illegal hookups, telecom bundles) come from the hash of the seed and an id, never from a scene's random. */\n readonly seed: number\n /** Ground no pole may stand on: the front of every gate and door, the meter posts. */\n readonly avoid?: readonly PlanRect[]\n /** Ground level at a point. Default 0 (the flat ground of a levelled city). */\n readonly groundAt?: GroundAt\n /** The distribution pole of the registry: its bands and its lamp's reach are read from its spec. Default `concrete_distribution`. */\n readonly pole?: { readonly id: string; readonly spec: DistributionSpec }\n}\n\nexport type GeneratedNetworks = {\n readonly networks: UtilityNetworks\n /** Every connection the networks link (the declared ones and the defaults), for `validateNetworks`. */\n readonly connections: readonly UtilityConnection[]\n /** Road, sidewalk or lot under a point, from the plan's streets: the `surfaceAt` of `validateNetworks`. */\n readonly surfaceAt: (x: number, z: number) => NetworkSurface\n /** The front of every lot on its street: the `frontages` of `validateNetworks` (the drop rules). */\n readonly frontages: readonly LotFrontage[]\n /** What the generator laid against its own rules because nothing else fit (empty for a plan it can lay). */\n readonly warnings: readonly NetworkWarning[]\n}\n\n/** What lies under a point: the roadway or the sidewalk of a street of the plan, else a lot. */\nexport function surfaceOf({ runs, sidewalk }: { readonly runs: readonly StreetRun[]; readonly sidewalk: number }): (x: number, z: number) => NetworkSurface {\n return (x, z) => {\n let surface: NetworkSurface = 'lot'\n for (const run of runs) {\n const [u, v] = frameOf({ frame: run, x, z })\n if (u < run.from || u > run.to) continue\n if (Math.abs(v) < run.width / 2) return 'road'\n if (Math.abs(v) < run.width / 2 + sidewalk) surface = 'sidewalk'\n }\n return surface\n }\n}\n\n/** Whether a point is in a district of the periphery (the last district of the plan that holds it decides). */\nfunction peripheryOf({ plan, kinds }: { readonly plan: CityPlanInput; readonly kinds: readonly string[] }): (x: number, z: number) => boolean {\n const districts = [...(plan.districts ?? [])].reverse()\n return (x, z) => {\n const holder = districts.find((district) => x >= district.rect[0] && x <= district.rect[2] && z >= district.rect[1] && z <= district.rect[3])\n return holder !== undefined && kinds.includes(holder.kind)\n }\n}\n\ntype Layout = { readonly rules: NetworkRules; readonly runs: readonly StreetRun[]; readonly served: readonly ServedLot[]; readonly sides: ReadonlyMap<string, 1 | -1>; readonly connections: UtilityConnection[] }\n\n/** The poles of every run, with the ones added to reach far lots, as a tree per feed. */\nfunction polesOf({ params, layout, sink }: { readonly params: GenerateNetworksParams; readonly layout: Layout; readonly sink: NetworkSink }) {\n const { rules, runs, served, sides } = layout\n const avoid = params.avoid ?? []\n const warn = (warning: NetworkWarning): void => void sink.warnings.push(warning)\n const stations = runs.map((run) => poleStationsOf({ run, side: sides.get(run.id) ?? -1, served, avoid, rules: rules.layout, warn }))\n const anchors = layout.connections.filter((connection) => connection.network === 'power' || connection.network === 'telecom')\n const isFree = (x: number, z: number): boolean => !avoid.some((rect) => x > rect[0] && x < rect[2] && z > rect[1] && z < rect[3])\n const surface = surfaceOf({ runs, sidewalk: rules.layout.sidewalk })\n const inside = (x: number, z: number, rect: PlanRect): boolean => x > rect[0] && x < rect[2] && z > rect[1] && z < rect[3]\n const canServe = ({ x, z, lot }: { readonly x: number; readonly z: number; readonly lot: string }): boolean =>\n surface(x, z) !== 'road' && !params.lots.some((other) => other.id !== lot && inside(x, z, other.rect))\n const reach = Math.min(rules.power.dropMaxLength, rules.telecom.dropMaxLength)\n const frontages = new Map(frontagesOf({ served, sidewalk: rules.layout.sidewalk }).map((frontage) => [frontage.lot, frontage]))\n const reached = reachLots({ runs: stations, anchors, served: new Map(served.map((entry) => [entry.lot.id, entry])), reach, rules: rules.layout, isFree, canServe, warn, frontages, power: rules.power })\n return { tree: poleTreeOf({ chains: [...reached.runs, ...reached.chains], sides, setback: rules.layout.poles.curbSetback }), feeds: reached.feeds }\n}\n\n/** The front of every lot on its street, for the drop rules (`validateNetworks`' `frontages`). */\nexport function frontagesOf({ served, sidewalk }: { readonly served: readonly ServedLot[]; readonly sidewalk: number }): LotFrontage[] {\n return served.map((entry) => ({ lot: entry.lot.id, rect: entry.lot.rect, frame: { along: entry.run.along, axis: entry.run.axis }, reach: entry.run.width / 2 + sidewalk, side: entry.side, span: entry.span }))\n}\n\n/**\n * The utility networks of a district from its city plan and the site's lots, as data: power (medium voltage from a feed where the trunk\n * leaves the map, transformers sized by the diversified demand, low voltage, a drop to every lot), a lamp on every street pole, telecom, sewer\n * to an interceptor along the river, drainage to headwalls on the bank, water from a reservoir at the border. Pure: the same input gives the same bytes.\n */\nexport function generateNetworks(params: GenerateNetworksParams): GeneratedNetworks {\n const rules = resolveNetworkRules(params.rules)\n const groundAt = params.groundAt ?? ((): number => 0)\n const runs = streetRunsOf({ plan: params.plan, edgeReach: rules.layout.edgeReach })\n const served = servedLotsOf({ lots: params.lots, runs })\n const sides = poleSidesOf({ runs, served })\n const connections = lotConnectionsOf({ served, declared: params.connections ?? [], rules, groundAt })\n const sink: NetworkSink = { nodes: [], edges: [], warnings: [] }\n const { tree, feeds } = polesOf({ params, layout: { rules, runs, served, sides, connections }, sink })\n const pole = params.pole ?? { id: 'concrete_distribution', spec: DISTRIBUTION }\n const heights = poleHeightsOf(pole.spec.slots)\n const isPeriphery = peripheryOf({ plan: params.plan, kinds: rules.layout.periphery.kinds })\n const unmetered = new Set(\n served\n .filter(({ lot }) => isPeriphery((lot.rect[0] + lot.rect[2]) / 2, (lot.rect[1] + lot.rect[3]) / 2) && hashOf({ seed: params.seed, id: `hookup:${lot.id}` }) < rules.layout.periphery.hookupShare)\n .map((entry) => entry.lot.id),\n )\n layPower({ tree, connections: ofNetwork({ connections, network: 'power' }), rules, heights, pole: { id: pole.id, lampReach: pole.spec.lamp.reach }, unmetered, feeds, sink })\n layTelecom({ tree, connections: ofNetwork({ connections, network: 'telecom' }), rules, heights, seed: params.seed, isPeriphery, feeds, sink })\n const [width, depth] = params.plan.size ?? [0, 0]\n const rivers = (params.plan.lines ?? []).filter((line) => line.kind === 'river')\n const context: BuriedContext = { runs, sides, served: new Map(served.map((entry) => [entry.lot.id, entry])), rules, groundAt, rivers, border: [width / 2, depth / 2], sink }\n const storm = layStorm({ context, connections: ofNetwork({ connections, network: 'storm' }) })\n layWater({ context, connections: ofNetwork({ connections, network: 'water' }) })\n laySewer({ context, connections: ofNetwork({ connections, network: 'sewer' }), above: storm })\n const networks: UtilityNetworks = { nodes: sink.nodes, edges: sink.edges, seed: params.seed, rules }\n return { networks, connections, surfaceAt: surfaceOf({ runs, sidewalk: rules.layout.sidewalk }), frontages: frontagesOf({ served, sidewalk: rules.layout.sidewalk }), warnings: sink.warnings }\n}\n","/** How the lamps of a street are kept: `lit` is the share of lamps that work, `flicker` the share of all lamps that work badly (a part of `lit`). The rest are burnt out. */\nexport type LampShares = { readonly lit: number; readonly flicker: number }\n\n/** One lamp: `on` for `PoleOptions.on`, `flicker` for `PoleOptions.flicker`. */\nexport type LampState = { readonly on: boolean; readonly flicker: boolean }\n\nexport type LampStateParams = { readonly seed: number; readonly x: number; readonly z: number; readonly shares: LampShares }\n\nconst UINT32 = 2 ** 32\n/** Salt of the flicker phase, so it is not the same roll as the lamp's state. */\nconst PHASE_SALT = 0x5f3759df\n\n/** The seed's 64 bits, as two 32-bit words: a large or fractional seed keeps every bit (no `| 0` truncation). */\nconst SEED_BITS = new DataView(new ArrayBuffer(8))\n\n/** FNV-1a of the seed and the spot (centimetres), into [0, 1). */\nconst hashLamp = (seed: number, x: number, z: number): number => {\n SEED_BITS.setFloat64(0, seed)\n let h = 2166136261\n for (const value of [SEED_BITS.getUint32(0), SEED_BITS.getUint32(4), Math.round(x * 100), Math.round(z * 100)]) {\n h ^= value & 0xffff\n h = Math.imul(h, 16777619)\n h ^= (value >>> 16) & 0xffff\n h = Math.imul(h, 16777619)\n }\n return (h >>> 0) / UINT32\n}\n\n/** The phase (radians, [0, 2π)) a failing lamp at `x, z` flickers on: its lens and its light share it. A drawer may round it: game-urban-three rounds it to 4 groups, so about a quarter of the failing lamps blink in step. */\nexport const flickerPhaseOf = (x: number, z: number): number => hashLamp(PHASE_SALT, x, z) * 2 * Math.PI\n\n/** Throws when the shares are not `0 <= flicker <= lit <= 1`. */\nexport function assertLampShares(shares: LampShares): void {\n const { lit, flicker } = shares\n if (!(lit >= 0 && lit <= 1)) throw new RangeError(`lamp shares: lit must be in [0, 1], got ${lit}`)\n if (!(flicker >= 0 && flicker <= lit)) throw new RangeError(`lamp shares: flicker must be in [0, lit], got ${flicker}`)\n}\n\n/**\n * Whether the lamp standing at `x, z` works, flickers or is burnt out, by a hash of the seed and the spot: the same street with the same seed keeps the same dead and failing lamps,\n * and the choice does not draw from the builder's random, so the scene around it keeps its draw order.\n */\nexport function lampStateOf({ seed, x, z, shares }: LampStateParams): LampState {\n assertLampShares(shares)\n const roll = hashLamp(seed, x, z)\n if (roll >= shares.lit) return { on: false, flicker: false }\n return { on: true, flicker: roll >= shares.lit - shares.flicker }\n}\n","import { flickerPhaseOf, lampStateOf } from '../lamps'\nimport type { LampShares, LampState } from '../lamps'\nimport type { UtilityNetworks } from './types'\n\n/** A street light of the network with the state of its lamp: `pole` is the pole its `light_feed` comes from. */\nexport type NetworkLamp = LampState & { readonly id: string; readonly pole: string; readonly at: readonly [number, number, number]; readonly flickerPhase?: number }\n\nexport type NetworkLampsParams = {\n readonly networks: UtilityNetworks\n /** The share of lamps that work and the share that flicker (the rest are burnt out). */\n readonly shares: LampShares\n /** By day every lamp is off. */\n readonly isNight: boolean\n}\n\n/**\n * Every `light` node with its lamp's state, `lampStateOf` by the network's seed and the node's place (the same draw a pole of the scene had), and\n * a failing lamp's flicker phase (`flickerPhaseOf`). A lamp is on at night when its state says so; the transformer that feeds it is T2.8f.\n */\nexport function networkLampsOf({ networks, shares, isNight }: NetworkLampsParams): NetworkLamp[] {\n const feeds = new Map(networks.edges.filter((edge) => edge.kind === 'light_feed').map((edge) => [edge.to, edge.from]))\n return networks.nodes\n .filter((node) => node.kind === 'light')\n .map((node): NetworkLamp => {\n const [x, , z] = node.at\n const state = isNight ? lampStateOf({ seed: networks.seed, x, z, shares }) : { on: false, flicker: false }\n return { id: node.id, pole: feeds.get(node.id) ?? '', at: node.at, ...state, ...(state.flicker ? { flickerPhase: flickerPhaseOf(x, z) } : {}) }\n })\n}\n","import { poleHeightsOf } from './networks/aerial'\nimport type { DistributionSpec } from './pole-specs'\n\n/** A point of a pole in its own frame: `x` toward the road (where the lamp hangs), `y` up from the ground, `z` along the line. */\nexport type PolePoint = readonly [number, number, number]\n\n/** What a piece of a distribution pole is, so a drawing can keep what another already draws (the single arm draws `arm`, `lamp` and the tank). */\nexport type HardwareRole = 'crossarm' | 'insulator' | 'lv_clamp' | 'telecom_clamp' | 'bracket' | 'bushing' | 'arm' | 'lamp' | 'tank'\n\n/** A box of the pole in its frame: `y` is the base, as the builder's boxes. */\nexport type HardwareBox = { readonly role: HardwareRole; readonly x: number; readonly y: number; readonly z: number; readonly width: number; readonly height: number; readonly depth: number; readonly color: number }\n/** An upright cylinder (the transformer tank): `y` is the base. */\nexport type HardwareCylinder = { readonly role: 'tank'; readonly x: number; readonly y: number; readonly z: number; readonly radius: number; readonly height: number; readonly color: number; readonly segments: number }\n\n/** Where each conductor is fixed on the pole, in its frame. */\nexport type PoleAttachments = {\n /** The three medium-voltage phases, on the tops of the pin insulators. */\n readonly mv: readonly PolePoint[]\n /** The low-voltage multiplexed cable in its suspension clamp. */\n readonly lv: PolePoint\n /** One clamp per telecom cable, the first on top. */\n readonly telecom: readonly PolePoint[]\n /** The transformer: its three bushing tops (medium voltage in) and the side of its tank the low voltage leaves from. */\n readonly transformer?: { readonly mv: readonly PolePoint[]; readonly lv: PolePoint }\n /** The guy wire's eye, under the crossarm. */\n readonly guy: PolePoint\n}\n\n/** The pieces and fixing points of a distribution pole. The lens is apart: its colour is the lamp's state. */\nexport type PoleHardware = { readonly boxes: readonly HardwareBox[]; readonly cylinders: readonly HardwareCylinder[]; readonly lens?: HardwareBox; readonly attachments: PoleAttachments }\n\nexport type PoleHardwareOptions = {\n /** The pole carries the medium voltage (its crossarm and insulators). */\n readonly mv: boolean\n /** A transformer hangs on it. */\n readonly transformer: boolean\n /** Its street light (arm, luminaire, lens). */\n readonly lamp: boolean\n /** Telecom cables fixed on it, `cableGap` apart (the network's `rules.layout.telecom.cableGap`). */\n readonly cables: number\n readonly cableGap: number\n}\n\n/** Least free gap between two pieces that touch (CLAUDE.md §13). */\nconst GAP = 0.002\n\n/** The crossarm and its three pin insulators, the top of each insulator in the medium-voltage band's top. */\nfunction mediumVoltage(spec: DistributionSpec): { boxes: HardwareBox[]; mv: PolePoint[] } {\n const { crossarm, insulators, slots } = spec\n const [bottom, top] = slots.bands.mv\n const pin = top - bottom - crossarm.height - GAP\n const boxes: HardwareBox[] = [{ role: 'crossarm', x: crossarm.reach, y: bottom, z: 0, width: crossarm.width, height: crossarm.height, depth: crossarm.depth, color: crossarm.color }]\n for (const x of insulators.at) boxes.push({ role: 'insulator', x, y: bottom + crossarm.height + GAP, z: 0, width: insulators.radius * 2, height: pin, depth: insulators.radius * 2, color: insulators.color })\n return { boxes, mv: insulators.at.map((x): PolePoint => [x, top, 0]) }\n}\n\n/** The tank on its bracket on the field side, under the crossarm, with three bushings on its lid. */\nfunction transformerOf(spec: DistributionSpec): { boxes: HardwareBox[]; tank: HardwareCylinder; points: NonNullable<PoleAttachments['transformer']> } {\n const t = spec.transformer\n const x = -t.offset\n const tank: HardwareCylinder = { role: 'tank', x, y: t.y, z: 0, radius: t.radius, height: t.height, color: t.color, segments: t.segments }\n const { bushings } = spec\n const lid = t.y + t.height + GAP\n const zs = [-bushings.spread, 0, bushings.spread]\n const boxes: HardwareBox[] = [\n { role: 'bracket', x: x / 2, y: t.y + t.height * 0.6, z: 0, width: t.offset, height: 0.08, depth: 0.1, color: spec.lowVoltage.color },\n ...zs.map((z): HardwareBox => ({ role: 'bushing', x, y: lid, z, width: bushings.radius * 2, height: bushings.height, depth: bushings.radius * 2, color: bushings.color })),\n ]\n return { boxes, tank, points: { mv: zs.map((z): PolePoint => [x, lid + bushings.height, z]), lv: [x + t.radius, t.y + t.height * 0.3, 0] } }\n}\n\n/** The arm over the road, the luminaire at its end and the lens under the luminaire (2 mm apart). */\nfunction lampOf(spec: DistributionSpec): { boxes: HardwareBox[]; lens: HardwareBox } {\n const { arm, lamp } = spec\n const lensHeight = 0.03\n return {\n boxes: [\n { role: 'arm', x: arm.reach, y: arm.y, z: 0, width: arm.width, height: arm.height, depth: arm.depth, color: arm.color },\n { role: 'lamp', x: lamp.reach, y: lamp.y, z: 0, width: lamp.width, height: lamp.height, depth: lamp.depth, color: arm.color },\n ],\n lens: { role: 'lamp', x: lamp.reach, y: lamp.y - lensHeight - GAP, z: 0, width: lamp.width * 0.8, height: lensHeight, depth: lamp.depth * 0.8, color: spec.lens.unlit },\n }\n}\n\n/**\n * The hardware of a distribution pole in its own frame, every fixing height read from its bands (`slots`) as the network generator reads them:\n * the crossarm with its pin insulators at the medium voltage, the transformer under it, the low-voltage cable's suspension clamp on the field\n * side, the street light's arm over the road, and one telecom clamp per cable under the lamp. Pure; the drawing places and instances it.\n */\nexport function distributionHardwareOf(spec: DistributionSpec, o: PoleHardwareOptions): PoleHardware {\n const heights = poleHeightsOf(spec.slots)\n const boxes: HardwareBox[] = []\n const cylinders: HardwareCylinder[] = []\n const mv = mediumVoltage(spec)\n if (o.mv || o.transformer) boxes.push(...mv.boxes)\n const lvAt: PolePoint = [-spec.lowVoltage.out, heights.lv, 0]\n boxes.push({ role: 'lv_clamp', x: -spec.lowVoltage.out / 2 - spec.mast.radiusTop / 2, y: heights.lv - 0.06, z: 0, width: spec.lowVoltage.out - spec.mast.radiusTop + 0.06, height: 0.12, depth: 0.08, color: spec.lowVoltage.color })\n const { telecom } = spec\n const cables = Math.max(o.cables, 0)\n const telecomAt = Array.from({ length: cables }, (_, index): PolePoint => [-telecom.out, heights.telecom - index * o.cableGap, 0])\n if (cables > 0) {\n const bottom = heights.telecom - (cables - 1) * o.cableGap - 0.05\n boxes.push({ role: 'telecom_clamp', x: -telecom.out / 2 - spec.mast.radiusTop / 2, y: bottom, z: 0, width: telecom.out - spec.mast.radiusTop + 0.04, height: heights.telecom + 0.05 - bottom, depth: 0.06, color: telecom.color })\n }\n const transformer = o.transformer ? transformerOf(spec) : undefined\n if (transformer) {\n boxes.push(...transformer.boxes)\n cylinders.push(transformer.tank)\n }\n const lamp = o.lamp ? lampOf(spec) : undefined\n if (lamp) boxes.push(...lamp.boxes)\n const attachments: PoleAttachments = { mv: mv.mv, lv: lvAt, telecom: telecomAt, guy: [0, spec.slots.bands.mv[0] - 0.15, 0], ...(transformer ? { transformer: transformer.points } : {}) }\n return { boxes, cylinders, ...(lamp ? { lens: lamp.lens } : {}), attachments }\n}\n","import { buildNetworkGraph } from './graph'\nimport type { NetworkGraph } from './graph'\nimport type { NetworkEdge, NetworkNode, NetworkSurface, UtilityNetworks } from './types'\n\n/** What shows of the buried networks: each one a piece standing at a node of the ground. */\nexport type SurfaceKind = 'manhole_cover' | 'cleanout_cover' | 'inlet_grate' | 'valve_cover' | 'hydrant' | 'wing_wall' | 'inspection_cover' | 'meter_box' | 'downspout_mouth'\n\n/** Ids of `game-destruction` materials. */\nexport type SurfaceMaterial = 'cast_iron' | 'concrete' | 'plastic'\n\n/** The pit under a cover, from the ground down to the pipe's bottom: round (a PV, a valve) or square (an inlet box, an inspection box). */\nexport type Shaft = { readonly shape: 'round' | 'square'; readonly width: number; readonly depth: number; readonly top: number; readonly bottom: number; readonly material: SurfaceMaterial }\n\nexport type SurfacePiece = {\n /** The id of the node it stands at. */\n readonly id: string\n readonly kind: SurfaceKind\n /** Ground level at the node. */\n readonly at: readonly [number, number, number]\n /** Turn about y: the piece's local x runs along the street (the kerb), its local z (the wing wall's front) across it. */\n readonly ry: number\n readonly spec: string | undefined\n readonly shape: 'round' | 'square'\n /** Width along the street, height over the ground, depth across it (a round piece: its diameter twice). */\n readonly size: readonly [number, number, number]\n readonly material: SurfaceMaterial\n /** It blocks a body (a hydrant, a wing wall, a meter box). A cover and a grate are ground: they are walked on and carry a vehicle. */\n readonly solid: boolean\n readonly shaft?: Shaft\n}\n\ntype PieceSpec = Pick<SurfacePiece, 'kind' | 'shape' | 'size' | 'material' | 'solid'> & { readonly shaft?: Pick<Shaft, 'shape' | 'width' | 'depth' | 'material'> }\n\nconst COVER = 0.6\nconst SHAFT_PV = { shape: 'round', width: 0.9, depth: 0.9, material: 'concrete' } as const\n\n/** The piece of each node by its kind and spec; a node that shows nothing (a saddle, a tee, the plant) has none. */\nfunction specOf(node: NetworkNode): PieceSpec | undefined {\n const network = node.carries[0]\n switch (node.kind) {\n case 'manhole':\n return node.spec === 'gallery_box'\n ? { kind: 'manhole_cover', shape: 'square', size: [COVER, 0.03, COVER], material: 'cast_iron', solid: false, shaft: { shape: 'square', width: 0.9, depth: 0.9, material: 'concrete' } }\n : { kind: 'manhole_cover', shape: 'round', size: [COVER, 0.03, COVER], material: 'cast_iron', solid: false, shaft: SHAFT_PV }\n case 'pumping_station':\n return { kind: 'manhole_cover', shape: 'round', size: [0.9, 0.03, 0.9], material: 'cast_iron', solid: false, shaft: { shape: 'round', width: 1.5, depth: 1.5, material: 'concrete' } }\n case 'cleanout':\n return { kind: 'cleanout_cover', shape: 'round', size: [0.25, 0.03, 0.25], material: 'cast_iron', solid: false, shaft: { shape: 'round', width: 0.2, depth: 0.2, material: 'plastic' } }\n case 'inlet':\n return { kind: 'inlet_grate', shape: 'square', size: [0.9, 0.03, 0.5], material: 'cast_iron', solid: false, shaft: { shape: 'square', width: 0.8, depth: 0.5, material: 'concrete' } }\n case 'valve':\n return { kind: 'valve_cover', shape: 'round', size: [0.2, 0.03, 0.2], material: 'cast_iron', solid: false, shaft: { shape: 'round', width: 0.1, depth: 0.1, material: 'cast_iron' } }\n case 'hydrant':\n return { kind: 'hydrant', shape: 'round', size: [0.2, 0.8, 0.2], material: 'cast_iron', solid: true, shaft: { shape: 'round', width: 0.1, depth: 0.1, material: 'cast_iron' } }\n case 'outfall':\n return { kind: 'wing_wall', shape: 'square', size: [3, 0.8, 1.6], material: 'concrete', solid: true }\n case 'connection':\n if (network === 'sewer') return { kind: 'inspection_cover', shape: 'square', size: [0.6, 0.03, 0.6], material: 'concrete', solid: false, shaft: { shape: 'square', width: 0.6, depth: 0.6, material: 'concrete' } }\n if (network === 'water') return { kind: 'meter_box', shape: 'square', size: [0.4, 0.3, 0.25], material: 'concrete', solid: true, shaft: { shape: 'round', width: 0.04, depth: 0.04, material: 'plastic' } }\n return network === 'storm' ? { kind: 'downspout_mouth', shape: 'square', size: [0.3, 0.02, 0.2], material: 'concrete', solid: false } : undefined\n default:\n return undefined\n }\n}\n\nconst unit = (dx: number, dz: number): readonly [number, number] => {\n const length = Math.hypot(dx, dz)\n return length === 0 ? [1, 0] : [dx / length, dz / length]\n}\n\nconst planOf = (graph: NetworkGraph, id: string, from: NetworkNode): readonly [number, number] => {\n const other = graph.nodes.get(id)\n return other === undefined ? [0, 0] : [other.at[0] - from.at[0], other.at[2] - from.at[2]]\n}\n\n/** The way the street runs at a node, from the pipe that leaves it: a lateral or a service leaves square to the street, a gutter or a main runs along it. */\nfunction alongOf(graph: NetworkGraph, node: NetworkNode): readonly [number, number] {\n const edges: readonly NetworkEdge[] = [...graph.outgoing(node.id), ...graph.incoming(node.id)]\n const square = edges.find((edge) => edge.kind === 'storm_lateral' || edge.kind === 'sewer_lateral' || edge.kind === 'water_service')\n if (square !== undefined) {\n const [dx, dz] = planOf(graph, square.from === node.id ? square.to : square.from, node)\n return unit(-dz, dx)\n }\n const along = edges.find((edge) => edge.kind === 'storm_gutter' || edge.kind === 'storm_gallery' || edge.kind === 'sewer_main')\n if (along === undefined) return [1, 0]\n const [dx, dz] = planOf(graph, along.from === node.id ? along.to : along.from, node)\n return unit(dx, dz)\n}\n\n/** The wing wall faces the way the gallery flows into it: its local z along the flow. */\nfunction headingOf(graph: NetworkGraph, node: NetworkNode): number {\n if (node.kind === 'outfall') {\n const into = graph.incoming(node.id).find((edge) => edge.kind === 'storm_gallery')\n const [bx, bz] = into === undefined ? ([0, -1] as const) : planOf(graph, into.from, node)\n const [fx, fz] = unit(-bx, -bz)\n return Math.atan2(fx, fz)\n }\n const [dx, dz] = alongOf(graph, node)\n return Math.atan2(-dz, dx)\n}\n\n/** Where `drawRoad` lays the asphalt over the terrain (`game-urban` streets): a cover on the road stands on it, not on the ground under it. */\nexport const ROAD_SURFACE_LEVEL = 0.02\n\nexport type SurfacePiecesOptions = {\n /** What lies under a point (`GeneratedNetworks.surfaceAt`): a piece on the road stands `roadLevel` higher. Without it every piece stands on the ground. */\n readonly surfaceAt?: (x: number, z: number) => NetworkSurface | undefined\n /** Default `ROAD_SURFACE_LEVEL`. */\n readonly roadLevel?: number\n}\n\n/**\n * What shows of the buried networks, a piece at each node that has a face on the ground: the PV and gallery box covers, the cleanout and valve\n * covers, the inlets' grates at the kerb, the hydrants, the wing walls at the outfalls, and at each lot the inspection box cover, the meter box\n * and the downspout's mouth. Each carries its pit down to the pipe's bottom.\n */\nexport function surfacePiecesOf(networks: Pick<UtilityNetworks, 'nodes' | 'edges'>, options: SurfacePiecesOptions = {}): SurfacePiece[] {\n const graph = buildNetworkGraph(networks)\n const lift = (node: NetworkNode): number => (options.surfaceAt?.(node.at[0], node.at[2]) === 'road' ? (options.roadLevel ?? ROAD_SURFACE_LEVEL) : 0)\n const taken: Array<{ readonly kind: SurfaceKind; readonly x: number; readonly z: number }> = []\n return networks.nodes.flatMap((node): SurfacePiece[] => {\n const spec = specOf(node)\n if (spec === undefined) return []\n // two pieces of one kind closer than their frame is wide (the galleries of the two kerbs meeting a main at one station, inlets at the end of a street) show as one\n const reach = spec.size[0] + 0.12\n if (taken.some((other) => other.kind === spec.kind && Math.hypot(other.x - node.at[0], other.z - node.at[2]) < reach)) return []\n taken.push({ kind: spec.kind, x: node.at[0], z: node.at[2] })\n const { shaft, ...piece } = spec\n const bottom = node.invert\n return [{ id: node.id, ...piece, at: [node.at[0], node.at[1] + lift(node), node.at[2]], ry: headingOf(graph, node), spec: node.spec, ...(shaft === undefined || bottom === undefined ? {} : { shaft: { ...shaft, top: node.at[1] + lift(node), bottom } }) }]\n })\n}\n","import { isAerialEdgeKind } from './classes'\nimport type { SurfaceMaterial } from './surface'\nimport type { BuriedEdgeKind, UtilityNetworks } from './types'\n\n/** What leaks from a pipe that breaks. */\nexport type PipeContent = 'sewage' | 'stormwater' | 'water'\n\n/** A buried pipe as a body in the ground: its centre line from end to end, laid at the depths the network was laid with. */\nexport type PipePiece = {\n /** The id of the edge. */\n readonly id: string\n readonly kind: BuriedEdgeKind\n readonly content: PipeContent\n /** The centre line's ends (world metres, `y` the centre of the bore). */\n readonly from: readonly [number, number, number]\n readonly to: readonly [number, number, number]\n /** Outer diameter, metres. */\n readonly diameter: number\n readonly material: SurfaceMaterial\n /** Ground level above each end. */\n readonly ground: readonly [number, number]\n}\n\nconst CONTENT: Readonly<Partial<Record<BuriedEdgeKind, PipeContent>>> = {\n sewer_main: 'sewage',\n sewer_lateral: 'sewage',\n storm_gallery: 'stormwater',\n storm_lateral: 'stormwater',\n water_main: 'water',\n water_service: 'water',\n}\n\nconst MATERIAL_OF: Readonly<Record<PipeContent, SurfaceMaterial>> = { sewage: 'plastic', water: 'plastic', stormwater: 'concrete' }\n\n/** Metres a pipe's wall is thicker than its bore, per metre of bore (a DN 600 gallery has rings of 0.07 m). */\nconst WALL_SHARE = 0.12\nconst HYDRANT_BRANCH_SHARE = 0.8\n\n/**\n * Every pipe of the sewer, the drainage and the water as a piece laid in the ground: from the inverts of its ends (its own, or its nodes'),\n * with the diameter the network gave plus its wall. The gutters are open channels at the kerb and have no pipe.\n */\nexport function pipePiecesOf(networks: Pick<UtilityNetworks, 'nodes' | 'edges'>): PipePiece[] {\n const nodes = new Map(networks.nodes.map((node) => [node.id, node]))\n return networks.edges.flatMap((edge): PipePiece[] => {\n const content = isAerialEdgeKind(edge.kind) ? undefined : CONTENT[edge.kind as BuriedEdgeKind]\n const [from, to] = [nodes.get(edge.from), nodes.get(edge.to)]\n if (content === undefined || from === undefined || to === undefined || edge.diameter === undefined) return []\n const inverts = edge.inverts ?? (from.invert !== undefined && to.invert !== undefined ? ([from.invert, to.invert] as const) : undefined)\n if (inverts === undefined) return []\n // the hydrant's branch runs on along the main's own line: a little slimmer, so the two never share a surface\n const diameter = edge.diameter * (1 + WALL_SHARE) * (to.kind === 'hydrant' ? HYDRANT_BRANCH_SHARE : 1)\n const centre = (invert: number): number => invert + edge.diameter! / 2\n return [{ id: edge.id, kind: edge.kind as BuriedEdgeKind, content, from: [from.at[0], centre(inverts[0]), from.at[2]], to: [to.at[0], centre(inverts[1]), to.at[2]], diameter, material: MATERIAL_OF[content], ground: [from.at[1], to.at[1]] }]\n })\n}\n\n/** Metres of ground over the top of a pipe at a share `t` of its length. */\nexport function coverOf(pipe: PipePiece, t: number): number {\n const ground = pipe.ground[0] + (pipe.ground[1] - pipe.ground[0]) * t\n const centre = pipe.from[1] + (pipe.to[1] - pipe.from[1]) * t\n return ground - (centre + pipe.diameter / 2)\n}\n","import { coverOf } from './pipes'\nimport type { PipeContent, PipePiece } from './pipes'\nimport type { SurfacePiece } from './surface'\n\nexport type PipeBreach = {\n readonly id: string\n readonly kind: PipePiece['kind']\n readonly content: PipeContent\n /** Where along the pipe (0 at its `from` end) the bowl reaches deepest, and the point of the centre line there. */\n readonly share: number\n readonly at: readonly [number, number, number]\n /** The bowl got down to the bore's centre line: the pipe is broken. */\n readonly severed: boolean\n}\n\n/** A bowl taken out of the ground: the shape of a `GroundLoss` (`game-contracts`) or of a terrain blow's result. */\nexport type Crater = { readonly x: number; readonly z: number; readonly radius: number; readonly depth: number }\n\n/** Metres a pipe is sampled every along its length. */\nconst SAMPLE_STEP = 0.25\n\n/** How deep the bowl is at a distance from its centre: a paraboloid, the full depth at the middle and nothing at the rim. */\nexport function bowlDepthAt(crater: Crater, distance: number): number {\n if (distance >= crater.radius) return 0\n return crater.depth * (1 - (distance / crater.radius) ** 2)\n}\n\n/** The deepest point of a pipe a crater reaches: its share along the pipe, and whether the bowl got down to the bore's centre line. */\nfunction reachOf(pipe: PipePiece, crater: Crater): PipeBreach | undefined {\n const length = Math.hypot(pipe.to[0] - pipe.from[0], pipe.to[2] - pipe.from[2])\n const steps = Math.max(1, Math.ceil(length / SAMPLE_STEP))\n let best: { share: number; margin: number } | undefined\n for (let step = 0; step <= steps; step++) {\n const share = step / steps\n const x = pipe.from[0] + (pipe.to[0] - pipe.from[0]) * share\n const z = pipe.from[2] + (pipe.to[2] - pipe.from[2]) * share\n const margin = bowlDepthAt(crater, Math.hypot(x - crater.x, z - crater.z)) - coverOf(pipe, share)\n if (margin >= 0 && (best === undefined || margin > best.margin)) best = { share, margin }\n }\n if (best === undefined) return undefined\n const { share } = best\n const lerp = (a: number, b: number): number => a + (b - a) * share\n return { id: pipe.id, kind: pipe.kind, content: pipe.content, share, at: [lerp(pipe.from[0], pipe.to[0]), lerp(pipe.from[1], pipe.to[1]), lerp(pipe.from[2], pipe.to[2])], severed: best.margin >= pipe.diameter / 2 }\n}\n\nexport type Breach = {\n /** Pipes the bowl reached (`severed`: down to the centre line, so the pipe is broken and leaks). */\n readonly pipes: readonly PipeBreach[]\n /** The covers, grates and boxes inside the bowl: they are thrown off, and the pit under them lies open. */\n readonly surface: readonly string[]\n /** What leaks, once, of the pipes severed. */\n readonly leaks: readonly PipeContent[]\n}\n\n/**\n * What a crater does to the networks under it: the pipes whose top the bowl got down to, and the surface pieces it swallowed. Pure, from\n * the pieces `pipePiecesOf` and `surfacePiecesOf` give, so a host calls it with the result of a terrain blow (`world.ground.on('blow')`)\n * and the same answer comes for the same bowl.\n */\nexport function breachOf({ pipes, surface }: { readonly pipes: readonly PipePiece[]; readonly surface: readonly SurfacePiece[] }, crater: Crater): Breach {\n const reached = pipes.flatMap((pipe) => reachOf(pipe, crater) ?? [])\n const covers = surface.filter((piece) => Math.hypot(piece.at[0] - crater.x, piece.at[2] - crater.z) <= crater.radius && bowlDepthAt(crater, Math.hypot(piece.at[0] - crater.x, piece.at[2] - crater.z)) > piece.size[1]).map((piece) => piece.id)\n return { pipes: reached, surface: covers, leaks: [...new Set(reached.filter((pipe) => pipe.severed).map((pipe) => pipe.content))] }\n}\n","import type { DestructibleSpec, GroundExcavation, PartShape } from '@adatechnology/game-contracts'\n\nimport type { SurfacePiece } from './surface'\n\n/** Id of the one part of a cover's plate in its `DestructibleSpec`: the drawing binds its meshes to it. */\nexport const COVER_PLATE_PART = 'plate'\n\n/** Metres the pit goes under the bottom of its shaft: the floor the shaft stands on is part of the opening. */\nconst PIT_FLOOR = 0.1\n\n/**\n * The hole a cover leaves where it was thrown off: the square of the shaft under it, down to the shaft's floor, as the ground dug away\n * (`GroundExcavation`, what `Terrain.open` takes). Undefined for a piece with no pit under it, or one that is no cover (a hydrant, a wing wall).\n */\nexport function openingOf(piece: SurfacePiece): GroundExcavation | undefined {\n if (piece.shaft === undefined || piece.solid) return undefined\n const half = piece.shaft.width / 2\n return { rect: [piece.at[0] - half, piece.at[2] - half, piece.at[0] + half, piece.at[2] + half], depth: piece.at[1] - piece.shaft.bottom + PIT_FLOOR }\n}\n\n/** A cover as a loose piece: a plate of its material (cast iron) in the shape of its frame, as the destruction world takes it, and where it stood. */\nexport type CoverBody = {\n readonly id: string\n readonly spec: DestructibleSpec\n readonly position: readonly [number, number, number]\n /** Turn about y, radians. */\n readonly ry: number\n /** Kilograms the plate weighs: density times volume (`game-destruction` gives the same when the part has no mass). */\n readonly mass: number\n}\n\n/** Kilograms per cubic metre of each material of a cover (the `game-destruction` table). */\nconst DENSITY: Readonly<Record<SurfacePiece['material'], number>> = { cast_iron: 7200, concrete: 2400, plastic: 950 }\n\nexport function coverBodyOf(piece: SurfacePiece): CoverBody | undefined {\n if (piece.shaft === undefined || piece.solid) return undefined\n const [width, height, depth] = piece.size\n const isRound = piece.shape === 'round'\n const shape: PartShape = isRound ? { kind: 'cylinder', radius: width / 2, height } : { kind: 'box', size: [width, height, depth] }\n const volume = isRound ? Math.PI * (width / 2) ** 2 * height : width * height * depth\n return {\n id: `cover:${piece.id}`,\n spec: { name: piece.kind, tags: ['network_cover'], parts: [{ id: COVER_PLATE_PART, material: piece.material, shape, position: [0, height / 2, 0] }] },\n position: piece.at,\n ry: piece.ry,\n mass: volume * DENSITY[piece.material],\n }\n}\n\n/** Metres per second a cover is thrown outward from the middle of the bowl at least, and how much each metre of the bowl's depth adds; upward the same, twice. */\nconst THROW_BASE = 1.5\nconst THROW_PER_DEPTH = 1.2\nconst THROW_UP = 2\n\n/**\n * The velocity a crater throws a cover off with: away from the middle of the bowl (along +x for a cover right at it), faster the deeper the bowl, and up. Pure: the same bowl\n * throws the same cover the same way, so a LAN client that repeats the blow sees the same lid land in the same place.\n */\nexport function coverThrowOf(piece: SurfacePiece, crater: { readonly x: number; readonly z: number; readonly depth: number }): readonly [number, number, number] {\n const [dx, dz] = [piece.at[0] - crater.x, piece.at[2] - crater.z]\n const length = Math.hypot(dx, dz)\n const [ux, uz] = length < 1e-6 ? [1, 0] : [dx / length, dz / length]\n const out = THROW_BASE + THROW_PER_DEPTH * crater.depth\n return [ux * out, THROW_UP * out, uz * out]\n}\n","import { connectedNodes, buildNetworkGraph } from './graph'\nimport type { Breach } from './breach'\nimport type { PipeContent } from './pipes'\nimport { pipePiecesOf } from './pipes'\nimport type { UtilityNetworks } from './types'\n\n/** What one broken pipe lets out: the fluid, where, how fast at most, and how much is there to lose (finite: a valve closes, a pipe empties). */\nexport type NetworkLeak = {\n /** The id of the pipe (its edge). */\n readonly id: string\n readonly content: PipeContent\n /** The break: world metres, `y` the pipe's centre line. */\n readonly at: readonly [number, number, number]\n readonly diameter: number\n /** Litres per second at most. */\n readonly rate: number\n /** Litres there are to lose, in all. */\n readonly volume: number\n /** It leaves under pressure (a water main), up out of the ground; the rest runs. */\n readonly isPressurised: boolean\n}\n\n/** The houses that lose their water, and the nodes of the network (hydrants, valves, services) that go with them. */\nexport type NetworkOutage = {\n readonly network: 'water'\n /** The pipes whose break cut the supply. */\n readonly causes: readonly string[]\n /** Nodes the reservoir no longer reaches. */\n readonly nodes: readonly string[]\n /** Lots (`NetworkNode.lot`) with no water. */\n readonly lots: readonly string[]\n}\n\n/** What a blast on the networks tells the host, in the order it happens: a pipe leaks, a house loses its water, a cover opens its hole. */\nexport type NetworkEvent =\n | { readonly type: 'network_leak'; readonly leak: NetworkLeak }\n | { readonly type: 'network_outage'; readonly outage: NetworkOutage }\n | { readonly type: 'network_hole'; readonly id: string; readonly kind: string }\n\nexport type LeakRule = {\n /** Litres per second of the break (a bored main, a service). */\n readonly mainRate: number\n readonly branchRate: number\n /** Seconds before the utility closes the valve (water), the inflow stops (sewage) or the rain does (drainage): the volume is `rate` times this. */\n readonly seconds: number\n readonly isPressurised: boolean\n}\n\nexport type LeakRules = Readonly<Record<PipeContent, LeakRule>>\n\nexport const DEFAULT_LEAK_RULES: LeakRules = {\n water: { mainRate: 6, branchRate: 0.8, seconds: 300, isPressurised: true },\n sewage: { mainRate: 0.5, branchRate: 0.15, seconds: 600, isPressurised: false },\n stormwater: { mainRate: 2, branchRate: 0.6, seconds: 240, isPressurised: false },\n}\n\nconst BRANCH_KINDS: ReadonlySet<string> = new Set(['water_service', 'sewer_lateral', 'storm_lateral'])\n\nexport type LeaksOptions = {\n /** The drainage only runs while it rains (`game-weather`: `effects.rain` above zero). */\n readonly isRaining: boolean\n readonly rules?: LeakRules\n}\n\n/**\n * The leaks a breach opens: one for each pipe the bowl severed, of its content, at the break. Water runs under pressure and comes up out of the crater; sewage runs slow; stormwater only runs\n * when it rains. Each is finite (`rate` for `seconds`): `drainLeak` gives what a step lets out until nothing is left. Pure, in the order of the breach.\n */\nexport function leaksOf(networks: Pick<UtilityNetworks, 'nodes' | 'edges'>, breach: Breach, { isRaining, rules = DEFAULT_LEAK_RULES }: LeaksOptions): NetworkLeak[] {\n const pipes = new Map(pipePiecesOf(networks).map((pipe) => [pipe.id, pipe]))\n return breach.pipes.flatMap((reached): NetworkLeak[] => {\n const pipe = pipes.get(reached.id)\n if (!reached.severed || pipe === undefined) return []\n if (reached.content === 'stormwater' && !isRaining) return []\n const rule = rules[reached.content]\n const rate = BRANCH_KINDS.has(pipe.kind) ? rule.branchRate : rule.mainRate\n return [{ id: reached.id, content: reached.content, at: reached.at, diameter: pipe.diameter, rate, volume: rate * rule.seconds, isPressurised: rule.isPressurised }]\n })\n}\n\n/** A leak being let out: what is left of it. */\nexport type LeakState = { readonly leak: NetworkLeak; remaining: number }\n\nexport function startLeak(leak: NetworkLeak): LeakState {\n return { leak, remaining: leak.volume }\n}\n\n/** Litres a step of `dt` seconds lets out of a leak (never more than its rate, never more than is left); takes them from `remaining`. */\nexport function drainLeak(state: LeakState, dt: number): number {\n const out = Math.min(state.leak.rate * Math.max(0, dt), state.remaining)\n state.remaining -= out\n return out\n}\n\n/**\n * The houses that lose their water when the pipes in `after` are broken and the ones in `before` already were: the nodes the reservoir reached then and reaches no more,\n * and the lots among them. Pure, from the graph walked once without the severed edges (a tree loses everything downstream of the break).\n */\nexport function waterOutageOf(networks: Pick<UtilityNetworks, 'nodes' | 'edges'>, { before, after }: { readonly before: readonly string[]; readonly after: readonly string[] }): NetworkOutage | undefined {\n const supplied = (severed: readonly string[]): ReadonlySet<string> => {\n const gone = new Set(severed)\n return connectedNodes(buildNetworkGraph({ nodes: networks.nodes, edges: networks.edges.filter((edge) => !gone.has(edge.id)) }), 'water')\n }\n const [was, is] = [supplied(before), supplied(after)]\n const lost = networks.nodes.filter((node) => node.carries.includes('water') && was.has(node.id) && !is.has(node.id))\n if (lost.length === 0) return undefined\n const lots = [...new Set(lost.flatMap((node) => node.lot ?? []))]\n const already = new Set(before)\n return { network: 'water', causes: after.filter((id) => !already.has(id)), nodes: lost.map((node) => node.id), lots }\n}\n"],"mappings":";AAKO,IAAM,eAA+D;AAAA,EAC1E,SAAS;AAAA,EACT,SAAS;AAA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AChE,QAAM,UAAU,IAAI,IAAI,MAAM;AAC9B,SAAO,EAAE,SAAS,SAAS,QAAQ,MAAM,OAAO,CAAC,OAAO,CAAC,QAAQ,IAAI,EAAE,CAAC,GAAG,OAAO,KAAK,IAAI,CAAC,SAAS,KAAK,EAAE,GAAG,KAAK;AACtH;","names":["distance","inside","length","length","inside","length","length","node","open","distance","distance","id","length","groundAt","length","ofNetwork","inside","at","distance","at","distance","id","length","length","x","z","length","inlet","length","kindOf","inside","groundAt","ofNetwork","UINT32","lampOf","unit","length","planOf","dx","dz","distance","reachOf","length","share","lerp","length"]}