Skip to content

A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D

13.2 KB
Raw Blame
import { near, riskIncrements } from "../../rules/risks.ts"
import * as Random from "@typeonce/ritmo/Random"
import { appealAt } from "../../world/appeal.ts"
import { ruinDraft } from "../../world/archetypes.ts"
import { goodIds, risk, upgradeAt, type GoodId } from "../../content/index.ts"
import { doors, nearest, pathTo, reach, useAt } from "../../world/grid.ts"
import { counted, placeName, type Landmark } from "../../world/places.ts"
import type { Point } from "../../world/iso.ts"
import { Appeal, Building, Burning, Charter, Chronicle, Condition, Figure, Fires, Game, Rules, Grid, House, Inventory, Mood, Paused, Rescue, Rising, Risk, Rng, Route, Ruin, Service, Sick, Site, Staff, Storage, Tile, Time, Treasury, Upgraded, WalkerOf } from "../../schema.ts"
import { elapsed, seasonAt, write } from "../shared.ts"

/** The risks are reckoned this often (once a second). */
export const RISK_TICKS = 60

export const Hazards = Game.System(
  "Town/Hazards",
  {
    queries: {
      cared: Game.Query({
        selection: {
          tile: Game.Query.read(Tile),
          risk: Game.Query.write(Risk),
          condition: Game.Query.read(Condition),
          house: Game.Query.optional(House),
          building: Game.Query.optional(Building),
          sick: Game.Query.optional(Sick),
          burning: Game.Query.optional(Burning),
          paused: Game.Query.optional(Paused)
        },
        without: [Site, Rising]
      }),
      sickness: Game.Query({ selection: { sick: Game.Query.write(Sick) } }),
      blazes: Game.Query({ selection: { burning: Game.Query.write(Burning) } }),
      landmarks: Game.Query({ selection: { tile: Game.Query.read(Tile), building: Game.Query.read(Building) }, without: [Site, Rising] }),
      watches: Game.Query({
        selection: { tile: Game.Query.read(Tile), service: Game.Query.read(Service), staff: Game.Query.read(Staff), upgraded: Game.Query.optional(Upgraded) },
        without: [Site, Rising, Burning]
      }),
      crews: Game.Query({ selection: { rescue: Game.Query.read(Rescue), home: Game.Query.readRelation(WalkerOf) } }),
      stores: Game.Query({ selection: { inventory: Game.Query.write(Inventory) }, with: [Storage], without: [Site, Rising] })
    },
    resources: {
      time: Game.System.readResource(Time),
      charter: Game.System.readResource(Charter),
      grid: Game.System.readResource(Grid),
      appeal: Game.System.readResource(Appeal),
      mood: Game.System.readResource(Mood),
      rng: Game.System.writeResource(Rng),
      treasury: Game.System.writeResource(Treasury),
      fires: Game.System.writeResource(Fires),
      chronicle: Game.System.writeResource(Chronicle)
    },
    services: { rules: Game.System.service(Rules) },
    commands: Game.System.commands(
      Game.System.spawns(Ruin, Rescue),
      Game.System.inserts(Burning, Sick),
      Game.System.removes(Sick),
      Game.System.despawns(Tile),
      Game.System.relates(WalkerOf)
    )
  },
  ({ queries, resources, commands, services }) => {
    const rules = services.rules
    const { kinds, goods, risk, winters, riskMax: RISK_MAX, riskTicks: RISK_TICKS } = rules

    const tick = resources.time.get().step
    if (tick % RISK_TICKS !== 0) return
    const charter = resources.charter.get()
    const t = elapsed(resources.time.get(), charter)
    const grid = resources.grid.get()
    const cells = resources.appeal.get().cells
    const approval = resources.mood.get().approval
    const season = seasonAt(t, charter, rules)
    const heating = season.severity !== null && winters[season.severity].heating
    const random = Random.draw(resources.rng)
    const news = (text: string, at: Point | null = null) => write(resources.chronicle, t, text, true, at)
    const landmarks: Array<Landmark> = queries.landmarks.each().map((entity) => ({ kind: queries.landmarks.data.building.get(entity).kind, ...queries.landmarks.data.tile.get(entity) }))
    const where = (cell: Point) => placeName(landmarks, cell)
    const fires = { ...resources.fires.get(), fires: resources.fires.get().fires.map((f) => ({ ...f })) }

    const rows = queries.cared.each()
    const { data: cared } = queries.cared
    const hot = rows.filter((row) => {
      const b = cared.building.get(row)
      return b !== undefined && kinds[b.kind].hot === true && !cared.burning.has(row)
    }).map((row) => cared.tile.get(row))
    const dusty = landmarks.filter((l) => kinds[l.kind].dusty)
    const waterNear = (tile: { readonly x: number; readonly y: number }) => {
      for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) if (useAt(grid, tile.x + dx, tile.y + dy) === "water") return true
      return false
    }
    const sickNow = rows.filter((row) => cared.sick.has(row)).length

    /** Turns a home or building into a ruin. */
    const ruin = (row: (typeof rows)[number], cause: "burnt" | "collapsed" | "derelict") => {
      commands.despawn(row)
      commands.spawn(ruinDraft(cared.tile.get(row), cause))
    }
    const lost = new Set<number>()
    const ignited = new Map<number, number>()

    // Rising risks, and what comes of them.
    for (const row of rows) {
      if (cared.burning.has(row)) continue
      const tile = cared.tile.get(row)
      const h = cared.house.get(row)
      // A closed home has nobody in it to fall sick, steal, or knock over a lamp.
      if (h && cared.paused.has(row)) continue
      const b = cared.building.get(row)
      const r = { ...cared.risk.get(row) }
      const increments = riskIncrements({
        tile, condition: cared.condition.get(row).value, desirability: appealAt(cells, tile.x, tile.y), approval, heating,
        hotNearby: hot.filter((source) => near(source, tile, risk.fire.reach)).length,
        dusty: dusty.some((d) => near(d, tile, risk.health.reach)), water: waterNear(tile),
        ...(h ? { house: h } : {}), ...(b ? { kind: b.kind } : {})
      }, rules)
      if (h) {
        if (!cared.sick.has(row)) r.health = Math.min(RISK_MAX, r.health + increments.health)
        r.order = Math.min(RISK_MAX, r.order + increments.order)
      }
      r.fire = Math.min(RISK_MAX, r.fire + increments.fire)

      if (r.fire >= RISK_MAX) {
        // Fire!
        const id = fires.next
        fires.next += 1
        fires.fires.push({ id, x: tile.x, y: tile.y, homes: 0, buildings: 0 })
        commands.insert(row, [Burning, { left: risk.fire.burns, fire: id }])
        ignited.set(row.id, id)
        r.fire = 0
        news(`Fire on ${where(tile)}!`, tile)
      }
      if (h && r.health >= RISK_MAX && !cared.sick.has(row)) {
        commands.insert(row, [Sick, { left: risk.health.lasts }])
        r.health = 0
        if (sickNow === 0) news(`Sickness on ${where(tile)}: a physician can cure it.`, tile)
      }
      if (h && r.order >= RISK_MAX) {
        if (r.thefts === 0) {
          // A theft: coins from the treasury, or goods from storage when it is empty.
          const coins = resources.treasury.get().coins
          const take = Math.min(risk.order.most, Math.max(0, coins), risk.order.coins + Math.floor(Math.max(0, coins) * risk.order.share))
          if (take > 0) {
            resources.treasury.set({ coins: coins - take })
            news(`Thieves on ${where(tile)} made off with ${take} coins.`, tile)
          } else {
            const stores = queries.stores.each()
            const { data: store } = queries.stores
            const held = (g: GoodId) => stores.reduce((n, s) => n + store.inventory.get(s).stock[g], 0)
            const good = [...goodIds].sort((a, b) => held(b) * goods[b].price - held(a) * goods[a].price)[0]!
            let owed = Math.min(risk.order.goods, held(good))
            for (const s of stores) {
              if (owed <= 0) break
              const inv = store.inventory.get(s)
              const n = Math.min(owed, inv.stock[good])
              store.inventory.set(s, { ...inv, stock: { ...inv.stock, [good]: inv.stock[good] - n } })
              owed -= n
            }
            if (held(good) > 0) news(`Thieves on ${where(tile)} made off with ${goods[good].title}.`, tile)
          }
          r.thefts += 1
          r.order = risk.order.after
        } else {
          news(`A home on ${where(tile)} stood empty after its thefts, and is left derelict.`, tile)
          ruin(row, "derelict")
          lost.add(row.id)
          continue
        }
      }
      cared.risk.set(row, r)
    }

    // Sickness runs its course, and spreads to homes close by.
    const homeRows = rows.filter((row) => cared.house.has(row) && !cared.burning.has(row) && !lost.has(row.id))
    const { data: sickness } = queries.sickness
    for (const entity of queries.sickness.each()) {
      const s = sickness.sick.get(entity)
      const left = s.left - RISK_TICKS
      if (left <= 0) {
        commands.remove(entity, Sick)
        continue
      }
      sickness.sick.set(entity, { left })
      if (random.next() >= risk.health.spreads) continue
      const me = rows.find((row) => row.id === entity.id)
      if (!me) continue
      const at = cared.tile.get(me)
      const target = random.pick(homeRows.filter((e) => e.id !== entity.id && !cared.sick.has(e) && near(cared.tile.get(e), at, 2)))
      if (target) {
        const r = cared.risk.get(target)
        cared.risk.set(target, { ...r, health: Math.min(RISK_MAX, r.health + risk.health.contagion) })
      }
    }

    // Fires burn down what they hold, and catch what stands beside them.
    const byId = new Map(rows.map((row) => [row.id as number, row]))
    const { data: blazes } = queries.blazes
    for (const entity of queries.blazes.each()) {
      const b = blazes.burning.get(entity)
      const row = byId.get(entity.id)
      if (!row) continue
      const fire = fires.fires.find((f) => f.id === b.fire)
      const left = b.left - RISK_TICKS
      if (left <= 0) {
        ruin(row, "burnt")
        lost.add(entity.id)
        if (fire) {
          if (cared.house.has(row)) fire.homes += 1
          else fire.buildings += 1
        }
        continue
      }
      blazes.burning.set(entity, { ...b, left })
      const tile = cared.tile.get(row)
      const neighbour = random.pick(rows.filter((e) => e.id !== entity.id && !cared.burning.has(e) && !ignited.has(e.id) && !lost.has(e.id) && near(cared.tile.get(e), tile, 1)))
      if (!neighbour) continue
      const chance = risk.fire.catches + (risk.fire.spread * cared.risk.get(neighbour).fire) / RISK_MAX
      if (random.next() < chance) {
        commands.insert(neighbour, [Burning, { left: risk.fire.burns, fire: b.fire }])
        ignited.set(neighbour.id, b.fire)
      }
    }

    // Firefighters run from the nearest fire watch to every blaze no one is running to.
    const out = new Map<number, number>()
    const crewed = new Set<number>()
    const { data: crews } = queries.crews
    for (const entity of queries.crews.each()) {
      out.set(crews.home.get(entity), (out.get(crews.home.get(entity)) ?? 0) + 1)
      if (!crews.rescue.get(entity).back) crewed.add(crews.rescue.get(entity).target)
    }
    const { data: watch } = queries.watches
    const watches = queries.watches.each().filter((entity) => watch.service.get(entity).service === "fire" && watch.staff.get(entity).assigned > 0)
    const burningNow = [...queries.blazes.each().map((entity) => entity.id as number), ...ignited.keys()].filter((id) => !lost.has(id))
    for (const id of burningNow) {
      if (crewed.has(id)) continue
      const target = byId.get(id)
      if (!target) continue
      const goal = doors(grid, cared.tile.get(target))
      let best: { readonly watch: (typeof watches)[number]; readonly roads: ReturnType<typeof reach>; readonly cell: Point; readonly distance: number } | null = null
      for (const station of watches) {
        // A fire brigade sends more (see `Upgrade.crews`).
        const sends = upgradeAt(kinds.firewatch, watch.upgraded.get(station)?.level ?? 0)?.crews ?? risk.fire.crews
        if ((out.get(station.id) ?? 0) >= sends) continue
        const starts = doors(grid, watch.tile.get(station))
        if (starts.length === 0) continue
        const roads = reach(grid, starts)
        const found = nearest(roads, goal)
        if (found && (best === null || found.distance < best.distance)) best = { watch: station, roads, ...found }
      }
      if (!best) continue
      const draft = Game.Command.spawn(
        [Figure, { role: "walker", color: 0xc4523f }],
        [Route, { cells: pathTo(best.roads, best.cell), index: 0, step: 0 }],
        [Rescue, { target: Game.Entity.handle(target.id, Tile), back: false }]
      )
      commands.spawn(Game.Command.relate(draft, WalkerOf, best.watch.id))
      out.set(best.watch.id, (out.get(best.watch.id) ?? 0) + 1)
    }

    // A fire with nothing left burning is over: the news says what it took.
    const stillBurning = new Set<number>()
    for (const entity of queries.blazes.each()) if (!lost.has(entity.id)) stillBurning.add(blazes.burning.get(entity).fire)
    for (const f of ignited.values()) stillBurning.add(f)
    const over = fires.fires.filter((f) => !stillBurning.has(f.id))
    for (const f of over) {
      const took = [f.homes > 0 ? counted(f.homes, "home") : "", f.buildings > 0 ? counted(f.buildings, "building") : ""].filter((s) => s !== "")
      news(`Fire on ${where(f)}: ${took.length > 0 ? `${took.join(" and ")} lost` : "put out"}.`, { x: f.x, y: f.y })
    }
    resources.fires.set({ fires: fires.fires.filter((f) => stillBurning.has(f.id)), next: fires.next })
  }
)