mirror of
https://github.com/db9979/uconsole_asw_game.git
synced 2026-12-06 04:44:18 +01:00
Weather & sonar analysis (key 0, uConsole full screen and every Remote Crew station): own-ship atmosphere derived from the weather system (barometer leading the sea with WMO tendency and storm warning, air temperature with cold outbreaks, snow and icing, gusts, Beaufort, cloud ceiling, twilight from sun elevation, moon phase), weather effects, and a helicopter flight decision (CLEAR/LIMITED/NO-GO; gusts, ceiling and icing now limit launch and dipping, light icing costs fuel). The ocean profile (layer, sound-speed curve, SOFAR axis, rays and shadow zone) appears only after a sonar bathythermograph measurement and is always that measurement. Rain freshens a surface lens in the Mackenzie sound speed; ray profiles and the BT continue to the seabed (to 1500 m) so a deep sound channel can form. New common v2 block `weather_station`, browser validator and dialog, protocol docs, manual EN/DE. Also included from the parallel session: selectable 30/60 FPS frame-rate preference with bounded catch-up of slow frames, elastic sonar audio buffering (local mixer and AudioWorklet), and a German presentation of the simulation under docs/presentation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
225 lines
11 KiB
Python
225 lines
11 KiB
Python
"""Real-browser contract for the solo console: station tabs and host controls.
|
|
|
|
Drives the packaged page in Chromium against the real Game, CommanderBridge and
|
|
a solo CommanderServer. Saves go to a temporary directory only.
|
|
"""
|
|
|
|
import json
|
|
import shutil
|
|
import subprocess
|
|
import time
|
|
|
|
import pytest
|
|
|
|
from src.commander import server as commander_transport
|
|
from src.core import config
|
|
from src.core.game import Game
|
|
from src.sonar.sonar import Contact
|
|
from src.core import manual
|
|
from test_commander_assets import ASSETS, PREFIX, Document, catalogs
|
|
|
|
|
|
CONSOLE_SCRIPT = r"""
|
|
(() => {
|
|
"use strict";
|
|
const $ = (id) => document.getElementById(id);
|
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
class Fail extends Error {}
|
|
const assert = (value, message) => { if (!value) throw new Fail(message); };
|
|
async function until(check, message, limit = 1500) {
|
|
for (let index = 0; index < limit; index++) {
|
|
if (check()) return;
|
|
await sleep(20);
|
|
}
|
|
throw new Fail(message);
|
|
}
|
|
const scriptErrors = [];
|
|
window.addEventListener("error", (event) => scriptErrors.push(event.message));
|
|
window.addEventListener("unhandledrejection", (event) => scriptErrors.push(String(event.reason)));
|
|
const active = () => document.querySelector(".station-tab[aria-selected='true']")?.dataset.station;
|
|
const showing = (role) => active() === role && !$(`station-${role}`).hidden && !$("operations").hidden;
|
|
const fits = (label) => assert(document.documentElement.scrollHeight <= innerHeight + 1,
|
|
`page scrolls instead of fitting the viewport (${label})`);
|
|
|
|
async function run() {
|
|
await until(() => !$("shell").hidden, "translations missing");
|
|
$("name").value = "Solo";
|
|
$("code").value = __CODE__;
|
|
$("pair-form").requestSubmit();
|
|
await until(() => $("station-tab-bridge") && showing("bridge"), "solo bridge console missing");
|
|
|
|
// Solo: one client holds every station, so there is nothing to add or release.
|
|
assert($("station-tabs").children.length === 9, "solo session must show nine station tabs");
|
|
assert([...$("station-tabs").children].every((tab, index) =>
|
|
tab.querySelector(".station-key").textContent === String(index + 1)), "tab hotkey numbers");
|
|
assert($("workstation-add-station").hidden && $("workstation-release").hidden, "add/release shown in solo");
|
|
assert(!$("host-bar").hidden && !$("role-rail").hidden === false, "host bar or role rail state");
|
|
fits("bridge");
|
|
|
|
// The operator's picture survives a station switch: returning to a station
|
|
// already visited repaints from its cache without blanking the console, and the
|
|
// map zoom and a half-typed sonar order are still there. (The very first visit
|
|
// to a station has nothing cached and may take one round trip.)
|
|
let blanked = 0;
|
|
new MutationObserver(() => { if ($("operations").hidden) blanked++; })
|
|
.observe($("operations"), {attributes: true, attributeFilter: ["hidden"]});
|
|
const before = $("role-map-scale").textContent;
|
|
$("role-map-zoom-in").click();
|
|
$("role-map-zoom-in").click();
|
|
await until(() => $("role-map-scale").textContent !== before, "map zoom did not change");
|
|
const zoomed = $("role-map-scale").textContent;
|
|
|
|
$("station-tab-sonar").click();
|
|
await until(() => showing("sonar"), "sonar tab did not activate");
|
|
await until(() => [...document.querySelectorAll("[data-sonar-plot]")].filter((panel) => !panel.hidden)
|
|
.every((panel) => panel.querySelector("canvas").width > 1), "overview plots not sized");
|
|
const shown = [...document.querySelectorAll("[data-sonar-plot]")].filter((panel) => !panel.hidden);
|
|
assert(shown.length >= 4, `sonar overview shows ${shown.length} plots`);
|
|
assert($("sonar-plots").dataset.layout.startsWith("overview"), "sonar defaults to the overview");
|
|
$("sonar-bearing").value = "77";
|
|
$("sonar-bearing").dispatchEvent(new Event("input", {bubbles: true}));
|
|
fits("sonar");
|
|
|
|
blanked = 0;
|
|
$("station-tab-bridge").click();
|
|
await until(() => showing("bridge"), "bridge tab did not activate");
|
|
await until(() => $("role-map-scale").textContent === zoomed, "map zoom was lost on station switch");
|
|
assert(blanked === 0, "the console was blanked during a station switch");
|
|
fits("bridge again");
|
|
|
|
// Hotkeys: a digit selects that station, [ and ] step through the held ones.
|
|
blanked = 0;
|
|
document.dispatchEvent(new KeyboardEvent("keydown", {key: "2", bubbles: true}));
|
|
await until(() => showing("sonar"), "hotkey 2 did not select sonar");
|
|
assert(blanked === 0, "the console was blanked returning to a visited station");
|
|
assert($("sonar-bearing").value === "77", "sonar draft was lost on station switch");
|
|
document.dispatchEvent(new KeyboardEvent("keydown", {key: "]", bubbles: true}));
|
|
await until(() => showing("weapons"), "] did not step to weapons");
|
|
blanked = 0;
|
|
document.dispatchEvent(new KeyboardEvent("keydown", {key: "[", bubbles: true}));
|
|
await until(() => showing("sonar"), "[ did not step back to sonar");
|
|
$("sonar-bearing").dispatchEvent(new KeyboardEvent("keydown", {key: "4", bubbles: true}));
|
|
await sleep(300);
|
|
assert(active() === "sonar", "a digit typed into a field switched station");
|
|
assert(blanked === 0, "the console was blanked by hotkey switching to a visited station");
|
|
|
|
// Solo host controls.
|
|
await until(() => !$("host-pause").disabled, "host pause never enabled");
|
|
$("host-pause").click();
|
|
await until(() => $("host-pause").getAttribute("aria-pressed") === "true", "pause not reflected");
|
|
await until(() => !$("host-pause").disabled, "host controls stayed locked after pause");
|
|
$("host-pause").click();
|
|
await until(() => $("host-pause").getAttribute("aria-pressed") === "false", "resume not reflected");
|
|
assert(!document.getElementById("host-time-scale"), "time compression control remains visible");
|
|
|
|
await until(() => !$("host-save").disabled, "save locked");
|
|
$("host-save").click();
|
|
await until(() => $("host-slot-dialog").open, "save dialog did not open");
|
|
await until(() => !document.querySelector('#host-slot-list button[data-slot="3"]').disabled &&
|
|
!$("host-save").disabled, "save slot unavailable");
|
|
document.querySelector('#host-slot-list button[data-slot="3"]').click();
|
|
assert($("host-status").dataset.status === "pending", "save command was not submitted");
|
|
await until(() => $("host-status").dataset.status === "applied" &&
|
|
!$("host-save").disabled, "save result missing");
|
|
|
|
await until(() => !$("host-new").disabled, "new game locked");
|
|
$("host-new").click();
|
|
await until(() => $("host-new-dialog").open, "new game dialog did not open");
|
|
$("host-new-scenario").value = "s1_patrouille";
|
|
$("host-new-scenario").dispatchEvent(new Event("change", {bubbles: true}));
|
|
assert(document.querySelector("#host-new-difficulty input").disabled,
|
|
"a scenario with a fixed difficulty must not offer difficulty controls");
|
|
$("host-new-world").value = "procedural";
|
|
$("host-new-seed").value = "4242";
|
|
$("host-new-form").requestSubmit();
|
|
// The world is replaced; the browser stays paired and returns to the console.
|
|
await until(() => window.__replaced === true || $("host-status").textContent.length > 0, "no new-game result");
|
|
await sleep(1500);
|
|
await until(() => $("station-tab-bridge") && !$("operations").hidden, "console lost after a new game", 3000);
|
|
assert($("station-tabs").children.length === 9, "stations missing after a new game");
|
|
assert(scriptErrors.length === 0, `script errors: ${scriptErrors.join(" | ")}`);
|
|
}
|
|
|
|
run().then(() => { document.documentElement.dataset.consoleTest = "passed"; },
|
|
(error) => {
|
|
document.documentElement.dataset.consoleTest = "failed";
|
|
document.documentElement.dataset.failure = String(error.stack || error);
|
|
});
|
|
})();
|
|
"""
|
|
|
|
|
|
def test_solo_console_tabs_keep_state_and_host_controls_drive_the_game(
|
|
tmp_path, monkeypatch):
|
|
chromium = shutil.which("chromium") or shutil.which("chromium-browser") or shutil.which("google-chrome")
|
|
if not chromium:
|
|
pytest.skip("Optional solo console browser contract: no installed Chromium")
|
|
saves = tmp_path / "saves"
|
|
monkeypatch.setattr(config, "SAVE_DIR", str(saves))
|
|
en, de = catalogs()
|
|
game = Game(seed=913, start_menu=False, audio_enabled=False, language="en")
|
|
game.sonar.contacts.clear()
|
|
for target_id, bearing in ((99001, 28.0), (99002, 52.0)):
|
|
contact = Contact(target_id - 99000, target_id, "passiv", "sub")
|
|
contact.update_passive(bearing, .8, .8, "hidden", game.sim_t)
|
|
game.sonar.contacts[target_id] = contact
|
|
console = game.commander
|
|
console.solo = True
|
|
console.port = 0
|
|
console._translations = {
|
|
"en": {key: value for key, value in en.items() if key.startswith(PREFIX)},
|
|
"de": {key: value for key, value in de.items() if key.startswith(PREFIX)},
|
|
}
|
|
console._contact_analysis_assets = {}
|
|
# Pre-rendered like the assets: resources.files is redirected below.
|
|
console._manual_pages = {}
|
|
console._manual_pages = {lang: manual.html_page(lang) for lang in manual.LANGUAGES}
|
|
html = ASSETS.joinpath("index.html").read_text().replace(
|
|
'<script src="./app.js" defer>',
|
|
'<script src="./console-test.js" defer></script><script src="./app.js" defer>')
|
|
for name, payload in (("index.html", html),
|
|
("app.js", ASSETS.joinpath("app.js").read_text()),
|
|
("style.css", ASSETS.joinpath("style.css").read_text()),
|
|
("sonar-audio-worklet.js", ASSETS.joinpath("sonar-audio-worklet.js").read_text()), ("manual.css", ASSETS.joinpath("manual.css").read_text()),
|
|
("voice.js", ASSETS.joinpath("voice.js").read_text()),
|
|
("voice-worklet.js", ASSETS.joinpath("voice-worklet.js").read_text())):
|
|
(tmp_path / name).write_text(payload, encoding="utf-8")
|
|
monkeypatch.setattr(commander_transport.resources, "files", lambda _package: tmp_path)
|
|
|
|
console.activate(game)
|
|
assert console.address is not None and console.server.solo_mode is True
|
|
script = CONSOLE_SCRIPT.replace("__CODE__", json.dumps(console.pairing_code))
|
|
console.server._http.assets["/console-test.js"] = (
|
|
"text/javascript; charset=utf-8", script.encode("utf-8"))
|
|
console.bridge.allowed = True
|
|
|
|
process = subprocess.Popen(
|
|
[chromium, "--headless", "--no-sandbox", "--disable-gpu",
|
|
"--disable-background-networking", "--no-first-run",
|
|
"--no-default-browser-check", "--disable-dev-shm-usage",
|
|
f"--user-data-dir={tmp_path / 'console-browser'}", "--virtual-time-budget=300000",
|
|
"--window-size=1600,900", "--dump-dom",
|
|
f"http://{console.address[0]}:{console.address[1]}/"],
|
|
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
|
started = time.monotonic()
|
|
try:
|
|
while process.poll() is None and time.monotonic() - started < 80:
|
|
console.pump(game)
|
|
if not game.paused:
|
|
game.update(.02)
|
|
time.sleep(.02)
|
|
stdout, stderr = process.communicate(timeout=5)
|
|
finally:
|
|
if process.poll() is None:
|
|
process.kill()
|
|
stdout, stderr = process.communicate(timeout=5)
|
|
console.stop()
|
|
game.audio.shutdown()
|
|
|
|
assert process.returncode == 0, stderr
|
|
root = next((attrs for tag, attrs in Document(stdout).elements if tag == "html"), {})
|
|
assert root.get("data-console-test") == "passed", root.get(
|
|
"data-failure", stdout[-4000:] + stderr[-2000:])
|
|
assert (saves / "slot3.json").is_file()
|
|
assert (game.seed, game.scenario_key, game.world_mode) == (4242, "s1_patrouille", "procedural")
|