// The village diorama scene: a floating low-poly plateau with the buildings laid out // by the client. The server only says which buildings exist and how much building // space they take; where they stand is decided here, deterministically: // the headquarters in the centre, everything else in id order on a golden-angle // spiral around it, keeping the path to the front free. import type { BuildingType, VillageState } from '~/types/game' import { type Face, hash, mix, ngon, orient, plane, type Poly, prism, project, pyramid, toPolys, type V2, type V3 } from './iso' import { buildingModel, C, crane, rock, scaffold, tree } from './models' /** World units per unit of building space, roughly. */ const U = 24 const GAP = U * 0.3 const PATH_HALF = U * 0.5 const GOLDEN = Math.PI * (3 - Math.sqrt(5)) /** The path runs from the headquarters straight towards the viewer. */ const DIR: V2 = [Math.SQRT1_2, Math.SQRT1_2] export interface SceneBuilding { id: number type: BuildingType level: number upgrading: boolean /** Screen point above the roof, for the level badge. */ label: V2 /** Screen ellipse of its ground footprint. */ ring: { cx: number; cy: number; rx: number; ry: number } /** Only one part of the wall takes keyboard focus. */ focusable: boolean } export interface SceneObject { key: string polys: Poly[] building?: SceneBuilding planned?: boolean } export interface Scene { viewBox: string shadow: { cx: number; cy: number; rx: number; ry: number } terrain: Poly[] decals: Poly[] objects: SceneObject[] } /** A scene object with its painter order (x + y of its ground point). */ type Ordered = SceneObject & { depth: number } interface Slot { key: string x: number y: number r: number } const footRadius = (space: number) => Math.sqrt(Math.max(space, 1)) * U * 0.7 const halfSize = (space: number) => Math.sqrt(Math.max(space, 1)) * U * 0.52 /** Distance from the path (a ray from the centre towards the viewer). */ function pathDistance(x: number, y: number) { const along = x * DIR[0] + y * DIR[1] return along < 0 ? Math.hypot(x, y) : Math.abs(x * DIR[1] - y * DIR[0]) } function layout(items: { key: string; space: number }[], hqRadius: number): Slot[] { const slots: Slot[] = [{ key: 'hq', x: 0, y: 0, r: hqRadius }] for (const item of items) { const r = footRadius(item.space) for (let i = 1; i < 8000; i++) { const d = U * 0.3 * Math.sqrt(i) const x = Math.cos(i * GOLDEN) * d const y = Math.sin(i * GOLDEN) * d if (pathDistance(x, y) < r + PATH_HALF) continue if (slots.some((s) => Math.hypot(x - s.x, y - s.y) < r + s.r + GAP)) continue slots.push({ key: item.key, x, y, r }) break } } return slots } function screenRing(x: number, y: number, r: number) { const [cx, cy] = project([x, y, 0]) return { cx, cy, rx: r * Math.SQRT2, ry: r * Math.SQRT1_2 } } // Terrain function plateau(R: number): { terrain: Poly[]; bottom: number } { const n = 24 const outer = Array.from({ length: n }, (_, i): V3 => { const a = (i / n) * Math.PI * 2 const k = 1 + 0.07 * (hash(i, 1) - 0.5) return [Math.cos(a) * R * k, Math.sin(a) * R * k, 0] }) const m = n / 2 const inner = Array.from({ length: m }, (_, i): V3 => { const a = ((i + 0.5) / m) * Math.PI * 2 const k = 0.5 + 0.12 * hash(i, 2) return [Math.cos(a) * R * k, Math.sin(a) * R * k, 1 + 4 * hash(i, 3)] }) const centre: V3 = [0, 0, 2] const below: V3 = [0, 0, -1000] const grass = (i: number) => mix(mix('#93c25d', '#78aa4b', hash(i, 4)), '#a6c96a', hash(i, 5) * 0.35) const top: Face[] = [] const tri = (pts: V3[], i: number) => top.push({ pts: orient(pts, below), color: grass(i) }) for (let i = 0; i < m; i++) { const a = inner[i]! const b = inner[(i + 1) % m]! tri([centre, a, b], i) const o0 = outer[2 * i]! const o1 = outer[2 * i + 1]! const o2 = outer[(2 * i + 2) % n]! tri([a, o0, o1], 100 + i) tri([a, o1, b], 200 + i) tri([b, o1, o2], 300 + i) } // Earth band under the grass, then a rocky cone tapering to a point. const drop = (i: number) => R * 0.12 + 8 * hash(i, 6) const rim = outer.map(([x, y], i): V3 => [x * 0.93, y * 0.93, -drop(i)]) const apex: V3 = [R * 0.06, -R * 0.04, -R * 0.55] const sides: Face[] = [] const cone: Face[] = [] for (let i = 0; i < n; i++) { const j = (i + 1) % n sides.push({ pts: orient([outer[i]!, outer[j]!, rim[j]!, rim[i]!], [0, 0, -R * 0.06]), color: mix('#9b7650', '#86633f', hash(i, 7)) }) cone.push({ pts: orient([rim[i]!, rim[j]!, apex], [0, 0, -R * 0.3]), color: mix('#857a6f', '#6f655b', hash(i, 8)) }) } return { terrain: [...toPolys(cone), ...toPolys(sides), ...toPolys(top)], bottom: project(apex)[1] } } function path(R: number, hqRadius: number): Poly[] { const steps = 7 const start = hqRadius * 0.5 const end = R * 1.02 const perp: V2 = [-DIR[1], DIR[0]] const left: V3[] = [] const right: V3[] = [] for (let k = 0; k <= steps; k++) { const t = start + ((end - start) * k) / steps const wobble = k === 0 ? 0 : (hash(k, 5) - 0.5) * U * 0.45 const w = PATH_HALF * (0.85 + 0.3 * hash(k, 6)) const cx = DIR[0] * t + perp[0] * wobble const cy = DIR[1] * t + perp[1] * wobble left.push([cx + perp[0] * w, cy + perp[1] * w, 2]) right.push([cx - perp[0] * w, cy - perp[1] * w, 2]) } const plaza = ngon(0, 0, hqRadius * 1.08, 9, 0.2).map(([x, y]): V3 => [x, y, 2]) return toPolys([plane(plaza, '#c9ab76'), plane([...left, ...right.reverse()], '#cdb07a')]) } // The wall rings the plateau; its look follows the level like the buildings. function wallFaces(R: number, level: number): { back: Face[]; front: Face[]; height: number } { const ring = R - U * 0.2 const gate = (PATH_HALF + 6) / ring const steps = Math.max(24, Math.round((Math.PI * 2 * ring) / (U * 0.55))) const h = U * (0.45 + Math.min(level, 20) * 0.035) const back: Face[] = [] const front: Face[] = [] const at = (a: number): V2 => [Math.cos(a) * ring, Math.sin(a) * ring] for (let i = 0; i < steps; i++) { const a0 = (i / steps) * Math.PI * 2 const a1 = ((i + 1) / steps) * Math.PI * 2 const mid = (a0 + a1) / 2 // Leave a gate where the path leaves the village. if (Math.abs(Math.atan2(Math.sin(mid - Math.PI / 4), Math.cos(mid - Math.PI / 4))) < gate) continue const [x, y] = at(mid) const faces: Face[] = level < 5 ? [...prism(ngon(x, y, U * 0.09, 5, i), 0, h, C.wood), ...pyramid(ngon(x, y, U * 0.09, 5, i), h, U * 0.12, C.woodDark)] : (() => { const [x0, y0] = at(a0) const [x1, y1] = at(a1) const nx = Math.cos(mid) * U * 0.09 const ny = Math.sin(mid) * U * 0.09 const base: V2[] = [ [x0 - nx, y0 - ny], [x1 - nx, y1 - ny], [x1 + nx, y1 + ny], [x0 + nx, y0 + ny], ] // Counter-clockwise from above, as prism() expects. const ccw = (base[1]![0] - base[0]![0]) * (base[2]![1] - base[0]![1]) - (base[1]![1] - base[0]![1]) * (base[2]![0] - base[0]![0]) > 0 const color = level < 15 ? C.wood : C.stone const seg = prism(ccw ? base : [...base].reverse(), 0, h, color, level < 15 ? C.plank : C.stoneDark) const tower = level >= 15 && i % 6 === 0 ? [...prism(ngon(x, y, U * 0.22, 6), 0, h * 1.5, C.stone), ...pyramid(ngon(x, y, U * 0.26, 6), h * 1.5, U * 0.35, C.slate)] : [] return [...seg, ...tower] })() ;(x + y < 0 ? back : front).push(...faces) } return { back, front, height: h } } // Decoration: trees and rocks inside the wall, away from buildings and the path. function decor(R: number, slots: Slot[]): Ordered[] { const out: Ordered[] = [] const taken: Slot[] = [] const want = Math.floor((R / U) * 1.6) for (let k = 0; k < 90 && taken.length < want; k++) { const a = k * GOLDEN * 1.7 + 0.3 const d = R * (0.6 + 0.32 * hash(k, 11)) const x = Math.cos(a) * d const y = Math.sin(a) * d const r = U * 0.4 if (Math.hypot(x, y) > R - U * 0.65) continue if (pathDistance(x, y) < PATH_HALF + r) continue if ([...slots, ...taken].some((s) => Math.hypot(x - s.x, y - s.y) < s.r + r + 2)) continue taken.push({ key: `d${k}`, x, y, r }) const size = U * (0.85 + 0.45 * hash(k, 12)) const faces = taken.length % 4 === 0 ? rock(x, y, size * 0.6, k) : tree(x, y, size, k) out.push({ key: `decor-${k}`, polys: toPolys(faces), depth: x + y }) } return out } export function buildScene(village: VillageState): Scene { const hq = village.buildings.find((b) => b.type === 'headquarters') const hqRadius = footRadius(hq?.space ?? 9) const placedBuildings = village.buildings.filter((b) => b.type !== 'headquarters' && b.space > 0) const planned = village.queue.filter((o) => o.action === 'build' && o.space > 0) const slots = layout( [...placedBuildings.map((b) => ({ key: `b${b.id}`, space: b.space })), ...planned.map((o) => ({ key: `o${o.id}`, space: o.space }))], hqRadius, ) const extent = Math.max(...slots.map((s) => Math.hypot(s.x, s.y) + s.r)) const R = Math.max(Math.sqrt((village.space.max * U * U * 2.3) / Math.PI), extent + U * 0.75) const slotOf = (key: string) => slots.find((s) => s.key === key)! const running = new Set(village.queue.filter((o) => o.builder !== null && o.building_id !== null).map((o) => o.building_id)) const objects: Ordered[] = [] let topY = Infinity for (const b of village.buildings) { if (b.type === 'wall') continue const slot = b.type === 'headquarters' ? slots[0]! : slotOf(`b${b.id}`) const s = halfSize(b.space) const model = buildingModel(b.type, b.level, s) const upgrading = running.has(b.id) const faces = upgrading ? [...model.faces, ...crane(s, model.height)] : model.faces const label = project([slot.x, slot.y, model.height + 10]) topY = Math.min(topY, label[1]) objects.push({ key: `b${b.id}`, depth: slot.x + slot.y, polys: toPolys(faces, [slot.x, slot.y, 0]), building: { id: b.id, type: b.type, level: b.level, upgrading, label, ring: screenRing(slot.x, slot.y, slot.r), focusable: true }, }) } for (const o of planned) { const slot = slotOf(`o${o.id}`) const model = scaffold(halfSize(o.space)) objects.push({ key: `o${o.id}`, depth: slot.x + slot.y, polys: toPolys(model.faces, [slot.x, slot.y, 0]), planned: true }) } objects.push(...decor(R, slots)) objects.sort((a, b) => a.depth - b.depth) // The wall wraps everything: its back half is drawn first, its front half last. const wall = village.buildings.find((b) => b.type === 'wall') const wallPlanned = !wall && village.queue.some((o) => o.action === 'build' && o.type === 'wall') const sorted: SceneObject[] = objects if (wall || wallPlanned) { const level = wall?.level ?? 0 const { back, front, height } = wallFaces(R, level) const gateAngle = Math.PI / 4 + 0.45 const label = project([Math.cos(gateAngle) * R, Math.sin(gateAngle) * R, height + 12]) const ring = { cx: 0, cy: 0, rx: 0, ry: 0 } const part = (key: string, faces: Face[], focusable: boolean): SceneObject => wall ? { key, polys: toPolys(faces), building: { id: wall.id, type: 'wall', level, upgrading: running.has(wall.id), label, ring, focusable } } : { key, polys: toPolys(faces), planned: true } sorted.unshift(part('wall-back', back, false)) sorted.push(part('wall-front', front, true)) } const { terrain, bottom } = plateau(R) const halfW = R * 1.08 * Math.SQRT2 + U const minY = Math.min(-R * 1.08 * Math.SQRT1_2, topY) - U * 1.2 const maxY = bottom + U * 2 return { viewBox: `${(-halfW).toFixed(0)} ${minY.toFixed(0)} ${(halfW * 2).toFixed(0)} ${(maxY - minY).toFixed(0)}`, shadow: { cx: 0, cy: bottom + U * 0.6, rx: R * 1.05, ry: R * 0.13 }, terrain, decals: path(R, hqRadius), objects: sorted.map(({ key, polys, building, planned }) => ({ key, polys, building, planned })), } }