game-village-politics-frontend/app/diorama/mapTiles.ts

257 lines
12 KiB
TypeScript
Raw Permalink Normal View History

// Villages on the world map as miniatures of the village diorama itself, like the little
// village pictures on the Die Stämme map: one fixed demo village per points tier (which
// buildings at which levels), drawn by the very same scene as the village view, cropped
// round its core on a clearing of trodden ground that steps out into the map's grass.
// Barbarian villages are the same villages worn: colours faded and darkened, no banners, no
// fire. The crown fort is a fortress: a stone keep for a headquarters behind a high stone wall.
// Pure: the pictures are painted on a canvas once per look (useMapTiles), never per village.
import type { Building, BuildingType, VillageState } from '~/types/game'
import { hash, mix, type Poly, project, scale } from './iso'
import { buildScene, type Scene, U } from './scene'
export type MapTier = 1 | 2 | 3 | 4 | 5 | 6
/** Lowest points of tiers 2 to 6; below the first, tier 1. Die Stämme's bands, its wide 3000–8999 split at 6000. */
export const MAP_TIER_POINTS = [300, 1000, 3000, 6000, 10000] as const
/** Six sizes by points, like the village pictures on the Die Stämme map. */
export const mapTier = (points: number): MapTier => (MAP_TIER_POINTS.findIndex((p) => points < p) + 1 || 6) as MapTier
/** A picture: its tier (or the crown fort), barbarian or not, and the layout variant. */
export interface MapLook {
id: string
tier: MapTier | 'crown'
worn: boolean
variant: 0 | 1
}
export const MAP_LOOKS: MapLook[] = [
...[false, true].flatMap((worn) =>
([1, 2, 3, 4, 5, 6] as MapTier[]).flatMap((tier) => ([0, 1] as const).map((variant) => ({ id: `mv-${worn ? 'barbarian' : 'player'}-${tier}-${variant}`, tier, worn, variant }))),
),
{ id: 'mv-crown', tier: 'crown', worn: true, variant: 0 },
{ id: 'mv-crown-player', tier: 'crown', worn: false, variant: 0 },
]
/** The look a village wears: its kind and tier, the variant from its id. */
export function mapLookOf(v: { id: number; points: number; crown: boolean; player: unknown }): string {
if (v.crown) return v.player ? 'mv-crown-player' : 'mv-crown'
return `mv-${v.player ? 'player' : 'barbarian'}-${mapTier(v.points)}-${Math.abs(v.id) % 2}`
}
// The demo villages. Farms and camps stand outside in their zones; everything else in the
// core, round the headquarters, inside the wall from the second tier.
const VILLAGES: Record<MapTier | 'crown', [BuildingType, number][]> = {
1: [['headquarters', 3], ['storage', 2], ['farm', 3], ['timber_camp', 3], ['clay_pit', 2], ['iron_mine', 1], ['rally_point', 1], ['hiding_place', 1]],
2: [['headquarters', 7], ['storage', 6], ['farm', 6], ['farm', 3], ['timber_camp', 5], ['timber_camp', 3], ['clay_pit', 5], ['iron_mine', 4], ['rally_point', 1], ['hiding_place', 3], ['barracks', 3], ['wall', 3]],
3: [
['headquarters', 12], ['storage', 10], ['storage', 4], ['farm', 9], ['farm', 6], ['timber_camp', 8], ['timber_camp', 6], ['clay_pit', 8], ['iron_mine', 7],
['rally_point', 1], ['hiding_place', 5], ['barracks', 7], ['stable', 3], ['wall', 8], ['market', 4],
],
4: [
['headquarters', 17], ['storage', 15], ['storage', 9], ['farm', 13], ['farm', 10], ['timber_camp', 12], ['timber_camp', 10], ['clay_pit', 12], ['clay_pit', 8], ['iron_mine', 11],
['rally_point', 1], ['hiding_place', 6], ['barracks', 12], ['stable', 8], ['workshop', 3], ['wall', 13], ['market', 9], ['hospital', 4], ['watchtower', 3],
],
5: [
['headquarters', 22], ['storage', 19], ['storage', 14], ['farm', 17], ['farm', 15], ['timber_camp', 16], ['timber_camp', 14], ['clay_pit', 16], ['clay_pit', 12], ['iron_mine', 15], ['iron_mine', 10],
['rally_point', 1], ['hiding_place', 8], ['barracks', 16], ['stable', 12], ['workshop', 7], ['wall', 17], ['market', 13], ['hospital', 8], ['watchtower', 8], ['academy', 1],
],
6: [
['headquarters', 28], ['storage', 25], ['storage', 20], ['farm', 22], ['farm', 20], ['timber_camp', 22], ['timber_camp', 20], ['clay_pit', 22], ['clay_pit', 18], ['iron_mine', 21], ['iron_mine', 16],
['rally_point', 1], ['hiding_place', 10], ['barracks', 22], ['barracks', 12], ['stable', 18], ['workshop', 12], ['wall', 20], ['market', 18], ['hospital', 12], ['watchtower', 14], ['academy', 3],
],
crown: [
['headquarters', 30], ['wall', 20], ['storage', 20], ['rally_point', 1], ['barracks', 20], ['stable', 15], ['workshop', 10], ['hospital', 10], ['watchtower', 20], ['hiding_place', 10],
],
}
const SPACE: Partial<Record<BuildingType, number>> = {
headquarters: 9, storage: 4, farm: 4, timber_camp: 4, clay_pit: 4, iron_mine: 4, hiding_place: 1, wall: 0, rally_point: 1, watchtower: 2, barracks: 6, stable: 6, workshop: 6, hospital: 4, market: 4, academy: 9,
}
/** A demo village as the scene reads it; variant 1 lays it out in the other order, the headquarters staying first. */
function demo(tier: MapTier | 'crown', variant: 0 | 1): VillageState {
const all = VILLAGES[tier]
const levels = variant ? [all[0]!, ...all.slice(1).reverse()] : all
const buildings = levels.map(([type, level], i): Building => ({
id: i + 1, type, level, space: SPACE[type] ?? 4, priority: 5,
workers: { assigned: 0, required: 0 }, staffing: 1, production: null, upgrade: null, demolish: null, effects: [], next_effects: null, instance_share: 1,
}))
const points = tier === 'crown' ? 12000 : [150, 600, 2000, 4500, 8000, 12000][tier - 1]!
return { id: 0, points, buildings, queue: [], troops: {}, support: { here: [], away: [] }, military: [], buildable: [], movements: [] } as unknown as VillageState
}
/** A picture to paint: back to front, in scene units; `clip` limits the ground under it to the clearing. */
export interface MapTileDrawing {
/** The clearing and the steps out to the grass, outermost first. */
steps: { points: string; fill: string }[]
/** The innermost step: the village's ground is cut to it. */
clip: string
ground: Poly[]
objects: Poly[]
/** Scene units that span the field: the clearing fills more of it as the village grows. */
units: number
}
/** How much of the field's width the clearing takes, per tier. */
const FILL: Record<MapTier | 'crown', number> = { 1: 0.8, 2: 0.86, 3: 0.9, 4: 0.94, 5: 0.97, 6: 1, crown: 1 }
/** The map's grass the clearing steps out into. */
const MEADOW = '#6b7049'
const CLEARING = '#6d6748'
/** A ring round the village in scene units, wandering in and out, projected. */
function ring(r: number, seed: number): [number, number][] {
const n = 28
return Array.from({ length: n }, (_, i) => {
const a = (i / n) * Math.PI * 2
const k = r * (0.92 + 0.14 * hash(i, seed) + 0.05 * Math.sin(a * 3 + seed))
return project([Math.cos(a) * k, Math.sin(a) * k, 0])
})
}
const pts = (p: [number, number][]) => p.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(' ')
/** Faded and darkened, for a barbarian village: what the weather and neglect do. */
function worn(color: string): string {
const n = Number.parseInt(color.slice(1), 16)
const [r, g, b] = [(n >> 16) & 255, (n >> 8) & 255, n & 255]
const grey = Math.round(r * 0.3 + g * 0.59 + b * 0.11)
const hex = `#${[grey, grey, grey].map((v) => v.toString(16).padStart(2, '0')).join('')}`
return scale(mix(color, hex, 0.5), 0.82)
}
/** The scene's roads and their ruts (flat, so lit at 1.02): at the map's size they would read as the spokes of a wheel. */
const ROADS = new Set([scale('#6b563f', 1.02), scale(mix('#6b563f', '#4e3f2f', 0.6), 1.02)])
/** Banners and fire: deep reds and the warm glow, which a barbarian village has none of. */
function bannerOrFire(color: string): boolean {
const n = Number.parseInt(color.slice(1), 16)
const [r, g, b] = [(n >> 16) & 255, (n >> 8) & 255, n & 255]
return r > 60 && r > g * 1.8 && r > b * 1.8
}
/** The middle of an object's lowest edge on screen. */
function baseOf(polys: Poly[]): [number, number] {
let minX = Infinity
let maxX = -Infinity
let maxY = -Infinity
for (const p of polys) {
for (const xy of p.points.split(' ')) {
const [x, y] = xy.split(',').map(Number) as [number, number]
if (x < minX) minX = x
if (x > maxX) maxX = x
if (y > maxY) maxY = y
}
}
return [(minX + maxX) / 2, maxY]
}
/** Back on the ground plane: the world point a screen point shows. */
const groundOf = ([X, Y]: [number, number]): [number, number] => [Y + X / 2, Y - X / 2]
/** An object drawn bigger round where it stands, so a building still reads as one at the map's size. */
function enlarge(polys: Poly[], [ax, ay]: [number, number], k: number): Poly[] {
const at = (xy: string) => {
const i = xy.indexOf(',')
return `${(ax + (Number(xy.slice(0, i)) - ax) * k).toFixed(1)},${(ay + (Number(xy.slice(i + 1)) - ay) * k).toFixed(1)}`
}
return polys.map((p) => ({ ...p, points: p.points.split(' ').map(at).join(' ') }))
}
/** How much bigger buildings, trees and props draw than in the village, the wall staying where it is. */
const ENLARGE = 2.3
/** Scenes by tier and layout: a player's and a barbarian's picture share one. */
const scenes = new Map<string, Scene>()
function sceneOf(tier: MapTier | 'crown', variant: 0 | 1): Scene {
const key = `${tier}-${variant}`
let scene = scenes.get(key)
if (!scene) scenes.set(key, (scene = buildScene(demo(tier, variant), 1)))
return scene
}
/** The picture of a look, cut out of the scene of its demo village. */
export function mapTileDrawing(look: MapLook): MapTileDrawing {
const scene = sceneOf(look.tier, look.variant)
// The village's own ground (its first decal) is a disc just outside the wall: the clearing
// reaches past it to the first fields and camps, then steps out into the grass.
const disc = scene.decals[0]!.points.split(' ').map((xy) => xy.split(',').map(Number) as [number, number])
const halfWidth = Math.max(...disc.map(([x]) => Math.abs(x)))
const Rv = halfWidth / Math.SQRT2 - U * 0.25
const Rc = Rv + U * 0.15
const recolor = (p: Poly): Poly => (look.worn ? { ...p, fill: worn(p.fill), stroke: worn(p.stroke) } : p)
// The ground wears less than the buildings, so a barbarian village still sits in the grass.
const recolorGround = (p: Poly): Poly => (look.worn ? { ...p, fill: mix(p.fill, worn(p.fill), 0.5), stroke: mix(p.stroke, worn(p.stroke), 0.5) } : p)
const keep = (p: Poly) => !(look.worn && bannerOrFire(p.fill))
const inside = (r: number) => r <= Rc * 0.98
// The steps fade into the grass whatever the village; only its own ground wears.
const clearing = look.worn ? mix(CLEARING, worn(CLEARING), 0.35) : CLEARING
const steps = [
{ r: Rc + U * 0.7, fill: mix(clearing, MEADOW, 0.7) },
{ r: Rc + U * 0.35, fill: mix(clearing, MEADOW, 0.38) },
{ r: Rc, fill: clearing },
].map((s, i) => ({ points: pts(ring(s.r, 11 + i)), fill: s.fill }))
const objects = scene.objects
.filter((o) => o.polys.length && !o.life && !o.walker)
.flatMap((o) => {
const base = baseOf(o.polys)
const [x, y] = groundOf(base)
if (!inside(Math.hypot(x, y))) return []
const polys = o.key.startsWith('wall-') ? o.polys : enlarge(o.polys, base, ENLARGE)
return polys.filter(keep).map(recolor)
})
return {
steps,
clip: steps[2]!.points,
ground: scene.decals.filter((p) => keep(p) && !ROADS.has(p.fill)).map(recolorGround),
objects,
units: (Math.max(...ring(Rc + U * 0.7, 11).map(([x]) => Math.abs(x))) * 2) / FILL[look.tier],
}
}
/** Paints a picture on a canvas of `size` × `size` pixels covering one field. */
export function paintTile(ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D, d: MapTileDrawing, size: number) {
const k = size / d.units
ctx.setTransform(k, 0, 0, k, size / 2, size * 0.6)
const path = (points: string) => {
ctx.beginPath()
let first = true
for (const xy of points.split(' ')) {
const i = xy.indexOf(',')
const x = Number(xy.slice(0, i))
const y = Number(xy.slice(i + 1))
if (first) ctx.moveTo(x, y)
else ctx.lineTo(x, y)
first = false
}
ctx.closePath()
}
ctx.lineJoin = 'round'
// A hair of each face's own colour round it closes the seams, as in the village view.
ctx.lineWidth = 0.9
for (const s of d.steps) {
path(s.points)
ctx.fillStyle = s.fill
ctx.fill()
}
ctx.save()
path(d.clip)
ctx.clip()
for (const p of d.ground) {
path(p.points)
ctx.fillStyle = p.fill
ctx.fill()
ctx.strokeStyle = p.stroke
ctx.stroke()
}
ctx.restore()
for (const p of d.objects) {
path(p.points)
ctx.fillStyle = p.fill
ctx.fill()
ctx.strokeStyle = p.stroke
ctx.stroke()
}
}