From e7f257f39b577a32620334dc402e1b1c497f3c0c Mon Sep 17 00:00:00 2001 From: coyotte508 Date: Mon, 28 Sep 2026 07:06:30 +0200 Subject: [PATCH] Add city management, settler expansion, and BGS viewer publishing --- .github/workflows/web-viewer.yml | 28 ++ server/src/game_api_wrapper.rs | 15 + server/src/unit.rs | 2 +- server/src/web_view.rs | 41 ++- server/src/web_view/actions.rs | 106 +++++++ web-client/.gitignore | 1 + web-client/README.md | 27 +- web-client/package.json | 3 +- web-client/scripts/build-bridge.sh | 2 +- web-client/scripts/publish.mjs | 86 ++++++ web-client/src/App.svelte | 60 +++- web-client/src/CityPanel.svelte | 173 +++++++++++ web-client/src/ResourceAmount.svelte | 20 ++ web-client/src/SettlerPanel.svelte | 69 +++++ web-client/src/board.ts | 79 ++++- web-client/src/bridge.ts | 14 + web-client/src/city.css | 415 +++++++++++++++++++++++++++ web-client/src/city.ts | 40 +++ web-client/src/controller.ts | 78 ++++- web-client/src/engine.test.ts | 78 +++++ web-client/src/style.css | 1 + web-client/src/types.ts | 49 +++- web-client/vite.config.ts | 1 + 23 files changed, 1346 insertions(+), 42 deletions(-) create mode 100644 .github/workflows/web-viewer.yml create mode 100644 server/src/web_view/actions.rs create mode 100644 web-client/scripts/publish.mjs create mode 100644 web-client/src/CityPanel.svelte create mode 100644 web-client/src/ResourceAmount.svelte create mode 100644 web-client/src/SettlerPanel.svelte create mode 100644 web-client/src/bridge.ts create mode 100644 web-client/src/city.css create mode 100644 web-client/src/city.ts diff --git a/.github/workflows/web-viewer.yml b/.github/workflows/web-viewer.yml new file mode 100644 index 00000000..bc5edec1 --- /dev/null +++ b/.github/workflows/web-viewer.yml @@ -0,0 +1,28 @@ +name: Web viewer +on: + pull_request: + paths: ['web-client/**', 'server/**', 'Cargo.*', '.github/workflows/web-viewer.yml'] + push: + branches: [feat/3d-web-viewer] +jobs: + verify: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: jdx/mise-action@v3 + with: + version: 2025.7.3 + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: npm + cache-dependency-path: web-client/package-lock.json + - run: rustup target add wasm32-unknown-unknown + - run: npm ci + working-directory: web-client + - run: npm run build:bridge && npm run check && npm test && npm run build + working-directory: web-client + - uses: actions/upload-artifact@v4 + with: + name: clash-viewer + path: web-client/dist/viewer.js diff --git a/server/src/game_api_wrapper.rs b/server/src/game_api_wrapper.rs index f9c31905..2162ffb0 100644 --- a/server/src/game_api_wrapper.rs +++ b/server/src/game_api_wrapper.rs @@ -215,3 +215,18 @@ pub fn try_move(data: String, action: String, player: usize) -> Result Result { + let units = serde_json::from_str(&units).map_err(|e| JsValue::from_str(&e.to_string()))?; + let city = serde_json::from_value(serde_json::Value::String(city)) + .map_err(|e| JsValue::from_str(&e.to_string()))?; + let result = crate::web_view::recruit_preview(&get_game(data), player, city, units) + .map_err(|e| JsValue::from_str(&e))?; + serde_json::to_string(&result).map_err(|e| JsValue::from_str(&e.to_string())) +} diff --git a/server/src/unit.rs b/server/src/unit.rs index b5ecf6c2..b059b4ca 100644 --- a/server/src/unit.rs +++ b/server/src/unit.rs @@ -662,7 +662,7 @@ fn save_carried_units(game: &mut Game, player: usize, pos: Position) { u.carrier_id .is_some_and(|id| game.player(player).try_get_unit(id).is_none()) }) - .map(|u| (u.id)) + .map(|u| u.id) .collect_vec(); if survivors.is_empty() { diff --git a/server/src/web_view.rs b/server/src/web_view.rs index 0cbd5a3b..098ff859 100644 --- a/server/src/web_view.rs +++ b/server/src/web_view.rs @@ -15,6 +15,8 @@ use crate::player::CostTrigger; use crate::playing_actions::{PlayingAction, PlayingActionType}; use crate::position::Position; use serde_json::{Value, json}; +mod actions; +pub use actions::recruit_preview; pub fn view(game: &Game, seat: Option) -> Value { let seat = seat.filter(|i| *i < game.players.len() && game.player(*i).is_human()); @@ -27,7 +29,9 @@ pub fn view(game: &Game, seat: Option) -> Value { Some(PersistentEventRequest::SelectHandCards(_)) ) }); - let supported_phase = playing || objective_phase; + let moving = matches!(game.state, GameState::Movement(_)) && game.events.is_empty(); + let choice = seat.and_then(|seat| choice_decision(game, seat)); + let supported_phase = playing || objective_phase || moving || choice.is_some(); let can_play = seat == Some(active) && playing; let players = game.players.iter().filter(|p| p.is_human()).map(|p| json!({ "index": p.index, "name": game.player_name(p.index), "civilization": p.civilization.name, @@ -35,7 +39,7 @@ pub fn view(game: &Game, seat: Option) -> Value { "cities": p.cities.iter().map(|c| json!({"position": c.position, "size": c.size(), "capacity": c.mood_modified_size(p), "mood": c.mood_state, "activations": c.activations})).collect::>() })).collect::>(); let Some(seat) = seat else { - return json!({"activePlayer": active, "canPlay": false, "supportedPhase": supported_phase, "players": players, "cities": [], "advances": [], "objectiveCards": [], "objectiveDecision": null, "canUndo": false, "canEndTurn": false}); + return json!({"activePlayer": active, "canPlay": false, "supportedPhase": supported_phase, "players": players, "cities": [], "advances": [], "objectiveCards": [], "objectiveDecision": null, "cityActions": [], "settlers": [], "stopMovement": null, "canUndo": false, "canEndTurn": false}); }; let p = game.player(seat); // Hidden cards use ID zero in the player-filtered state; never resolve them. @@ -84,7 +88,38 @@ pub fn view(game: &Game, seat: Option) -> Value { "bonus":info.bonus.as_ref().map(|bonus| bonus.resources()),"unlocks":info.unlocked_building.map(|building| building.to_string())}) }).collect::>(); advances.sort_by_key(|a| a["name"].as_str().unwrap_or_default().to_string()); - json!({"activePlayer":active,"canPlay":can_play,"supportedPhase":supported_phase,"players":players,"cities":cities,"advances":advances,"objectiveCards":objective_cards,"objectiveDecision":objective_decision(game, seat),"canUndo":seat == active && game.can_undo(),"canEndTurn":can_play && PlayingActionType::EndTurn.is_available(game, seat).is_ok()}) + json!({"activePlayer":active,"canPlay":can_play,"supportedPhase":supported_phase,"players":players,"cities":cities,"advances":advances,"objectiveCards":objective_cards,"objectiveDecision":objective_decision(game, seat), + "choiceDecision":choice, + "cityActions":actions::cities(game, seat, can_play), "settlers":actions::settlers(game, seat, (can_play && PlayingActionType::MoveUnits.is_available(game,seat).is_ok()) || (moving && seat == active)), + "stopMovement":if moving && seat == active {Some(Action::Movement(crate::movement::MovementAction::Stop))} else {None}, + "canUndo":seat == active && game.can_undo(),"canEndTurn":can_play && PlayingActionType::EndTurn.is_available(game, seat).is_ok()}) +} + +fn choice_decision(game: &Game, seat: usize) -> Option { + use crate::resource::ResourceType; + use crate::resource_pile::ResourcePile; + let event = game.events.last()?; + if event.player.index != seat { + return None; + } + let handler = game.current_event_handler()?; + if handler.response.is_some() { + return None; + } + match &handler.request { + PersistentEventRequest::ResourceReward(request) + if request.reward.payment_options.default.amount() == 1 => + { + let choices = ResourceType::all().into_iter().map(|r| ResourcePile::of(r,1)) + .filter(|pile|request.reward.payment_options.is_valid_payment(pile)) + .map(|pile|json!({"name":pile.to_string(),"pile":pile,"action":Action::Response(EventResponse::ResourceReward(pile.clone()))})).collect::>(); + Some(json!({"name":request.name,"choices":choices})) + } + PersistentEventRequest::BoolRequest(name) => Some(json!({"name":name,"choices":[ + {"name":"Yes","action":Action::Response(EventResponse::Bool(true))}, + {"name":"No","action":Action::Response(EventResponse::Bool(false))}]})), + _ => None, + } } fn objective_decision(game: &Game, seat: usize) -> Option { diff --git a/server/src/web_view/actions.rs b/server/src/web_view/actions.rs new file mode 100644 index 00000000..1d19895c --- /dev/null +++ b/server/src/web_view/actions.rs @@ -0,0 +1,106 @@ +use crate::action::Action; +use crate::city::MoodState; +use crate::city_pieces::BUILDINGS; +use crate::construct::{Construct, can_construct, new_building_positions}; +use crate::game::{Game, GameState}; +use crate::happiness::{IncreaseHappiness, happiness_base_event_origin, happiness_cost}; +use crate::map::Terrain; +use crate::movement::{MoveUnits, MovementAction, possible_move_routes}; +use crate::player::CostTrigger; +use crate::playing_actions::{PlayingAction, PlayingActionType}; +use crate::position::Position; +use crate::recruit::{Recruit, recruit_cost}; +use crate::unit::{UnitType, Units}; +use serde_json::{Value, json}; + +fn action_reason( + game: &Game, + seat: usize, + can_play: bool, + kind: PlayingActionType, +) -> Option { + if !can_play { + Some("Wait for your turn or finish the current decision".into()) + } else { + kind.is_available(game, seat).err() + } +} + +pub fn cities(game: &Game, seat: usize, can_play: bool) -> Vec { + let p = game.player(seat); + p.cities.iter().map(|city| { + let buildings = BUILDINGS.into_iter().map(|building| { + let cost = p.building_cost(game, building, CostTrigger::NoModifiers); + let payment = cost.cost.first_valid_payment(&p.resources).unwrap_or_else(|| cost.cost.default_payment()); + let positions = new_building_positions(game, building, city); + let reason = action_reason(game, seat, can_play, PlayingActionType::Construct) + .or_else(|| can_construct(city, building, p, game, CostTrigger::NoModifiers, &[]).err()) + .or_else(|| positions.is_empty().then(|| "Needs an adjacent sea tile".to_string())); + let choices = if reason.is_none() {positions.into_iter().map(|port| json!({"position":port, + "action":Action::Playing(PlayingAction::Construct(Construct::new(city.position, building, payment.clone()).with_port_position(port)))})).collect::>()} else {vec![]}; + json!({"name":building.to_string(),"owned":!city.pieces.can_add_building(building), + "required":game.cache.get_building_advance(building).name(game),"payment":payment,"reason":reason,"choices":choices, + "moodWillDecrease":cost.activate_city && city.is_activated()}) + }).collect::>(); + let recruits = [UnitType::Settler,UnitType::Infantry,UnitType::Cavalry,UnitType::Elephant,UnitType::Ship].into_iter().map(|unit| { + let mut units = Units::empty(); units += &unit; + let result = recruit_cost(game,p,&units,city.position,&[],CostTrigger::NoModifiers); + let reason = action_reason(game,seat,can_play,PlayingActionType::Recruit).or_else(||result.as_ref().err().cloned()); + let payment = result.map(|c|c.cost.first_valid_payment(&p.resources).unwrap_or_else(||c.cost.default_payment())).unwrap_or_else(|_|unit.cost()); + json!({"type":unit,"payment":payment,"reason":reason,"available":p.available_units().get_amount(&unit)}) + }).collect::>(); + let max_steps = match city.mood_state {MoodState::Happy=>0, MoodState::Neutral=>1, MoodState::Angry=>2}; + let happiness = (1..=max_steps).map(|steps| { + let kind = PlayingActionType::IncreaseHappiness; + let cost = happiness_cost(seat,city.size() as u8 * steps,CostTrigger::NoModifiers,&kind,game,&happiness_base_event_origin()); + let payment = cost.cost.first_valid_payment(&p.resources); + let reason = action_reason(game,seat,can_play,kind.clone()).or_else(||payment.is_none().then(||"Not enough resources".into())); + let payment = payment.unwrap_or_else(||cost.cost.default_payment()); + let action = reason.is_none().then(||Action::Playing(PlayingAction::IncreaseHappiness(IncreaseHappiness::new(vec![(city.position,steps)],payment.clone(),kind)))); + json!({"steps":steps,"mood":if steps==max_steps {"Happy"} else {"Neutral"},"payment":payment,"reason":reason,"action":action}) + }).collect::>(); + json!({"position":city.position,"buildings":buildings,"recruits":recruits,"happiness":happiness}) + }).collect() +} + +pub fn recruit_preview( + game: &Game, + seat: usize, + city: Position, + units: Units, +) -> Result { + if seat >= game.players.len() || seat != game.active_player() || !game.player(seat).is_human() { + return Err("Wait for your turn".into()); + } + PlayingActionType::Recruit.is_available(game, seat)?; + if units.is_empty() { + return Err("Choose at least one unit".into()); + } + let p = game.player(seat); + let city_data = p.try_get_city(city).ok_or("Choose one of your cities")?; + let cost = recruit_cost(game, p, &units, city, &[], CostTrigger::NoModifiers)?; + let payment = cost + .cost + .first_valid_payment(&p.resources) + .ok_or("Not enough resources")?; + Ok( + json!({"payment":payment,"moodWillDecrease":city_data.is_activated(), + "action":Action::Playing(PlayingAction::Recruit(Recruit::new(&units,city,payment.clone())))}), + ) +} + +pub fn settlers(game: &Game, seat: usize, can_move: bool) -> Vec { + let p = game.player(seat); + p.units.iter().filter(|u|u.is_settler() && !u.is_transported()).map(|unit| { + let mut destinations = if can_move {possible_move_routes(p,game,&[unit.id],unit.position,None).unwrap_or_default().into_iter() + .filter(|route|game.map.is_land(route.destination) && game.map.get(route.destination)!=Some(&Terrain::Unexplored) && game.enemy_player(seat,route.destination).is_none()) + .filter_map(|route|route.cost.first_valid_payment(&p.resources).map(|payment|json!({ + "position":route.destination,"terrain":game.map.get(route.destination),"payment":payment, + "action":Action::Movement(MovementAction::Move(MoveUnits::new(vec![unit.id],route.destination,None,payment.clone())))}))).collect::>() } else {vec![]}; + destinations.sort_by_key(|d|d["position"].as_str().unwrap_or_default().to_string()); + let found_reason = action_reason(game,seat,game.state==GameState::Playing && seat==game.active_player(),PlayingActionType::FoundCity) + .or_else(||(!unit.can_found_city(game)).then(||"Move to an empty land tile to found a city".into())); + json!({"id":unit.id,"position":unit.position,"destinations":destinations,"foundReason":found_reason, + "foundAction":found_reason.is_none().then(||Action::Playing(PlayingAction::FoundCity{settler:unit.id}))}) + }).collect() +} diff --git a/web-client/.gitignore b/web-client/.gitignore index 4599ef6b..20995bed 100644 --- a/web-client/.gitignore +++ b/web-client/.gitignore @@ -1,2 +1,3 @@ .engine/ public/engine/ +.bridge/ diff --git a/web-client/README.md b/web-client/README.md index d4bc613f..5588767c 100644 --- a/web-client/README.md +++ b/web-client/README.md @@ -1,6 +1,6 @@ # Clash of Cultures — web viewer -First playable slice of a Svelte/TypeScript interface with a Three.js board. The Rust engine remains the rule authority. The existing Macroquad client is unchanged. +First playable slice of a Svelte/TypeScript interface with a Three.js board. The Rust engine remains the rule authority. ## Run locally @@ -25,6 +25,10 @@ No production games, catalog records, or chat rooms are modified. Remaining acti - Collect resources: Rust supplies legal tiles, resource alternatives, capacity, total gain, waste, and an activation warning. Confirming submits the original Rust action format. - Research: a searchable tree with pictograms, short effect summaries, prerequisite branches, costs, bonuses, and unlocked buildings. Rust supplies the graph, full rules, payments, and action payloads; selecting an advance opens its full rule text before confirmation. - End turn and undo, with state and journal reconciliation. +- City management: buildings with visible effects and requirements, Port placement, combined recruitment of standard units, and one-city happiness actions. Payments and legal actions come from Rust; repeat activations warn about mood loss. +- Settler movement on revealed land without enemies, movement completion, and founding cities. Destination rings and map clicks work alongside accessible destination buttons. +- One-resource bonus choices (including Temples) and yes/no decisions. These remain private to the player who must answer. +- Buildings appear around city centers; recruited units have separate positions and basic type markers. - BGS registration/lifecycle, player/spectator handling, theme, avatars, and the shared chat controller/panel. Chat sends, failed-send drafts, updates/deletions, mentions, read reports, editing and translation handlers are supplied by the protocol package; the host decides which features are enabled. - Journal entries use action and resource pictograms. Setup is summarized as player, civilization, and original starting tile. Text equivalents are published with `replaceLog` so undo cannot leave stale entries. - Full-width board with floating action controls and dismissible journal/chat panels. The layout stays within the viewport on desktop and mobile; panels scroll internally. City/action controls are keyboard accessible, and the board renders only when changed. @@ -43,18 +47,29 @@ cargo test -p server --lib web_view After building, `http://127.0.0.1:8643/?built` loads the production IIFE bundle inside the preview host. -Upload the contents of `dist/` together, preserving `engine/` alongside `viewer.js`. The viewer resolves its WASM bridge relative to its own script URL. It exports `window.clash3d.launch(selector)` and uses string state/move payloads, matching the existing engine. Configure `topLevelVariable: "clash3d"`, `fullScreen: true`, `chat: true`, and `replayable: false`. No extra runtime scripts or stylesheets are needed. Fonts currently load from Google Fonts; system fonts remain available if blocked. +`dist/viewer.js` contains the interface, styles, and Rust WASM bridge in one uploadable file. It exports `window.clash3d.launch(selector)` and uses string state/move payloads, matching the existing engine. Configure `topLevelVariable: "clash3d"`, `fullScreen: true`, `chat: true`, and `replayable: false`. No extra runtime scripts or stylesheets are needed. Fonts currently load from Google Fonts; system fonts remain available if blocked. + +## Publish to BGS + +After building and verifying, use the admin API token from `BGS_ADMIN_TOKEN` or `~/.bgs`: + +```sh +npm run publish:bgs -- --version=1 --dry-run +npm run publish:bgs -- --version=1 +``` + +The script uploads the viewer, verifies the hosted bytes, then updates only the version's viewer configuration. It preserves the engine and visibility settings, checks for concurrent viewer changes, and saves the previous version document under `.engine/releases/` for rollback. Publishing is separate from pushing Git commits. The GitHub workflow builds and tests the viewer and retains the bundle as an artifact; it does not publish automatically. ## Next slices -The new controls do not yet cover movement/exploration, construction, recruitment, action cards, cultural influence, happiness actions, combat, civilization selection, or status/event choices other than objective claims. City buildings beyond the center and unit types beyond settlers still need distinct models. Full replay and analysis controls are not advertised. The interface text is currently English; existing game translations need to be wired into the new presentation layer. Audio and advanced accessibility preferences need a separate pass. +The controls do not yet cover army/fleet movement, exploration, unit replacement/leader recruitment, wonders, action cards, cultural influence, combat, civilization selection, or most status/event choices. Free/custom-action variants and multi-city happiness selection are also pending. Models for buildings and units are preliminary. Full replay and analysis controls are not advertised. The interface text is currently English; existing game translations need to be wired into the new presentation layer. Audio and advanced accessibility preferences need a separate pass. -Before making this the default viewer: complete action/phase coverage, verify against an actual BGS staging game (including reconnects, moderation, translation, and read-state persistence), and test larger multiplayer boards on mobile hardware. +Before public release: complete action/phase coverage, verify against an actual BGS staging game (including reconnects, moderation, translation, and read-state persistence), and test larger multiplayer boards on mobile hardware. ## Architecture -`server/src/web_view.rs` exposes read-only rule queries; `game_api_wrapper.rs` exports them to WASM. Queries consume the same player-filtered state BGS sends to the viewer. They neither mutate the game nor send moves. The server always validates actual moves. +`server/src/web_view.rs` and `web_view/actions.rs` expose read-only rule queries; `game_api_wrapper.rs` exports them to WASM. Queries consume the same player-filtered state BGS sends to the viewer. They neither mutate the game nor send moves. The server always validates actual moves. `src/bridge.ts` initializes the embedded WASM; `.bridge/` and `.engine/` are generated by `build:bridge`. `src/controller.ts` coordinates state, choices, and the BGS commands. `src/App.svelte` owns the HTML interface. `src/board.ts` owns and disposes the Three.js scene. `src/viewer.ts` is the production entry. `src/local-host.ts` and `scripts/preview-api.ts` are development-only. -The protocol dependency is AGPL-3.0-only. The existing engine and classic viewer retain their respective licensing. +The protocol dependency is AGPL-3.0-only. The engine retains its existing licensing. diff --git a/web-client/package.json b/web-client/package.json index d7bf1e27..70a0b138 100644 --- a/web-client/package.json +++ b/web-client/package.json @@ -8,7 +8,8 @@ "build": "vite build", "check": "svelte-check --tsconfig ./tsconfig.json", "test": "node --experimental-strip-types --test src/*.test.ts", - "build:bridge": "bash scripts/build-bridge.sh" + "build:bridge": "bash scripts/build-bridge.sh", + "publish:bgs": "node scripts/publish.mjs" }, "dependencies": { "@boardgamers/protocol": "0.6.1", diff --git a/web-client/scripts/build-bridge.sh b/web-client/scripts/build-bridge.sh index 68f46688..c3d09c68 100644 --- a/web-client/scripts/build-bridge.sh +++ b/web-client/scripts/build-bridge.sh @@ -2,6 +2,6 @@ set -euo pipefail cd "$(dirname "$0")/../.." cargo build -p server --lib --target wasm32-unknown-unknown --release -wasm-bindgen target/wasm32-unknown-unknown/release/server.wasm --target web --out-dir web-client/public/engine +wasm-bindgen target/wasm32-unknown-unknown/release/server.wasm --target web --out-dir web-client/.bridge wasm-bindgen target/wasm32-unknown-unknown/release/server.wasm --target nodejs --out-dir web-client/.engine printf '{"type":"commonjs"}\n' > web-client/.engine/package.json diff --git a/web-client/scripts/publish.mjs b/web-client/scripts/publish.mjs new file mode 100644 index 00000000..7ad5176c --- /dev/null +++ b/web-client/scripts/publish.mjs @@ -0,0 +1,86 @@ +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { createHash } from 'node:crypto'; +import { fileURLToPath } from 'node:url'; + +const root = fileURLToPath(new URL('..', import.meta.url)); +const version = process.argv.find((a) => a.startsWith('--version='))?.split('=')[1] ?? '1'; +if (!/^\d+$/.test(version)) throw new Error('Use --version='); +const token = + process.env.BGS_ADMIN_TOKEN ?? (await fs.readFile(path.join(os.homedir(), '.bgs'), 'utf8')).trim(); +const endpoint = `https://admin.boardgamers.space/api/admin/gameinfo/clash/${version}`; +async function api(url, options = {}) { + const res = await fetch(url, { + ...options, + signal: AbortSignal.timeout(60000), + redirect: 'error', + headers: { Authorization: `Bearer ${token}`, ...options.headers }, + }); + if (!res.ok) throw new Error(`BGS API ${res.status}: ${await res.text()}`); + return res.json(); +} +const previous = await api(endpoint); +const bytes = await fs.readFile(path.join(root, 'dist/viewer.js')); +if (bytes.length > 25 * 1024 * 1024) throw new Error('Viewer exceeds the BGS upload limit'); +const hash = createHash('sha256').update(bytes).digest('hex'); +const filename = `viewer-${hash.slice(0, 16)}.js`; +console.log( + JSON.stringify( + { + game: 'clash', + version: Number(version), + bytes: bytes.length, + sha256: hash, + previousViewer: previous.viewer.url, + dryRun: process.argv.includes('--dry-run'), + }, + null, + 2, + ), +); +if (!process.argv.includes('--dry-run')) { + const backupDir = path.join(root, '.engine/releases'); + await fs.mkdir(backupDir, { recursive: true }); + const backup = path.join(backupDir, `version-${version}-${Date.now()}.json`); + await fs.writeFile(backup, JSON.stringify(previous, null, 2)); + const uploaded = await api(`${endpoint}/viewer/file?filename=${filename}`, { + method: 'POST', + headers: { 'Content-Type': 'application/octet-stream' }, + body: bytes, + }); + const asset = await fetch(uploaded.url, { redirect: 'error', signal: AbortSignal.timeout(60000) }); + if ( + !asset.ok || + createHash('sha256') + .update(new Uint8Array(await asset.arrayBuffer())) + .digest('hex') !== hash + ) + throw new Error('Uploaded asset verification failed; version metadata was not changed'); + const viewer = { + ...previous.viewer, + url: uploaded.url, + topLevelVariable: 'clash3d', + dependencies: { scripts: [], stylesheets: [] }, + fullScreen: true, + fullScreenMobile: true, + replayable: false, + chat: true, + }; + const current = await api(endpoint); + if (JSON.stringify(current.viewer) !== JSON.stringify(previous.viewer)) + throw new Error('The viewer changed during upload; version metadata was not changed'); + await api(endpoint, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ viewer }), + }); + const saved = await api(endpoint); + if ( + saved.viewer.url !== uploaded.url || + saved.viewer.topLevelVariable !== 'clash3d' || + JSON.stringify(saved.engine) !== JSON.stringify(previous.engine) + ) + throw new Error('Published version verification failed; inspect the saved backup'); + console.log(JSON.stringify({ published: uploaded.url, backup, engineUnchanged: true }, null, 2)); +} diff --git a/web-client/src/App.svelte b/web-client/src/App.svelte index 4f736999..883d5224 100644 --- a/web-client/src/App.svelte +++ b/web-client/src/App.svelte @@ -37,6 +37,9 @@ import { mountChat } from '@boardgamers/protocol/chat/dom'; import { World } from './board'; import ResearchTree from './ResearchTree.svelte'; + import CityPanel from './CityPanel.svelte'; + import SettlerPanel from './SettlerPanel.svelte'; + import ResourceAmount from './ResourceAmount.svelte'; import type { Controller } from './controller'; import type { Resource } from './types'; import { resources, resourceNames, playerColors } from './types'; @@ -75,15 +78,20 @@ let log = $derived($session.game ? journal($session.game) : []); let totalActions = $derived($session.game?.actions_left ?? 0); let objectiveDecision = $derived($session.view?.objectiveDecision); + let choiceDecision = $derived($session.view?.choiceDecision); let focusTerrain = $derived($session.game?.map.tiles.find(([p]) => p === $session.focus)?.[1]); let actionTitle = $derived( $session.seat === undefined ? 'Spectating' - : objectiveDecision - ? 'Objective available' - : $session.view?.canPlay - ? 'Your turn' - : `${$session.view?.players.find((p) => p.index === $session.view?.activePlayer)?.civilization ?? 'Opponent'}’s turn`, + : choiceDecision + ? 'Choose a bonus' + : objectiveDecision + ? 'Objective available' + : $session.view?.stopMovement + ? 'Moving settlers' + : $session.view?.canPlay + ? 'Your turn' + : `${$session.view?.players.find((p) => p.index === $session.view?.activePlayer)?.civilization ?? 'Opponent'}’s turn`, ); onMount(() => { try { @@ -285,7 +293,7 @@
YOUR CITIES
{#each $session.view?.cities ?? [] as c} + + - {#if objectiveDecision || ($session.game && !$session.view?.supportedPhase && $session.seat === $session.view?.activePlayer) || $session.mode === 'collect' || confirmEnd || $session.error} + {#if choiceDecision || objectiveDecision || ($session.game && !$session.view?.supportedPhase && $session.seat === $session.view?.activePlayer) || $session.mode === 'collect' || confirmEnd || ($session.error && $session.mode === 'overview')}
- {#if !objectiveDecision && $session.view?.supportedPhase}{/if} - {#if objectiveDecision} + {#if choiceDecision} +

{choiceDecision.name}

+
+ {#each choiceDecision.choices as choice}{/each} +
+ {:else if objectiveDecision}

{objectiveDecision.name}

{objectiveDecision.description}

{#each objectiveDecision.cards as card (card.id)} @@ -449,6 +489,7 @@ {#if $session.error}{/if}
{/if} + {#if $session.mode === 'settlers'}{/if}