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

299 lines
12 KiB
Vue
Raw Normal View History

<script setup lang="ts">
import type { BuildingType, VillageState } from '~/types/game'
import { buildScene, type SceneBuilding, type SceneInset, type ScenePlot } from '~/diorama/scene'
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
/** With `fill`: pixels at the edges that windows cover; the whole village fits into the rest. */
inset?: SceneInset
}>()
/** 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 }) : 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())
// 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))
const SHIRTS = ['#6b4f3a', '#7b1e16', '#3d5a26', '#57391f', '#5a5f63']
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
}
/** 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))
// 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 = 13 * 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
})
// 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 + 13 * K && Math.abs(p.y - y) < half.h + 13 * K)
return scene.value.timers
.map((tm) => {
const badge = tm.buildingId !== null ? badges.value.find((p) => p.b.id === tm.buildingId) : undefined
const lift = badge ? 29 : 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="h-full w-full overflow-y-hidden bg-[#74864a]" :class="fill ? 'overflow-x-hidden' : 'overflow-x-auto'">
<div ref="stage" class="h-full" :class="fill ? '' : 'min-w-[640px]'">
<svg
class="block h-full w-full select-none"
:viewBox="scene.viewBox"
preserveAspectRatio="xMidYMid slice"
role="group"
:aria-label="$t('village.diorama.title')"
@click="clear"
>
<g stroke-width="0.6" stroke-linejoin="round">
<polygon v-for="(p, i) in scene.terrain" :key="`t${i}`" :points="p.points" :fill="p.fill" :stroke="p.stroke" />
<polygon v-for="(p, i) in scene.decals" :key="`d${i}`" :points="p.points" :fill="p.fill" :stroke="p.stroke" />
</g>
<!-- Villagers on their way to work and back, under the buildings they walk into. -->
<g v-if="motion" class="pointer-events-none">
<template v-for="(w, i) in scene.walks" :key="`walk-${i}-${w.d.length}`">
<g v-for="n in w.count" :key="n">
<VillageWalker transform="scale(1.35)" :shirt="SHIRTS[(i * 3 + n) % SHIRTS.length]!" />
<animateMotion
:dur="`${w.seconds}s`"
:begin="`${-((n - 1) * w.seconds) / w.count - i * 3}s`"
repeatCount="indefinite"
keyPoints="0;1;0"
keyTimes="0;0.5;1"
calcMode="linear"
:path="w.d"
/>
</g>
</template>
</g>
<!-- 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="pick(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="toggle(scene.wallBand.id)"
/>
<template v-for="obj in scene.objects" :key="obj.key">
<g
v-if="obj.building"
v-memo="[obj, selected === obj.building.id]"
class="bld"
:class="{ 'is-selected': selected === obj.building.id }"
:role="obj.building.focusable ? 'button' : undefined"
:tabindex="obj.building.focusable ? 0 : -1"
:aria-hidden="obj.building.focusable ? undefined : 'true'"
:aria-label="obj.building.focusable ? label(obj.building) : undefined"
:aria-pressed="obj.building.focusable ? selected === obj.building.id : undefined"
stroke-width="0.6"
stroke-linejoin="round"
@click.stop="toggle(obj.building.id)"
@keydown.enter.prevent="toggle(obj.building.id)"
@keydown.space.prevent="toggle(obj.building.id)"
>
<polygon v-if="obj.building.hit" class="hit" :points="obj.building.hit" />
<ellipse v-if="obj.building.ring.rx" class="ring" v-bind="obj.building.ring" />
<polygon v-for="(p, i) in obj.polys" :key="i" :points="p.points" :fill="p.fill" :stroke="p.stroke" />
<title>{{ label(obj.building) }}</title>
</g>
<g v-else v-memo="[obj]" stroke-width="0.6" stroke-linejoin="round">
<polygon v-for="(p, i) in obj.polys" :key="i" :points="p.points" :fill="p.fill" :stroke="p.stroke" />
<title v-if="obj.planned">{{ $t('village.diorama.planned') }}</title>
</g>
</template>
<!-- Smoke from chimneys, forges and kilns: flat puffs that rise, drift and shrink away. -->
<g v-if="motion" class="pointer-events-none" fill="#d6cfbf" stroke="#b3ab98" stroke-width="0.5">
<g v-for="(p, i) in scene.smoke" :key="`smoke-${i}`" :transform="`translate(${p[0]} ${p[1]})`">
<circle v-for="n in 3" :key="n" class="puff" r="5.5" :style="{ animationDelay: `${-(n * 1.3 + i * 0.9)}s` }" />
</g>
</g>
<!-- Level badges and countdowns. Flat colours only. -->
<g class="pointer-events-none" font-family="ui-sans-serif, system-ui, sans-serif" text-anchor="middle">
<g
v-for="{ b, x, y } in badges"
:key="`badge-${b.id}`"
class="pointer-events-auto cursor-pointer"
:transform="`translate(${x} ${y})`"
@click.stop="toggle(b.id)"
>
<circle
:r="12 * k"
:fill="b.upgrading ? '#c49a2c' : '#f3e7c9'"
:stroke="selected === b.id ? '#7b1e16' : '#57391f'"
:stroke-width="1.6 * k"
/>
<text :y="4.6 * k" :font-size="13 * k" font-weight="700" :fill="b.upgrading ? '#1f150c' : '#2f2013'">{{ b.level }}</text>
</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 && toggle(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>
</div>
</template>
<style scoped>
/* 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. */
.bld,
.plot {
cursor: pointer;
outline: none;
}
.ring,
.plot,
.hit {
fill: transparent;
stroke: transparent;
}
.band {
fill: none;
stroke: transparent;
pointer-events: stroke;
cursor: pointer;
}
.bld.is-selected .ring,
.plot.is-selected {
stroke: #7b1e16;
stroke-width: 2;
}
.bld:focus-visible .ring,
.plot:focus-visible {
stroke: #7b1e16;
stroke-width: 2;
stroke-dasharray: 4 3;
}
/* A puff starts small at the chimney, grows as it rises and drifts, then shrinks to nothing. */
.puff {
transform-box: fill-box;
transform-origin: center;
animation: puff 3.9s linear infinite;
}
@keyframes puff {
0% {
transform: translate(0, 0) scale(0.25);
}
55% {
transform: translate(-6px, -15px) scale(1);
}
100% {
transform: translate(-13px, -27px) scale(0);
}
}
</style>