game-village-politics-frontend/app/components/village/Diorama.vue

421 lines
20 KiB
Vue
Raw Permalink Normal View History

<script setup lang="ts">
import type { BuildingType, Cost, Offer, Resources, VillageState } from '~/types/game'
import { buildScene, type SceneBuilding, type SceneInset, type ScenePlot } from '~/diorama/scene'
import type { BuildingTag } from '~/utils/buildingTags'
const props = defineProps<{
village: VillageState
/** Whole seconds until a server timestamp, on the server's clock. */
secondsUntil: (iso: string) => number
/** Fill the whole stage at any shape, without the sideways scroll of narrow frames. */
fill?: boolean
/** A picture only (the landing page): no pan, zoom or land beyond the view. */
still?: boolean
/** With `fill`: pixels at the edges that windows cover; the whole village fits into the rest. */
inset?: SceneInset
/** Projected stock, for the storage's tag. */
resources?: Resources | null
/** A window or card is open: a click in the village closes it instead of opening another. */
dismiss?: boolean
/** Given: every tag gets an upgrade button next to its level (the overview). */
canAfford?: (cost: Cost) => boolean
/** A change is under way: the upgrade buttons wait. */
busy?: boolean
}>()
const emit = defineEmits<{ upgrade: [buildingId: number] }>()
/** Id of the building whose details are open. */
const selected = defineModel<number | null>('selected', { default: null })
/** Type whose empty plot was picked, to build it. */
const plot = defineModel<BuildingType | null>('plot', { default: null })
const { t } = useI18n()
// 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<HTMLElement | null>(null)
const stage = ref<HTMLElement | null>(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(() =>
props.fill ? buildScene(props.village, { width: size.value.w, height: size.value.h, inset: props.inset, surroundings: !props.still }) : buildScene(props.village, aspect.value),
)
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())
// On a stage the player pans and zooms over the land round the village.
const { view, viewBox, panning, zoomIn, zoomOut, reset, canZoomIn, canZoomOut, atHome } = useDioramaCamera({
id: () => props.village.id,
stage,
home: () => scene.value.home,
bounds: () => scene.value.bounds,
inset: () => props.inset ?? { top: 0, right: 0, bottom: 0, left: 0 },
enabled: () => !!props.fill && !props.still,
})
/** The zoom buttons sit in the bottom right corner of the part no window covers. */
const controlsAt = computed(() => ({ right: `${(props.inset?.right ?? 0) + 8}px`, bottom: `${(props.inset?.bottom ?? 0) + 8}px` }))
// Walkers and smoke only move for players who don't ask for reduced motion.
const motion = ref(false)
onMounted(() => (motion.value = !window.matchMedia('(prefers-reduced-motion: reduce)').matches))
// The picture is WebGL (useDioramaGl); the SVG over it only takes clicks and focus and
// carries the tags. The ground rings under the open building and the one keyboard focus
// is on are drawn in the picture, under the buildings.
const canvas = ref<HTMLCanvasElement | null>(null)
const focused = ref<{ id: number; dashed: boolean } | null>(null)
const onFocus = (id: number, e: FocusEvent) => (focused.value = { id, dashed: (e.target as Element).matches(':focus-visible') })
const marks = computed(() => [
...(selected.value !== null ? [{ id: selected.value, dashed: false }] : []),
...(focused.value?.dashed ? [focused.value] : []),
])
useDioramaGl({ canvas, scene: () => scene.value, view: () => view.value, size: () => size.value, motion: () => motion.value, marks: () => marks.value, background: '#6a7049' })
const targets = computed(() => scene.value.objects.flatMap((o) => (o.building ? [{ key: o.key, b: o.building }] : [])))
const name = (b: SceneBuilding) => t(`buildings.${b.type}`)
const label = (b: SceneBuilding) => t('village.diorama.label', { name: name(b), level: b.level })
const plotLabel = (p: ScenePlot) => t(p.another ? 'village.diorama.plot_another' : 'village.diorama.plot', { name: t(`buildings.${p.type}`) })
// Buildings stand still: hovering changes nothing but the cursor and the tooltip.
// A click opens the details and marks the ground under it.
function toggle(id: number) {
plot.value = null
selected.value = selected.value === id ? null : id
}
function pick(type: BuildingType) {
selected.value = null
plot.value = plot.value === type ? null : type
}
function clear() {
selected.value = null
plot.value = null
}
// A pointer click while something is open only closes it, so a stray click never swaps
// the window for another; keys still open what has focus.
const press = (id: number) => (props.dismiss ? clear() : toggle(id))
const pressPlot = (type: BuildingType) => (props.dismiss ? clear() : pick(type))
/** viewBox units per screen pixel: badges keep the same size however the scene is scaled or zoomed. */
const k = computed(() => (view.value.w / Math.max(1, size.value.w)) * (size.value.w < 900 ? 0.85 : 1))
// Every building wears a tag like the old village views: its level and the one number
// that says what it does now (app/utils/buildingTags.ts). Sizes are screen pixels, scaled
// by k into the scene, so tags read the same however the village is scaled.
const TAG = { h: 20, chip: 20, btn: 18, icon: 14, gap: 4, pad: 6, font: 12 }
const FONT = 'ui-sans-serif, system-ui, sans-serif'
let measurer: CanvasRenderingContext2D | null = null
const widths = new Map<string, number>()
function textWidth(text: string) {
if (!widths.has(text)) {
measurer ??= import.meta.client ? document.createElement('canvas').getContext('2d') : null
if (measurer) measurer.font = `700 ${TAG.font}px ${FONT}`
widths.set(text, measurer ? Math.ceil(measurer.measureText(text).width) : text.length * 7.5)
}
return widths.get(text)!
}
const TONES = {
plain: { fill: '#f3e7c9', stroke: '#57391f', text: '#2f2013', icon: '#57391f' },
warn: { fill: '#e8cd7c', stroke: '#8a6a1c', text: '#2f2013', icon: '#57391f' },
alarm: { fill: '#7b1e16', stroke: '#4a120d', text: '#f3e7c9', icon: '#f3e7c9' },
}
// Tags that would overlap move up above the one in front, nearest buildings first.
const badges = computed(() => {
const K = k.value
const list = scene.value.objects.flatMap((o) => (o.building?.focusable ? [o.building] : []))
const placed: { b: SceneBuilding; info: BuildingTag | null; offer: Offer | null; btn: number; x: number; y: number; w: number; h: number }[] = []
const overlaps = (x: number, y: number, w: number, h: number) =>
placed.some((p) => Math.abs(p.x - x) < (p.w + w) / 2 + 2 * K && Math.abs(p.y - y) < (p.h + h) / 2 + 2 * K)
for (const b of [...list].sort((p, q) => q.label[1] - p.label[1])) {
const building = props.village.buildings.find((x) => x.id === b.id)
const info = building && props.resources ? buildingTag(props.village, building, props.resources, props.secondsUntil, t) : null
const inner = info ? TAG.pad + (info.icon ? TAG.icon + TAG.gap : 0) + textWidth(info.text) + TAG.pad : 0
// The next level, one click away from the overview.
const offer = props.canAfford ? (building?.upgrade ?? null) : null
const btn = offer ? TAG.btn : 0
const w = (TAG.chip + btn + inner) * K
const h = TAG.h * K
const [x] = b.label
let y = b.label[1]
for (let n = 0; n < 8 && overlaps(x, y, w, h); n++) y -= h * 1.2
placed.push({ b, info, offer, btn, x, y, w, h })
}
return placed
})
// The upgrade button's card: target level, cost against the stock, build time.
const tip = ref<{ id: number; x: number; y: number } | null>(null)
const tipOffer = computed(() => (tip.value ? (badges.value.find((p) => p.b.id === tip.value!.id)?.offer ?? null) : null))
/** Which building the card is about: "Hiding place 2" when there are several. */
const tipBuilding = computed(() => (tip.value ? (props.village.buildings.find((x) => x.id === tip.value!.id) ?? null) : null))
const tipName = computed(() => (tipBuilding.value ? buildingName(props.village, tipBuilding.value, t) : ''))
function showTip(id: number, e: Event) {
const r = (e.currentTarget as Element).getBoundingClientRect()
tip.value = { id, x: r.left + r.width / 2, y: r.top }
}
const affordable = (offer: Offer) => !offer.blocked && !!props.canAfford?.(offer.cost)
function upgradeNow(id: number, offer: Offer) {
if (!props.busy && affordable(offer)) emit('upgrade', id)
}
const tagTitle = (b: SceneBuilding, info: BuildingTag | null) => [label(b), info?.title].filter(Boolean).join(' · ')
// Countdowns sit right above what is being built: over the level badge, or over the
// scaffold of a new building.
// A timer that would cover another timer or a level badge moves up until it is clear.
const timers = computed(() => {
const K = k.value
const half = { w: 41 * K, h: 12.5 * K }
const placed: { x: number; y: number }[] = []
const hits = (x: number, y: number) =>
placed.some((p) => Math.abs(p.x - x) < half.w * 2 && Math.abs(p.y - y) < half.h * 2) ||
badges.value.some((p) => Math.abs(p.x - x) < half.w + p.w / 2 && Math.abs(p.y - y) < half.h + p.h / 2)
return scene.value.timers
.map((tm) => {
const badge = tm.buildingId !== null ? badges.value.find((p) => p.b.id === tm.buildingId) : undefined
const lift = badge ? 24 : 2
return { ...tm, x: badge?.x ?? tm.at[0], y: (badge?.y ?? tm.at[1]) - lift * K }
})
.sort((a, b) => b.y - a.y)
.map((tm) => {
let y = tm.y
for (let n = 0; n < 8 && hits(tm.x, y); n++) y -= half.h * 2.1
placed.push({ x: tm.x, y })
return { ...tm, y }
})
})
</script>
<template>
<div ref="scroller" class="relative h-full w-full overflow-y-hidden bg-[#6a7049]" :class="fill ? 'overflow-x-hidden' : 'overflow-x-auto'">
<div ref="stage" class="relative h-full" :class="[fill ? (still ? '' : 'pan touch-none') : 'min-w-[640px]', { panning }]">
<canvas ref="canvas" class="absolute inset-0 block h-full w-full" aria-hidden="true" />
<svg
class="absolute inset-0 block h-full w-full select-none"
:viewBox="viewBox"
preserveAspectRatio="xMidYMid slice"
role="group"
:aria-label="$t('village.diorama.title')"
@click="clear"
>
<!-- Empty plots: nothing to see, but each opens its building type's build card. -->
<ellipse
v-for="p in scene.plots"
:key="p.key"
class="plot"
:class="{ 'is-selected': plot === p.type }"
v-bind="p.ring"
role="button"
tabindex="0"
:aria-label="plotLabel(p)"
:aria-pressed="plot === p.type"
@click.stop="pressPlot(p.type)"
@keydown.enter.prevent="pick(p.type)"
@keydown.space.prevent="pick(p.type)"
>
<title>{{ plotLabel(p) }}</title>
</ellipse>
<!-- The wall is thin: a wide band along its ring opens it too. -->
<ellipse
v-if="scene.wallBand"
class="band"
v-bind="scene.wallBand.ring"
:stroke-width="scene.wallBand.width"
aria-hidden="true"
@click.stop="press(scene.wallBand.id)"
/>
<!-- Each building's outline, back to front, so the one in front takes the click. -->
<g
v-for="{ key, b } in targets"
:key="key"
class="bld"
:role="b.focusable ? 'button' : undefined"
:tabindex="b.focusable ? 0 : -1"
:aria-hidden="b.focusable ? undefined : 'true'"
:aria-label="b.focusable ? label(b) : undefined"
:aria-pressed="b.focusable ? selected === b.id : undefined"
@click.stop="press(b.id)"
@keydown.enter.prevent="toggle(b.id)"
@keydown.space.prevent="toggle(b.id)"
@focus="onFocus(b.id, $event)"
@blur="focused = null"
>
<polygon v-if="b.hit" class="hit" :points="b.hit" />
<title>{{ label(b) }}</title>
</g>
<!-- Building tags (level and what it does now) and countdowns. Flat colours only. -->
<g class="pointer-events-none" :font-family="FONT" text-anchor="middle">
<g
v-for="{ b, info, offer, btn, x, y, w } in badges"
:key="`badge-${b.id}`"
class="pointer-events-auto cursor-pointer"
:transform="`translate(${x - w / 2} ${y}) scale(${k})`"
@click.stop="press(b.id)"
>
<title>{{ tagTitle(b, info) }}</title>
<rect
:width="w / k"
:height="TAG.h"
:y="-TAG.h / 2"
:fill="TONES[info?.tone ?? 'plain'].fill"
:stroke="selected === b.id ? '#7b1e16' : TONES[info?.tone ?? 'plain'].stroke"
:stroke-width="selected === b.id ? 2.4 : 1.4"
/>
<rect :width="TAG.chip" :height="TAG.h" :y="-TAG.h / 2" :fill="b.upgrading ? '#c49a2c' : '#57391f'" />
<text :x="TAG.chip / 2" :y="4.3" :font-size="TAG.font" font-weight="700" :fill="b.upgrading ? '#1f150c' : '#f3e7c9'">{{ b.level }}</text>
<!-- Upgrade right here: green when the stock covers it, grey when not. -->
<g
v-if="offer"
role="button"
:tabindex="0"
:aria-label="$t('village.diorama.upgrade_aria', { name: label(b), level: offer.target_level })"
:aria-disabled="!affordable(offer) || busy"
:class="affordable(offer) && !busy ? 'cursor-pointer' : 'cursor-not-allowed'"
@click.stop="upgradeNow(b.id, offer)"
@keydown.enter.stop.prevent="upgradeNow(b.id, offer)"
@pointerenter="showTip(b.id, $event)"
@pointerleave="tip = null"
@focus="showTip(b.id, $event)"
@blur="tip = null"
>
<title />
<rect :x="TAG.chip" :width="TAG.btn" :height="TAG.h" :y="-TAG.h / 2" :fill="affordable(offer) ? '#4f6b2a' : '#cdbf9e'" />
<path
:d="`M${TAG.chip + TAG.btn / 2} -5.5v11M${TAG.chip + TAG.btn / 2 - 4.5} -1l4.5 -4.5 4.5 4.5`"
fill="none"
:stroke="affordable(offer) ? '#f3e7c9' : '#8a7d63'"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</g>
<template v-if="info">
<g v-if="info.icon" :transform="`translate(${TAG.chip + btn + TAG.pad} ${-TAG.icon / 2})`" :style="{ color: TONES[info.tone].icon }">
<IconResource v-if="info.icon.kind === 'resource'" :resource="info.icon.name" :width="TAG.icon" :height="TAG.icon" />
<IconUnit v-else-if="info.icon.kind === 'unit'" :unit="info.icon.name" :width="TAG.icon" :height="TAG.icon" />
<IconUi v-else :name="info.icon.name" :width="TAG.icon" :height="TAG.icon" />
</g>
<text
:x="TAG.chip + btn + TAG.pad + (info.icon ? TAG.icon + TAG.gap : 0)"
:y="4.3"
text-anchor="start"
:font-size="TAG.font"
font-weight="700"
:fill="TONES[info.tone].text"
>
{{ info.text }}
</text>
</template>
</g>
<g
v-for="tm in timers"
:key="`timer-${tm.orderId}`"
:class="tm.buildingId ? 'pointer-events-auto cursor-pointer' : ''"
:transform="`translate(${tm.x} ${tm.y})`"
@click.stop="tm.buildingId && press(tm.buildingId)"
>
<rect :x="-39 * k" :y="-11.5 * k" :width="78 * k" :height="22 * k" :rx="2 * k" fill="#2f2013" stroke="#c49a2c" :stroke-width="1.2 * k" />
<g :transform="`translate(${-27.5 * k} ${-0.5 * k}) scale(${1.15 * k})`" fill="none" stroke="#d9b44a" stroke-width="1.4" stroke-linecap="round">
<circle r="5" />
<path d="M0 -3v3l2 1.5" />
</g>
<text :x="7 * k" :y="4.6 * k" :font-size="13 * k" font-weight="700" fill="#f3e7c9" class="tabular-nums">
{{ formatDuration(secondsUntil(tm.finishesAt)) }}
</text>
</g>
</g>
</svg>
</div>
<!-- Zoom: the wheel, a pinch, + − 0 or these; drag the land to look round. -->
<div v-if="fill && !still" class="float absolute z-[1] flex border border-wood-900 bg-parchment-200" :style="controlsAt">
<button type="button" class="btn btn-ghost" :disabled="atHome" :title="$t('village.diorama.whole_key')" @click="reset">
{{ $t('village.diorama.whole') }}
</button>
<button type="button" class="btn btn-ghost px-2.5" :disabled="!canZoomOut" :aria-label="$t('village.diorama.zoom_out')" :title="$t('village.diorama.zoom_out_key')" @click="zoomOut">
−
</button>
<button type="button" class="btn btn-ghost px-2.5" :disabled="!canZoomIn" :aria-label="$t('village.diorama.zoom_in')" :title="$t('village.diorama.zoom_in_key')" @click="zoomIn">
+
</button>
</div>
<!-- The upgrade button's card, over everything. -->
<Teleport to="body">
<div
v-if="tip && tipOffer"
class="float pointer-events-none fixed z-50 -translate-x-1/2 -translate-y-full border border-wood-900 bg-parchment-100 px-2 py-1.5 text-sm"
:style="{ left: `${tip.x}px`, top: `${tip.y - 6}px` }"
role="tooltip"
>
<p class="mb-1 font-semibold whitespace-nowrap text-wood-900">{{ $t('village.diorama.upgrade_to', { name: tipName, from: tipOffer.target_level - 1, level: tipOffer.target_level }) }}</p>
<div class="flex items-center gap-3 whitespace-nowrap">
<UiCost :cost="tipOffer.cost" :have="resources ?? undefined" :villagers="tipOffer.villagers" :idle="village.population.idle" nowrap />
<span class="inline-flex items-center gap-1 text-ink-700 tabular-nums"><IconUi name="clock" class="size-3.5" />{{ formatDuration(tipOffer.seconds) }}</span>
</div>
<p v-if="tipBuilding && isCopy(tipBuilding.instance_share)" class="mt-1">
<span class="badge badge-gold">{{ $t('village.copy.this', { share: sharePercent(tipBuilding.instance_share) }) }}</span>
</p>
<p v-if="tipOffer.blocked" class="mt-1 text-xs font-semibold text-blood-700">{{ $t(`village.blocked.${tipOffer.blocked}`) }}</p>
<p v-else-if="!affordable(tipOffer)" class="mt-1 text-xs font-semibold text-blood-700">{{ $t('village.blocked.resources') }}</p>
</div>
</Teleport>
</div>
</template>
<style scoped>
/* The land drags; while it does, nothing under the pointer looks clickable. */
.pan {
cursor: grab;
}
.panning,
.panning .bld,
.panning .plot,
.panning .band,
.panning .cursor-pointer {
cursor: grabbing;
}
/* Buildings are massive and stay put: no lift, no glow, nothing on hover. Only a click
(or keyboard focus) outlines the ground they stand on, drawn in the picture. */
.bld,
.plot {
cursor: pointer;
outline: none;
}
.plot,
.hit {
fill: transparent;
stroke: transparent;
}
.band {
fill: none;
stroke: transparent;
pointer-events: stroke;
cursor: pointer;
}
.plot.is-selected {
stroke: #7b1e16;
stroke-width: 2;
}
.plot:focus-visible {
stroke: #7b1e16;
stroke-width: 2;
stroke-dasharray: 4 3;
}
</style>