diff --git a/app/components/village/Diorama.vue b/app/components/village/Diorama.vue index 1936536..5b0186c 100644 --- a/app/components/village/Diorama.vue +++ b/app/components/village/Diorama.vue @@ -7,157 +7,131 @@ const props = defineProps<{ village: VillageState }>() const selected = defineModel('selected', { default: null }) const { t } = useI18n() -const scene = computed(() => buildScene(props.village)) +// The scene is cut to the stage's shape, so the land always fills it edge to edge. +// On narrow screens the stage keeps a minimum width and scrolls sideways instead. +const scroller = ref(null) +const stage = ref(null) +const size = ref({ w: 1200, h: 520 }) +const aspect = computed(() => Math.round((size.value.w / Math.max(1, size.value.h)) * 10) / 10) +const scene = computed(() => buildScene(props.village, aspect.value)) const hovered = ref(null) -const uid = useId() + +function measure() { + const el = stage.value + if (el && el.clientWidth && el.clientHeight) size.value = { w: el.clientWidth, h: el.clientHeight } +} +let observer: ResizeObserver | undefined +onMounted(() => { + measure() + observer = new ResizeObserver(measure) + if (stage.value) observer.observe(stage.value) + // Start a scrolled phone view on the village centre. + const sc = scroller.value + if (sc) sc.scrollLeft = (sc.scrollWidth - sc.clientWidth) / 2 +}) +onBeforeUnmount(() => observer?.disconnect()) const name = (b: SceneBuilding) => t(`buildings.${b.type}`) const label = (b: SceneBuilding) => t('village.diorama.label', { name: name(b), level: b.level }) -const badges = computed(() => scene.value.objects.flatMap((o) => (o.building?.focusable ? [o.building] : []))) const isActive = (id: number) => selected.value === id || hovered.value === id function toggle(id: number) { selected.value = selected.value === id ? null : id } -// Badges keep the same size on screen however the scene is scaled. -const svg = ref(null) -const unitsPerPx = ref(1) -function measure() { - const el = svg.value - if (!el) return - const [, , w, h] = scene.value.viewBox.split(' ').map(Number) as [number, number, number, number] - const scale = Math.min(el.clientWidth / w, el.clientHeight / h) - // Smaller badges on phones, where the whole village is only a few hundred pixels wide. - if (scale > 0) unitsPerPx.value = (el.clientWidth < 640 ? 0.75 : 1) / scale -} -let observer: ResizeObserver | undefined -onMounted(() => { - measure() - observer = new ResizeObserver(measure) - if (svg.value) observer.observe(svg.value) -}) -onBeforeUnmount(() => observer?.disconnect()) -watch(() => scene.value.viewBox, () => nextTick(measure)) - -const k = computed(() => unitsPerPx.value) +/** viewBox units per screen pixel: badges keep the same size however the scene is scaled. */ +const k = computed(() => (scene.value.width / Math.max(1, size.value.w)) * (size.value.w < 900 ? 0.85 : 1)) const pillWidth = (b: SceneBuilding) => (name(b).length * 6.6 + 18) * k.value + +// Badges that would overlap move up above the one in front, nearest buildings first. +const badges = computed(() => { + const list = scene.value.objects.flatMap((o) => (o.building?.focusable ? [o.building] : [])) + const r = 11 * k.value + const placed: { b: SceneBuilding; x: number; y: number }[] = [] + for (const b of [...list].sort((p, q) => q.label[1] - p.label[1])) { + const [x] = b.label + let y = b.label[1] + for (let n = 0; n < 6 && placed.some((p) => Math.abs(p.x - x) < r * 2.1 && Math.abs(p.y - y) < r * 2.1); n++) y -= r * 2.2 + placed.push({ b, x, y }) + } + return placed +}) - - - - - - {{ name(b) }} + + + + + + + + {{ name(b) }} + + + {{ b.level }} - - {{ b.level }} - - + + @@ -175,21 +149,21 @@ const pillWidth = (b: SceneBuilding) => (name(b).length * 6.6 + 18) * k.value stroke: transparent; } .bld.is-active .ring { - fill: rgb(251 191 36 / 0.22); - stroke: #d97706; + fill: #c4a676; + stroke: #9c7a1f; stroke-width: 1.2; } .bld.is-selected .ring { - fill: rgb(251 191 36 / 0.32); - stroke: #b45309; + fill: #d9b44a; + stroke: #7b1e16; stroke-width: 2; } .bld.is-selected polygon { - stroke: #b45309; + stroke: #7b1e16; stroke-width: 1; } .bld:focus-visible .ring { - stroke: #b45309; + stroke: #7b1e16; stroke-width: 2; stroke-dasharray: 4 3; } diff --git a/app/diorama/scene.ts b/app/diorama/scene.ts index b64ea88..00d12ec 100644 --- a/app/diorama/scene.ts +++ b/app/diorama/scene.ts @@ -1,20 +1,46 @@ -// 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. +// The village diorama: a stretch of land seen from a raised camera, in the layout of a +// classic village overview. The village core sits in the middle: the headquarters on a +// dirt plaza, with storage, hiding places and the rally point around it, inside the wall +// when there is one. Resource sites stand outside in their own zones of the surrounding +// land: iron mines below a rocky hill (top left), clay pits on clay ground (bottom left), +// timber camps at the forest edge (bottom right) and farms with their fields (right). +// Dirt paths run from the plaza through the gates to every zone; forest fills the rest. +// +// The server only says which buildings exist; where they stand is decided here, +// deterministically and in id order, so buildings stay put when new ones are added. 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' +import { type Face, hash, ngon, plane, type Poly, prism, project, pyramid, toPolys, type V2, type V3 } from './iso' +import { broadleaf, buildingModel, bush, C, conifer, crane, rock, scaffold, well } 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] +const deg = (d: number) => (d * Math.PI) / 180 +const dir = (a: number): V2 => [Math.cos(a), Math.sin(a)] + +// World angles seen on screen: 0° lower right, 90° lower left, 180° upper left, +// 270° upper right. 45° points at the viewer: the main gate and road. +const FRONT = deg(45) +const PATH_HALF = U * 0.5 +const ZONE_PATH_HALF = U * 0.38 + +type Zone = 'iron' | 'clay' | 'timber' | 'farm' +const ZONE_OF: Partial> = { iron_mine: 'iron', clay_pit: 'clay', timber_camp: 'timber', farm: 'farm' } +/** Centre angle, half the angle it spans, model scale, and slot spacing in model sizes. */ +const ZONES: Record = { + iron: { angle: deg(196), half: deg(26), scale: 1.15, gap: 2.5, ground: '#7c776a' }, + clay: { angle: deg(102), half: deg(24), scale: 1.1, gap: 2.4, ground: '#8d5a3b' }, + timber: { angle: deg(8), half: deg(22), scale: 1.1, gap: 2.4, ground: '#76703f' }, + farm: { angle: deg(-62), half: deg(27), scale: 1.3, gap: 2.6, ground: null }, +} +const ZONE_NAMES = Object.keys(ZONES) as Zone[] + +const GRASS = ['#7a8b48', '#778848', '#7d8d4a', '#748546'] +const DIRT = '#9c8157' +const PLAZA = '#a3885c' +const VILLAGE_GROUND = '#868d4d' +const WALL_EARTH = '#8c7350' export interface SceneBuilding { id: number @@ -38,7 +64,9 @@ export interface SceneObject { export interface Scene { viewBox: string - shadow: { cx: number; cy: number; rx: number; ry: number } + /** viewBox size, for keeping badges a fixed size on screen. */ + width: number + height: number terrain: Poly[] decals: Poly[] objects: SceneObject[] @@ -51,33 +79,20 @@ interface Slot { key: string x: number y: number + /** Clearance radius on the ground. */ r: number + /** Model half-size. */ + s: 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 +/** Distance from a ray that starts at the centre and runs along angle `a`. */ +function rayDistance(x: number, y: number, a: number) { + const [dx, dy] = dir(a) + const along = x * dx + y * dy + return along < 0 ? Math.hypot(x, y) : Math.abs(x * dy - y * dx) } function screenRing(x: number, y: number, r: number) { @@ -85,167 +100,245 @@ function screenRing(x: number, y: number, r: number) { return { cx, cy, rx: r * Math.SQRT2, ry: r * Math.SQRT1_2 } } -// Terrain +// Layout -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) +/** Inside the village: a golden-angle spiral around the headquarters, keeping the roads free. */ +function layoutCore(items: { key: string; space: number }[], hqRadius: number, roads: number[]): Slot[] { + const slots: Slot[] = [{ key: 'hq', x: 0, y: 0, r: hqRadius, s: 0 }] + 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 (roads.some((a) => rayDistance(x, y, a) < r + PATH_HALF)) continue + if (slots.some((s) => Math.hypot(x - s.x, y - s.y) < r + s.r + U * 0.3)) continue + slots.push({ key: item.key, x, y, r, s: halfSize(item.space) }) + break + } } - - // 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] } + return slots } -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]] +/** + * A zone outside the wall: rows of slots along an arc, nearest row first, filled from + * the zone's road outwards on both sides. `count` slots, however many buildings exist, + * so an empty zone still shows its ground. + */ +function layoutZone(zone: Zone, space: number, count: number, Rv: number): Slot[] { + const z = ZONES[zone] + const s = halfSize(space) * z.scale + const slots: Slot[] = [] + for (let row = 0; slots.length < count && row < 20; row++) { + const r = Rv + U * 1.7 + s * 1.3 + row * s * z.gap + const step = (s * z.gap) / r + for (let k = 0; slots.length < count; k++) { + const offset = (k % 2 ? -1 : 1) * (Math.floor(k / 2) + 0.5) + if (Math.abs(offset) * step > z.half) break + const [x, y] = dir(z.angle + offset * step) + slots.push({ key: `${zone}-${slots.length}`, x: x * r, y: y * r, r: s * 1.15, s }) + } + } + return slots +} + +// Ground + +function inverse([X, Y]: V2): V2 { + return [Y + X / 2, Y - X / 2] +} + +/** A low-poly ground mesh that covers the view; vertices hash from their grid index, so it never shifts. */ +function ground(view: { x: number; y: number; w: number; h: number }): Poly[] { + const g = U * 2.6 + const corners = [ + inverse([view.x, view.y]), + inverse([view.x + view.w, view.y]), + inverse([view.x, view.y + view.h]), + inverse([view.x + view.w, view.y + view.h]), + ] + const i0 = Math.floor(Math.min(...corners.map((c) => c[0])) / g) - 1 + const i1 = Math.ceil(Math.max(...corners.map((c) => c[0])) / g) + 1 + const j0 = Math.floor(Math.min(...corners.map((c) => c[1])) / g) - 1 + const j1 = Math.ceil(Math.max(...corners.map((c) => c[1])) / g) + 1 + const vertex = (i: number, j: number): V3 => [ + (i + (hash(i, j, 1) - 0.5) * 0.6) * g, + (j + (hash(i, j, 2) - 0.5) * 0.6) * g, + (hash(i, j, 3) - 0.5) * 4, + ] + const faces: Face[] = [] + for (let i = i0; i < i1; i++) { + for (let j = j0; j < j1; j++) { + const a = vertex(i, j) + const b = vertex(i + 1, j) + const c = vertex(i + 1, j + 1) + const d = vertex(i, j + 1) + const xs = [a, b, c, d].map((p) => project(p)) + const minX = Math.min(...xs.map((p) => p[0])) + const maxX = Math.max(...xs.map((p) => p[0])) + const minY = Math.min(...xs.map((p) => p[1])) + const maxY = Math.max(...xs.map((p) => p[1])) + if (maxX < view.x || minX > view.x + view.w || maxY < view.y || minY > view.y + view.h) continue + const tone = (k: number) => GRASS[Math.floor(hash(i, j, k) * GRASS.length)]! + faces.push({ pts: [a, b, c], color: tone(4), twoSided: true }, { pts: [a, c, d], color: tone(5), twoSided: true }) + } + } + return toPolys(faces).map((p) => ({ ...p, stroke: p.fill })) +} + +function disc(cx: number, cy: number, r: number, n: number, seed: number, z = 0.6): V3[] { + return ngon(cx, cy, r, n, hash(seed, 1) * 6).map(([x, y], i): V3 => { + const k = 0.82 + 0.3 * hash(seed, i) + return [cx + (x - cx) * k, cy + (y - cy) * k, z] + }) +} + +/** A dirt road from radius r0 to r1 along angle `a`, gently winding. */ +function road(a: number, r0: number, r1: number, half: number, seed: number): Face { + const [dx, dy] = dir(a) + const px = -dy + const py = dx + const steps = Math.max(2, Math.ceil((r1 - r0) / (U * 1.4))) 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 t = r0 + ((r1 - r0) * k) / steps + const wobble = k === 0 ? 0 : (hash(seed, k, 5) - 0.5) * U * 0.4 + const w = half * (0.85 + 0.3 * hash(seed, k, 6)) + const cx = dx * t + px * wobble + const cy = dy * t + py * wobble + left.push([cx + px * w, cy + py * w, 1.2]) + right.push([cx - px * w, cy - py * w, 1.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')]) + return plane([...left, ...right.reverse()], DIRT) } -// The wall rings the plateau; its look follows the level like the buildings. +/** A band around the village: worn earth under the wall, or the village's edge without one. */ +function ringBand(r: number, width: number, color: string): Face[] { + const n = 56 + const faces: Face[] = [] + for (let i = 0; i < n; i++) { + const a0 = (i / n) * Math.PI * 2 + const a1 = ((i + 1) / n) * Math.PI * 2 + const r0 = r - width / 2 + const r1 = r + width / 2 + faces.push( + plane( + [ + [Math.cos(a0) * r0, Math.sin(a0) * r0, 1], + [Math.cos(a1) * r0, Math.sin(a1) * r0, 1], + [Math.cos(a1) * r1, Math.sin(a1) * r1, 1], + [Math.cos(a0) * r1, Math.sin(a0) * r1, 1], + ], + color, + ), + ) + } + return faces +} -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] +// The wall rings the village; its look follows the level like the buildings, and each +// segment is its own object so it sorts correctly against buildings inside and out. + +function wallSegments(Rv: number, level: number, gates: number[]): { faces: Face[]; depth: number }[] { + const steps = Math.max(28, Math.round((Math.PI * 2 * Rv) / (U * 0.55))) + const gateHalf = (PATH_HALF + U * 0.3) / Rv + const h = U * (0.5 + Math.min(level, 20) * 0.035) + const at = (a: number): V2 => [Math.cos(a) * Rv, Math.sin(a) * Rv] + const inGate = (a: number) => gates.some((g) => Math.abs(Math.atan2(Math.sin(a - g), Math.cos(a - g))) < gateHalf) + const out: { faces: Face[]; depth: number }[] = [] 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 + if (inGate(mid)) continue + const nextToGate = inGate(mid + (Math.PI * 2) / steps) || inGate(mid - (Math.PI * 2) / steps) 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 }) + let faces: Face[] + if (level < 5) { + // Palisade of sharpened stakes. + const p = ngon(x, y, U * 0.09, 5, i) + faces = [...prism(p, 0, h, C.wood), ...pyramid(p, h, U * 0.12, C.woodDark)] + } else { + const [x0, y0] = at(a0) + const [x1, y1] = at(a1) + const nx = Math.cos(mid) * U * 0.1 + const ny = Math.sin(mid) * U * 0.1 + 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 stone = level >= 15 + faces = prism(ccw ? base : [...base].reverse(), 0, h, stone ? C.stone : C.wood, stone ? C.stoneDark : C.plank) + if (stone && (i % 7 === 0 || nextToGate)) { + faces.push(...prism(ngon(x, y, U * 0.24, 6), 0, h * 1.55, C.stone, C.stoneDark), ...pyramid(ngon(x, y, U * 0.28, 6), h * 1.55, U * 0.38, C.slate)) + } else if (!stone && nextToGate) { + faces.push(...prism(ngon(x, y, U * 0.16, 4, Math.PI / 4), 0, h * 1.4, C.woodDark), ...pyramid(ngon(x, y, U * 0.22, 4, Math.PI / 4), h * 1.4, U * 0.25, C.roofRed)) + } + } + out.push({ faces, depth: x + y }) } return out } -export function buildScene(village: VillageState): Scene { +export function buildScene(village: VillageState, aspect = 2.2): Scene { + const isZone = (type: BuildingType) => ZONE_OF[type] !== undefined 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)! + // Zone members in id order: existing buildings first, then queued new ones. + const members: Record = { iron: [], clay: [], timber: [], farm: [] } + for (const b of [...village.buildings].sort((p, q) => p.id - q.id)) { + const zone = ZONE_OF[b.type] + if (zone) members[zone].push({ key: `b${b.id}`, space: b.space }) + } + for (const o of [...planned].sort((p, q) => p.id - q.id)) { + const zone = ZONE_OF[o.type] + if (zone) members[zone].push({ key: `o${o.id}`, space: o.space }) + } + const activeZones = ZONE_NAMES.filter((z) => members[z].length) + const roads = [FRONT, ...activeZones.map((z) => ZONES[z].angle)] + + const coreItems = [ + { key: 'well', space: 1.4 }, + ...village.buildings.filter((b) => b.type !== 'headquarters' && b.type !== 'wall' && b.space > 0 && !isZone(b.type)).map((b) => ({ key: `b${b.id}`, space: b.space })), + ...planned.filter((o) => !isZone(o.type)).map((o) => ({ key: `o${o.id}`, space: o.space })), + ] + const core = layoutCore(coreItems, hqRadius, roads) + const Rv = Math.max(U * 5.2, ...core.map((s) => Math.hypot(s.x, s.y) + s.r + U * 0.9)) + + const zoneSlots: Record = { iron: [], clay: [], timber: [], farm: [] } + for (const zone of ZONE_NAMES) { + const space = members[zone][0]?.space ?? 4 + // Show at least two plots of each zone's ground, built on or not. + const slots = layoutZone(zone, space, Math.max(members[zone].length, 2), Rv) + members[zone].forEach((m, i) => (slots[i]!.key = m.key)) + zoneSlots[zone] = slots + } + const allSlots = [...core, ...ZONE_NAMES.flatMap((z) => zoneSlots[z].slice(0, members[z].length))] + const slotOf = (key: string) => allSlots.find((s) => s.key === key)! + const zoneEnd = (zone: Zone) => Math.max(Rv + U * 3, ...zoneSlots[zone].map((s) => Math.hypot(s.x, s.y) + s.r)) + 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 + const labelTops: number[] = [] + // Buildings and queued new ones. 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 slot = b.type === 'headquarters' ? core[0]! : slotOf(`b${b.id}`) + const zone = ZONE_OF[b.type] + const s = zone ? slot.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]) + labelTops.push(label[1]) objects.push({ key: `b${b.id}`, depth: slot.x + slot.y, @@ -255,39 +348,156 @@ export function buildScene(village: VillageState): Scene { } for (const o of planned) { const slot = slotOf(`o${o.id}`) - const model = scaffold(halfSize(o.space)) + const model = scaffold(ZONE_OF[o.type] ? slot.s : 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) + const wellSlot = slotOf('well') + objects.push({ key: 'well', depth: wellSlot.x + wellSlot.y, polys: toPolys(well(U * 0.55).faces, [wellSlot.x, wellSlot.y, 0]) }) - // The wall wraps everything: its back half is drawn first, its front half last. + // The wall: every segment sorts on its own. 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 + let wallTop = 0 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 segments = wallSegments(Rv, level, roads) + wallTop = U * (0.5 + Math.min(level, 20) * 0.035) * 1.55 + U * 0.4 + const gateSide = FRONT + deg(24) + const label = project([Math.cos(gateSide) * Rv, Math.sin(gateSide) * Rv, wallTop + 10]) + labelTops.push(label[1]) 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)) + // The segment nearest the badge takes keyboard focus for the whole wall. + const focusIndex = segments.reduce((best, seg, i) => (seg.depth > segments[best]!.depth ? i : best), 0) + segments.forEach((seg, i) => { + objects.push({ + key: `wall-${i}`, + depth: seg.depth, + polys: toPolys(seg.faces), + ...(wall + ? { building: { id: wall.id, type: 'wall' as const, level, upgrading: running.has(wall.id), label, ring, focusable: i === focusIndex } } + : { planned: 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 + // The frame: the village and every zone, with room for labels; then widened or + // heightened to the container's shape, where more land and forest show. + const Rz = Math.max(Rv + U * 4.5, ...ZONE_NAMES.map(zoneEnd)) + const pts: V2[] = [] + for (let i = 0; i < 24; i++) { + const [x, y] = dir((i / 24) * Math.PI * 2) + pts.push(project([x * (Rv + U * 2.5), y * (Rv + U * 2.5), 0])) + } + for (const s of allSlots) pts.push(project([s.x - s.r, s.y + s.r, 0]), project([s.x + s.r, s.y - s.r, 0]), project([s.x + s.r, s.y + s.r, 0])) + let minX = Math.min(...pts.map((p) => p[0])) + let maxX = Math.max(...pts.map((p) => p[0])) + let minY = Math.min(...pts.map((p) => p[1]), ...labelTops) - U * 1.2 + let maxY = Math.max(...pts.map((p) => p[1])) + U * 0.8 + const padX = (maxX - minX) * 0.04 + minX -= padX + maxX += padX + let w = maxX - minX + let h = maxY - minY + if (w / h < aspect) { + const extra = h * aspect - w + minX -= extra / 2 + w += extra + } else { + const extra = w / aspect - h + minY -= extra * 0.45 + h += extra + } + maxX = minX + w + maxY = minY + h + const view = { x: minX, y: minY, w, h } + + // Decals on the ground, back to front by layer. + const decalFaces: Face[] = [plane(disc(0, 0, Rv + U * 0.25, 40, 7, 0.5), VILLAGE_GROUND)] + for (const zone of ZONE_NAMES) { + const color = ZONES[zone].ground + if (!color) continue + zoneSlots[zone].forEach((s, i) => decalFaces.push(plane(disc(s.x, s.y, s.r * 1.3, 9, 30 + i * 7 + zone.length, 0.8), color))) + } + decalFaces.push(road(FRONT, hqRadius * 0.9, Rz * 3, PATH_HALF, 1)) + for (const zone of activeZones) decalFaces.push(road(ZONES[zone].angle, hqRadius * 0.9, zoneEnd(zone) + U * 0.5, ZONE_PATH_HALF, ZONE_NAMES.indexOf(zone) + 2)) + decalFaces.push(...ringBand(Rv, U * (wall || wallPlanned ? 0.55 : 0.4), wall || wallPlanned ? WALL_EARTH : DIRT)) + decalFaces.push(plane(disc(0, 0, hqRadius * 1.3, 11, 3, 1.6), PLAZA)) + + // Landscape: a rocky hill behind the iron zone, then forest everywhere else. + const taken: { x: number; y: number; r: number }[] = allSlots.map((s) => ({ x: s.x, y: s.y, r: s.r + U * 0.45 })) + const iron = ZONES.iron + const hillFrom = zoneEnd('iron') + for (let k = 0; k < 11; k++) { + const a = iron.angle + (hash(k, 41) - 0.5) * 2 * (iron.half + deg(8)) + const r = hillFrom + U * (0.6 + 3 * hash(k, 42)) + const [x, y] = [Math.cos(a) * r, Math.sin(a) * r] + const size = U * (1.5 + 1.4 * hash(k, 43)) + taken.push({ x, y, r: size * 0.45 }) + objects.push({ key: `hill-${k}`, depth: x + y, polys: toPolys(rock(x, y, size, 100 + k, hash(k, 44) > 0.5 ? C.stoneDark : C.rock)) }) + } + + const roadClear = (x: number, y: number) => + rayDistance(x, y, FRONT) < PATH_HALF + U * 0.5 || + activeZones.some((z) => { + const [dx, dy] = dir(ZONES[z].angle) + return x * dx + y * dy < zoneEnd(z) + U && rayDistance(x, y, ZONES[z].angle) < ZONE_PATH_HALF + U * 0.45 + }) + const inSector = (x: number, y: number, zone: Zone, pad: number) => { + const a = Math.atan2(y, x) + return Math.abs(Math.atan2(Math.sin(a - ZONES[zone].angle), Math.cos(a - ZONES[zone].angle))) < ZONES[zone].half + pad + } + + const f = U * 1.25 + const cornersW = [inverse([view.x, view.y]), inverse([view.x + w, view.y]), inverse([view.x, view.y + h]), inverse([view.x + w, view.y + h])] + const fi0 = Math.floor(Math.min(...cornersW.map((c) => c[0])) / f) + const fi1 = Math.ceil(Math.max(...cornersW.map((c) => c[0])) / f) + const fj0 = Math.floor(Math.min(...cornersW.map((c) => c[1])) / f) + const fj1 = Math.ceil(Math.max(...cornersW.map((c) => c[1])) / f) + const cx = view.x + w / 2 + for (let i = fi0; i <= fi1; i++) { + for (let j = fj0; j <= fj1; j++) { + const x = (i + hash(i, j, 61) * 0.8) * f + const y = (j + hash(i, j, 62) * 0.8) * f + const [X, Y] = project([x, y, 0]) + if (X < view.x - U || X > view.x + w + U || Y < view.y || Y > view.y + h + U * 2) continue + const r = Math.hypot(x, y) + if (r < Rv + U * 1.5) continue + if (roadClear(x, y)) continue + if (taken.some((t) => Math.hypot(x - t.x, y - t.y) < t.r + U * 0.35)) continue + // Open meadow round the village, forest thickening towards the sides and the back. + const edge = Math.abs(X - cx) / (w / 2) + const far = Math.min(1, Math.max(0, (r - Rz * 0.75) / (Rz * 0.5))) + let density = 0.05 + 0.25 * far + 0.75 * Math.max(0, edge - 0.55) / 0.45 + (Y < view.y + h * 0.15 ? 0.15 : 0) + if (inSector(x, y, 'timber', deg(22)) && r > zoneEnd('timber') - U && r < zoneEnd('timber') + U * 4) density += 0.4 + if (inSector(x, y, 'farm', deg(6)) && r < zoneEnd('farm') + U * 1.5) density *= 0.15 + if (inSector(x, y, 'iron', deg(10))) density *= 0.45 + if (inSector(x, y, 'clay', deg(4)) && r < zoneEnd('clay') + U) density *= 0.4 + if (hash(i, j, 63) > Math.min(density, 0.88)) continue + const kind = hash(i, j, 64) + const size = U * (1.0 + 0.55 * hash(i, j, 65)) + const seed = i * 131 + j + const faces = kind < 0.1 ? bush(x, y, size * 0.8, seed) : kind < 0.62 ? conifer(x, y, size, seed) : broadleaf(x, y, size, seed) + taken.push({ x, y, r: size * 0.3 }) + objects.push({ key: `t${i}:${j}`, depth: x + y, polys: toPolys(faces) }) + } + } + // A few stones in the meadows. + for (let k = 0; k < 14; k++) { + const a = hash(k, 71) * Math.PI * 2 + const r = Rv + U * (1.4 + 6 * hash(k, 72)) + const [x, y] = [Math.cos(a) * r, Math.sin(a) * r] + if (roadClear(x, y) || taken.some((t) => Math.hypot(x - t.x, y - t.y) < t.r + U * 0.3)) continue + objects.push({ key: `stone-${k}`, depth: x + y, polys: toPolys(rock(x, y, U * (0.45 + 0.4 * hash(k, 73)), 200 + k)) }) + } + + objects.sort((a, b) => a.depth - b.depth) 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 })), + viewBox: `${view.x.toFixed(1)} ${view.y.toFixed(1)} ${w.toFixed(1)} ${h.toFixed(1)}`, + width: w, + height: h, + terrain: ground(view), + // One at a time, so the layers keep the order they were added in. + decals: decalFaces.flatMap((face) => toPolys([face])), + objects: objects.map(({ key, polys, building, planned }) => ({ key, polys, building, planned })), } }