diff --git a/README.md b/README.md index 82b3452..e413f89 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ The repository is public; the game is listed on BGS as a beta. Supplied artwork Node 24+, pnpm. `pnpm install`, `pnpm build`, `pnpm dev` (port 5246). `pnpm test` runs rules tests; install the browser once with `pnpm exec playwright install chromium`; `pnpm test:browser` checks the viewer. -BGS supplies the shared `colorBlind` and `sound` preferences. Color-blind mode adds player symbols and K/C/B resource labels; game sounds give a quiet confirmation after successful moves. The toggles in Rules & help update the same BGS account settings. Standalone practice stores its own preferences locally. +BGS supplies the shared `colorBlind` and `sound` preferences. Color-blind mode adds player symbols and K/C/B resource labels; game sounds give a quiet confirmation after successful moves. The toggles in Rules & help update the same BGS account settings. Standalone practice stores its own preferences locally. The 2D/3D switch saves the `mapView` preference through BGS; 3D is the default, with a 2D fallback when WebGL is unavailable. Motion follows the browser’s reduced-motion setting. Marker retrieval is manual by default, including the last unusable action stack. Each player can opt into automatic retrieval when retrieving one stack is the only available move in Rules & help; this setting is saved separately for each game. Automatic retrieval never skips optional treasure exchanges or chooses between multiple stacks. Guided lessons always use manual retrieval. diff --git a/engine/index.js b/engine/index.js index 48d2e42..d3730f8 100644 --- a/engine/index.js +++ b/engine/index.js @@ -810,13 +810,17 @@ function endRound(s) { s._demandDiscards.push(d); s.demands = s.demands.filter((d) => !d.filled.every(Boolean)); while (s.demands.length < 3) s.demands.push(revealDemand(s)); - for (const t of Object.values(s.board)) + const refills = []; + for (const [cell, t] of Object.entries(s.board)) if ( t.type === "island" && !t.submerged && sum(Object.values(t.goods)) === 0 - ) + ) { t.goods = { ...TILES[t.id].goods }; + if (sum(Object.values(t.goods))) + refills.push({ cell, goods: { ...t.goods } }); + } if (s.players.length === 2) { const previous = new Set([ ...s.characters, @@ -838,7 +842,12 @@ function endRound(s) { s.planningPass = 0; s.neutral = emptyMarkers(); s.neutralPlaced = 0; - say(s, "round", { round: s.round, first: s.first, tourists: s.tourists }); + say(s, "round", { + round: s.round, + first: s.first, + tourists: s.tourists, + refills, + }); } function finish(s) { for (const [p, a] of s.players.entries()) { diff --git a/package.json b/package.json index 2fa172a..5980512 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@boardgamers/vanuatu", - "version": "0.1.10", + "version": "0.2.0", "private": true, "type": "module", "main": "dist/engine.js", @@ -11,7 +11,7 @@ "build": "node scripts/build.mjs", "test": "node --test test/*.test.js", "dev": "node scripts/dev.mjs", - "test:browser": "node test/browser.mjs && node test/undo-browser.mjs && node test/journal-browser.mjs && node test/map-zoom-browser.mjs && node test/map-drag-browser.mjs && node test/redraw-browser.mjs && node test/mobile-layout-browser.mjs && node test/prose-browser.mjs && node test/effects-browser.mjs", + "test:browser": "node test/browser.mjs && node test/undo-browser.mjs && node test/journal-browser.mjs && node test/map-zoom-browser.mjs && node test/map-drag-browser.mjs && node test/redraw-browser.mjs && node test/mobile-layout-browser.mjs && node test/prose-browser.mjs && node test/effects-browser.mjs && node test/three-viewer-browser.mjs", "check": "pnpm test:locales && pnpm build && pnpm test && pnpm test:browser && pnpm test:tutorial:browser", "test:locales": "node scripts/check-locales.mjs viewer/localization && node --test scripts/localization.test.mjs", "test:tutorial:browser": "node test/tutorial-browser.mjs && node test/tutorial-walkthrough-browser.mjs && node test/tutorial-errors-browser.mjs" @@ -19,7 +19,8 @@ "dependencies": { "@boardgamers/protocol": "0.10.0", "@noble/hashes": "2.0.1", - "morphdom": "2.7.8" + "morphdom": "2.7.8", + "three": "0.186.1" }, "devDependencies": { "esbuild": "0.25.12", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 57060b7..b28052c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -17,6 +17,9 @@ importers: morphdom: specifier: 2.7.8 version: 2.7.8 + three: + specifier: 0.186.1 + version: 0.186.1 devDependencies: esbuild: specifier: 0.25.12 @@ -221,6 +224,9 @@ packages: engines: {node: '>=14'} hasBin: true + three@0.186.1: + resolution: {integrity: sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==} + zod@4.6.5: resolution: {integrity: sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==} @@ -354,4 +360,6 @@ snapshots: prettier@3.6.2: {} + three@0.186.1: {} + zod@4.6.5: {} diff --git a/scripts/publish-beta.mjs b/scripts/publish-beta.mjs index cac025b..805789f 100644 --- a/scripts/publish-beta.mjs +++ b/scripts/publish-beta.mjs @@ -1,3 +1,7 @@ +import { + mapViewPreference, + releasePreferences, +} from "./release-preferences.mjs"; import { uploadViewerFiles } from "./viewer-files.mjs"; import { chapterMetadata } from "../viewer/tutorials.js"; import { readFile, mkdir, writeFile } from "node:fs/promises"; @@ -68,12 +72,7 @@ const defaults = { default: false, }, { name: "sound", label: "Game sounds", type: "checkbox", default: true }, - { - name: "animations", - label: "Animations", - type: "checkbox", - default: true, - }, + mapViewPreference, { name: "language", label: "Language", @@ -123,17 +122,9 @@ const files = await uploadViewerFiles( const viewer = { url: files.url }, style = { url: files.stylesheets[0] }; const patch = { - preferences: [ - ...(existing?.preferences ?? defaults.preferences).filter( - (preference) => preference.name !== "animations", - ), - existing?.preferences?.find( - (preference) => preference.name === "animations", - ) ?? - defaults.preferences.find( - (preference) => preference.name === "animations", - ), - ], + preferences: releasePreferences( + existing?.preferences ?? defaults.preferences, + ), settings: [ ...(existing?.settings ?? []).filter( (setting) => setting.name !== "autoRetrieve", @@ -207,6 +198,10 @@ if (existing) { } else assert.ok(!meta.unlisted); assert.equal(published.engine.package.version, pkg.version); assert.equal(published.viewer.chat, true); +assert.deepEqual( + published.preferences, + releasePreferences(existing?.preferences ?? defaults.preferences), +); await writeFile( ".local/release/published.json", JSON.stringify(published, null, 2), diff --git a/scripts/release-preferences.mjs b/scripts/release-preferences.mjs new file mode 100644 index 0000000..f3b8415 --- /dev/null +++ b/scripts/release-preferences.mjs @@ -0,0 +1,24 @@ +export const mapViewPreference = { + name: "mapView", + label: "2D / 3D", + type: "select", + default: "3d", + items: [ + { name: "2d", label: "2D" }, + { name: "3d", label: "3D" }, + ], +}; + +export function releasePreferences(existing) { + const preferences = existing.filter( + ({ name }) => name !== "animations" && name !== "mapView", + ); + if (!preferences.some(({ name }) => name === "sound")) + preferences.push({ + name: "sound", + label: "Game sounds", + type: "checkbox", + default: true, + }); + return [...preferences, mapViewPreference]; +} diff --git a/test/browser.mjs b/test/browser.mjs index c5e18d8..5bfa2c2 100644 --- a/test/browser.mjs +++ b/test/browser.mjs @@ -42,6 +42,7 @@ const page = await browser.newPage({ locale: "fr-FR", }); page.on("pageerror", (e) => errors.push(e.message)); +await page.addInitScript(() => localStorage.setItem("vanuatu-map-view", "2d")); await page.goto(base + "/?new&hotseat"); await page.waitForSelector("[data-character-choice]"); // Decorative motion must never move a tile's clickable/focusable SVG bounds. @@ -94,6 +95,9 @@ for (const locale of [ "utf8", ), ); + await page.addInitScript(() => + localStorage.setItem("vanuatu-map-view", "2d"), + ); await page.goto(`${base}/?new&hotseat&locale=${locale}`); await page.waitForFunction( (expected) => @@ -116,6 +120,7 @@ for (const locale of [ ); } } +await page.addInitScript(() => localStorage.setItem("vanuatu-map-view", "2d")); await page.goto(base + "/?new&hotseat"); await page.waitForSelector("[data-character-choice]"); // Action descriptions remain available even before an action can be selected. @@ -763,6 +768,7 @@ await page.locator("[data-scores]").click(); assert.equal(await page.locator(".final-scores>div").count(), 3); await page.locator("[data-close]").click(); // Hosted protocol: replay, names, analysis chat visibility, hover anchors and board thumbnail. +await page.addInitScript(() => localStorage.setItem("vanuatu-map-view", "2d")); await page.goto(base + "/"); await page.evaluate(() => { document.body.innerHTML = '
'; diff --git a/test/effects-browser.mjs b/test/effects-browser.mjs index 0526b28..897c7a6 100644 --- a/test/effects-browser.mjs +++ b/test/effects-browser.mjs @@ -93,6 +93,7 @@ try { } }; }); + await p.addInitScript(() => localStorage.setItem("vanuatu-map-view", "2d")); await p.goto(`http://127.0.0.1:${server.address().port}/`); if (width === 1440) { const samples = await p.evaluate(async () => { @@ -293,13 +294,8 @@ try { 0, "Reduced motion suppresses overlays", ); - await p.emulateMedia({ reducedMotion: "no-preference" }); await p.evaluate(() => - host.emit("preferences", { - locale: "fr", - sound: false, - animations: false, - }), + host.emit("preferences", { locale: "fr", sound: false, mapView: "2d" }), ); await emit(s); const mutedAt = await p.evaluate(() => window.played); @@ -311,11 +307,9 @@ try { "Muted incoming moves are silent", ); await p.locator("[data-help]").first().click(); - assert.equal( - await p.locator('[data-pref="animations"]').isChecked(), - false, - ); - await p.locator('[data-pref="animations"]').check(); + assert.equal(await p.locator('[data-pref="animations"]').count(), 0); + assert.equal(await p.locator("[data-map-preference]").inputValue(), "2d"); + await p.emulateMedia({ reducedMotion: "no-preference" }); await p.locator("dialog [data-close]").click(); await emit(s); await emit(sailed); diff --git a/test/journal-browser.mjs b/test/journal-browser.mjs index c1b4c20..44dac12 100644 --- a/test/journal-browser.mjs +++ b/test/journal-browser.mjs @@ -108,6 +108,9 @@ try { }); const errors = []; page.on("pageerror", (e) => errors.push(e.message)); + await page.addInitScript(() => + localStorage.setItem("vanuatu-map-view", "2d"), + ); await page.goto(`http://127.0.0.1:${server.address().port}`); await page.evaluate((state) => { window.fixture = state; diff --git a/test/map-drag-browser.mjs b/test/map-drag-browser.mjs index 33287f0..694d2a9 100644 --- a/test/map-drag-browser.mjs +++ b/test/map-drag-browser.mjs @@ -38,6 +38,9 @@ try { }); const errors = []; page.on("pageerror", (e) => errors.push(e.message)); + await page.addInitScript(() => + localStorage.setItem("vanuatu-map-view", "2d"), + ); await page.goto(base + "/?new&hotseat"); await page.waitForFunction(() => window.vanuatuDemo); const state = E.init(3, [], {}, "mouse-pan"); @@ -156,15 +159,13 @@ try { await page.evaluate((type) => { if (type === "blur") window.dispatchEvent(new Event("blur")); else - document - .querySelector(".map-scroll") - .dispatchEvent( - new PointerEvent(type, { - bubbles: true, - pointerId: window.lastPointer, - pointerType: "mouse", - }), - ); + document.querySelector(".map-scroll").dispatchEvent( + new PointerEvent(type, { + bubbles: true, + pointerId: window.lastPointer, + pointerType: "mouse", + }), + ); }, cancel); await page.mouse.up(); assert.equal(await map.getAttribute("data-pan"), "ready"); diff --git a/test/map-zoom-browser.mjs b/test/map-zoom-browser.mjs index 23f8260..5701c7a 100644 --- a/test/map-zoom-browser.mjs +++ b/test/map-zoom-browser.mjs @@ -98,6 +98,9 @@ try { const page = await browser.newPage({ viewport: { width, height } }); page.on("pageerror", (error) => errors.push(error.message)); for (const state of [E.init(3, [], {}, "map-fit"), partial, expanded]) { + await page.addInitScript(() => + localStorage.setItem("vanuatu-map-view", "2d"), + ); await page.goto(base + "/?hotseat"); await page.evaluate( (s) => localStorage.setItem("vanuatu-practice-v1", JSON.stringify(s)), @@ -230,6 +233,9 @@ try { viewport: { width: 390, height: 844 }, }); resizedPage.on("pageerror", (error) => errors.push(error.message)); + await resizedPage.addInitScript(() => + localStorage.setItem("vanuatu-map-view", "2d"), + ); await resizedPage.goto(base + "/?hotseat"); await resizedPage.evaluate( (s) => localStorage.setItem("vanuatu-practice-v1", JSON.stringify(s)), @@ -264,6 +270,9 @@ try { hasTouch: true, }); page.on("pageerror", (error) => errors.push(error.message)); + await page.addInitScript(() => + localStorage.setItem("vanuatu-map-view", "2d"), + ); await page.goto(base + "/?new&hotseat&locale=fr"); await page.waitForSelector(".map-scroll[data-zoom]"); assert.equal( diff --git a/test/mobile-layout-browser.mjs b/test/mobile-layout-browser.mjs index e4bddf1..6b6dc18 100644 --- a/test/mobile-layout-browser.mjs +++ b/test/mobile-layout-browser.mjs @@ -43,6 +43,9 @@ try { }); page.on("pageerror", (error) => errors.push(error.message)); for (const count of [2, 3, 5]) { + await page.addInitScript(() => + localStorage.setItem("vanuatu-map-view", "2d"), + ); await page.goto(`${base}/?new&hotseat&players=${count}&locale=fr`); await page.waitForFunction(() => window.vanuatuDemo); await page.evaluate(() => { diff --git a/test/navigation.test.js b/test/navigation.test.js new file mode 100644 index 0000000..217bef0 --- /dev/null +++ b/test/navigation.test.js @@ -0,0 +1,145 @@ +import assert from "node:assert/strict"; +import { + seaRoute, + routePosition, + giveWay, + passingSide, + arrivalFraction, + stepYield, +} from "../viewer/three/navigation.js"; +import * as engine from "../engine/index.js"; +const opening = engine.init(3, [], {}, "navigation"); +const expanded = structuredClone(opening); +for (const cell of ["2,0", "2,1", "2,2", "1,2", "0,2", "-1,1", "-1,0"]) + expanded.board[cell] = engine.tileState("c1"); +const scenes = { opening, expanded }; +const tilt = Math.PI / 9; +function position(id) { + const [q, r] = id.split(",").map(Number), + x = q * 162 - r * 81, + z = r * 140.3; + return { + x: (x * Math.cos(tilt) - z * Math.sin(tilt)) / 60, + z: (x * Math.sin(tilt) + z * Math.cos(tilt)) / 60, + }; +} +let checks = 0; +for (const state of Object.values(scenes)) { + const seas = Object.keys(state.board).filter( + (id) => state.board[id].type === "sea", + ); + for (const from of seas) + for (const to of seas) { + if (from === to) continue; + for (let count = 1; count <= 3; count++) { + const a = position(from), + b = position(to), + start = { x: a.x, z: a.z - 0.15 }, + end = { x: b.x + (count - 1) * 0.47, z: b.z - 0.15 }; + const path = seaRoute(state.board, from, to, start, end, position); + assert.ok( + path.length >= 2, + "Every sea destination has an animation even when crowded", + ); + assert.deepEqual(routePosition(path, 0), start); + assert.deepEqual(routePosition(path, 1), end); + for (let i = 0; i <= 100; i++) { + const p = routePosition(path, i / 100); + assert.ok(Number.isFinite(p.x) && Number.isFinite(p.z)); + } + checks++; + } + } +} +const path = [ + { x: 0, z: 0 }, + { x: 5, z: 0 }, + ], + near = { x: 2.5, z: 0.2 }; +const boat = { minX: -0.28, maxX: 0.46, minZ: -0.52, maxZ: 0.3 }; +const fish = { minX: -0.43, maxX: 0.43, minZ: -0.26, maxZ: 0.26 }; +const side = passingSide(path, near, 0); +const offset = giveWay( + near, + { x: 2.5, z: 0 }, + { x: 1, z: 0 }, + side, + boat, + fish, +); +assert.ok( + near.z + offset.z + fish.minZ > boat.maxZ, + "An intersecting fish moves far enough aside", +); +assert.deepEqual( + giveWay(near, { x: 5, z: 0 }, { x: 1, z: 0 }, side, boat, fish), + { x: 0, z: 0 }, + "It returns after the boat passes", +); +for (const direction of [ + { x: 1, z: 0 }, + { x: 0, z: 1 }, + { x: 1, z: 1 }, + { x: -1, z: 1 }, +]) { + for (const sign of [-1, 1]) { + for (const point of [ + { x: 0, z: -10 }, + { x: 0, z: 10 }, + { x: -10, z: 0 }, + { x: 10, z: 0 }, + { x: 2.7, z: 0 }, + ]) { + assert.deepEqual( + giveWay(point, { x: 0, z: 0 }, direction, sign, boat, fish), + { x: 0, z: 0 }, + "Remote and neighbouring-tile resources stay still, even on the opposite side of the route", + ); + } + } +} +assert.equal( + arrivalFraction(6), + 0, + "No destination rearrangement at departure", +); +assert.equal( + arrivalFraction(1.1), + 0, + "Wait until the boat is actually approaching its berth", +); +assert.ok( + arrivalFraction(0.6) > 0 && arrivalFraction(0.6) < 1, + "Rearrange progressively on approach", +); +assert.equal(arrivalFraction(0), 1, "Berths settle completely on arrival"); +console.log( + `${checks} routes checked; local contact only, remote pieces stay still, destination waits for arrival.`, +); + +const pose = { x: 0, z: 0, yaw: 0, vx: 0, vz: 0, vyaw: 0 }; +let previous = 0; +for (let i = 0; i < 40; i++) { + stepYield(pose, { x: 0.5, z: 0, yaw: 0.2 }, 1 / 60); + assert.ok( + pose.x >= previous && pose.x <= 0.5, + "Yielding approaches its target without reversing or overshooting", + ); + previous = pose.x; +} +assert.ok(pose.yaw > 0.19, "The piece pivots while giving way"); +for (let i = 0; i < 60; i++) { + stepYield(pose, { x: 0, z: 0, yaw: 0 }, 1 / 60); + assert.ok( + pose.x >= 0 && pose.x <= previous, + "Returning home never overshoots or oscillates", + ); + previous = pose.x; +} +assert.ok( + Math.hypot(pose.x, pose.z, pose.yaw) < 0.0001, + "Position and orientation settle completely", +); +console.log( + "Yielding: gradual pivot, damped slide, no oscillation and complete restoration passed.", +); diff --git a/test/persian-browser.mjs b/test/persian-browser.mjs index 2cb087e..ad05c27 100644 --- a/test/persian-browser.mjs +++ b/test/persian-browser.mjs @@ -36,6 +36,9 @@ try { p.setDefaultTimeout(5000); const errors = []; p.on("pageerror", (e) => errors.push(e.message)); + await p.addInitScript(() => + localStorage.setItem("vanuatu-map-view", "2d"), + ); await p.goto(`http://127.0.0.1:${server.address().port}/`); await p.evaluate(async (id) => { window.progress = null; @@ -139,6 +142,7 @@ try { const p = await browser.newPage({ viewport: { width, height: 1000 } }); const errors = []; p.on("pageerror", (error) => errors.push(error.message)); + await p.addInitScript(() => localStorage.setItem("vanuatu-map-view", "2d")); await p.goto(`http://127.0.0.1:${server.address().port}/`); const state = init(3, [], {}, "persian-switch"); state.players[0].name = "Draw"; diff --git a/test/presentation-transitions.test.js b/test/presentation-transitions.test.js new file mode 100644 index 0000000..957eb4a --- /dev/null +++ b/test/presentation-transitions.test.js @@ -0,0 +1,157 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import * as engine from "../engine/index.js"; +import { tradeFrames } from "../viewer/trade-transition.js"; +import { eventCells, journalRows } from "../viewer/journal.js"; +import { goodsSlots } from "../viewer/goods-slots.js"; + +function lastExport() { + const s = engine.init(3, [], {}, "smooth-transitions"); + s.phase = "actions"; + s.actor = s.first = 0; + s.players.forEach((p) => { + p.character = null; + p.markers = Object.fromEntries(engine.ACTIONS.map((a) => [a, 0])); + }); + s.players[0].markers.buy = 1; + s.players[0].money = 3; + s.players[0].boat = "1,0"; + s.board["0,0"].goods = { kava: 0, copra: 0, beef: 1 }; + s.demands[0] = { + id: 101, + goods: ["kava", "copra", "beef"], + filled: [true, true, false], + }; + return s; +} +function exportLast(s) { + return engine.move( + s, + engine + .availableMoves(s) + .find( + (m) => + m.type === "act" && + m.action === "buy" && + m.good === "beef" && + !m.bonus, + ), + 0, + ); +} + +test("last export keeps the completed ship available for presentation after the next round starts", () => { + const before = lastExport(), + unchanged = structuredClone(before), + after = exportLast(before); + assert.equal(after.round, 2); + const events = after.events.slice(before.events.length), + frames = tradeFrames(before, after, events); + assert.deepEqual(frames.departing, [101]); + assert.deepEqual(frames.initial[0].filled, [true, true, false]); + assert.deepEqual(frames.delivered[0].filled, [true, true, true]); + assert.ok(!after.demands.some((d) => d.id === 101)); + assert.deepEqual( + before, + unchanged, + "presentation never mutates the engine state", + ); + assert.equal( + tradeFrames(before, after, []), + null, + "loading or replaying does not animate", + ); +}); +test("a Buyer delivering twice fills distinct slots in order", () => { + const before = { + demands: [{ id: 1, goods: ["kava", "kava"], filled: [false, false] }], + }, + after = structuredClone(before); + const frame = tradeFrames(before, after, [ + { + good: "kava", + details: { shipments: [{ ship: 1 }, { ship: 1, complete: true }] }, + }, + ]); + assert.deepEqual(frame.delivered[0].filled, [true, true]); + assert.deepEqual(frame.completed, [1]); +}); +test("only fully empty islands refill, and each refill is logged with exact goods", () => { + const s = lastExport(); + s.board["2,1"] = engine.tileState("a1"); + s.board["2,1"].goods = { kava: 1, copra: 0, beef: 0 }; + const after = exportLast(s), + round = after.events.findLast((e) => e.type === "round"); + assert.deepEqual(round.refills, [ + { cell: "0,0", goods: engine.TILES.efate.goods }, + ]); + assert.deepEqual(after.board["2,1"].goods, s.board["2,1"].goods); + const rows = journalRows(engine.stripSecret(after, 0)).filter( + (r) => r.event?.type === "restock", + ); + assert.deepEqual( + rows.map((r) => [r.event.cell, r.event.goods]), + [["0,0", engine.TILES.efate.goods]], + ); +}); +test("older complete journals reconstruct refill locations without guessing from current stock", () => { + const s = engine.init(3, [], {}, "legacy-refill"); + s.events = [ + { type: "start", round: 1, p: 0 }, + ...["kava", "copra", "beef"].map((good) => ({ + type: "action", + action: "buy", + cell: "0,0", + p: 0, + round: 1, + good, + })), + { type: "round", round: 2, first: 0 }, + ]; + const before = structuredClone(s); + const rows = journalRows(s).filter((r) => r.event?.type === "restock"); + assert.deepEqual( + rows.map((r) => r.event.cell), + ["0,0"], + ); + assert.deepEqual(rows[0].event.goods, engine.TILES.efate.goods); + assert.deepEqual(s, before); + const incomplete = { ...s, events: s.events.slice(1) }; + assert.equal( + journalRows(incomplete).filter((r) => r.event?.type === "restock").length, + 0, + ); +}); +test("journal highlights the actual route and affected tile, never malformed coordinates", () => { + assert.deepEqual( + eventCells({ path: ["1,0", "2,0"], details: { from: "0,0", cell: "2,0" } }), + ["0,0", "1,0", "2,0"], + ); + assert.deepEqual(eventCells({ type: "restock", cell: "-1,0" }), ["-1,0"]); + assert.deepEqual(eventCells({ cell: "`; + const server = createServer(async (req, res) => { + try { + const url = new URL(req.url, "http://local"); + if (url.pathname === "/qa/hosted.html") { + res.setHeader("Content-Type", "text/html"); + return res.end(html); + } + const base = resolve( + url.pathname.startsWith("/qa/") ? ".local/qa" : "dist", + ); + const name = url.pathname.startsWith("/qa/") + ? url.pathname.slice(3) + : url.pathname === "/" + ? "/index.html" + : url.pathname; + const file = resolve(base, "." + name); + if (!file.startsWith(base + "/")) throw Error("Invalid path"); + res.setHeader( + "Content-Type", + { + ".js": "text/javascript", + ".css": "text/css", + ".html": "text/html", + ".json": "application/json", + ".webp": "image/webp", + }[extname(file)] ?? "application/octet-stream", + ); + res.setHeader("Cache-Control", "no-store"); + res.end(await readFile(file)); + } catch { + res.writeHead(404); + res.end("Not found"); + } + }); + await new Promise((resolve) => server.listen(port, "127.0.0.1", resolve)); + return { server, base: `http://127.0.0.1:${server.address().port}` }; +} diff --git a/test/three-viewer-harness.js b/test/three-viewer-harness.js new file mode 100644 index 0000000..128abb1 --- /dev/null +++ b/test/three-viewer-harness.js @@ -0,0 +1,106 @@ +import * as engine from "../engine/index.js"; + +let host, + state, + preferences = { locale: "fr", sound: false, mapView: "3d" }, + updates = []; +const root = document.querySelector("#game"), + status = document.querySelector("#status"); +const params = new URLSearchParams(location.search); +if (params.has("saved")) + preferences = + JSON.parse(localStorage.getItem("qa-bgs-preferences")) ?? preferences; +function fixture() { + const s = engine.init(3, [], {}, "hosted-3d-release"); + s.phase = "actions"; + s.actor = s.first = 0; + s.players.forEach((p) => { + p.character = null; + p.markers = Object.fromEntries(engine.ACTIONS.map((a) => [a, 0])); + }); + s.players[0].markers.buy = 1; + s.players[0].money = 3; + s.players[0].boat = "1,0"; + s.board["0,0"].goods = { kava: 0, copra: 0, beef: 1 }; + s.demands[0] = { + id: 101, + goods: ["kava", "copra", "beef"], + filled: [true, true, false], + }; + return s; +} +function report() { + status.textContent = JSON.stringify({ + preferences, + updates, + round: state.round, + phase: state.phase, + }); +} +function show() { + host.emit("state", engine.stripSecret(state, 0)); + report(); +} +function launch() { + host = window.vanuatu.launch("#game"); + host.on("update:preference", (value) => { + updates.push(value); + preferences = { ...preferences, [value.name]: value.value }; + localStorage.setItem("qa-bgs-preferences", JSON.stringify(preferences)); + host.emit("preferences", preferences); + report(); + }); + host.on("move", (move) => { + state = engine.move(state, move, 0); + show(); + }); + host.emit("player", { index: 0 }); + host.emit("preferences", preferences); + show(); +} +document.querySelector("[data-reset]").onclick = () => { + state = fixture(); + show(); +}; +document.querySelector("[data-export]").onclick = () => { + const move = engine + .availableMoves(state) + .find( + (m) => + m.type === "act" && m.action === "buy" && m.good === "beef" && !m.bonus, + ); + if (move) { + state = engine.move(state, move, 0); + show(); + } +}; +document.querySelector("[data-remote]").onclick = () => { + preferences = { + ...preferences, + mapView: preferences.mapView === "3d" ? "2d" : "3d", + }; + host.emit("preferences", preferences); + report(); +}; +document.querySelector("[data-german]").onclick = () => { + preferences = { ...preferences, locale: "de" }; + host.emit("preferences", preferences); + report(); +}; +document.querySelector("[data-place]").onclick = () => { + const move = engine.availableMoves(state).find((m) => m.type === "place"); + if (move) { + state = engine.move(state, move, state.actor); + show(); + } +}; +if (params.has("no-webgl")) { + const getContext = HTMLCanvasElement.prototype.getContext; + HTMLCanvasElement.prototype.getContext = function (kind, ...args) { + return kind.startsWith("webgl") + ? null + : getContext.call(this, kind, ...args); + }; +} +state = fixture(); +launch(); diff --git a/test/tutorial-browser.mjs b/test/tutorial-browser.mjs index 7f364b4..6bdc9c8 100644 --- a/test/tutorial-browser.mjs +++ b/test/tutorial-browser.mjs @@ -35,6 +35,9 @@ try { errors.push(e.message); console.error(e.message); }); + await page.addInitScript(() => + localStorage.setItem("vanuatu-map-view", "2d"), + ); await page.goto(`http://127.0.0.1:${server.address().port}/`); await page.evaluate(async () => { window.progress = null; @@ -113,6 +116,9 @@ try { ["nl", "Varen", "Als je bij geen enkele actie de meerderheid hebt"], ]) { const page = await browser.newPage(); + await page.addInitScript(() => + localStorage.setItem("vanuatu-map-view", "2d"), + ); await page.goto(`http://127.0.0.1:${server.address().port}/`); await page.evaluate(async (locale) => { await window.vanuatu.launchTutorial("#game", { @@ -168,6 +174,9 @@ try { }); }, locale); }; + await page.addInitScript(() => + localStorage.setItem("vanuatu-map-view", "2d"), + ); await page.goto(`http://127.0.0.1:${server.address().port}/`); await launch(); assert.equal(await page.locator(".fish-price b").innerText(), "3"); @@ -246,6 +255,9 @@ try { const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, }); + await page.addInitScript(() => + localStorage.setItem("vanuatu-map-view", "2d"), + ); await page.goto(`http://127.0.0.1:${server.address().port}/`); await page.evaluate( async (entries) => { diff --git a/test/tutorial-errors-browser.mjs b/test/tutorial-errors-browser.mjs index b23f623..392ba45 100644 --- a/test/tutorial-errors-browser.mjs +++ b/test/tutorial-errors-browser.mjs @@ -41,6 +41,9 @@ try { const page = await browser.newPage({ viewport: { width, height: 844 } }); const errors = []; page.on("pageerror", (e) => errors.push(e.message)); + await page.addInitScript(() => + localStorage.setItem("vanuatu-map-view", "2d"), + ); await page.goto(`${base}/?lesson=full-round&locale=${locale}`); const guide = page.locator(".vanuatu-tutorial"); const instruction = guide.locator(".bgs-tutorial-body > p").first(); diff --git a/test/tutorial-walkthrough-browser.mjs b/test/tutorial-walkthrough-browser.mjs index 3269041..8138ed6 100644 --- a/test/tutorial-walkthrough-browser.mjs +++ b/test/tutorial-walkthrough-browser.mjs @@ -36,6 +36,9 @@ try { p.setDefaultTimeout(5000); const errors = []; p.on("pageerror", (e) => errors.push(e.message)); + await p.addInitScript(() => + localStorage.setItem("vanuatu-map-view", "2d"), + ); await p.goto(`http://127.0.0.1:${server.address().port}/`); await p.evaluate(async (id) => { window.progress = null; diff --git a/test/undo-browser.mjs b/test/undo-browser.mjs index 5b31338..20abc9e 100644 --- a/test/undo-browser.mjs +++ b/test/undo-browser.mjs @@ -37,6 +37,7 @@ const browser = await chromium.launch({ const errors = []; const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); page.on("pageerror", (e) => errors.push(e.message)); +await page.addInitScript(() => localStorage.setItem("vanuatu-map-view", "2d")); await page.goto(`http://127.0.0.1:${server.address().port}/?new&hotseat`); await page.waitForSelector("[data-character-choice]"); diff --git a/test/zh-cn-browser.mjs b/test/zh-cn-browser.mjs index 26e9e8e..e339d08 100644 --- a/test/zh-cn-browser.mjs +++ b/test/zh-cn-browser.mjs @@ -36,6 +36,9 @@ try { p.setDefaultTimeout(5000); const errors = []; p.on("pageerror", (e) => errors.push(e.message)); + await p.addInitScript(() => + localStorage.setItem("vanuatu-map-view", "2d"), + ); await p.goto(`http://127.0.0.1:${server.address().port}/`); await p.evaluate(async (id) => { window.progress = null; @@ -139,6 +142,7 @@ try { const p = await browser.newPage({ viewport: { width, height: 1000 } }); const errors = []; p.on("pageerror", (error) => errors.push(error.message)); + await p.addInitScript(() => localStorage.setItem("vanuatu-map-view", "2d")); await p.goto(`http://127.0.0.1:${server.address().port}/`); const state = init(3, [], {}, "zh-cn-switch"); state.players[0].name = "Draw"; diff --git a/viewer/activity.js b/viewer/activity.js index 57600a6..96e71d0 100644 --- a/viewer/activity.js +++ b/viewer/activity.js @@ -12,11 +12,18 @@ import { esc, } from "./art.js"; import { translator } from "./labels.js"; -import { journalRows } from "./journal.js"; +import { journalRows, eventCells } from "./journal.js"; import { ACTIONS, CHARACTERS, COLORS } from "../engine/catalog.js"; export function mountActivity( target, - { chat, openPlayer, avatarForPlayer, onBack, language = "en" } = {}, + { + chat, + openPlayer, + avatarForPlayer, + onBack, + onHighlight, + language = "en", + } = {}, ) { let colorBlind = false, lang = language; @@ -166,6 +173,17 @@ export function mountActivity( function eventHtml(e) { const d = e.details ?? {}; switch (e.type) { + case "restock": + return ( + heading(e, text("Goods replenished"), "buy") + + details( + Object.entries(e.goods) + .filter(([, n]) => n > 0) + .map(([good, n]) => gain(good, n)) + .join(""), + ) + + location(e.cell) + ); case "touristDraw": return ( heading(e, text("Tourist tile")) + @@ -367,8 +385,12 @@ export function mountActivity( return `
  • ${symbol ? icon(symbol) : ""}${text(label)}${row.pass ? `${row.pass}/3` : ""}
  • `; } const html = eventHtml(row.event); + const cells = eventCells(row.event); + const button = cells.length + ? `` + : html; return html - ? `
  • ${html}
  • ` + ? `
  • ${button}
  • ` : ""; } function refresh() { @@ -395,6 +417,83 @@ export function mountActivity( if (following) list.scrollTop = list.scrollHeight; }); } + const interactions = new AbortController(), + listener = { signal: interactions.signal }; + let pinned, hovered, focused; + function highlight() { + const row = hovered ?? focused ?? pinned; + for (const button of list.querySelectorAll("[data-journal-cells]")) { + button.classList.toggle("inspected", button === row); + button.setAttribute("aria-pressed", String(button === pinned)); + } + onHighlight?.(row?.dataset.journalCells.split(" ") ?? []); + } + function clearHighlight() { + pinned = hovered = focused = null; + highlight(); + } + list.addEventListener( + "pointerover", + (e) => { + if (e.pointerType === "touch") return; + const row = e.target.closest("[data-journal-cells]"); + if (row !== hovered) { + hovered = row; + highlight(); + } + }, + listener, + ); + list.addEventListener( + "pointerleave", + () => { + hovered = null; + highlight(); + }, + listener, + ); + list.addEventListener( + "focusin", + (e) => { + focused = e.target.closest("[data-journal-cells]"); + highlight(); + }, + listener, + ); + list.addEventListener( + "focusout", + () => { + focused = null; + highlight(); + }, + listener, + ); + list.addEventListener( + "click", + (e) => { + const row = e.target.closest("[data-journal-cells]"); + if (!row) return; + pinned = pinned === row ? null : row; + hovered = focused = null; + highlight(); + if (pinned) onBack?.(); + }, + listener, + ); + document.addEventListener( + "pointerdown", + (e) => { + if (pinned && !e.target.closest("[data-journal-cells]")) clearHighlight(); + }, + listener, + ); + document.addEventListener( + "keydown", + (e) => { + if (e.key === "Escape") clearHighlight(); + }, + listener, + ); root.addEventListener("click", (e) => { const b = e.target.closest("button"); if (!b) return; @@ -410,6 +509,7 @@ export function mountActivity( open, update(s, isAnalysis, isColorBlind = false) { colorBlind = isColorBlind; + if (state && s.historyLength < state.historyLength) clearHighlight(); state = s; const changed = analysis !== isAnalysis; analysis = isAnalysis; @@ -443,6 +543,7 @@ export function mountActivity( refresh(); }, destroy() { + interactions.abort(); cancelAnimationFrame(followFrame); wide.removeEventListener("change", resize); view?.destroy(); diff --git a/viewer/board.js b/viewer/board.js index 1edd33a..4215ea0 100644 --- a/viewer/board.js +++ b/viewer/board.js @@ -1,3 +1,4 @@ +import { goodsSlots } from "./goods-slots.js"; import { playerSymbolGlyph } from "@boardgamers/protocol/player-symbols"; import { boardCells, tileState, TILES, COLORS } from "../engine/catalog.js"; import { esc, svgIcon, iconLabel } from "./art.js"; @@ -143,22 +144,16 @@ export function boardSvg( })), ); } else { - const goods = Object.entries(tile.goods).filter(([, n]) => n > 0); + const slots = goodsSlots(tile); svg += ''; - let j = 0; - for (const [good, n] of goods) - for (let k = 0; k < n; k++, j++) - svg += svgIcon( - good, - c.x - - goods.reduce((sum, [, count]) => sum + count, 0) * 14 + - j * 28, - c.y + 34, - 29, - "currentColor", - `${label(good)} · ${"available to export"}`, - colorBlind, - ); + for (const [j, { good, filled }] of slots.entries()) { + const x = c.x - slots.length * 14 + j * 28, + y = c.y + 34; + const help = `${label(good)} · ${filled ? "available to export" : "Empty goods space"}`; + svg += `${esc(help)}`; + svg += svgIcon(good, x, y, 29, "currentColor", help, colorBlind); + svg += ""; + } svg += ""; const huts = tile.huts; for (let i = 0; i < spec.huts; i++) { diff --git a/viewer/effects.js b/viewer/effects.js index efb5baf..87afae0 100644 --- a/viewer/effects.js +++ b/viewer/effects.js @@ -80,11 +80,17 @@ export function createEffects(root, { icon, sound, center }) { root.append(layer); const animations = new Set(); let frame = 0, - enabled = true; + enabled = true, + ready = Promise.resolve(), + resolveReady; const allowed = () => enabled && !motion.matches && !doc.hidden; const query = (selector) => root.querySelector(selector); const point = (element) => { - if (!element) return null; + if ( + !element || + (root.dataset.mapView === "3d" && element.closest(".map-scroll")) + ) + return null; const r = element.getBoundingClientRect(); if ( !r.width || @@ -121,6 +127,8 @@ export function createEffects(root, { icon, sound, center }) { for (const animation of animations) animation.cancel(); animations.clear(); layer.replaceChildren(); + resolveReady?.(); + resolveReady = null; } function animate( node, @@ -142,6 +150,10 @@ export function createEffects(root, { icon, sound, center }) { const finish = () => { animations.delete(animation); if (remove) node.remove(); + if (!animations.size && !frame) { + resolveReady?.(); + resolveReady = null; + } }; animation.onfinish = () => { animation.cancel(); @@ -237,16 +249,22 @@ export function createEffects(root, { icon, sound, center }) { cancel(); if (doc.hidden) return; const cue = soundFor(events); - if (cue) void sound.play(cue); + if (cue && !(cue === "sail" && root.dataset.mapView === "3d")) + void sound.play(cue); if (!allowed()) return; // Pending controls and dialog closure can render again in the same turn. // Position effects once, after that work, without a per-frame layout loop. + ready = new Promise((resolve) => (resolveReady = resolve)); frame = view.requestAnimationFrame(() => { frame = 0; if (!allowed()) return; for (const event of events) { const p = event.p; const d = event.details ?? {}; + if (event.type === "place" && root.dataset.mapView !== "3d") { + const placed = query(`.map-cell[data-cell="${event.cell}"]`); + if (placed) animate(placed, [{ opacity: 0 }, { opacity: 1 }], 650); + } if (["plan", "neutral"].includes(event.type)) { for (const action of new Set(event.actions)) drop( @@ -316,7 +334,6 @@ export function createEffects(root, { icon, sound, center }) { for (const shipment of d.shipments ?? []) { const ship = query(`[data-ship="${shipment.ship}"]`); fly(icon(event.good), source, point(ship)); - if (shipment.complete) pulse(ship); } const changes = rewards(event); if (changes.length) @@ -328,7 +345,7 @@ export function createEffects(root, { icon, sound, center }) { `${value > 0 ? "+" : "−"}${Math.abs(value)}${icon(name)}`, ) .join(""), - event.action === "sail" ? 500 : 130, + ["sail", "buy"].includes(event.action) ? 500 : 130, ); if (event.type === "conversion") gain( @@ -357,6 +374,10 @@ export function createEffects(root, { icon, sound, center }) { ) pulse(query(`[data-action="${action}"]`)); } + if (!animations.size) { + resolveReady?.(); + resolveReady = null; + } }); } // Cancel overlays on scrolling instead of tracking layout on every frame. @@ -377,6 +398,7 @@ export function createEffects(root, { icon, sound, center }) { motion.addEventListener("change", cancel); return { capture, + whenIdle: () => ready, show, cancel, drop, diff --git a/viewer/goods-slots.js b/viewer/goods-slots.js new file mode 100644 index 0000000..f5f543f --- /dev/null +++ b/viewer/goods-slots.js @@ -0,0 +1,11 @@ +import { TILES } from "../engine/catalog.js"; +// The original assortment defines stable positions, including bought cubes. +export function goodsSlots(tile) { + if (tile.type !== "island" || tile.submerged) return []; + return Object.entries(TILES[tile.id].goods).flatMap(([good, count]) => + Array.from({ length: count }, (_, i) => ({ + good, + filled: i < (tile.goods[good] ?? 0), + })), + ); +} diff --git a/viewer/journal.js b/viewer/journal.js index acbde4c..bfe681a 100644 --- a/viewer/journal.js +++ b/viewer/journal.js @@ -7,6 +7,17 @@ const total = (values) => values.reduce((a, b) => a + b, 0); // Old saves contain the moves, but not their outcomes. Reconstruct only public, // deterministic information. In particular, never guess old trade-ship bonuses // or use today's character, fish price or board contents for an earlier action. +export function eventCells(event) { + const d = event.details ?? {}; + return [ + ...new Set( + [d.from, ...(event.path ?? []), d.cell, event.cell].filter( + (cell) => typeof cell === "string" && /^-?\d+,-?\d+$/.test(cell), + ), + ), + ]; +} + export function journalRows(state) { const events = state.events ?? state.lastEvents ?? []; const completeHistory = events[0]?.type === "start"; @@ -52,6 +63,36 @@ export function journalRows(state) { tourists: e.tourists, }, }); + if (e.type === "round") { + const refills = + e.refills ?? + (completeHistory + ? Object.entries(board) + .filter( + ([, tile]) => + tile.type === "island" && + !tile.submerged && + Object.values(tile.goods).every((n) => n === 0), + ) + .map(([cell, tile]) => ({ + cell, + goods: { ...tileState(tile.id).goods }, + })) + : []); + for (const refill of refills) { + if (board[refill.cell]) + board[refill.cell].goods = { ...refill.goods }; + rows.push({ + kind: "event", + event: { + type: "restock", + round: e.round, + cell: refill.cell, + goods: refill.goods, + }, + }); + } + } continue; } const player = players[e.p]; @@ -108,6 +149,7 @@ export function journalRows(state) { fallback.income = total(e.fish) * context.market; } } + if (e.action === "sell" && completeHistory) fallback.cell = player.boat; e.details = { ...fallback, ...e.details }; const tile = board[e.cell ?? player.boat]; if (e.action === "sail") player.boat = e.path.at(-1); @@ -118,6 +160,8 @@ export function journalRows(state) { if (e.action === "explore") tile.treasure--; if (e.action === "build" && e.hut) tile.huts.push(e.p); if (e.action === "draw") tile.drawings++; + if (e.action === "buy") + tile.goods[e.good] = Math.max(0, (tile.goods[e.good] ?? 0) - 1); } player.markers[e.action] = 0; } @@ -131,6 +175,8 @@ export function journalRows(state) { player.markers[e.from] = 0; } if (e.type === "submerged" && board[e.cell]) { + board[e.cell].submerged = true; + board[e.cell].goods = {}; board[e.cell].huts = []; board[e.cell].drawings = 0; } diff --git a/viewer/learning.js b/viewer/learning.js index 5bb528d..ab90525 100644 --- a/viewer/learning.js +++ b/viewer/learning.js @@ -24,3 +24,6 @@ export const EXTEND_RULE = export const EXPORT_RULE = "The coloured cubes on islands are goods. Buy one beside your boat and send it straight to the first ship that needs it. Pay vatus; gain prosperity. No hut or cargo space is needed."; + +export const REFILL_RULE = + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished."; diff --git a/viewer/localization/da.json b/viewer/localization/da.json index 336c93e..e7bf3f9 100644 --- a/viewer/localization/da.json +++ b/viewer/localization/da.json @@ -948,5 +948,8 @@ "Wait for your turn.": "Vent på din tur.", "Choose an action to take back its markers without acting.": "Vælg en handling, hvis markører du tager tilbage uden at handle.", "Undo my move": "Fortryd mit træk", - "Automatically retrieve markers when there is no choice": "Tag automatisk markører tilbage, når der ikke er noget valg" + "Automatically retrieve markers when there is no choice": "Tag automatisk markører tilbage, når der ikke er noget valg", + "Goods replenished": "Varer genopfyldt", + "Empty goods space": "Tom vareplads", + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "Ved begyndelsen af hver runde udskiftes fyldte skibe. En ø uden varer får sit oprindelige udvalg igen. Hvis blot én terning er tilbage, genopfyldes intet." } diff --git a/viewer/localization/de.json b/viewer/localization/de.json index 3d8da9f..fb9bb35 100644 --- a/viewer/localization/de.json +++ b/viewer/localization/de.json @@ -948,5 +948,8 @@ "Wait for your turn.": "Warte, bis du am Zug bist.", "Choose an action to take back its markers without acting.": "Wähle eine Aktion, deren Marker du ohne Aktion zurücknimmst.", "Undo my move": "Zug zurücknehmen", - "Automatically retrieve markers when there is no choice": "Marker automatisch zurücknehmen, wenn es keine Wahl gibt" + "Automatically retrieve markers when there is no choice": "Marker automatisch zurücknehmen, wenn es keine Wahl gibt", + "Goods replenished": "Waren aufgefüllt", + "Empty goods space": "Leerer Warenplatz", + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "Zu Beginn jeder Runde werden volle Schiffe ersetzt. Eine Insel ohne Waren erhält ihren ursprünglichen Warenbestand zurück. Solange auch nur ein Würfel übrig ist, wird nichts aufgefüllt." } diff --git a/viewer/localization/el.json b/viewer/localization/el.json index 11c3a7c..397706f 100644 --- a/viewer/localization/el.json +++ b/viewer/localization/el.json @@ -948,5 +948,8 @@ "Wait for your turn.": "Περιμένετε τη σειρά σας.", "Choose an action to take back its markers without acting.": "Επίλεξε μια ενέργεια για να πάρεις πίσω τους δείκτες της χωρίς να την εκτελέσεις.", "Undo my move": "Αναίρεση κίνησης", - "Automatically retrieve markers when there is no choice": "Αυτόματη ανάκτηση δεικτών όταν δεν υπάρχει επιλογή" + "Automatically retrieve markers when there is no choice": "Αυτόματη ανάκτηση δεικτών όταν δεν υπάρχει επιλογή", + "Goods replenished": "Αναπλήρωση αγαθών", + "Empty goods space": "Κενή θέση αγαθού", + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "Στην αρχή κάθε γύρου, τα γεμάτα πλοία αντικαθίστανται. Ένα νησί χωρίς κανένα αγαθό λαμβάνει ξανά την αρχική του συλλογή. Αν απομένει έστω ένας κύβος, δεν αναπληρώνεται τίποτα." } diff --git a/viewer/localization/en.json b/viewer/localization/en.json index 4e8188c..aee4ab2 100644 --- a/viewer/localization/en.json +++ b/viewer/localization/en.json @@ -948,5 +948,8 @@ "Wait for your turn.": "Wait for your turn.", "Choose an action to take back its markers without acting.": "Choose an action to take back its markers without acting.", "Undo my move": "Undo my move", - "Automatically retrieve markers when there is no choice": "Automatically retrieve markers when there is no choice" + "Automatically retrieve markers when there is no choice": "Automatically retrieve markers when there is no choice", + "Goods replenished": "Goods replenished", + "Empty goods space": "Empty goods space", + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished." } diff --git a/viewer/localization/fa.json b/viewer/localization/fa.json index a9e418d..170b7ed 100644 --- a/viewer/localization/fa.json +++ b/viewer/localization/fa.json @@ -948,5 +948,8 @@ "Wait for your turn.": "منتظر نوبت خود باشید.", "Choose an action to take back its markers without acting.": "اقدامی را انتخاب کنید تا مهره‌هایش را بدون انجام آن پس بگیرید.", "Undo my move": "بازگرداندن حرکت", - "Automatically retrieve markers when there is no choice": "پس‌گرفتن خودکار نشانگرها وقتی انتخابی وجود ندارد" + "Automatically retrieve markers when there is no choice": "پس‌گرفتن خودکار نشانگرها وقتی انتخابی وجود ندارد", + "Goods replenished": "کالاها دوباره تأمین شدند", + "Empty goods space": "جای خالی کالا", + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "در آغاز هر دور، کشتی‌های تکمیل‌شده جایگزین می‌شوند. جزیره‌ای که هیچ کالایی در آن نمانده، دوباره مجموعهٔ اولیهٔ کالاهایش را دریافت می‌کند. اگر حتی یک مکعب باقی مانده باشد، هیچ کالایی اضافه نمی‌شود." } diff --git a/viewer/localization/fr.json b/viewer/localization/fr.json index ef88a37..35c2302 100644 --- a/viewer/localization/fr.json +++ b/viewer/localization/fr.json @@ -948,5 +948,8 @@ "Wait for your turn.": "Attendez votre tour.", "Choose an action to take back its markers without acting.": "Choisissez une action dont vous reprenez les marqueurs sans agir.", "Undo my move": "Annuler mon coup", - "Automatically retrieve markers when there is no choice": "Reprendre automatiquement les marqueurs lorsqu'il n'y a pas de choix" + "Automatically retrieve markers when there is no choice": "Reprendre automatiquement les marqueurs lorsqu'il n'y a pas de choix", + "Goods replenished": "Marchandises réapprovisionnées", + "Empty goods space": "Emplacement de marchandise vide", + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "Au début de chaque manche, les navires complets sont remplacés. Une île sans aucune marchandise retrouve son assortiment initial. S’il reste ne serait-ce qu’un cube, rien n’est réapprovisionné." } diff --git a/viewer/localization/hi.json b/viewer/localization/hi.json index b137237..91b6b5b 100644 --- a/viewer/localization/hi.json +++ b/viewer/localization/hi.json @@ -948,5 +948,8 @@ "Wait for your turn.": "अपनी बारी का इंतज़ार करें।", "Choose an action to take back its markers without acting.": "एक कार्रवाई चुनें जिसके मार्कर आप बिना कार्रवाई किए वापस लेंगे।", "Undo my move": "अपनी चाल वापस लें", - "Automatically retrieve markers when there is no choice": "कोई विकल्प न होने पर मार्कर अपने-आप वापस लें" + "Automatically retrieve markers when there is no choice": "कोई विकल्प न होने पर मार्कर अपने-आप वापस लें", + "Goods replenished": "माल फिर भरा गया", + "Empty goods space": "माल की खाली जगह", + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "हर दौर की शुरुआत में भरे हुए जहाज़ बदल दिए जाते हैं। जिस द्वीप पर कोई माल नहीं बचा है, वहाँ शुरुआती माल फिर रख दिया जाता है। अगर एक भी घन बचा हो, तो कोई माल नहीं भरा जाता।" } diff --git a/viewer/localization/it.json b/viewer/localization/it.json index c8d4583..e094bce 100644 --- a/viewer/localization/it.json +++ b/viewer/localization/it.json @@ -948,5 +948,8 @@ "Wait for your turn.": "Attendi il tuo turno.", "Choose an action to take back its markers without acting.": "Scegli un’azione di cui riprendere i segnalini senza agire.", "Undo my move": "Annulla la mossa", - "Automatically retrieve markers when there is no choice": "Ritirare automaticamente i segnalini quando non c'è scelta" + "Automatically retrieve markers when there is no choice": "Ritirare automaticamente i segnalini quando non c'è scelta", + "Goods replenished": "Merci rifornite", + "Empty goods space": "Spazio merce vuoto", + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "All’inizio di ogni round, le navi complete vengono sostituite. Un’isola senza più merci riceve nuovamente il suo assortimento iniziale. Se rimane anche un solo cubetto, non viene rifornito nulla." } diff --git a/viewer/localization/ko.json b/viewer/localization/ko.json index b80f115..ab4a1a5 100644 --- a/viewer/localization/ko.json +++ b/viewer/localization/ko.json @@ -948,5 +948,8 @@ "Wait for your turn.": "차례를 기다리세요.", "Choose an action to take back its markers without acting.": "행동하지 않고 마커를 회수할 행동을 선택하세요.", "Undo my move": "내 수 되돌리기", - "Automatically retrieve markers when there is no choice": "선택의 여지가 없을 때 마커 자동 회수" + "Automatically retrieve markers when there is no choice": "선택의 여지가 없을 때 마커 자동 회수", + "Goods replenished": "상품 보충", + "Empty goods space": "빈 상품 자리", + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "매 라운드 시작 시 가득 찬 배를 교체합니다. 상품이 하나도 남지 않은 섬은 처음의 상품 구성을 다시 받습니다. 큐브가 하나라도 남아 있으면 보충하지 않습니다." } diff --git a/viewer/localization/nl.json b/viewer/localization/nl.json index bb66d93..29fdf37 100644 --- a/viewer/localization/nl.json +++ b/viewer/localization/nl.json @@ -948,5 +948,8 @@ "Wait for your turn.": "Wacht op je beurt.", "Choose an action to take back its markers without acting.": "Kies een actie waarvan je de markers zonder actie terugneemt.", "Undo my move": "Zet ongedaan maken", - "Automatically retrieve markers when there is no choice": "Markeringen automatisch terugnemen als er geen keuze is" + "Automatically retrieve markers when there is no choice": "Markeringen automatisch terugnemen als er geen keuze is", + "Goods replenished": "Goederen aangevuld", + "Empty goods space": "Lege goederenplek", + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "Aan het begin van elke ronde worden volle schepen vervangen. Een eiland zonder goederen krijgt zijn oorspronkelijke assortiment terug. Als er ook maar één blokje over is, wordt niets aangevuld." } diff --git a/viewer/localization/pl.json b/viewer/localization/pl.json index 7f2442d..fed94bc 100644 --- a/viewer/localization/pl.json +++ b/viewer/localization/pl.json @@ -948,5 +948,8 @@ "Wait for your turn.": "Poczekaj na swoją turę.", "Choose an action to take back its markers without acting.": "Wybierz akcję, z której zabierasz znaczniki bez jej wykonywania.", "Undo my move": "Cofnij ruch", - "Automatically retrieve markers when there is no choice": "Automatycznie zabieraj znaczniki, gdy nie ma wyboru" + "Automatically retrieve markers when there is no choice": "Automatycznie zabieraj znaczniki, gdy nie ma wyboru", + "Goods replenished": "Uzupełniono towary", + "Empty goods space": "Puste miejsce na towar", + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "Na początku każdej rundy pełne statki są zastępowane nowymi. Wyspa, na której nie ma już żadnych towarów, odzyskuje swój początkowy zestaw. Jeśli pozostała choć jedna kostka, niczego się nie uzupełnia." } diff --git a/viewer/localization/pt-BR.json b/viewer/localization/pt-BR.json index cc62874..a965bfb 100644 --- a/viewer/localization/pt-BR.json +++ b/viewer/localization/pt-BR.json @@ -948,5 +948,8 @@ "Wait for your turn.": "Aguarde sua vez.", "Choose an action to take back its markers without acting.": "Escolha uma ação para recolher os marcadores dela sem agir.", "Undo my move": "Desfazer jogada", - "Automatically retrieve markers when there is no choice": "Recolher marcadores automaticamente quando não há escolha" + "Automatically retrieve markers when there is no choice": "Recolher marcadores automaticamente quando não há escolha", + "Goods replenished": "Mercadorias reabastecidas", + "Empty goods space": "Espaço vazio de mercadoria", + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "No início de cada rodada, os navios completos são substituídos. Uma ilha sem nenhuma mercadoria recebe novamente seu conjunto original. Se restar um único cubo, nada é reabastecido." } diff --git a/viewer/localization/ro.json b/viewer/localization/ro.json index b0ed088..6e6dfe5 100644 --- a/viewer/localization/ro.json +++ b/viewer/localization/ro.json @@ -948,5 +948,8 @@ "Wait for your turn.": "Așteaptă-ți rândul.", "Choose an action to take back its markers without acting.": "Alege o acțiune ale cărei marcaje le retragi fără a acționa.", "Undo my move": "Anulează mutarea", - "Automatically retrieve markers when there is no choice": "Retrage automat marcatorii când nu există altă opțiune" + "Automatically retrieve markers when there is no choice": "Retrage automat marcatorii când nu există altă opțiune", + "Goods replenished": "Mărfuri reaprovizionate", + "Empty goods space": "Loc gol pentru marfă", + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "La începutul fiecărei runde, navele complete sunt înlocuite. O insulă fără nicio marfă primește din nou sortimentul inițial. Dacă a rămas chiar și un singur cub, nu se reaprovizionează nimic." } diff --git a/viewer/localization/ru.json b/viewer/localization/ru.json index 6e9bd6c..158b96c 100644 --- a/viewer/localization/ru.json +++ b/viewer/localization/ru.json @@ -948,5 +948,8 @@ "Wait for your turn.": "Дождитесь своего хода.", "Choose an action to take back its markers without acting.": "Выберите действие, маркеры которого вы заберёте без выполнения действия.", "Undo my move": "Отменить ход", - "Automatically retrieve markers when there is no choice": "Автоматически забирать маркеры, когда нет выбора" + "Automatically retrieve markers when there is no choice": "Автоматически забирать маркеры, когда нет выбора", + "Goods replenished": "Товары пополнены", + "Empty goods space": "Пустое место для товара", + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "В начале каждого раунда заполненные корабли заменяются. Остров, на котором не осталось товаров, снова получает исходный набор. Если остался хотя бы один кубик, товары не пополняются." } diff --git a/viewer/localization/vi.json b/viewer/localization/vi.json index ac1fde7..ef996d5 100644 --- a/viewer/localization/vi.json +++ b/viewer/localization/vi.json @@ -948,5 +948,8 @@ "Wait for your turn.": "Hãy chờ đến lượt bạn.", "Choose an action to take back its markers without acting.": "Chọn một hành động để thu hồi dấu của nó mà không thực hiện hành động.", "Undo my move": "Hoàn tác nước đi", - "Automatically retrieve markers when there is no choice": "Tự động thu hồi dấu khi không có lựa chọn" + "Automatically retrieve markers when there is no choice": "Tự động thu hồi dấu khi không có lựa chọn", + "Goods replenished": "Đã bổ sung hàng hóa", + "Empty goods space": "Ô hàng hóa trống", + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "Ở đầu mỗi vòng, các tàu đã đầy được thay thế. Một đảo không còn hàng hóa nào sẽ được bổ sung lại đúng loại và số lượng ban đầu. Nếu vẫn còn dù chỉ một khối, sẽ không bổ sung gì." } diff --git a/viewer/localization/zh-CN.json b/viewer/localization/zh-CN.json index ddec371..6fe712c 100644 --- a/viewer/localization/zh-CN.json +++ b/viewer/localization/zh-CN.json @@ -948,5 +948,8 @@ "Wait for your turn.": "请等待你的回合。", "Choose an action to take back its markers without acting.": "选择一个行动,收回其标记而不执行。", "Undo my move": "撤销我的行动", - "Automatically retrieve markers when there is no choice": "没有选择时自动收回标记" + "Automatically retrieve markers when there is no choice": "没有选择时自动收回标记", + "Goods replenished": "货物已补充", + "Empty goods space": "空货物格", + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "每轮开始时,已装满的船会被替换。完全没有货物的岛屿会重新补上原本的货物组合。只要还剩一颗方块,就不会补充任何货物。" } diff --git a/viewer/localization/zh-TW.json b/viewer/localization/zh-TW.json index 36fecb3..28044c8 100644 --- a/viewer/localization/zh-TW.json +++ b/viewer/localization/zh-TW.json @@ -948,5 +948,8 @@ "Wait for your turn.": "請等待輪到你。", "Choose an action to take back its markers without acting.": "選擇一個行動,收回其標記但不執行行動。", "Undo my move": "撤回我的行動", - "Automatically retrieve markers when there is no choice": "無其他選擇時自動收回標記" + "Automatically retrieve markers when there is no choice": "無其他選擇時自動收回標記", + "Goods replenished": "貨物已補充", + "Empty goods space": "空貨物格", + "At the start of each round, completed ships are replaced. An island with no goods left receives its original assortment again. If even one cube remains, none are replenished.": "每輪開始時,已裝滿的船會被替換。完全沒有貨物的島嶼會重新補上原本的貨物組合。只要還剩一顆方塊,就不會補充任何貨物。" } diff --git a/viewer/map-zoom.js b/viewer/map-zoom.js index 60e122c..305e1ae 100644 --- a/viewer/map-zoom.js +++ b/viewer/map-zoom.js @@ -17,6 +17,32 @@ export function mountMapZoom(root) { autoFit = true, suppressClick = false; const events = new AbortController(); + const motion = matchMedia("(prefers-reduced-motion: reduce)"); + let enabled = true, + flight, + ready = Promise.resolve(), + resolveReady; + function settle() { + flight?.cancel(); + flight = null; + const map = elements()?.map; + if (map) delete map.dataset.mapTransition; + resolveReady?.(); + resolveReady = null; + } + const canAnimate = () => + enabled && + !motion.matches && + !document.hidden && + root.closest("[data-map-view]")?.dataset.mapView !== "3d"; + motion.addEventListener("change", settle, { signal: events.signal }); + document.addEventListener( + "visibilitychange", + () => { + if (document.hidden) settle(); + }, + { signal: events.signal }, + ); const observer = new ResizeObserver(() => update(capture())); const elements = () => { const map = root.querySelector(".map-scroll"); @@ -72,9 +98,9 @@ export function mountMapZoom(root) { const world = new DOMPoint(client.x, client.y).matrixTransform( matrix.inverse(), ); - return { world, client: point }; + return { world, client: point, matrix: matrix }; } - function update(anchor) { + function update(anchor, { smooth = true } = {}) { const el = elements(); if (!el) return; const { map, canvas, svg } = el, @@ -122,6 +148,18 @@ export function mountMapZoom(root) { viewport, size + 2 * Math.max(0, viewport / 2 - Math.min(middle, size - middle)), ); + const nextLayout = [ + box.x, + box.y, + box.width, + box.height, + svg.dataset.focusBox, + f.width, + f.height, + zoom, + ].join(); + const changed = layoutKey !== nextLayout; + if (changed) settle(); let resized = false; for (const [node, property, value] of [ [ @@ -151,16 +189,6 @@ export function mountMapZoom(root) { resized = true; } } - const nextLayout = [ - box.x, - box.y, - box.width, - box.height, - svg.dataset.focusBox, - f.width, - f.height, - zoom, - ].join(); if (map.dataset.zoom !== String(zoom)) map.dataset.zoom = String(zoom); if (!autoFit && anchor && (resized || layoutKey !== nextLayout)) { const client = anchor.client ?? center(map); @@ -175,6 +203,35 @@ export function mountMapZoom(root) { map.scrollLeft += middle.x - (f.x + f.width / 2); map.scrollTop += middle.y - (f.y + f.height / 2); } + if ( + changed && + !initial && + smooth && + anchor?.matrix && + canAnimate() && + svg.animate + ) { + const next = svg.getScreenCTM(), + r = svg.getBoundingClientRect(); + const ratio = anchor.matrix.a / next.a; + const dx = anchor.matrix.e - ratio * next.e + (ratio - 1) * r.left; + const dy = anchor.matrix.f - ratio * next.f + (ratio - 1) * r.top; + if (Math.abs(ratio - 1) > 0.001 || Math.hypot(dx, dy) > 1) { + map.dataset.mapTransition = "reframe"; + ready = new Promise((resolve) => (resolveReady = resolve)); + flight = svg.animate( + [ + { + transformOrigin: "0 0", + transform: `translate(${dx}px,${dy}px) scale(${ratio})`, + }, + { transformOrigin: "0 0", transform: "none" }, + ], + { duration: 850, easing: "cubic-bezier(.22,.61,.36,1)" }, + ); + flight.onfinish = settle; + } + } layoutKey = nextLayout; updatePanCursor(map); for (const [selector, disabled] of [ @@ -195,6 +252,7 @@ export function mountMapZoom(root) { map.addEventListener( type, () => { + settle(); autoFit = false; }, { @@ -225,11 +283,11 @@ export function mountMapZoom(root) { observed = map; } } - function setZoom(value, anchor = capture()) { + function setZoom(value, anchor = capture(), smooth = true) { endDrag(); autoFit = false; zoom = clamp(value, minZoom, MAX_ZOOM); - update(anchor); + update(anchor, { smooth }); } function endDrag(event) { if ( @@ -335,10 +393,14 @@ export function mountMapZoom(root) { if (!pinch || event.touches.length !== 2) return; if (event.cancelable) event.preventDefault(); const { distance, point } = geometry(event.touches); - setZoom((pinch.zoom * distance) / pinch.distance, { - ...pinch.anchor, - client: point, - }); + setZoom( + (pinch.zoom * distance) / pinch.distance, + { + ...pinch.anchor, + client: point, + }, + false, + ); } root.addEventListener( "pointerdown", @@ -365,10 +427,19 @@ export function mountMapZoom(root) { return { capture, update, + settle, + whenIdle: async () => { + while (flight) await ready; + }, + setEnabled(value) { + enabled = value; + if (!enabled) settle(); + }, step(direction) { setZoom((zoom ?? 1) * STEP ** direction); }, destroy() { + settle(); endPinch(); endDrag(); mapEvents?.abort(); diff --git a/viewer/preview.js b/viewer/preview.js index fbdc924..c923009 100644 --- a/viewer/preview.js +++ b/viewer/preview.js @@ -58,10 +58,11 @@ if (params.has("lesson")) { let undoRequests = 0; const ui = mountGame(document.querySelector("#game"), { onUndo: () => (undoRequests += 1), - onMove: (m) => { + onMove: async (m) => { state = engine.move(state, m, hotseat ? state.actor : 0); save(); show(); + await ui.whenIdle(); scheduleBots(); }, onSetting: (name, value) => { @@ -101,10 +102,11 @@ if (params.has("lesson")) { function scheduleBots() { clearTimeout(timer); if (!hotseat && !state.finished && state.actor !== 0) - timer = setTimeout(() => { + timer = setTimeout(async () => { state = engine.moveAI(state, state.actor); save(); show(); + await ui.whenIdle(); scheduleBots(); }, 450); } @@ -145,6 +147,7 @@ if (params.has("lesson")) { state = engine.moveAI(state, state.actor); save(); show(); + await ui.whenIdle(); await new Promise((r) => setTimeout(r, 160)); } autoplay = false; diff --git a/viewer/rules.js b/viewer/rules.js index 2cbbc7f..c524a6a 100644 --- a/viewer/rules.js +++ b/viewer/rules.js @@ -1,5 +1,6 @@ import { EXPORT_RULE, + REFILL_RULE, EXTEND_TITLE, EXTEND_RULE, ROUND_TITLE, @@ -90,7 +91,8 @@ export function rulesHtml(lang = "en", colorBlind = false) { "" + message("Completing a ship adds {p0} to the good's reward.", [ token("point", "+2"), - ]), + ]) + + `

    ${prose(REFILL_RULE)}`, ], [ "Develop the islands", diff --git a/viewer/style.css b/viewer/style.css index d4ad2e2..d1152a6 100644 --- a/viewer/style.css +++ b/viewer/style.css @@ -2020,3 +2020,45 @@ body:has(.vanuatu) { .vanuatu .obstacles .obstacle:not(:has(> .icon)) { padding-inline-start: calc(1.4em + 6px); } + +/* Journal locations are ordinary buttons: touch scrolling stays native. */ +.vanuatu .journal-location { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 5px 8px; + width: 100%; + text-align: start; + color: inherit; + font: inherit; + border: 0; + border-radius: 4px; + padding: 5px 7px; + background: transparent; + box-shadow: none; + touch-action: pan-x pan-y; +} +.vanuatu .journal-location.inspected, +.vanuatu .journal-location:focus-visible { + background: #78c8df26; + outline: 1px solid #357fb3; +} +.vanuatu .journal-locate { + margin-inline-start: auto; + opacity: 0.6; +} +.vanuatu .journal-locate .icon { + width: 19px; + height: 19px; +} +.vanuatu .cell-highlight.journal-highlight { + fill: #8ad9ff30; + stroke: #256cae; + stroke-width: 5; + stroke-dasharray: 9 5; +} +.vanuatu .map-3d .map-label.journal-highlight { + outline: 2px solid #256cae; + outline-offset: 3px; + background: #e1f5ff; +} diff --git a/viewer/three/board.js b/viewer/three/board.js new file mode 100644 index 0000000..fc09c37 --- /dev/null +++ b/viewer/three/board.js @@ -0,0 +1,1866 @@ +import * as THREE from "three"; +import { translateText } from "../localization/index.js"; +import { goodsSlots } from "../goods-slots.js"; +import { OrbitControls } from "three/addons/controls/OrbitControls.js"; +import { TILES } from "../../engine/catalog.js"; +import { icon, token as renderToken, esc } from "../art.js"; +import { + seaRoute, + routePosition, + passingSide, + giveWay, + arrivalFraction, + stepYield, +} from "./navigation.js"; +import { createSailingSound } from "./sailing-sound.js"; +import { liveEvents } from "../effects.js"; +import { + createSandDrawing, + setDrawingProgress, + newDrawingSlots, + DRAW_DURATION, +} from "./sand-drawing.js"; +import "./style.css"; + +// Presentation only: selection is handed back to the regular viewer. The engine +// is the sole authority for legal actions, resources, turn order and bot moves. +export function mountBoard3D(target, { onSelect } = {}) { + const events = new AbortController(); + const listen = (node, type, callback, options = {}) => + node.addEventListener(type, callback, { + ...options, + signal: events.signal, + }); + target.innerHTML = '
    '; + target.setAttribute("translate", "no"); + const host = target.querySelector(".world"), + labelHost = target.querySelector(".labels"); + let words = {}, + presentation = {}, + state, + visible = true, + selected = null, + pending = 0; + let tiles = [], + labels = [], + selection, + center = new THREE.Vector3(), + bounds; + let boats = [], + solids = [], + protectedPieces = [], + motion = null, + ghostTiles = [], + highlights; + let drawings = [], + drawingMotion = null, + cameraMotion = null, + tileMotion = null, + cameraFramed = false; + let viewportWidth = 0, + viewportHeight = 0; + let cameraReady = Promise.resolve(), + resolveCamera, + tileReady = Promise.resolve(), + resolveTiles; + let tileGroups = new Map(); + let contentKey, layoutKey, selectionKey, styleKey, ready, resolveReady; + const sailingSound = createSailingSound(); + const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)"); + const token = (kind, n, label) => + renderToken(kind, n, label, presentation.colorBlind); + let renderer; + try { + renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false }); + } catch { + target.innerHTML = `

    ${"3D unavailable — use 2D."}

    `; + throw Error("WebGL unavailable"); + } + renderer.setPixelRatio(Math.min(devicePixelRatio, 1.6)); + renderer.outputColorSpace = THREE.SRGBColorSpace; + renderer.toneMapping = THREE.ACESFilmicToneMapping; + renderer.toneMappingExposure = 0.92; + renderer.shadowMap.enabled = true; + renderer.shadowMap.type = THREE.PCFShadowMap; + renderer.shadowMap.autoUpdate = false; + host.append(renderer.domElement); + renderer.domElement.tabIndex = 0; + renderer.domElement.setAttribute("aria-label", "Vanuatu · 3D"); + renderer.domElement.setAttribute("role", "img"); + const scene = new THREE.Scene(); + scene.background = new THREE.Color("#9fcace"); + scene.fog = new THREE.Fog("#9fcace", 44, 90); + const camera = new THREE.PerspectiveCamera(36, 1, 0.1, 150); + const gestureSurface = target; + const controls = new OrbitControls(camera, gestureSurface); + controls.enableDamping = false; + controls.screenSpacePanning = false; + controls.minDistance = 4; + controls.maxDistance = 65; + controls.minPolarAngle = 0.02; + controls.maxPolarAngle = Math.PI * 0.41; + controls.mouseButtons.LEFT = THREE.MOUSE.PAN; + controls.enableRotate = false; + controls.mouseButtons.RIGHT = null; + controls.touches.ONE = THREE.TOUCH.PAN; + controls.touches.TWO = THREE.TOUCH.DOLLY_PAN; + controls.panSpeed = 0.8; + scene.add(new THREE.HemisphereLight("#fff7df", "#4d9290", 1.6)); + const sun = new THREE.DirectionalLight("#fff0ce", 2.2); + sun.position.set(-10, 17, 10); + sun.castShadow = true; + sun.shadow.mapSize.set(2048, 2048); + Object.assign(sun.shadow.camera, { + left: -19, + right: 19, + top: 19, + bottom: -19, + near: 0.5, + far: 55, + }); + sun.shadow.normalBias = 0.035; + sun.shadow.bias = -0.00015; + scene.add(sun); + let board = new THREE.Group(); + scene.add(board); + const palette = new Map(), + goodsLabels = new Map(); + function material(color, roughness = 0.8) { + const key = `${color}:${roughness}`; + if (!palette.has(key)) + palette.set( + key, + new THREE.MeshStandardMaterial({ + color, + roughness, + flatShading: true, + side: THREE.DoubleSide, + }), + ); + return palette.get(key); + } + function mesh(g, geometry, color, x = 0, y = 0, z = 0) { + const m = new THREE.Mesh( + geometry, + typeof color === "string" ? material(color) : color, + ); + m.position.set(x, y, z); + m.castShadow = true; + m.receiveShadow = true; + g.add(m); + return m; + } + const ocean = mesh( + scene, + new THREE.PlaneGeometry(180, 180), + new THREE.MeshBasicMaterial({ color: "#9fcace" }), + 0, + -0.24, + 0, + ); + ocean.rotation.x = -Math.PI / 2; + ocean.castShadow = false; + ocean.receiveShadow = false; + const oceanShadow = mesh( + scene, + new THREE.PlaneGeometry(180, 180), + new THREE.ShadowMaterial({ opacity: 0.16 }), + 0, + -0.235, + 0, + ); + oceanShadow.rotation.x = -Math.PI / 2; + oceanShadow.castShadow = false; + const tilt = Math.PI / 9; + function position(id) { + const [q, r] = id.split(",").map(Number), + x = q * 162 - r * 81, + z = r * 140.3; + return { + x: (x * Math.cos(tilt) - z * Math.sin(tilt)) / 60, + z: (x * Math.sin(tilt) + z * Math.cos(tilt)) / 60, + }; + } + function tileShape() { + const h = 140.3 / 3; + const v = [ + [81, -h], + [81, h], + [0, 2 * h], + [-81, h], + [-81, -h], + [0, -2 * h], + ].map(([x, z]) => [ + (x * Math.cos(tilt) - z * Math.sin(tilt)) / 60, + -(x * Math.sin(tilt) + z * Math.cos(tilt)) / 60, + ]); + const shape = new THREE.Shape(); + shape.moveTo(...v[0]); + for (let i = 0; i < 6; i++) { + const [ax, ay] = v[i], + [bx, by] = v[(i + 1) % 6], + dx = bx - ax, + dy = by - ay; + shape.bezierCurveTo( + ax + dx / 3 + dy * 0.28, + ay + dy / 3 - dx * 0.28, + ax + (2 * dx) / 3 - dy * 0.28, + ay + (2 * dy) / 3 + dx * 0.28, + bx, + by, + ); + } + shape.closePath(); + return shape; + } + const shape = tileShape(); + function extrude(g, shape, height, color, x = 0, y = 0, z = 0, bevel = 0.01) { + const geometry = new THREE.ExtrudeGeometry(shape, { + depth: height, + bevelEnabled: bevel > 0, + bevelThickness: bevel, + bevelSize: bevel, + bevelSegments: 1, + curveSegments: 8, + }); + geometry.rotateX(-Math.PI / 2); + return mesh(g, geometry, color, x, y, z); + } + function line(g, points, color, opacity = 1, loop = false) { + const geo = new THREE.BufferGeometry().setFromPoints( + points.map((p) => new THREE.Vector3(...p)), + ); + const m = new THREE.LineBasicMaterial({ + color, + transparent: opacity < 1, + opacity, + }); + const obj = loop ? new THREE.LineLoop(geo, m) : new THREE.Line(geo, m); + g.add(obj); + return obj; + } + function blob(radius, seed) { + const s = new THREE.Shape(), + v = []; + for (let i = 0; i < 12; i++) { + const a = (i / 12) * Math.PI * 2, + r = radius * (1 + Math.sin(i * 2.7 + seed) * 0.12); + v.push(new THREE.Vector2(Math.cos(a) * r, Math.sin(a) * r * 0.84)); + } + const curve = new THREE.SplineCurve([...v, v[0], v[1]]); + const p = curve.getPoints(70).slice(0, 65); + s.moveTo(p[0].x, p[0].y); + for (const v of p.slice(1)) s.lineTo(v.x, v.y); + s.closePath(); + return s; + } + function box(g, color, w, h, d, x = 0, y = h / 2, z = 0) { + return mesh(g, new THREE.BoxGeometry(w, h, d), color, x, y, z); + } + function beam(g, color, radius, a, b) { + const from = new THREE.Vector3(...a), + to = new THREE.Vector3(...b), + center = from.clone().add(to).multiplyScalar(0.5); + const part = mesh( + g, + new THREE.CylinderGeometry(radius, radius * 1.2, from.distanceTo(to), 6), + color, + ...center.toArray(), + ); + part.quaternion.setFromUnitVectors( + new THREE.Vector3(0, 1, 0), + to.sub(from).normalize(), + ); + return part; + } + function palm(g, x, z, seed) { + const p = new THREE.Group(); + g.add(p); + p.position.set(x, 0.23, z); + p.rotation.y = seed; + beam(p, "#9e7950", 0.036, [0, 0, 0], [0.1, 0.67, -0.07]); + beam(p, "#b09260", 0.028, [0.1, 0.67, -0.07], [0.18, 0.99, -0.1]); + for (let i = 0; i < 6; i++) { + const a = (i / 6) * Math.PI * 2, + dx = Math.cos(a), + dz = Math.sin(a), + w = 0.12; + const verts = [ + 0.18, + 0.99, + -0.1, + 0.18 + dx * 0.3 - dz * w, + 1.1, + -0.1 + dz * 0.3 + dx * w, + 0.18 + dx * 0.68, + 0.87, + -0.1 + dz * 0.68, + 0.18 + dx * 0.3 + dz * w, + 1.06, + -0.1 + dz * 0.3 - dx * w, + ]; + const geo = new THREE.BufferGeometry(); + geo.setAttribute("position", new THREE.Float32BufferAttribute(verts, 3)); + geo.setIndex([0, 1, 2, 0, 2, 3]); + geo.computeVertexNormals(); + mesh(p, geo, i % 2 ? "#5d914d" : "#80a752"); + } + mesh( + p, + new THREE.IcosahedronGeometry(0.065, 0), + "#8e633e", + 0.18, + 0.96, + -0.1, + ); + } + function hut(g, color, x, z) { + const h = new THREE.Group(); + g.add(h); + h.position.set(x, 0.23, z); + box(h, "#d5bf86", 0.48, 0.06, 0.44, 0, 0.03); + box(h, color, 0.37, 0.36, 0.34, 0, 0.22); + box(h, "#fff0c5", 0.105, 0.22, 0.013, 0.025, 0.15, 0.177); + box(h, "#4e6055", 0.085, 0.15, 0.012, -0.1, 0.29, 0.18); + const roof = new THREE.Shape(); + roof.moveTo(-0.26, 0); + roof.lineTo(0, 0.25); + roof.lineTo(0.26, 0); + roof.closePath(); + const geo = new THREE.ExtrudeGeometry(roof, { + depth: 0.48, + bevelEnabled: false, + }); + geo.translate(0, 0, -0.24); + mesh(h, geo, "#ab7e42", 0, 0.4, 0); + for (const dx of [-0.17, -0.08, 0.08, 0.17]) + line( + h, + [ + [dx, 0.65 - Math.abs(dx) * 0.95, -0.245], + [dx, 0.65 - Math.abs(dx) * 0.95, 0.245], + ], + "#d8b06a", + ); + } + function emptyHut(g, x, z) { + // Above both the sand bevel and the grass, so vacant sites remain visible. + const site = new THREE.Group(); + site.position.set(x, 0.33, z); + g.add(site); + box(site, "#dfcb97", 0.4, 0.018, 0.38, 0, 0, 0); + const outline = new THREE.LineLoop( + new THREE.BufferGeometry().setFromPoints([ + new THREE.Vector3(-0.2, 0.012, -0.19), + new THREE.Vector3(0.2, 0.012, -0.19), + new THREE.Vector3(0.2, 0.012, 0.19), + new THREE.Vector3(-0.2, 0.012, 0.19), + ]), + new THREE.LineDashedMaterial({ + color: "#836a47", + dashSize: 0.05, + gapSize: 0.035, + }), + ); + outline.computeLineDistances(); + site.add(outline); + for (const dx of [-0.17, 0.17]) + for (const dz of [-0.16, 0.16]) + box(site, "#9e8353", 0.035, 0.045, 0.035, dx, 0.025, dz); + protectedPieces.push(site); + } + function island(g, t, index, id) { + const spec = TILES[t.id]; + const lagoon = extrude( + g, + blob(1.22, index + 1), + 0.015, + "#81d9c5", + 0, + 0.035, + 0, + 0, + ); + lagoon.castShadow = false; + const sand = new THREE.Shape(); + blob(1.04, index) + .getPoints(80) + .forEach((p, i) => { + // A slightly wider beach lip keeps the drawings in front of the goods. + const y = p.y < 0 ? p.y * 1.4 : p.y; + if (i) sand.lineTo(p.x, y); + else sand.moveTo(p.x, y); + }); + sand.closePath(); + extrude( + g, + sand, + 0.17, + [material("#f2de9f"), material("#cfb77e")], + 0, + 0.055, + 0, + 0.035, + ); + + const coast = sand.getPoints(70).map((p) => [p.x, 0.06, -p.y]); + line(g, coast, "#d7f3d9", 0.85, true); + extrude(g, blob(0.73, index + 4), 0.065, "#99b76c", 0, 0.23, -0.24, 0.02); + for (let i = 0; i < 4; i++) { + const a = i * 2.3 + index, + px = Math.cos(a) * 0.42, + pz = -0.42 + Math.sin(a) * 0.14; + const rock = mesh( + g, + new THREE.IcosahedronGeometry(0.24, 0), + ["#9ab470", "#7fa363", "#adbd7b"][i % 3], + px, + 0.32, + pz, + ); + rock.scale.set(1, 0.58, 1); + } + palm(g, -0.58, -0.31, index * 0.6); + palm(g, 0.43, -0.4, index * 0.6 + 1.3); + for (let i = 0; i < spec.huts; i++) { + const x = (i - (spec.huts - 1) / 2) * 0.49; + if (t.huts[i] !== undefined) + hut(g, state.players[t.huts[i]].color, x, 0.19); + else emptyHut(g, x, 0.19); + } + const goodsGroup = new THREE.Group(); + g.add(goodsGroup); + const goods = goodsSlots(t); + goods.forEach(({ good, filled }, i) => { + const x = (i - (goods.length - 1) / 2) * 0.3; + const slot = new THREE.Group(); + slot.position.set(x, 0.37, 0.66); + slot.rotation.y = 0.12; + goodsGroup.add(slot); + const color = { kava: "#9aca49", copra: "#fff7dc", beef: "#e77557" }[ + good + ]; + if (filled) box(slot, color, 0.23, 0.24, 0.23, 0, 0, 0); + else { + // A solid, flat colour patch marks the missing cube's footprint. + const footprint = mesh( + slot, + new THREE.PlaneGeometry(0.26, 0.26), + new THREE.MeshBasicMaterial({ color, side: THREE.DoubleSide }), + 0, + -0.097, + 0, + ); + footprint.rotation.x = -Math.PI / 2; + footprint.castShadow = false; + footprint.receiveShadow = false; + } + if (presentation.colorBlind) { + if (!goodsLabels.has(good)) { + const canvas = document.createElement("canvas"); + canvas.width = 64; + canvas.height = 64; + const ctx = canvas.getContext("2d"); + ctx.font = "bold 50px sans-serif"; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.fillStyle = "#29423d"; + ctx.fillText({ kava: "K", copra: "C", beef: "B" }[good], 32, 34); + const texture = new THREE.CanvasTexture(canvas); + texture.colorSpace = THREE.SRGBColorSpace; + goodsLabels.set( + good, + new THREE.SpriteMaterial({ map: texture, depthTest: true }), + ); + } + if (filled) { + const letter = new THREE.Sprite(goodsLabels.get(good)); + letter.position.set(0, 0.02, 0.13); + letter.scale.set(0.18, 0.18, 1); + slot.add(letter); + } else { + const letter = mesh( + slot, + new THREE.PlaneGeometry(0.16, 0.16), + new THREE.MeshBasicMaterial({ + map: goodsLabels.get(good).map, + transparent: true, + depthWrite: false, + }), + 0, + -0.094, + 0, + ); + letter.rotation.x = -Math.PI / 2; + letter.castShadow = false; + letter.receiveShadow = false; + } + } + }); + for (let slot = 0; slot < t.drawings; slot++) { + const drawing = createSandDrawing(slot, spec.drawings); + drawing.cell = id; + drawing.slot = slot; + g.add(drawing.group); + drawings.push(drawing); + protectedPieces.push(drawing.group); + } + if (goods.length) protectedPieces.push(goodsGroup); + return goods.length ? goodsGroup : null; + } + function boat(g, color, x, z, index) { + const b = new THREE.Group(); + g.add(b); + b.position.set(x, 0.08, z); + b.scale.setScalar(0.85); + const hull = new THREE.Shape(); + hull.moveTo(-0.19, -0.34); + hull.lineTo(-0.22, 0.25); + hull.lineTo(0, 0.59); + hull.lineTo(0.22, 0.25); + hull.lineTo(0.19, -0.34); + hull.closePath(); + extrude( + b, + hull, + 0.14, + [material(color), material("#375b5b")], + 0, + 0.015, + 0, + 0.018, + ); + line( + b, + hull.getPoints().map((p) => [p.x, 0.17, -p.y]), + "#fff0c5", + 1, + true, + ); + box(b, "#d9bc7b", 0.26, 0.03, 0.38, 0, 0.17, 0.06); + beam(b, "#5c6c5b", 0.018, [0, 0.17, 0.04], [0, 1.15, 0.04]); + const sail = new THREE.Shape(); + sail.moveTo(0.025, 0.31); + sail.lineTo(0.025, 1.1); + sail.quadraticCurveTo(0.27, 1.03, 0.54, 0.38); + sail.closePath(); + const geo = new THREE.ExtrudeGeometry(sail, { + depth: 0.016, + bevelEnabled: false, + curveSegments: 8, + }); + mesh(b, geo, color, 0, 0, 0.035); + line( + b, + [ + [0.04, 0.33, 0.055], + [0.51, 0.39, 0.055], + ], + "#fff4da", + ); + const small = new THREE.Shape(); + small.moveTo(-0.04, 0.37); + small.lineTo(-0.04, 0.94); + small.lineTo(-0.33, 0.4); + small.closePath(); + mesh(b, new THREE.ShapeGeometry(small), "#fff5d4", 0, 0, 0.035); + for (const dx of [-1, 1]) + line( + b, + [ + [dx * 0.29, 0.015, 0.2], + [dx * 0.39, 0.015, 0.42], + [dx * 0.45, 0.015, 0.61], + ], + "#ddf7e8", + 0.5, + ); + return b; + } + + function fishPiece(group, x, z) { + const fish = new THREE.Group(); + group.add(fish); + fish.position.set(x, 0.065, z); + const body = new THREE.Shape(); + body.moveTo(-0.41, 0); + body.bezierCurveTo(-0.2, 0.29, 0.1, 0.28, 0.24, 0.11); + body.lineTo(0.43, 0.25); + body.lineTo(0.43, -0.25); + body.lineTo(0.24, -0.11); + body.bezierCurveTo(0.1, -0.28, -0.2, -0.29, -0.41, 0); + body.closePath(); + extrude( + fish, + body, + 0.075, + [material("#e58bad"), material("#a94d77")], + 0, + 0, + 0, + 0.016, + ); + const eye = mesh( + fish, + new THREE.SphereGeometry(0.025, 8, 6), + "#5b3452", + -0.22, + 0.095, + -0.055, + ); + eye.scale.y = 0.45; + line( + fish, + [ + [0.02, 0.096, -0.09], + [0.09, 0.096, 0], + [0.02, 0.096, 0.09], + ], + "#b46589", + ); + return fish; + } + function treasurePiece(group, x, z) { + const chest = new THREE.Group(); + group.add(chest); + chest.position.set(x, 0.055, z); + chest.rotation.y = 0.12; + box(chest, "#a96835", 0.5, 0.24, 0.36, 0, 0.12); + const lid = new THREE.Shape(); + lid.moveTo(-0.25, 0); + lid.bezierCurveTo(-0.25, 0.21, 0.25, 0.21, 0.25, 0); + lid.closePath(); + const geometry = new THREE.ExtrudeGeometry(lid, { + depth: 0.36, + bevelEnabled: false, + curveSegments: 8, + }); + geometry.translate(0, 0, -0.18); + mesh(chest, geometry, "#c68c48", 0, 0.24, 0); + box(chest, "#e9c25f", 0.52, 0.025, 0.38, 0, 0.24); + for (const x of [-0.18, 0.18]) { + box(chest, "#dcb357", 0.035, 0.23, 0.012, x, 0.12, 0.187); + box(chest, "#dcb357", 0.035, 0.23, 0.012, x, 0.12, -0.187); + const arch = []; + for (let i = 0; i <= 12; i++) { + const z = -0.18 + i * 0.03; + arch.push([x, 0.24 + 0.13 * Math.sin((i / 12) * Math.PI), z]); + } + line(chest, arch, "#f8d581"); + } + box(chest, "#f5d675", 0.09, 0.1, 0.027, 0, 0.22, 0.203); + box(chest, "#805121", 0.021, 0.038, 0.01, 0, 0.22, 0.222); + return chest; + } + + function addMapLabel(id, html, point, priority, help, model = false) { + const leader = document.createElement("span"); + leader.className = "map-label-link"; + leader.hidden = true; + leader.setAttribute("aria-hidden", "true"); + labelHost.append(leader); + const el = document.createElement("button"); + el.className = "map-label" + (model ? " model-label" : ""); + el.innerHTML = html; + el.setAttribute("aria-label", help); + el.setAttribute("aria-pressed", "false"); + el.dataset.mapTile = id; + el.title = help; + el.onclick = (e) => { + if (e.detail === 0) selectTile(id); + }; + labelHost.append(el); + const label = { el, leader, id, priority, point }; + labels.push(label); + return label; + } + + function resourceMarkup(t) { + const spec = TILES[t.id]; + return t.type === "island" + ? token("tourist", `${t.tourists}/${spec.tourists}`, words.tourist) + + token("draw", `${t.drawings}/${spec.drawings}`, words.draw) + : (t.fish > 0 ? token("fish", t.fish, words.fish) : "") + + (t.treasure > 0 ? token("explore", t.treasure, words.treasure) : ""); + } + function tileName(t, id) { + return t.type === "island" + ? t.id === "efate" + ? "Éfaté" + : `${words.island} ${id}` + : t.fish + ? words.sea + : words.emptySea; + } + function disposeBoard() { + finishCamera(false); + settleAnimations(); + board.traverse((o) => { + o.geometry?.dispose(); + if (o.isLine || o.material?.isMeshBasicMaterial) o.material.dispose(); + }); + scene.remove(board); + board = new THREE.Group(); + scene.add(board); + labelHost.replaceChildren(); + tiles = []; + labels = []; + boats = []; + solids = []; + protectedPieces = []; + drawings = []; + tileGroups.clear(); + ghostTiles = []; + selectionKey = undefined; + } + function buildBoard() { + disposeBoard(); + let i = 0; + for (const [id, t] of Object.entries(state.board)) { + const p = position(id), + g = new THREE.Group(); + g.position.set(p.x, 0, p.z); + board.add(g); + tileGroups.set(id, g); + const top = new THREE.Color().setHSL( + 0.5 + (i % 3) * 0.006, + 0.8, + 0.29 + (i % 4) * 0.012, + ); + const tile = extrude( + g, + shape, + 0.14, + [material("#" + top.getHexString(), 0.55), material("#29878a")], + 0, + -0.11, + 0, + 0.008, + ); + tile.scale.set(0.994, 1, 0.994); + tile.userData.cell = id; + tiles.push(tile); + line( + g, + shape.getPoints(60).map((p) => [p.x * 0.994, 0.052, -p.y * 0.994]), + "#a5eadb", + 0.72, + true, + ); + for (let j = 0; j < 5; j++) { + const wave = []; + for (let k = 0; k < 15; k++) { + let x = -0.8 + k * 0.12; + wave.push([ + x, + 0.056, + -0.95 + j * 0.44 + Math.sin(k * 0.38 + j + i) * 0.065, + ]); + } + line(g, wave, "#d5f4dc", 0.3); + } + const goods = t.type === "island" ? island(g, t, i, id) : null; + const here = state.players + .map((p, index) => ({ ...p, index })) + .filter((p) => p.boat === id); + here.forEach((player, j) => { + const x = (j - (here.length - 1) / 2) * 0.94; + const model = boat( + board, + player.color, + p.x + x, + p.z - 0.15, + player.index, + ); + boats[player.index] = { model, cell: id, slot: x }; + if (presentation.colorBlind) { + const label = addMapLabel( + id, + esc( + presentation.symbols?.[player.index] ?? + ["●", "◆", "▲", "■", "✦"][player.index], + ), + model.position.clone().add(new THREE.Vector3(0, 1.35, 0)), + 3, + player.name, + true, + ); + label.boat = player.index; + } + }); + if (t.type === "island") { + const label = addMapLabel( + id, + resourceMarkup(t), + new THREE.Vector3(p.x, 0.2, p.z + 1.02), + 2, + tileName(t, id), + ); + label.piece = goods; + } else { + const resources = [ + ...(t.fish > 0 ? [["fish", t.fish]] : []), + ...(t.treasure > 0 ? [["treasure", t.treasure]] : []), + ]; + const resourceZ = 0.83; + resources.forEach(([kind, value], j) => { + const x = (j - (resources.length - 1) / 2) * 0.94; + const piece = + kind === "fish" + ? fishPiece(g, x, resourceZ) + : treasurePiece(g, x, resourceZ); + solids.push({ object: piece, kind }); + protectedPieces.push(piece); + const label = addMapLabel( + id, + `${value}`, + new THREE.Vector3(p.x + x, 0.13, p.z + resourceZ + 0.37), + 1, + `${words[kind]} : ${value}`, + true, + ); + label.piece = piece; + }); + } + i++; + } + const pts = shape.getPoints(80).map((p) => [p.x, 0.08, -p.y]); + selection = line(board, pts, "#a76d2d", 1, true); + selection.visible = false; + board.updateMatrixWorld(true); + for (const piece of protectedPieces) + piece.userData.labelBox = new THREE.Box3().setFromObject(piece); + bounds = new THREE.Box3().setFromObject(board); + center = bounds.getCenter(new THREE.Vector3()); + center.y = 0.2; + + highlights = new THREE.Group(); + board.add(highlights); + renderer.shadowMap.needsUpdate = true; + } + function selectTile(id) { + if (id) onSelect?.(id); + } + function selectionUpdate() { + const key = JSON.stringify([ + presentation.selected, + presentation.targets, + presentation.hoverTile, + presentation.journalCells, + ]); + if (key === selectionKey) return; + selectionKey = key; + selected = presentation.selected; + const targets = new Set(presentation.targets ?? []), + journal = new Set(presentation.journalCells ?? []); + highlights.traverse((o) => { + o.geometry?.dispose(); + o.material?.dispose(); + }); + highlights.clear(); + ghostTiles = []; + for (const id of new Set([ + ...targets, + ...journal, + ...(selected ? [selected] : []), + ])) { + const p = position(id), + g = new THREE.Group(); + g.position.set(p.x, 0, p.z); + highlights.add(g); + const color = journal.has(id) + ? "#1255ad" + : id === selected + ? "#a76d2d" + : "#fff5c5"; + const ring = line( + g, + shape.getPoints(60).map((v) => [v.x * 0.97, 0.078, -v.y * 0.97]), + color, + 1, + true, + ); + if (!state.board[id] && id !== selected) { + ring.material.dispose(); + ring.material = new THREE.LineDashedMaterial({ + color, + dashSize: 0.1, + gapSize: 0.065, + }); + ring.computeLineDistances(); + } + ring.material.depthTest = false; + ring.renderOrder = 5; + if (journal.has(id)) { + const wash = mesh( + g, + new THREE.ShapeGeometry(shape), + new THREE.MeshBasicMaterial({ + color: "#8ad9ff", + transparent: true, + opacity: 0.3, + depthWrite: false, + side: THREE.DoubleSide, + }), + 0, + 0.08, + 0, + ); + wash.rotation.x = -Math.PI / 2; + } + if (!state.board[id]) { + const ghost = mesh( + g, + new THREE.ShapeGeometry(shape), + new THREE.MeshBasicMaterial({ + color: "#eaf9d9", + transparent: true, + opacity: id === selected ? 0.62 : 0.23, + side: THREE.DoubleSide, + depthWrite: false, + }), + 0, + 0.02, + 0, + ); + ghost.rotation.x = -Math.PI / 2; + ghost.castShadow = false; + ghost.receiveShadow = false; + ghost.userData.cell = id; + ghostTiles.push(ghost); + } + } + for (const label of labels) { + label.el.setAttribute("aria-pressed", String(label.id === selected)); + label.el.classList.toggle("legal", targets.has(label.id)); + label.el.classList.toggle("journal-highlight", journal.has(label.id)); + } + // Empty expansion slots also need keyboard-accessible targets. + for (const label of labels.filter((l) => l.ghost)) { + label.el.remove(); + label.leader.remove(); + } + labels = labels.filter((l) => !l.ghost); + for (const id of targets) { + if (labels.some((label) => label.id === id)) continue; + const spec = + !state.board[id] && state.phase === "expand" + ? TILES[presentation.hoverTile] + : null; + const preview = spec + ? { ...spec, id: presentation.hoverTile, tourists: 0, drawings: 0 } + : null; + const html = preview + ? resourceMarkup(preview) + : state.board[id] + ? icon("sail") + : ""; + const resources = + preview?.type === "sea" + ? [ + preview.fish > 0 ? `${words.fish} : ${preview.fish}` : "", + preview.treasure > 0 + ? `${words.treasure} : ${preview.treasure}` + : "", + ] + .filter(Boolean) + .join(", ") + : preview + ? `${words.tourist} : ${spec.tourists}, ${words.draw} : ${spec.drawings}` + : ""; + const p = position(id), + label = addMapLabel( + id, + html, + new THREE.Vector3(p.x, 0.1, p.z), + preview ? 4 : 0, + `${words.choose} ${id}${resources ? " · " + resources : ""}`, + !preview, + ); + label.ghost = true; + label.el.classList.add("legal"); + label.el.setAttribute("aria-pressed", String(id === selected)); + if (preview) { + label.el.classList.add("placement-label"); + label.el.classList.toggle("empty-placement", !html); + label.el.dataset.placementTile = presentation.hoverTile; + } + } + invalidate(); + } + function update(next, config = {}) { + const previous = state; + const expansionTargetsChanged = + next.phase === "expand" && + JSON.stringify(presentation.targets) !== JSON.stringify(config.targets); + presentation = { ...presentation, ...config }; + words = Object.fromEntries( + Object.entries({ + island: "Island", + sea: "Ocean", + emptySea: "Ocean", + fish: "Fish value", + treasure: "Treasure value", + tourist: "Tourists", + draw: "Sand drawings", + choose: "Choose", + }).map(([key, value]) => [ + key, + translateText(value, presentation.language), + ]), + ); + const newStyle = JSON.stringify([ + presentation.language, + presentation.colorBlind, + presentation.symbols, + next.players.map((p) => p.color), + ]); + const newContent = JSON.stringify(next.board), + newLayout = Object.keys(next.board).join("|"); + const moves = + previous && config.live !== false ? liveEvents(previous, next) : []; + const sailing = moves.find( + (e) => + e.type === "action" && + e.action === "sail" && + previous.players[e.p].boat !== next.players[e.p].boat, + ); + const boatChanged = + previous && + previous.players.some((p, i) => p.boat !== next.players[i]?.boat); + const rebuild = + !state || + newContent !== contentKey || + newStyle !== styleKey || + (boatChanged && !sailing); + const reframe = !state || newLayout !== layoutKey; + const enteringExpansion = + state?.phase !== "expand" && next.phase === "expand"; + // Never let decorative animation hold an authoritative state update hostage. + // Local bots wait for it, but a catch-up/replay can safely settle immediately. + if ( + (motion || drawingMotion) && + previous?.historyLength !== next.historyLength + ) + settleAnimations(); + state = next; + const viewport = resizeViewport(); + if (rebuild) buildBoard(); + contentKey = newContent; + layoutKey = newLayout; + styleKey = newStyle; + selectionUpdate(); + if ( + reframe || + enteringExpansion || + expansionTargetsChanged || + viewport?.widthChanged + ) + resetCamera({ + animate: + !!previous && (config.live !== false || expansionTargetsChanged), + }); + const placed = moves + .filter((e) => e.type === "place") + .map((e) => tileGroups.get(e.cell)) + .filter(Boolean); + if (placed.length && canAnimate()) startTiles(placed); + if ( + sailing && + !rebuild && + visible && + presentation.animations !== false && + !reducedMotion.matches && + !document.hidden + ) + sailTo(sailing.p, next.players[sailing.p].boat, sailing.path); + else if (sailing && !rebuild) { + sailTo(sailing.p, next.players[sailing.p].boat, sailing.path); + finishSailing(); + } + if ( + visible && + presentation.animations !== false && + !reducedMotion.matches && + !document.hidden + ) { + const slots = newDrawingSlots(moves, previous, next); + const fresh = drawings.filter((d) => + slots.some((s) => s.cell === d.cell && s.slot === d.slot), + ); + if (fresh.length) startDrawing(fresh); + } + if (presentation.sound !== true) sailingSound.stop(); + if (presentation.animations === false) settleAnimations(); + invalidate(); + } + function canAnimate() { + return ( + visible && + presentation.animations !== false && + !reducedMotion.matches && + !document.hidden + ); + } + function finishCamera(complete = true) { + if (!cameraMotion) return; + if (complete) { + camera.position.copy(cameraMotion.to); + controls.target.copy(cameraMotion.target); + controls.update(); + } + cameraMotion = null; + delete target.dataset.cameraTransition; + resolveCamera?.(); + resolveCamera = null; + invalidate(); + } + function animateCamera(now) { + if (!cameraMotion) return; + const m = cameraMotion; + m.start ??= now; + const t = Math.min(1, (now - m.start) / 850), + ease = 1 - Math.pow(1 - t, 3); + camera.position.lerpVectors(m.from, m.to, ease); + controls.target.lerpVectors(m.origin, m.target, ease); + controls.update(); + if (t === 1) finishCamera(); + } + function startTiles(groups) { + finishTiles(); + tileMotion = { groups, start: null }; + tileReady = new Promise((resolve) => (resolveTiles = resolve)); + for (const g of groups) { + g.position.y = -0.22; + g.scale.setScalar(0.96); + } + target.dataset.tileTransition = "arrival"; + invalidate(); + } + function finishTiles() { + if (!tileMotion) return; + for (const g of tileMotion.groups) { + g.position.y = 0; + g.scale.setScalar(1); + } + tileMotion = null; + delete target.dataset.tileTransition; + resolveTiles?.(); + resolveTiles = null; + renderer.shadowMap.needsUpdate = true; + invalidate(); + } + function animateTiles(now) { + if (!tileMotion) return; + const m = tileMotion; + m.start ??= now; + const t = Math.min(1, (now - m.start) / 650), + ease = 1 - Math.pow(1 - t, 3); + for (const g of m.groups) { + g.position.y = -0.22 * (1 - ease); + g.scale.setScalar(0.96 + 0.04 * ease); + } + renderer.shadowMap.needsUpdate = true; + if (t === 1) finishTiles(); + } + function resetCamera({ animate = true } = {}) { + const from = camera.position.clone(), + origin = controls.target.clone(); + finishCamera(false); + controls.target.copy(center); + const narrow = host.clientWidth < 700; + const direction = ( + narrow + ? new THREE.Vector3(1.45, 1.8, -0.18) + : new THREE.Vector3(0.12, 1.5, 1.4) + ).normalize(); + const corners = []; + for (const [id, t] of Object.entries({ + ...Object.fromEntries( + (presentation.targets ?? []).map((id) => [id, { type: "sea" }]), + ), + ...state.board, + })) { + const p = position(id); + for (const v of shape.getPoints(18)) + corners.push(new THREE.Vector3(p.x + v.x, 0, p.z - v.y)); + if (t.type === "island" || state.players.some((p) => p.boat === id)) + corners.push(new THREE.Vector3(p.x, 1.45, p.z)); + } + let distance = 8; + for (let i = 0; i < 100; i++) { + camera.position.copy(center).addScaledVector(direction, distance); + camera.lookAt(center); + camera.updateMatrixWorld(); + if ( + corners.every((p) => { + const v = p.clone().project(camera); + return Math.abs(v.x) < 0.89 && Math.abs(v.y) < 0.77; + }) + ) + break; + distance *= 1.04; + } + // Center the actual silhouette, not the empty corners of its bounding box. + for (let i = 0; i < 6; i++) { + const screen = corners.map((p) => p.clone().project(camera)); + const mid = new THREE.Vector2( + (Math.min(...screen.map((p) => p.x)) + + Math.max(...screen.map((p) => p.x))) / + 2, + (Math.min(...screen.map((p) => p.y)) + + Math.max(...screen.map((p) => p.y))) / + 2, + ); + const ray = new THREE.Raycaster(); + ray.setFromCamera(mid, camera); + const target = ray.ray.intersectPlane( + new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.2), + new THREE.Vector3(), + ); + if (target) { + const delta = target.sub(controls.target); + camera.position.add(delta); + controls.target.add(delta); + camera.lookAt(controls.target); + camera.updateMatrixWorld(); + } + if (i < 5) { + const screen = corners.map((p) => p.clone().project(camera)); + const usage = Math.max( + ...screen.map((p) => + Math.max(Math.abs(p.x) / 0.87, Math.abs(p.y) / 0.79), + ), + ); + distance *= usage; + camera.position + .copy(controls.target) + .addScaledVector(direction, distance); + camera.lookAt(controls.target); + camera.updateMatrixWorld(); + } + } + if ( + animate && + cameraFramed && + canAnimate() && + (from.distanceTo(camera.position) > 0.01 || + origin.distanceTo(controls.target) > 0.01) + ) { + cameraMotion = { + from, + origin, + to: camera.position.clone(), + target: controls.target.clone(), + start: null, + }; + cameraReady = new Promise((resolve) => (resolveCamera = resolve)); + target.dataset.cameraTransition = "reframe"; + camera.position.copy(from); + controls.target.copy(origin); + } + cameraFramed = true; + controls.update(); + invalidate(); + } + + function sailTo(index, destination, cellPath) { + const route = routeFor(index, destination, cellPath); + if (!route) return; + const length = route.path + .slice(1) + .reduce( + (sum, p, i) => + sum + Math.hypot(p.x - route.path[i].x, p.z - route.path[i].z), + 0, + ); + motion = { + ...route, + index, + destination, + length, + elapsed: 0, + last: 0, + duration: Math.max(1000, Math.min(5000, length * 530)), + }; + ready = new Promise((resolve) => (resolveReady = resolve)); + target.setAttribute("aria-busy", "true"); + if (presentation.sound === true && visible) sailingSound.start(); + invalidate(); + } + function finishSailing() { + if (!motion) return; + const current = motion, + vessel = boats[current.index], + end = current.path.at(-1); + vessel.model.position.set(end.x, 0.08, end.z); + vessel.cell = current.destination; + for (const neighbour of current.neighbours) { + neighbour.object.position.copy(neighbour.target); + neighbour.object.rotation.copy(neighbour.rotation); + } + board.updateMatrixWorld(true); + for (const piece of protectedPieces) + piece.userData.labelBox.setFromObject(piece); + sailingSound.stop(); + motion = null; + renderer.shadowMap.needsUpdate = true; + resolveAnimation(); + invalidate(); + } + function resolveAnimation() { + if (motion || drawingMotion) return; + target.setAttribute("aria-busy", "false"); + resolveReady?.(); + resolveReady = null; + } + function startDrawing(fresh) { + drawingMotion = { fresh, elapsed: 0, last: null }; + for (const drawing of fresh) setDrawingProgress(drawing, 0); + ready = new Promise((resolve) => (resolveReady = resolve)); + target.setAttribute("aria-busy", "true"); + target.dataset.drawingCell = fresh[0].cell; + invalidate(); + } + function finishDrawing() { + if (!drawingMotion) return; + for (const drawing of drawingMotion.fresh) setDrawingProgress(drawing, 1); + drawingMotion = null; + delete target.dataset.drawingCell; + resolveAnimation(); + invalidate(); + } + function animateDrawing(now) { + if (!drawingMotion) return; + const current = drawingMotion; + if (current.last !== null) + current.elapsed += Math.min(80, now - current.last); + current.last = now; + const progress = Math.min(1, current.elapsed / DRAW_DURATION); + for (const drawing of current.fresh) setDrawingProgress(drawing, progress); + if (progress === 1) finishDrawing(); + } + function settleAnimations() { + finishSailing(); + finishDrawing(); + finishTiles(); + finishCamera(); + } + function zoom(factor) { + finishCamera(false); + const offset = camera.position.clone().sub(controls.target); + const length = Math.max( + controls.minDistance, + Math.min(controls.maxDistance, offset.length() * factor), + ); + camera.position.copy(controls.target).add(offset.setLength(length)); + controls.update(); + invalidate(); + } + const raycaster = new THREE.Raycaster(), + activePointers = new Set(); + let down, + moved = false; + listen(gestureSurface, "pointerdown", (e) => { + if (!visible) return; + finishCamera(false); + activePointers.add(e.pointerId); + if (activePointers.size > 1) { + down = null; + moved = true; + } else if (e.button === 0) { + down = { + x: e.clientX, + y: e.clientY, + id: e.pointerId, + cell: e.target.closest("[data-map-tile]")?.dataset.mapTile, + }; + moved = false; + } + }); + listen(gestureSurface, "pointermove", (e) => { + if (!visible) return; + if (down && Math.hypot(e.clientX - down.x, e.clientY - down.y) > 5) + moved = true; + }); + listen(gestureSurface, "pointerup", (e) => { + if (!visible) return; + activePointers.delete(e.pointerId); + if (!down || down.id !== e.pointerId) return; + if (!moved) { + const r = host.getBoundingClientRect(); + raycaster.setFromCamera( + new THREE.Vector2( + ((e.clientX - r.left) / r.width) * 2 - 1, + (-(e.clientY - r.top) / r.height) * 2 + 1, + ), + camera, + ); + selectTile( + down.cell ?? + raycaster.intersectObjects([...tiles, ...ghostTiles], false)[0] + ?.object.userData.cell ?? + null, + ); + } + down = null; + }); + listen(gestureSurface, "pointercancel", (e) => { + activePointers.delete(e.pointerId); + down = null; + }); + listen(renderer.domElement, "keydown", (e) => { + const keys = [ + "ArrowLeft", + "ArrowRight", + "ArrowUp", + "ArrowDown", + "+", + "=", + "-", + "0", + "Escape", + ]; + if (!keys.includes(e.key)) return; + e.preventDefault(); + if (e.key === "Escape") selectTile(null); + else if (e.key === "0") resetCamera(); + else if (e.key === "+" || e.key === "=") zoom(0.8); + else if (e.key === "-") zoom(1.25); + else { + const delta = new THREE.Vector3( + e.key === "ArrowLeft" ? -0.6 : e.key === "ArrowRight" ? 0.6 : 0, + 0, + e.key === "ArrowUp" ? -0.6 : e.key === "ArrowDown" ? 0.6 : 0, + ); + camera.position.add(delta); + controls.target.add(delta); + controls.update(); + invalidate(); + } + }); + function screenBox(box) { + const points = []; + for (const x of [box.min.x, box.max.x]) + for (const y of [box.min.y, box.max.y]) + for (const z of [box.min.z, box.max.z]) { + const p = new THREE.Vector3(x, y, z).project(camera); + points.push({ + x: (p.x * 0.5 + 0.5) * host.clientWidth, + y: (0.5 - p.y * 0.5) * host.clientHeight, + }); + } + const x = Math.min(...points.map((p) => p.x)), + y = Math.min(...points.map((p) => p.y)); + return { + x, + y, + w: Math.max(...points.map((p) => p.x)) - x, + h: Math.max(...points.map((p) => p.y)) - y, + }; + } + function updateLabels() { + const w = host.clientWidth, + h = host.clientHeight; + // Reserve the projected volume of goods: HTML badges have no depth testing. + const pieces = new Map( + protectedPieces.map((piece) => [ + piece, + screenBox(piece.userData.labelBox), + ]), + ); + const occupied = [...pieces.values()]; + const frame = host.getBoundingClientRect(); + for (const overlay of target.parentElement.querySelectorAll( + ".market-info, .demand-ships, .map-tools, .upcoming", + )) { + const r = overlay.getBoundingClientRect(); + if (r.width && r.height) + occupied.push({ + x: r.left - frame.left, + y: r.top - frame.top, + w: r.width, + h: r.height, + }); + } + const overlaps = (r, o) => + r.x < o.x + o.w + 4 && + r.x + r.w + 4 > o.x && + r.y < o.y + o.h + 4 && + r.y + r.h + 4 > o.y; + for (const label of [...labels].sort((a, b) => b.priority - a.priority)) { + label.leader.hidden = true; + if (label.boat !== undefined) + label.point + .copy(boats[label.boat].model.position) + .add(new THREE.Vector3(0, 1.35, 0)); + const p = label.point.clone().project(camera); + label.el.hidden = p.z > 1 || p.z < -1; + if (label.el.hidden) continue; + const lw = label.el.offsetWidth, + lh = label.el.offsetHeight; + const piece = pieces.get(label.piece); + const model = label.el.classList.contains("model-label"); + const x = model && piece ? piece.x + piece.w / 2 : (p.x * 0.5 + 0.5) * w; + const y = Math.max( + (0.5 - p.y * 0.5) * h, + piece ? piece.y + piece.h + lh / 2 + 5 : -Infinity, + ); + let rect = null; + const candidates = + model && piece + ? [ + { x, y: piece.y + piece.h + lh / 2 + 5 }, + { x: piece.x + piece.w + lw / 2 + 5, y: piece.y + piece.h / 2 }, + { x: piece.x - lw / 2 - 5, y: piece.y + piece.h / 2 }, + { x, y: piece.y - lh / 2 - 5 }, + ] + : []; + for (const offset of [ + 0, + 5, + 10, + 15, + 20, + lh + 5, + -lh - 5, + 2 * (lh + 5), + -2 * (lh + 5), + 3 * (lh + 5), + -3 * (lh + 5), + ]) { + for (const dx of [0, -lw * 0.5, lw * 0.5, -lw, lw]) + candidates.push({ x: x + dx, y: y + offset }); + } + for (const point of candidates) { + const candidate = { + x: Math.max(4, Math.min(w - lw - 4, point.x - lw / 2)), + y: Math.max(4, Math.min(h - lh - 4, point.y - lh / 2)), + w: lw, + h: lh, + }; + if (!occupied.some((o) => overlaps(candidate, o))) { + rect = candidate; + break; + } + } + if (!rect) { + label.el.hidden = true; + continue; + } + occupied.push(rect); + label.el.style.transform = `translate(${rect.x + lw / 2}px,${rect.y + lh / 2}px) translate(-50%,-50%)`; + label.el.style.zIndex = String(Math.round((1 - p.z) * 100)); + const ax = (p.x * 0.5 + 0.5) * w, + ay = (0.5 - p.y * 0.5) * h, + dx = rect.x + lw / 2 - ax, + dy = rect.y + lh / 2 - ay; + if (Math.hypot(dx, dy) > Math.max(42, lh * 1.3)) { + label.leader.hidden = false; + label.leader.style.width = `${Math.hypot(dx, dy)}px`; + label.leader.style.transform = `translate(${ax}px,${ay}px) rotate(${Math.atan2(dy, dx)}rad)`; + } + } + } + function pieceFootprint(object) { + const box = new THREE.Box3(), + origin = object.getWorldPosition(new THREE.Vector3()); + object.traverse((part) => { + if (part.isMesh) { + part.geometry.computeBoundingBox(); + box.union( + part.geometry.boundingBox.clone().applyMatrix4(part.matrixWorld), + ); + } + }); + return { + minX: box.min.x - origin.x, + maxX: box.max.x - origin.x, + minZ: box.min.z - origin.z, + maxZ: box.max.z - origin.z, + }; + } + function routeFor(index, destination, cellPath) { + const vessel = boats[index], + p = position(destination); + if (state.board[destination]?.type !== "sea" || vessel.cell === destination) + return null; + const occupants = boats + .map((b, i) => ({ b, i })) + .filter(({ b, i }) => i === index || b.cell === destination); + const targets = new Map( + occupants.map(({ i }, j) => [ + i, + new THREE.Vector3( + p.x + (j - (occupants.length - 1) / 2) * 0.94, + 0.08, + p.z - 0.15, + ), + ]), + ); + const departure = position(vessel.cell); + const staying = boats + .map((b, i) => ({ b, i })) + .filter(({ b, i }) => i !== index && b.cell === vessel.cell); + staying.forEach(({ i }, j) => + targets.set( + i, + new THREE.Vector3( + departure.x + (j - (staying.length - 1) / 2) * 0.94, + 0.08, + departure.z - 0.15, + ), + ), + ); + const goal = targets.get(index), + origin = vessel.model.position; + const path = seaRoute( + state.board, + vessel.cell, + destination, + { x: origin.x, z: origin.z }, + { x: goal.x, z: goal.z }, + position, + cellPath, + ); + board.updateMatrixWorld(true); + const pieces = [ + ...boats.filter((b, i) => i !== index).map((b) => b.model), + ...solids.map((s) => s.object), + ]; + const neighbours = pieces.map((object, i) => { + const local = object.position.clone(), + world = object.getWorldPosition(new THREE.Vector3()); + const boatIndex = boats.findIndex((b) => b.model === object), + target = targets.get(boatIndex)?.clone() ?? local.clone(); + return { + object, + local, + world, + target, + departing: staying.some((p) => p.i === boatIndex), + rotation: object.rotation.clone(), + isBoat: boatIndex >= 0, + footprint: pieceFootprint(object), + side: passingSide(path, world, i), + pose: { x: 0, z: 0, yaw: 0, vx: 0, vz: 0, vyaw: 0 }, + }; + }); + return { + path, + targets, + neighbours, + footprint: pieceFootprint(vessel.model), + }; + } + function animateSailing(now) { + if (!motion) return; + const dt = motion.last ? Math.min(80, now - motion.last) : 16; + motion.elapsed += motion.last ? dt : 0; + motion.last = now; + const t = Math.min(1, motion.elapsed / motion.duration), + ease = t * t * (3 - 2 * t), + p = routePosition(motion.path, ease); + sailingSound.setRemainingTime((motion.duration - motion.elapsed) / 1000); + const ahead = routePosition(motion.path, Math.min(1, ease + 0.018)), + behind = routePosition(motion.path, Math.max(0, ease - 0.018)); + const direction = { x: ahead.x - behind.x, z: ahead.z - behind.z }; + boats[motion.index].model.position.set( + p.x, + 0.08 + Math.sin(t * Math.PI) * 0.025, + p.z, + ); + const arrival = arrivalFraction(motion.length * (1 - ease)); + const passing = routePosition( + motion.path, + Math.min(1, ease + 0.1 / Math.max(0.1, motion.length)), + ); + if (t === 1 && !motion.arrived) { + motion.arrived = true; + sailingSound.stop(); + } + for (const neighbour of motion.neighbours) { + const departure = THREE.MathUtils.smoothstep( + motion.length * ease, + 0.9, + 1.8, + ); + const base = neighbour.local + .clone() + .lerp(neighbour.target, neighbour.departing ? departure : arrival); + const world = neighbour.world + .clone() + .add(base.clone().sub(neighbour.local)); + const nudge = + t === 1 + ? { x: 0, z: 0 } + : giveWay( + world, + passing, + direction, + neighbour.side, + motion.footprint, + neighbour.footprint, + ); + const amount = Math.hypot(nudge.x, nudge.z), + maxAngle = neighbour.isBoat ? 0.26 : 0.13; + const yaw = amount + ? THREE.MathUtils.clamp( + Math.atan2(-nudge.x, -nudge.z), + -maxAngle, + maxAngle, + ) * Math.min(1, amount / 0.28) + : 0; + const pose = stepYield( + neighbour.pose, + { x: nudge.x, z: nudge.z, yaw }, + dt / 1000, + ); + neighbour.object.position + .copy(base) + .add(new THREE.Vector3(pose.x, 0, pose.z)); + neighbour.object.rotation.y = neighbour.rotation.y + pose.yaw; + neighbour.object.rotation.z = + neighbour.rotation.z + + (neighbour.isBoat + ? THREE.MathUtils.clamp(pose.vx * 0.018, -0.025, 0.025) + : 0); + } + board.updateMatrixWorld(true); + for (const solid of solids) + solid.object.userData.labelBox.setFromObject(solid.object); + renderer.shadowMap.needsUpdate = true; + if ( + t === 1 && + (motion.elapsed - motion.duration > 500 || + motion.neighbours.every( + (n) => Math.hypot(n.pose.x, n.pose.z, n.pose.yaw) < 0.001, + )) + ) + finishSailing(); + } + + function invalidate() { + if (visible && !pending && !document.hidden) + pending = requestAnimationFrame(render); + } + function render(now) { + pending = 0; + if (document.hidden || !visible) return; + animateSailing(now); + animateDrawing(now); + animateCamera(now); + animateTiles(now); + updateLabels(); + renderer.render(scene, camera); + if (motion || drawingMotion || cameraMotion || tileMotion) invalidate(); + } + controls.addEventListener("change", invalidate); + function resizeViewport() { + const w = host.clientWidth, + h = host.clientHeight; + if (!w || !h || (w === viewportWidth && h === viewportHeight)) return null; + const widthChanged = w !== viewportWidth; + // A taller/shorter action panel must not reset a player's zoom or pan. + // Preserve the on-screen scale while adjusting the available canvas height. + if (cameraFramed && viewportHeight) { + const ratio = h / viewportHeight; + camera.position + .sub(controls.target) + .multiplyScalar(ratio) + .add(controls.target); + if (cameraMotion) { + cameraMotion.from + .sub(cameraMotion.origin) + .multiplyScalar(ratio) + .add(cameraMotion.origin); + cameraMotion.to + .sub(cameraMotion.target) + .multiplyScalar(ratio) + .add(cameraMotion.target); + } + } + viewportWidth = w; + viewportHeight = h; + renderer.setSize(w, h); + camera.aspect = w / h; + camera.updateProjectionMatrix(); + controls.update(); + invalidate(); + return { widthChanged }; + } + const resize = new ResizeObserver(() => { + const changed = resizeViewport(); + if (changed?.widthChanged && bounds) resetCamera({ animate: cameraFramed }); + }); + resize.observe(host); + listen( + target, + "pointerdown", + () => { + if (presentation.sound === true) sailingSound.unlock(); + }, + { passive: true }, + ); + listen(document, "visibilitychange", () => { + if (document.hidden) { + settleAnimations(); + cancelAnimationFrame(pending); + pending = 0; + sailingSound.stop(); + } else invalidate(); + }); + listen(gestureSurface, "wheel", () => finishCamera(false), { passive: true }); + listen(window, "pagehide", () => { + settleAnimations(); + sailingSound.stop(); + }); + listen(reducedMotion, "change", () => { + if (reducedMotion.matches) settleAnimations(); + }); + return { + update, + zoom, + reset: resetCamera, + unlock: () => { + if (presentation.sound === true) sailingSound.unlock(); + }, + setVisible(value) { + if (visible === value) return; + visible = value; + controls.enabled = value; + if (!value) { + settleAnimations(); + cancelAnimationFrame(pending); + pending = 0; + sailingSound.stop(); + } else invalidate(); + }, + whenIdle: async () => { + do { + await Promise.all([ready, cameraReady, tileReady]); + } while (motion || drawingMotion || cameraMotion || tileMotion); + }, + settle: settleAnimations, + destroy() { + visible = false; + events.abort(); + resize.disconnect(); + settleAnimations(); + cancelAnimationFrame(pending); + controls.dispose(); + disposeBoard(); + for (const m of palette.values()) m.dispose(); + for (const m of goodsLabels.values()) { + m.map.dispose(); + m.dispose(); + } + scene.traverse((o) => { + o.geometry?.dispose(); + if (!Array.isArray(o.material)) o.material?.dispose(); + }); + renderer.dispose(); + target.replaceChildren(); + }, + }; +} diff --git a/viewer/three/navigation.js b/viewer/three/navigation.js new file mode 100644 index 0000000..902ad11 --- /dev/null +++ b/viewer/three/navigation.js @@ -0,0 +1,180 @@ +const distance = (a, b) => Math.hypot(a.x - b.x, a.z - b.z); +const neighbours = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + [1, 1], + [-1, -1], +]; + +// Only the game's sea topology guides the illustration. Pieces never block it. +export function seaRoute(board, from, to, start, end, position, cellPath) { + const queue = [from], + parent = new Map([[from, null]]); + for (let i = 0; i < queue.length && !parent.has(to); i++) { + const [q, r] = queue[i].split(",").map(Number); + for (const [dq, dr] of neighbours) { + const id = `${q + dq},${r + dr}`; + if (board[id]?.type === "sea" && !parent.has(id)) { + parent.set(id, queue[i]); + queue.push(id); + } + } + } + const cells = cellPath?.length ? [from, ...cellPath] : []; + if (!cells.length && parent.has(to)) + for (let id = to; id; id = parent.get(id)) cells.unshift(id); + const points = [ + start, + ...cells.slice(1, -1).map((id) => { + const p = position(id); + return { x: p.x, z: p.z - 0.15 }; + }), + end, + ]; + const path = [start]; + for (let i = 1; i < points.length - 1; i++) { + const a = points[i - 1], + b = points[i], + c = points[i + 1]; + const radius = Math.min(0.28, distance(a, b) * 0.25, distance(b, c) * 0.25); + if (!radius) continue; + const entry = { + x: b.x + ((a.x - b.x) * radius) / distance(a, b), + z: b.z + ((a.z - b.z) * radius) / distance(a, b), + }; + const exit = { + x: b.x + ((c.x - b.x) * radius) / distance(b, c), + z: b.z + ((c.z - b.z) * radius) / distance(b, c), + }; + for (let j = 0; j <= 8; j++) { + const t = j / 8, + u = 1 - t; + path.push({ + x: u * u * entry.x + 2 * u * t * b.x + t * t * exit.x, + z: u * u * entry.z + 2 * u * t * b.z + t * t * exit.z, + }); + } + } + path.push(end); + return path; +} + +export function routePosition(path, progress) { + if (progress <= 0) return path[0]; + if (progress >= 1) return path.at(-1); + const lengths = path.slice(1).map((p, i) => distance(path[i], p)); + let remaining = progress * lengths.reduce((a, b) => a + b, 0); + for (let i = 0; i < lengths.length; i++) { + if (remaining <= lengths[i]) { + const t = lengths[i] ? remaining / lengths[i] : 1; + return { + x: path[i].x + (path[i + 1].x - path[i].x) * t, + z: path[i].z + (path[i + 1].z - path[i].z) * t, + }; + } + remaining -= lengths[i]; + } + return path.at(-1); +} + +export function passingSide(path, point, index) { + let nearest = Infinity, + side = index % 2 ? 1 : -1; + for (let i = 1; i < path.length; i++) { + const a = path[i - 1], + b = path[i], + dx = b.x - a.x, + dz = b.z - a.z, + length = Math.hypot(dx, dz); + if (!length) continue; + const t = Math.max( + 0, + Math.min( + 1, + ((point.x - a.x) * dx + (point.z - a.z) * dz) / (length * length), + ), + ); + const x = a.x + dx * t, + z = a.z + dz * t, + d = Math.hypot(point.x - x, point.z - z); + if (d < nearest) { + nearest = d; + const cross = (point.x - x) * -dz + (point.z - z) * dx; + if (Math.abs(cross) > 0.02) side = Math.sign(cross); + } + } + return side; +} + +export function arrivalFraction(remaining) { + const t = Math.max(0, Math.min(1, 1 - remaining / 1.1)); + return t * t * (3 - 2 * t); +} + +export function giveWay(point, vessel, direction, side, boat, piece) { + const gap = 0.055; + const a = { + minX: point.x + piece.minX, + maxX: point.x + piece.maxX, + minZ: point.z + piece.minZ, + maxZ: point.z + piece.maxZ, + }; + const b = { + minX: vessel.x + boat.minX - gap, + maxX: vessel.x + boat.maxX + gap, + minZ: vessel.z + boat.minZ - gap, + maxZ: vessel.z + boat.maxZ + gap, + }; + // Both axes must overlap. An infinite strip perpendicular to the route was + // making remote pieces move, especially when the route changed direction. + if ( + a.maxX <= b.minX || + a.minX >= b.maxX || + a.maxZ <= b.minZ || + a.minZ >= b.maxZ + ) + return { x: 0, z: 0 }; + const length = Math.hypot(direction.x, direction.z); + if (!length) return { x: 0, z: 0 }; + const normal = { x: -direction.z / length, z: direction.x / length }; + function clearance(sign) { + const x = normal.x * sign, + z = normal.z * sign; + return Math.min( + x > 1e-6 + ? (b.maxX - a.minX) / x + : x < -1e-6 + ? (a.maxX - b.minX) / -x + : Infinity, + z > 1e-6 + ? (b.maxZ - a.minZ) / z + : z < -1e-6 + ? (a.maxZ - b.minZ) / -z + : Infinity, + ); + } + const left = clearance(1), + right = clearance(-1); + const sign = Math.abs(left - right) < 0.08 ? side : left < right ? 1 : -1; + const amount = sign === 1 ? left : right; + return { x: normal.x * sign * amount, z: normal.z * sign * amount }; +} + +// Critically damped: accelerate and settle without oscillating back and forth. +export function stepYield(pose, target, seconds) { + const omega = 23, + decay = Math.exp(-omega * seconds); + for (const [key, velocity] of [ + ["x", "vx"], + ["z", "vz"], + ["yaw", "vyaw"], + ]) { + const change = pose[key] - target[key], + step = (pose[velocity] + omega * change) * seconds; + pose[key] = target[key] + (change + step) * decay; + pose[velocity] = (pose[velocity] - omega * step) * decay; + } + return pose; +} diff --git a/viewer/three/sailing-sound.js b/viewer/three/sailing-sound.js new file mode 100644 index 0000000..7d9277e --- /dev/null +++ b/viewer/three/sailing-sound.js @@ -0,0 +1,95 @@ +// Continuous filtered water noise, tied to animation start/stop rather than a +// fixed-length cue. No ambience runs while the board is idle. +export function createSailingSound( + createContext = () => + new (globalThis.AudioContext ?? globalThis.webkitAudioContext)(), +) { + let context, + buffer, + voices = [], + generation = 0, + ready = Promise.resolve(), + level = 1; + function unlock() { + try { + context ??= createContext(); + if (context.state === "suspended") + ready = context.resume().catch(() => {}); + } catch {} + } + function stop(fade = 0.72) { + generation++; + const current = voices; + voices = []; + for (const { source, gain } of current) { + const now = context.currentTime; + if (gain.gain.cancelAndHoldAtTime) gain.gain.cancelAndHoldAtTime(now); + else { + gain.gain.cancelScheduledValues(now); + gain.gain.setValueAtTime(Math.max(0.0001, gain.gain.value), now); + } + gain.gain.setTargetAtTime(0.0001, now, fade / 4.5); + try { + source.stop(now + fade); + } catch {} + } + } + async function start() { + if (voices.length) return; + stop(0.12); + level = 1; + const request = generation; + unlock(); + await ready; + if (request !== generation || context?.state !== "running") return; + try { + if (!buffer) { + buffer = context.createBuffer( + 1, + context.sampleRate * 2, + context.sampleRate, + ); + const data = buffer.getChannelData(0); + let seed = 9173; + for (let i = 0; i < data.length; i++) { + seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; + data[i] = seed / 2147483648 - 1; + } + } + for (const [frequency, volume] of [ + [700, 0.095], + [1100, 0.045], + ]) { + const source = context.createBufferSource(), + filter = context.createBiquadFilter(), + gain = context.createGain(); + source.buffer = buffer; + source.loop = true; + filter.type = "lowpass"; + filter.frequency.value = frequency; + source.connect(filter).connect(gain).connect(context.destination); + const now = context.currentTime; + gain.gain.setValueAtTime(0.0001, now); + gain.gain.exponentialRampToValueAtTime(volume * level, now + 0.12); + source.onended = () => { + source.disconnect(); + filter.disconnect(); + gain.disconnect(); + }; + voices.push({ source, gain, volume }); + source.start(); + } + } catch { + stop(); + } + } + function setRemainingTime(seconds) { + const t = Math.max(0, Math.min(1, seconds / 0.6)), + next = 0.35 + 0.65 * t * t * (3 - 2 * t); + if (Math.abs(level - next) < 0.005) return; + level = next; + for (const { gain, volume } of voices) + gain.gain.setTargetAtTime(volume * level, context.currentTime, 0.045); + } + return { unlock, start, stop, setRemainingTime }; +} diff --git a/viewer/three/sand-drawing.js b/viewer/three/sand-drawing.js new file mode 100644 index 0000000..24cf55a --- /dev/null +++ b/viewer/three/sand-drawing.js @@ -0,0 +1,74 @@ +import * as THREE from "three"; + +export const DRAW_DURATION = 1500; +const SEGMENTS = 160; +const SIDES = 5; + +// Stable slots: adding a drawing never slides the ones already in the sand. +export function createSandDrawing(slot, capacity) { + const group = new THREE.Group(); + group.position.set((slot - (capacity - 1) / 2) * 0.43, 0.271, 0.94); + const points = Array.from({ length: 121 }, (_, i) => { + const t = (i / 120) * Math.PI * 4; + return new THREE.Vector3(Math.sin(t) * 0.17, 0, Math.sin(t * 1.5) * 0.105); + }); + const curve = new THREE.CatmullRomCurve3(points, false, "centripetal"); + const groove = new THREE.Mesh( + new THREE.TubeGeometry(curve, SEGMENTS, 0.01, SIDES, false), + new THREE.MeshBasicMaterial({ color: "#906437" }), + ); + const rim = new THREE.Mesh( + new THREE.TubeGeometry(curve, SEGMENTS, 0.017, SIDES, false), + new THREE.MeshBasicMaterial({ color: "#ffe8b4" }), + ); + rim.position.y = -0.008; + group.add(rim, groove); + const tip = new THREE.Group(); + const grains = new THREE.MeshBasicMaterial({ + color: "#fff0c7", + transparent: true, + opacity: 0, + }); + for (let i = 0; i < 3; i++) { + const grain = new THREE.Mesh( + new THREE.IcosahedronGeometry(0.018 - i * 0.003, 0), + grains, + ); + grain.position.set((i - 1) * 0.025, 0.027 + i * 0.009, -i * 0.016); + tip.add(grain); + } + group.add(tip); + tip.visible = false; + const drawing = { group, groove, rim, tip, curve, grains }; + setDrawingProgress(drawing, 1); + return drawing; +} + +export function setDrawingProgress(drawing, progress) { + const p = Math.max(0, Math.min(1, progress)); + // Leave time for the fresh sand at the tip to settle after the line closes. + const trace = Math.min(1, p / 0.88); + const count = Math.floor(trace * SEGMENTS) * SIDES * 6; + for (const mesh of [drawing.groove, drawing.rim]) + mesh.geometry.setDrawRange(0, count); + drawing.tip.visible = p > 0 && p < 1; + if (drawing.tip.visible) { + drawing.tip.position.copy(drawing.curve.getPointAt(trace)); + drawing.grains.opacity = Math.min(1, p / 0.08, (1 - p) / 0.12); + } +} + +// Call only with adjacent live events. Loading/replaying a state does not draw +// its old patterns again, and a third drawing is as visible as the first two. +export function newDrawingSlots(events, before, after) { + const slots = []; + for (const event of events) { + if (event.type !== "action" || event.action !== "draw") continue; + const cell = event.cell ?? event.details?.cell; + const start = before?.board[cell]?.drawings; + const end = after?.board[cell]?.drawings; + if (!Number.isInteger(start) || !Number.isInteger(end)) continue; + for (let slot = start; slot < end; slot++) slots.push({ cell, slot }); + } + return slots; +} diff --git a/viewer/three/style.css b/viewer/three/style.css new file mode 100644 index 0000000..f23c843 --- /dev/null +++ b/viewer/three/style.css @@ -0,0 +1,166 @@ +.vanuatu .map-3d { + position: absolute; + inset: 0 0 var(--tray-height, 73px); + isolation: isolate; + overflow: hidden; + touch-action: none; + display: none; +} +.vanuatu[data-map-view="3d"] .map-3d { + display: block; +} +.vanuatu[data-map-view="3d"] .map-scroll { + visibility: hidden; + pointer-events: none; +} +.vanuatu .map-3d .world, +.vanuatu .map-3d canvas, +.vanuatu .map-3d .labels { + position: absolute; + inset: 0; + width: 100%; + height: 100%; +} +.vanuatu .map-3d canvas { + display: block; + cursor: grab; +} +.vanuatu .map-3d canvas:active { + cursor: grabbing; +} +.vanuatu .map-3d .labels { + pointer-events: none; + overflow: hidden; +} +.vanuatu .map-3d .map-label-link { + position: absolute; + left: 0; + top: 0; + border-top: 1px dashed #fff9df; + filter: drop-shadow(0 1px 1px #31595788); + transform-origin: 0 0; + pointer-events: none; +} +.vanuatu .map-3d .map-label { + position: absolute; + left: 0; + top: 0; + display: flex; + align-items: center; + gap: 7px; + white-space: nowrap; + pointer-events: auto; + background: #fffae6f5; + border: 1px solid #f8f9dacc; + color: #244d4e; + border-radius: 14px; + padding: 3px 7px; + box-shadow: 0 2px 3px #194e4c22; + font-size: 13px; + touch-action: none; +} +.vanuatu .map-3d .map-label .icon { + width: 21px; + height: 21px; +} +.vanuatu .map-3d .map-label .token { + gap: 1px; +} +.vanuatu .map-3d .map-label[aria-pressed="true"] { + outline: 2px solid #a7692f; + outline-offset: 2px; +} +.vanuatu .map-3d .map-label.legal { + border-color: #a7692f; +} +.vanuatu .map-3d .map-label[hidden] { + display: none; +} +.vanuatu .map-3d .map-label.model-label { + min-width: 24px; + min-height: 24px; + justify-content: center; + padding: 1px 6px; + border-radius: 50%; + font-size: 13px; +} +.vanuatu .map-3d .map-label.placement-label { + font-size: 15px; + padding: 4px 8px; + border-color: #f8f9dacc; +} +.vanuatu .map-3d .map-label.placement-label .icon { + width: 24px; + height: 24px; +} +.vanuatu .map-3d .map-label.placement-label[aria-pressed="true"] { + outline: none; +} +.vanuatu .map-3d .map-label.placement-label:focus-visible { + outline: 2px solid #a7692f; + outline-offset: 2px; +} +.vanuatu .map-3d .map-label.empty-placement { + width: 44px; + height: 44px; + border: 0; + background: none; + box-shadow: none; +} +.vanuatu .map-view-switch, +.vanuatu .three-tools { + display: flex; + gap: 4px; +} +.vanuatu .map-view-switch { + margin-right: 6px; +} +.vanuatu .map-view-switch button { + font-weight: 700; + min-width: 40px; + padding: 6px 8px; +} +.vanuatu .map-view-switch button[aria-pressed="true"] { + background: #fdf9e7; + border-color: #876c3b; +} +.vanuatu[data-map-view="2d"] .three-tools { + display: none; +} +.vanuatu[data-map-view="3d"] .map-tools > [data-zoom-in], +.vanuatu[data-map-view="3d"] .map-tools > [data-zoom-out] { + display: none; +} +@media (max-width: 700px) { + .vanuatu .map-3d .map-label { + font-size: 11px; + gap: 4px; + padding: 2px 4px; + } + .vanuatu .map-3d .map-label .icon { + width: 17px; + height: 17px; + } + .vanuatu .map-3d .map-label.model-label { + min-width: 20px; + min-height: 20px; + padding: 1px 5px; + font-size: 11px; + } + .vanuatu .map-3d .map-label.placement-label { + flex-direction: column; + gap: 1px; + padding: 3px 5px; + font-size: 14px; + } + .vanuatu .map-3d .map-label.placement-label .icon { + width: 20px; + height: 20px; + } + .vanuatu .map-view-switch { + margin-right: 2px; + } + .vanuatu .map-view-switch button { + min-width: 34px; + } +} diff --git a/viewer/trade-transition.js b/viewer/trade-transition.js new file mode 100644 index 0000000..9f92496 --- /dev/null +++ b/viewer/trade-transition.js @@ -0,0 +1,188 @@ +// Reconstruct deliveries from the public event; never delay the actual game state. +export function tradeFrames(before, after, events) { + if (!before || !events.length) return null; + const initial = before.demands.map((d) => ({ + ...d, + goods: [...d.goods], + filled: [...d.filled], + })); + const delivered = initial.map((d) => ({ ...d, filled: [...d.filled] })); + const touched = new Set(), + completed = new Set(); + for (const event of events) + for (const shipment of event.details?.shipments ?? []) { + const ship = delivered.find((d) => d.id === shipment.ship); + const slot = ship?.goods.findIndex( + (good, i) => good === event.good && !ship.filled[i], + ); + if (slot >= 0) { + ship.filled[slot] = true; + touched.add(ship.id); + } + if (shipment.complete) completed.add(shipment.ship); + } + const departing = initial + .filter((d) => !after.demands.some((n) => n.id === d.id)) + .map((d) => d.id); + return touched.size || departing.length + ? { + initial, + delivered, + touched: [...touched], + completed: [...completed], + departing, + } + : null; +} + +export function createTradeTransition(root, repaint) { + const motion = matchMedia("(prefers-reduced-motion: reduce)"); + let enabled = true, + plan, + visual, + epoch = 0, + ready = Promise.resolve(), + resolveReady; + const timers = new Map(), + animations = new Set(); + const allowed = () => enabled && !motion.matches && !document.hidden; + const ships = () => [...root.querySelectorAll(".demand-ship")]; + const animate = (node, frames, duration, fill = "none") => { + const a = node.animate(frames, { + duration, + fill, + easing: "cubic-bezier(.22,.61,.36,1)", + }); + animations.add(a); + a.onfinish = () => { + if (fill === "none") { + animations.delete(a); + a.cancel(); + } + }; + }; + const wait = (ms) => + new Promise((resolve) => { + const id = setTimeout(() => { + timers.delete(id); + resolve(); + }, ms); + timers.set(id, resolve); + }); + function cancel(render = true) { + epoch++; + for (const [id, resolve] of timers) { + clearTimeout(id); + resolve(); + } + timers.clear(); + for (const a of animations) a.cancel(); + animations.clear(); + const changed = !!visual; + visual = plan = null; + delete root.dataset.tradeTransition; + resolveReady?.(); + resolveReady = null; + if (changed && render) repaint(); + } + function prepare(before, after, events) { + cancel(false); + plan = allowed() ? tradeFrames(before, after, events) : null; + if (plan) visual = plan.touched.length ? plan.initial : plan.delivered; + } + async function run() { + if (!plan) return; + const current = epoch, + frame = plan; + ready = new Promise((resolve) => (resolveReady = resolve)); + root.dataset.tradeTransition = "delivery"; + if (frame.touched.length) { + await wait(420); + if (epoch !== current) return; + visual = frame.delivered; + repaint(); + for (const ship of ships().filter((n) => + frame.touched.includes(Number(n.dataset.ship)), + )) + animate( + ship, + [ + { boxShadow: "0 0 0 3px #ba913866", background: "#fff4bd" }, + { boxShadow: "0 0 0 0 transparent" }, + ], + 800, + ); + } + if (frame.departing.length) { + root.dataset.tradeTransition = "completed"; + await wait(650); + if (epoch !== current) return; + root.dataset.tradeTransition = "departure"; + for (const ship of ships().filter((n) => + frame.departing.includes(Number(n.dataset.ship)), + )) + animate( + ship, + [ + { opacity: 1, transform: "translateX(0)" }, + { opacity: 0, transform: "translateX(32px)" }, + ], + 360, + "forwards", + ); + await wait(360); + if (epoch !== current) return; + const positions = new Map( + ships().map((n) => [n.dataset.ship, n.getBoundingClientRect()]), + ); + for (const a of animations) a.cancel(); + animations.clear(); + visual = null; + repaint(); + root.dataset.tradeTransition = "arrival"; + for (const ship of ships()) { + const old = positions.get(ship.dataset.ship), + next = ship.getBoundingClientRect(); + animate( + ship, + old + ? [ + { + transform: `translate(${old.left - next.left}px,${old.top - next.top}px)`, + }, + { transform: "none" }, + ] + : [ + { opacity: 0, transform: "translateX(-20px)" }, + { opacity: 1, transform: "none" }, + ], + 360, + ); + } + await wait(360); + } else await wait(frame.completed.length ? 800 : 300); + if (epoch === current) cancel(); + } + const stop = () => cancel(); + const visibility = () => { + if (document.hidden) cancel(); + }; + motion.addEventListener("change", stop); + document.addEventListener("visibilitychange", visibility); + return { + prepare, + run, + cancel, + demands: (fallback) => visual ?? fallback, + whenIdle: () => ready, + setEnabled(value) { + enabled = value; + if (!allowed()) cancel(); + }, + destroy() { + cancel(false); + motion.removeEventListener("change", stop); + document.removeEventListener("visibilitychange", visibility); + }, + }; +} diff --git a/viewer/ui.js b/viewer/ui.js index 8dafbbb..279cc43 100644 --- a/viewer/ui.js +++ b/viewer/ui.js @@ -1,3 +1,5 @@ +import { createTradeTransition } from "./trade-transition.js"; +import { mountBoard3D } from "./three/board.js"; import { playerSymbolGlyph } from "@boardgamers/protocol/player-symbols"; import { blockingHtml, @@ -109,8 +111,17 @@ export function mountGame(target, options = {}) { revision, stateKey, focusReturn; + let board3D, + threeUnavailable = false, + mapView = "3d", + mapLive = false, + journalCells = []; + try { + if (localStorage.getItem("vanuatu-map-view") === "2d") mapView = "2d"; + } catch {} + root.dataset.mapView = mapView; const patch = createRenderer( - ".game-header, .action-dock, .market-info, .demand-ships, .map-scroll, .map-tools, .upcoming, .turn-tray, .player-card, .play-footer", + ".map-3d, .game-header, .action-dock, .market-info, .demand-ships, .map-scroll, .map-tools, .upcoming, .turn-tray, .player-card, .play-footer", (from, to) => { // These attributes belong to the layout/zoom controllers, not the state. const attr = from.matches(".sea-board, .map-canvas, .archipelago") @@ -138,12 +149,41 @@ export function mountGame(target, options = {}) { const effects = createEffects(root, { icon, sound: moveSound, center }); const events = new AbortController(); const listener = { signal: events.signal }; - root.addEventListener("pointerdown", () => moveSound.unlock(), { - ...listener, - passive: true, - }); - root.addEventListener("keydown", () => moveSound.unlock(), listener); + root.addEventListener( + "pointerdown", + () => { + moveSound.unlock(); + board3D?.unlock(); + }, + { + ...listener, + passive: true, + }, + ); + root.addEventListener( + "keydown", + () => { + moveSound.unlock(); + board3D?.unlock(); + }, + listener, + ); + const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)"); const mapZoom = mountMapZoom(play); + const tradeTransition = createTradeTransition(root, () => { + const node = play.querySelector(".demand-ships"); + if (node && s) patch(node, tradeShips()); + }); + function syncMotion() { + animations = !reducedMotion.matches; + effects.setEnabled(animations); + mapZoom.setEnabled(animations); + tradeTransition.setEnabled(animations); + root.dataset.animations = String(animations); + syncBoard3D(); + } + reducedMotion.addEventListener("change", syncMotion, listener); + syncMotion(); const trayObserver = new ResizeObserver(([entry]) => { const parent = entry.target.parentElement; const height = `${entry.borderBoxSize?.[0]?.blockSize ?? entry.target.getBoundingClientRect().height}px`; @@ -153,6 +193,13 @@ export function mountGame(target, options = {}) { let observedTray; function observeTray() { const tray = play.querySelector(".turn-tray"); + // Size the map from the final panel before either renderer frames it. + // Waiting for ResizeObserver used to trigger a second camera fit. + if (tray) { + const height = `${tray.getBoundingClientRect().height}px`; + if (tray.parentElement.style.getPropertyValue("--tray-height") !== height) + tray.parentElement.style.setProperty("--tray-height", height); + } if (tray === observedTray) return; trayObserver.disconnect(); if (tray) trayObserver.observe(tray, { box: "border-box" }); @@ -162,7 +209,19 @@ export function mountGame(target, options = {}) { chat: options.chat, openPlayer: options.onOpenPlayer, avatarForPlayer: (index) => avatars[index], - onBack: () => play.scrollIntoView({ block: "start" }), + onBack: () => + play.scrollIntoView({ + block: "start", + behavior: + animations && !matchMedia("(prefers-reduced-motion: reduce)").matches + ? "smooth" + : "instant", + }), + onHighlight(cells) { + journalCells = cells; + updateMapFocus(); + syncBoard3D(); + }, language: lang, }); activity.setLanguage(lang); @@ -430,7 +489,13 @@ export function mountGame(target, options = {}) { } function tradeShips() { const help = `Foreign trade\n${colorBlind ? "K: kava · C: copra · B: beef." : "Green: kava · White: copra · Red: beef."}\nEach export fills the first ship (1 → 3) still needing that good. ✓ = already delivered.\nCompleting a ship adds 2 prosperity points.`; - return `
    ${s.demands.map((d, i) => `
    ${i + 1}${d.goods.map((g, j) => `${icon(g)}${d.filled[j] ? icon("check") : ""}`).join("")}${icon("buy")}
    `).join("")}
    `; + return `
    ${tradeTransition + .demands(s.demands) + .map( + (d, i) => + `
    ${i + 1}${d.goods.map((g, j) => `${icon(g)}${d.filled[j] ? icon("check") : ""}`).join("")}${icon("buy")}
    `, + ) + .join("")}
    `; } function renderControls() { const focus = document.activeElement?.getAttribute("data-action"); @@ -461,11 +526,71 @@ export function mountGame(target, options = {}) { } } updateMapFocus(); + syncBoard3D(); if (focus) play .querySelector(`[data-action="${focus}"]`) ?.focus({ preventScroll: true }); } + function setMapView(value, notify = false) { + if (value !== "2d" && value !== "3d") return; + mapView = threeUnavailable ? "2d" : value; + root.dataset.mapView = mapView; + try { + localStorage.setItem("vanuatu-map-view", mapView); + } catch {} + const select = dialog.querySelector("[data-map-preference]"); + if (select) select.value = mapView; + effects.cancel(); + moveSound.stop(); + if (notify) options.onPreference?.("mapView", mapView); + } + function syncBoard3D() { + if (!s) return; + const host = play.querySelector(".map-3d"); + if (mapView === "3d" && !board3D && !threeUnavailable) { + try { + board3D = mountBoard3D(host, { onSelect: cellClick }); + } catch (error) { + console.warn("3D unavailable; using 2D", error); + threeUnavailable = true; + mapView = "2d"; + root.dataset.mapView = mapView; + for (const button of play.querySelectorAll("[data-map-view]")) { + button.setAttribute( + "aria-pressed", + String(button.dataset.mapView === mapView), + ); + if (button.dataset.mapView === "3d") button.disabled = true; + } + } + } + play + .querySelector(".map-scroll") + ?.toggleAttribute("inert", mapView === "3d"); + if (!board3D) return; + const targets = + s.phase === "expand" + ? working() + .filter((m) => m.type === "place" && m.tile === tile) + .map((m) => m.cell) + : actualTargets(); + board3D.setVisible(mapView === "3d"); + board3D.update(s, { + selected, + targets, + hoverTile: tile, + player, + colorBlind, + journalCells, + symbols: s.players.map((_, i) => symbol(i)), + language: lang, + animations, + sound, + live: mapLive, + }); + mapLive = false; + } let boardKey, boardHtml; function renderBoard(targets) { const hoverTile = s.phase === "expand" ? tile : null; @@ -514,13 +639,14 @@ export function mountGame(target, options = {}) { .map((m) => m.cell) : actualTargets(); const html = `
    ${btn("🏝️ Vanuatu", "data-boardgame", "wordmark")}
    Designed by Alain EpronPublished by Quined Games
    ${Array.from({ length: 8 }, (_, i) => `${i + 1}`).join("")}
    -
    ${dock()}
    ${icon("fish", marketHelp)} = ${token("coin", s.market, marketHelp)}${token("tourist", s.tourists, `${"Tourists available this round"}: ${s.tourists}`)}${s.waterCountdown !== null ? `${token("water", s.waterCountdown, `${t("waterLeft")}: ${s.waterCountdown}`)}` : ""}
    ${tradeShips()}
    ${renderBoard(targets)}
    ${titled("Zoom out", icon("zoomOut"), "data-zoom-out", "icon-button")}${titled("Zoom in", icon("zoom"), "data-zoom-in", "icon-button")}
    ${s.upcoming.length && s.phase !== "expand" ? titled(t("next"), `${s.upcoming.map((id) => tilePreviewSvg(id, { t, colorBlind, language: lang, prefix: "upcoming-" + id })).join("")}${icon("zoom", t("next"))}`, "data-upcoming", "upcoming") : ""}${trayHtml}
    ${s.players.map(playerCard).join("")}
    `; +
    ${dock()}
    ${icon("fish", marketHelp)} = ${token("coin", s.market, marketHelp)}${token("tourist", s.tourists, `${"Tourists available this round"}: ${s.tourists}`)}${s.waterCountdown !== null ? `${token("water", s.waterCountdown, `${t("waterLeft")}: ${s.waterCountdown}`)}` : ""}
    ${tradeShips()}
    ${renderBoard(targets)}
    ${btn("2D", `data-map-view="2d" aria-pressed="${mapView === "2d"}"`)}${btn("3D", `data-map-view="3d" aria-pressed="${mapView === "3d"}" ${threeUnavailable ? "disabled" : ""}`)}${titled(translateText("Overview", lang), icon("overview"), "data-three-home", "icon-button")}${titled("Zoom out", icon("zoomOut"), "data-three-out", "icon-button")}${titled("Zoom in", icon("zoom"), "data-three-in", "icon-button")}${titled("Zoom out", icon("zoomOut"), "data-zoom-out", "icon-button")}${titled("Zoom in", icon("zoom"), "data-zoom-in", "icon-button")}
    ${s.upcoming.length && s.phase !== "expand" ? titled(t("next"), `${s.upcoming.map((id) => tilePreviewSvg(id, { t, colorBlind, language: lang, prefix: "upcoming-" + id })).join("")}${icon("zoom", t("next"))}`, "data-upcoming", "upcoming") : ""}${trayHtml}
    ${s.players.map(playerCard).join("")}
    `; // Patch in place so cached SVG tile images and focused controls survive // preference changes and incoming state updates. patch(play, `
    ${html}
    `, true); updateMapFocus(); observeTray(); mapZoom.update(mapAnchor); + syncBoard3D(); if (focus) play .querySelector(`[data-action="${focus}"]`) @@ -650,6 +776,11 @@ export function mountGame(target, options = {}) { else renderControls(); } function updateMapFocus() { + for (const cell of play.querySelectorAll("[data-highlight-cell]")) + cell.classList.toggle( + "journal-highlight", + journalCells.includes(cell.dataset.highlightCell), + ); const cell = play.querySelector('.map-cell[role="button"]:focus-visible'); const highlight = cell && @@ -684,6 +815,23 @@ export function mountGame(target, options = {}) { } if (!button || button.disabled) return; const d = button.dataset; + if ("mapView" in d) { + setMapView(d.mapView, true); + render(); + return; + } + if ("threeHome" in d) { + board3D?.reset(); + return; + } + if ("threeIn" in d) { + board3D?.zoom(0.8); + return; + } + if ("threeOut" in d) { + board3D?.zoom(1.25); + return; + } if ("undoMove" in d) { options.onUndo?.(); return; @@ -835,7 +983,7 @@ export function mountGame(target, options = {}) { } if ("help" in d) { showDialog( - `

    ${t("help")}

    ${options.onSetting && Number.isInteger(player) && !analysis ? `` : ""}${ + `

    ${t("help")}

    ${options.onSetting && Number.isInteger(player) && !analysis ? `` : ""}${ hostedLocale ? "" : `