Add bridge lookouts, radar room, ops tooling, graphic mails and Pi deploy

- Escorts: bridge lookouts (periscope feather, snorkel, surfaced boats,
  torpedo tracks), spoken sighting reports, 3D bridge station with
  binoculars and own foredeck, lookout hit inset
- 3D sea split into models/shaders: multi-wave ocean with whitecaps,
  clouds, sun and moon, detailed ships with smoke and turning radar
- Radar room rebuilt as phosphor PPI with range scales, ESM rose and
  radar status; NATO symbols on plot, mission charts and replay
- Sortable and filterable contact list, leaderboard and alert log;
  smoothed list bearings; clear convoy progress bar
- Ops: backups, metrics, structured logs, CI, Elo ratings, private
  matches, corvette and coastal sub, network load test
- Mail: configurable SMTP (Gmail/iCloud), signal-style HTML mails with
  inline sonar header, mail test command
- Fixes: spoofable client IP behind proxy, phone layout and lost taps,
  stacked debriefs, station 5 rejected by server
- Raspberry Pi deploy script and .env.example
This commit is contained in:
db9979 committed 2026-11-22 09:15:08 +01:00
1 parent 2902d0d601
commit 7b0a071e8e
79 files changed
+3371 -509

No files matched your search

+3
View File
@@ -5,3 +5,6 @@ node_modules
*.db
.git
.claude
.env
.env.*
!.env.example
+36
View File
@@ -0,0 +1,36 @@
# Copy to .env next to docker-compose.yml and fill in. Never commit the real .env.
# Public HTTPS address of the game (used in verification / password-reset mails)
PUBLIC_URL=https://spiel.example.de
# 1 behind an HTTPS reverse proxy; 0 only for plain HTTP tests in the LAN
COOKIE_SECURE=1
# Moderator accounts (callsigns, comma-separated)
ADMIN=
# ── Outgoing mail (verification and password-reset links). Empty SMTP_HOST = links only in the server log.
# Gmail: SMTP_HOST=smtp.gmail.com SMTP_PORT=587 SMTP_SECURITY=starttls
# SMTP_USER=you@gmail.com SMTP_PASS=<app password: myaccount.google.com/apppasswords, needs 2-step verification>
# iCloud: SMTP_HOST=smtp.mail.me.com SMTP_PORT=587 SMTP_SECURITY=starttls
# SMTP_USER=you@icloud.com SMTP_PASS=<app-specific password: account.apple.com → Sign-In and Security>
# MAIL_FROM must be your iCloud address or an iCloud+ custom-domain address
# Other: port 465 → SMTP_SECURITY=ssl, port 587 → starttls, port 25 in the LAN → none
SMTP_HOST=
SMTP_PORT=587
SMTP_SECURITY=starttls
SMTP_USER=
SMTP_PASS=
# Sender address (empty = SMTP_USER); Gmail/iCloud only accept your own address or a verified alias
MAIL_FROM=
MAIL_FROM_NAME=Tiefenkontakt
# Optional: where replies go
MAIL_REPLY_TO=
# 0 only for a LAN mail server with a self-signed certificate
SMTP_TLS_VERIFY=1
SMTP_TIMEOUT_S=20
# Bearer token for /api/metrics (empty = moderators only)
METRICS_TOKEN=
# Host port of the game server
HOST_PORT=8787
# Raspberry Pi with SD card: save running matches less often
MATCH_SAVE_S=30
# Backups in the data volume
BACKUP_KEEP=7
BACKUP_EVERY_H=24
+31
View File
@@ -0,0 +1,31 @@
# Typecheck, tests and build on every push and pull request; the Docker image is built too.
name: CI
on:
push:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm run typecheck
- run: npm test
- run: npm -w @tk/client run build
docker:
runs-on: ubuntu-latest
needs: test
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- run: docker build -t tiefenkontakt:ci .
- name: Container starts and answers
run: |
docker run -d --name tk -p 8787:8787 -e COOKIE_SECURE=0 tiefenkontakt:ci
for i in $(seq 1 30); do curl -sf localhost:8787/api/health && exit 0; sleep 1; done
docker logs tk; exit 1
+1
View File
@@ -13,6 +13,7 @@ ENV NODE_ENV=production \
TRUST_PROXY=1 \
DB_PATH=/data/tiefenkontakt.db \
MATCH_DIR=/data/matches \
BACKUP_DIR=/data/backups \
CLIENT_DIST=/app/apps/client/dist
VOLUME /data
EXPOSE 8787
+3 -1
View File
@@ -103,6 +103,8 @@ export const EN_PHRASES: [RegExp, string][] = [
[/Ausbildung (\d): /, 'Training $1: '], [/Einsatz (\d): /, 'Mission $1: '], [/Horchen und Klassifizieren/, 'Listening and classifying'],
[/Zielbewegungsanalyse/, 'Target motion analysis'], [/Torpedoangriff/, 'Torpedo attack'], [/U-Jagd mit Fregatte/, 'ASW with a frigate'],
[/Grönland-Lücke bei Tag gewinnen/, 'Win the Greenland gap by day'], [/Schelfmeer in der Dämmerung gewinnen/, 'Win the shelf sea at dusk'],
[/Fjordausfahrt bei Nacht gewinnen/, 'Win the fjord exit at night'], [/^Dienstbuch/i, 'Service record'], [/ PUNKTE\b/, ' POINTS'], [/ SCHIFFE\b/, ' SHIPS'],
[/Fjordausfahrt bei Nacht gewinnen/, 'Win the fjord exit at night'], [/Hafenangriff in der Dämmerung gewinnen/, 'Win the harbour attack at dusk'],
[/Schelfmeer bei Nacht gewinnen/, 'Win the shelf sea at night'], [/U-Boot-Duell bei Nacht gewinnen/, 'Win the submarine duel at night'],
[/U-Boot-Duell gewinnen/, 'Win the submarine duel'], [/Grönland-Lücke bei Nacht gewinnen/, 'Win the Greenland gap at night'], [/^Dienstbuch/i, 'Service record'], [/ PUNKTE\b/, ' POINTS'], [/ SCHIFFE\b/, ' SHIPS'],
[/ PARTIEN\b/g, ' MATCHES'], [/ SIEGE\b/g, ' WINS'], [/ALLE SPIELER UND KI/, 'ALL PLAYERS AND AI'], [/^WEST /, 'WEST '], [/ OST /, ' EAST '], [/GEWONNEN/g, 'WON'], [/VERLOREN/g, 'LOST'], [/REGEN/g, 'RAIN'], [/KLAR/g, 'CLEAR'], [/SEEGANG/g, 'SEA STATE'],
];
+4 -1
View File
@@ -116,7 +116,10 @@ export const EN_UI: [string, string][] = [
['ENTF.', 'RANGE'], ['SENSOR', 'SENSOR'], ['GEIST?', 'GHOST?'], ['(BOJE)', '(BUOY)'], ['KEINE KONTAKTE', 'NO CONTACTS'], ['Klicken zum Auswählen', 'Click to select'],
['Schadensabwehr', 'Damage control'], ['KLICK AUF EIN SYSTEM = ZUERST REPARIEREN', 'CLICK A SYSTEM = REPAIR FIRST'], ['KEINE SCHÄDEN', 'NO DAMAGE'],
['Fregatte F-12', 'Frigate F-12'], ['Atom-U-Boot Projekt 9', 'Nuclear submarine Project 9'], ['Diesel-U-Boot Projekt 4', 'Diesel submarine Project 4'],
['Fregatte', 'Frigate'], ['Atom-U-Boot', 'Nuclear submarine'], ['Diesel-U-Boot', 'Diesel submarine'], ['Frachter', 'Merchant'], ['U-Boot', 'Submarine'],
['Fregatte', 'Frigate'], ['KÜSTEN-U-BOOT', 'COASTAL SUBMARINE'], ['KORVETTE', 'CORVETTE'], ['Korvette K-7', 'Corvette K-7'], ['Korvette', 'Corvette'],
['Küsten-U-Boot Projekt 2', 'Coastal submarine Project 2'], ['Küsten-U-Boot', 'Coastal submarine'], ['Korvette K-7 (Diesel)', 'Corvette K-7 (diesel)'],
['Extrem leise, klein und wendig; nur 4 Rohre, kleine Batterie, 200 m', 'Extremely quiet, small and agile; only 4 tubes, small battery, 200 m'],
['Leise, schnell, wendig; kurzes Schleppsonar, kein Hubschrauber', 'Quiet, fast, agile; short towed array, no helicopter'], ['Atom-U-Boot', 'Nuclear submarine'], ['Diesel-U-Boot', 'Diesel submarine'], ['Frachter', 'Merchant'], ['U-Boot', 'Submarine'],
['Kriegsschiff', 'Warship'], ['Unbekannt', 'Unknown'],
['Standard wiederherstellen', 'Restore defaults'], ['Taste drücken …', 'Press a key …'], ['Hineinzoomen', 'Zoom in'], ['Herauszoomen', 'Zoom out'],
['Auf eigenes Schiff zentrieren', 'Centre on own ship'], ['Karte hier zentrieren', 'Centre map here'], ['stumm', 'mute'], ['melden', 'report'],
+32 -2
View File
@@ -1,5 +1,23 @@
/** German → English: briefing, settings, lobby cards and chat, ranks, empty states. */
export const EN_UX: [string, string][] = [
['ZIELHAFEN', 'DESTINATION'], ['KONVOI', 'CONVOY'], ['RUDEL', 'WOLFPACK'], ['SPERRE', 'BARRIER'], ['ANKERPLATZ', 'ANCHORAGE'], ['ANGRIFF', 'ATTACK'], ['⚙ FREI', '⚙ CUSTOM'], ['≈ 23 KM', '≈ 23 KM'],
['Brücke', 'Bridge'], ['Brücke · Ausguck', 'Bridge · Lookout'], ['Fernglas 7×', 'Binoculars 7×'], ['Voraus', 'Ahead'], ['Auf Meldung', 'To report'],
['Auf Kontakt', 'To contact'], ['ZIEHEN DREHT · A / D', 'DRAG TURNS · A / D'], ['Blick nach links', 'Look left'], ['Blick nach rechts', 'Look right'],
['Ausguck', 'Lookout'], ['AUSGUCK', 'LOOKOUT'], ['20 M AUGENHÖHE', '20 M EYE HEIGHT'], ['SICHT', 'VISIBILITY'], ['GUT', 'GOOD'], ['MÄSSIG', 'MODERATE'], ['SCHLECHT', 'POOR'],
['SEHROHR (6 KN) BIS', 'PERISCOPE (6 KN) TO'], ['SCHNORCHEL BIS', 'SNORKEL TO'], ['AUFGETAUCHT BIS', 'SURFACED TO'], ['MELDUNGEN', 'REPORTS'],
['NOCH KEINE SICHTUNG', 'NO SIGHTING YET'], ['LADE …', 'LOADING …'], ['KEINE 3D-GRAFIK (WEBGL2) · MELDUNGEN RECHTS', 'NO 3D GRAPHICS (WEBGL2) · REPORTS ON THE RIGHT'],
['Die Ausgucks melden Sehrohr-Fahnen, Schnorchel und Torpedolaufbahnen selbst. Nachts, bei Regen und hohem Seegang sehen sie kaum etwas.', 'The lookouts report periscope feathers, snorkels and torpedo tracks on their own. At night, in rain and in heavy seas they see very little.'],
['AKTUELL', 'CURRENT'], ['OHNE EIGENE', 'NO FRIENDLIES'], ['OPTIK', 'OPTICS'], ['ALARM', 'ALARM'], ['WARNUNG', 'WARNING'], ['INFO', 'INFO'],
['Sortieren', 'Sort'], ['Nur Kontakte der letzten 30 s', 'Only contacts from the last 30 s'], ['Eigene und verbündete Einheiten ausblenden', 'Hide own and allied units'],
['KEINE KONTAKTE FÜR DIESEN FILTER', 'NO CONTACTS FOR THIS FILTER'], ['KEINE MELDUNGEN FÜR DIESEN FILTER', 'NO REPORTS FOR THIS FILTER'],
['KLICK AUF SPALTE SORTIERT', 'CLICK A COLUMN TO SORT'], ['RUFZ.', 'CALLSIGN'], ['PKT', 'PTS'], ['QUOTE', 'RATE'], ['VERS.', 'SUNK'], ['BRT', 'GRT'], ['SIEGE', 'WINS'],
['Radarstatus', 'Radar status'], ['ESM · Funkpeilung', 'ESM · DF'], ['ROSE UND LISTE', 'ROSE AND LIST'], ['KLICK AUF ECHO WÄHLT', 'CLICK AN ECHO TO SELECT'],
['SENDER', 'TRANSMITTER'], ['EIN · SENDET', 'ON · TRANSMITTING'], ['AUS · STANDBY', 'OFF · STANDBY'], ['STANDBY', 'STANDBY'], ['BEREICH / ANTENNE', 'RANGE / ANTENNA'],
['ECHOS', 'ECHOES'], ['SEEGANG-STÖRUNG', 'SEA CLUTTER'], ['GERING', 'LOW'], ['STARK', 'HEAVY'], ['SEHR STARK', 'VERY HEAVY'], ['GEGNER-ESM HÖRT UNS', 'ENEMY ESM HEARS US'],
['● ABSTRAHLUNG', '● EMITTING'], ['○ STILL', '○ SILENT'], ['STANDBY · SENDER AUS', 'STANDBY · TRANSMITTER OFF'], ['ESM HÖRT WEITER MIT', 'ESM KEEPS LISTENING'],
['RADAR AUS · KEINE SPUREN', 'RADAR OFF · NO TRACKS'], ['KEINE FUNKPEILUNGEN · ALLES STILL', 'NO INTERCEPTS · ALL QUIET'],
['Jede U-Boot-Funkpeilantenne in 40 SM peilt uns jetzt. Schnorchel und Sehrohre zeigt das Radar nur auf kurze Distanz.', 'Every submarine DF antenna within 40 NM is taking our bearing now. Radar shows snorkels and periscopes only at short range.'],
['Ohne Radar bleibt die Fregatte still. Kurz einschalten, Lage aufnehmen, wieder aus.', 'Without radar the frigate stays silent. Switch on briefly, take the picture, switch off again.'],
['LAGEBESPRECHUNG', 'BRIEFING'], ['AUFTRAG', 'ORDERS'], ['EIGENES SCHIFF', 'OWN SHIP'], ['LAGE', 'SITUATION'], ['ERSTE SCHRITTE', 'FIRST STEPS'],
['Auf Station', 'Man your station'], ['Schelfmeer', 'Shelf sea'], ['Fjordausfahrt', 'Fjord exit'],
['Enger Kanal zwischen Untiefen; wer ihn verlässt, läuft auf', 'Narrow channel between shoals; leave it and you run aground'],
@@ -29,9 +47,21 @@ export const EN_UX: [string, string][] = [
['Leutnant zur See', 'Sub-Lieutenant'], ['Oberleutnant zur See', 'Lieutenant (jg)'], ['Kapitänleutnant', 'Lieutenant'], ['Korvettenkapitän', 'Lieutenant Commander'],
['Fregattenkapitän', 'Commander'], ['Kapitän zur See', 'Captain'], ['LzS', 'SLt'], ['OLzS', 'LtJG'], ['KptLt', 'Lt'], ['KKpt', 'LCdr'], ['FKpt', 'Cdr'], ['KptzS', 'Capt'],
['Torpedo-Fahrt', 'Torpedo speed'], ['Abstrahlung', 'Radiated noise'],
['PRIVAT', 'PRIVATE'], ['Nicht in der Liste; nur per Einladungslink', 'Not listed; invite link only'], ['EINLADEN', 'INVITE'],
['PRIVATE PARTIE · NUR PER LINK', 'PRIVATE MATCH · LINK ONLY'], ['Link kopieren', 'Copy link'], ['Kopiert ✓', 'Copied ✓'], ['Wertung', 'Rating'],
['Einladung ungültig oder Partie läuft schon', 'Invite invalid or the match has already started'], ['BACKUP_DIR ist nicht gesetzt', 'BACKUP_DIR is not set'],
];
export const EN_UX_PHRASES: [RegExp, string][] = [
[/^VERLOREN (\d+) %$/, 'LOST $1 %'], [/^SICHER (\d+) %$/, 'SAFE $1 %'], [/^VERSENKT (\d+) %$/, 'SUNK $1 %'], [/^ENTKOMMEN (\d+) %$/, 'ESCAPED $1 %'],
[/^· SIEG: ÜBER 50 % SICHER$/, '· WIN: OVER 50 % SAFE'], [/^· SIEG: 50 % VERSENKT$/, '· WIN: 50 % SUNK'],
[/^Konvoi-Tonnage\. Rot: versenkt \((\d+) %\), blau: sicher im Zielhafen \((\d+) %\)\..*$/, 'Convoy tonnage. Red: sunk ($1 %), blue: safe in port ($2 %). More than half in port = win, half sunk = defeat. At the time limit the escort loses from 30 % lost (tick).'],
[/^Konvoi-Tonnage\. Rot: von uns versenkt \((\d+) %\), blau: entkommen \((\d+) %\)\..*$/, 'Convoy tonnage. Red: sunk by us ($1 %), blue: escaped ($2 %). Half sunk = win; if more than half arrives, we lose. At the time limit 30 % is enough (tick).'],
[/^SENDET · (\d+) U\/MIN$/, 'TRANSMITTING · $1 RPM'], [/^(\d+) · DAVON EIGENE (\d+)$/, '$1 · OWN $2'], [/^BIS (\d+) SM$/, 'TO $1 NM'], [/^(\d+) SM · (\d+) U\/MIN$/, '$1 NM · $2 RPM'], [/^Bereich (\d+) SM$/, 'Range $1 NM'],
[/^AUSGUCK · SEHROHR PEILUNG/, 'LOOKOUT · PERISCOPE BEARING'], [/^AUSGUCK · SCHNORCHEL PEILUNG/, 'LOOKOUT · SNORKEL BEARING'], [/^AUSGUCK · U-BOOT AUFGETAUCHT PEILUNG/, 'LOOKOUT · SUBMARINE SURFACED BEARING'],
[/ · CA\. (\d+),(\d) KM$/, ' · ABOUT $1.$2 KM'], [/^BLICK (\d+)° · VORAUS$/, 'VIEW $1° · AHEAD'], [/^BLICK (\d+)° · (\d+)° STB$/, 'VIEW $1° · $2° STBD'], [/^BLICK (\d+)° · (\d+)° BB$/, 'VIEW $1° · $2° PORT'],
[/^(A\d+) SEHROHR$/, '$1 PERISCOPE'], [/^(A\d+) SCHNORCHEL$/, '$1 SNORKEL'], [/^(A\d+) AUFGETAUCHT$/, '$1 SURFACED'],
[/^TIEFE ~(\d+),(\d) KM$/, 'DEPTH ~$1.$2 KM'], [/^TIEFE ~/, 'DEPTH ~'],
[/^Gegner zuletzt gemeldet: etwa Peilung (\d+), (\d+) km$/, 'Enemy last reported: about bearing $1, $2 km'],
[/^Aufklärung: Konvoi etwa Peilung (\d+), (\d+) km \(ungenau\)$/, 'Intelligence: convoy about bearing $1, $2 km (imprecise)'],
[/^Aufklärung: Ankerplatz etwa Peilung (\d+), (\d+) km \(ungenau\)$/, 'Intelligence: anchorage about bearing $1, $2 km (imprecise)'],
@@ -40,6 +70,6 @@ export const EN_UX_PHRASES: [RegExp, string][] = [
[/^Konvoi: Peilung (\d+), (\d+) km, (\d+) Frachter$/, 'Convoy: bearing $1, $2 km, $3 merchants'],
[/^Ankerplatz: Peilung (\d+), (\d+) km, (\d+) Frachter$/, 'Anchorage: bearing $1, $2 km, $3 merchants'],
[/^Bedrohung: (\d+) U-Boot\(e\), vermutlich voraus des Konvois$/, 'Threat: $1 submarine(s), probably ahead of the convoy'],
[/Atom-U-Boot Projekt 9/, 'Nuclear submarine Project 9'], [/Diesel-U-Boot Projekt 4/, 'Diesel submarine Project 4'], [/^Fregatte F-12/, 'Frigate F-12'],
[/^AN BORD: /, 'ABOARD: '], [/ UHR\b/, ''], [/AKTIVSONAR/g, 'ACTIVE SONAR'],
[/Atom-U-Boot Projekt 9/, 'Nuclear submarine Project 9'], [/Diesel-U-Boot Projekt 4/, 'Diesel submarine Project 4'], [/Küsten-U-Boot Projekt 2/, 'Coastal submarine Project 2'], [/^Korvette K-7/, 'Corvette K-7'], [/^Fregatte F-12/, 'Frigate F-12'],
[/^AN BORD: /, 'ABOARD: '], [/ · WERTUNG (\d+)/, ' · RATING $1'], [/ UHR\b/, ''], [/AKTIVSONAR/g, 'ACTIVE SONAR'],
];
+3
View File
@@ -40,6 +40,9 @@ function translate(de: string): string {
// Bullets and markers in front of a known sentence: "▸ Güte über 60 % bringen"
const lead = /^([▸·✓•–\s]+)(.+)$/.exec(de);
if (lead) return lead[1]! + translate(lead[2]!);
// Sort arrows after a column name: "PEILUNG ▲"
const tail = /^(.+?)( [▲▼])$/.exec(de);
if (tail) return translate(tail[1]!) + tail[2]!;
// Composite labels like "1 · OPZ" or "Westbund · Geleitschutz": translate each part
let out = de.includes(' · ') ? de.split(' · ').map((p) => dict.get(p) ?? p).join(' · ') : de;
for (const [re, rep] of PHRASES) out = out.replace(re, rep);
+6
View File
@@ -30,6 +30,12 @@ const toLobby = () => go('lobby', () => lobbyScreen(root, me!));
net.on((m: ServerMsg) => {
if (m.t === 'welcome') {
me = { playerId: m.playerId, callsign: m.callsign };
// Invite link: #join=<match id> joins that match right after connecting
const inv = /^#join=([a-f0-9]{8})$/.exec(location.hash);
if (inv) {
history.replaceState(null, '', location.pathname);
net.send({ t: 'join_code', matchId: inv[1]! });
}
store.playerId = m.playerId;
// A returning player is put back into the match by the server; otherwise show the lobby
if (!m.resume && screen !== 'lobby') toLobby();
+24 -7
View File
@@ -1,12 +1,13 @@
import { net } from '../net.js';
import { esc, h } from '../widgets/format.js';
import { bindSortable, sortHead, sortRows, type SortState } from '../widgets/sortable.js';
interface Step {
id: string;
kind: 'lesson' | 'mission';
title: string;
lesson?: 'klassifizieren' | 'tma' | 'angriff' | 'ujagd';
mission?: 'groenland' | 'schelf' | 'fjord';
mission?: 'groenland' | 'schelf' | 'fjord' | 'duell' | 'hafen';
timeOfDay?: 'tag' | 'daemmerung' | 'nacht';
done: boolean;
unlocked: boolean;
@@ -18,7 +19,7 @@ export function careerPanels(): HTMLElement {
const el = h(`<div class="grid2" style="margin-top:10px"><div class="panel" id="c-me"></div><div style="display:flex;flex-direction:column;gap:10px"><div class="panel" id="c-board"></div><div class="panel" id="c-balance"></div></div></div>`);
const balance = el.querySelector<HTMLElement>('#c-balance')!;
const MISSION: Record<string, string> = { groenland: 'Grönland', schelf: 'Schelf', fjord: 'Fjord' };
const CLS: Record<string, string> = { ffg: 'Fregatte', ssk: 'Diesel-U-Boot', ssn: 'Atom-U-Boot' };
const CLS: Record<string, string> = { ffg: 'Fregatte', kor: 'Korvette', ssk: 'Diesel-U-Boot', ssn: 'Atom-U-Boot', ssc: 'Küsten-U-Boot' };
fetch('/api/balance').then(async (r) => {
const b = (await r.json()) as { total: number; missions: { key: string; games: number; westWins: number; eastWins: number; avgMin: number }[]; classes: { key: string; games: number; wins: number }[] };
const pct = (a: number, n: number) => (n ? Math.round((100 * a) / n) : 0);
@@ -38,9 +39,9 @@ export function careerPanels(): HTMLElement {
me.innerHTML = '<div class="hd"><span>Dienstbuch und Kampagne</span></div><div class="dim">MIT KONTO WERDEN ERGEBNISSE, PUNKTE UND KAMPAGNE GESPEICHERT.</div>';
return;
}
const d = (await r.json()) as { summary?: Summary; campaign: Step[] };
const d = (await r.json()) as { summary?: Summary; campaign: Step[]; rating?: number };
const s = d.summary;
me.innerHTML = `<div class="hd"><span>Dienstbuch · ${esc(s?.callsign ?? '')}</span><span>${s?.points ?? 0} PUNKTE</span></div>
me.innerHTML = `<div class="hd"><span>Dienstbuch · ${esc(s?.callsign ?? '')}</span><span>${s?.points ?? 0} PUNKTE · WERTUNG ${d.rating ?? 1000}</span></div>
<div class="row"><span class="dim">PARTIEN / SIEGE</span><span>${s?.matches ?? 0} / ${s?.wins ?? 0}</span></div>
<div class="row"><span class="dim">VERSENKT</span><span>${s?.kills ?? 0} SCHIFFE · ${Math.round((s?.tonnage ?? 0) / 1000)}K BRT</span></div>
<div class="hd" style="margin-top:8px"><span>Kampagne</span><span class="dim">${d.campaign.filter((c) => c.done).length}/${d.campaign.length}</span></div>
@@ -62,9 +63,25 @@ export function careerPanels(): HTMLElement {
fetch('/api/leaderboard').then(async (r) => {
const rows = (await r.json()) as Summary[];
board.innerHTML = `<div class="hd"><span>Rangliste</span><span class="dim">PUNKTE · SIEGE · VERSENKT</span></div>` +
(rows.length ? rows.map((x, i) => `<div class="row"><span>${i + 1}. ${esc(x.callsign)}</span><span>${x.points} · ${x.wins} · ${x.kills}</span></div>`).join('')
: '<div class="dim">NOCH KEINE ERGEBNISSE</div>');
// Rank stays the points rank; columns re-sort the view
const ranked = rows.map((x, i) => ({ ...x, rank: i + 1 }));
const ID = 'leaderboard';
const DEF: SortState = { key: 'rank', dir: 1 };
const draw = () => {
const view = sortRows(ranked, ID, DEF, {
rank: (x) => x.rank, callsign: (x) => x.callsign.toLowerCase(), points: (x) => x.points, wins: (x) => x.wins,
rate: (x) => (x.matches ? x.wins / x.matches : undefined), kills: (x) => x.kills, tonnage: (x) => x.tonnage,
});
const hd = (k: string, l: string) => sortHead(ID, k, l, DEF);
board.innerHTML = `<div class="hd"><span>Rangliste</span><span class="dim">KLICK AUF SPALTE SORTIERT</span></div>` +
(rows.length
? `<div class="row dim ltable">${hd('rank', '#')}${hd('callsign', 'RUFZ.')}${hd('points', 'PKT')}${hd('wins', 'SIEGE')}${hd('rate', 'QUOTE')}${hd('kills', 'VERS.')}${hd('tonnage', 'BRT')}</div>` +
view.map((x) => `<div class="row ltable"><span>${x.rank}</span><span>${esc(x.callsign)}</span><span>${x.points}</span><span>${x.wins}/${x.matches}</span><span>${x.matches ? Math.round((100 * x.wins) / x.matches) + ' %' : '—'}</span><span>${x.kills}</span><span>${Math.round(x.tonnage / 1000)}K</span></div>`).join('')
: '<div class="dim">NOCH KEINE ERGEBNISSE</div>');
};
const desc = { points: -1, wins: -1, rate: -1, kills: -1, tonnage: -1 } as const;
bindSortable(board, ID, DEF, draw, { firstDir: desc });
draw();
}).catch(() => undefined);
return el;
}
+34 -11
View File
@@ -1,7 +1,9 @@
import { onTap } from '../widgets/touch.js';
import { CLASSES, NM, headingVec, targetPosAt, type Debrief, type Vec2 } from '@tk/shared';
import { store } from '../store.js';
import { CLASS_LABEL, COL, clock, esc, fitCanvas, h } from '../widgets/format.js';
import { debriefTips, timelineMarkers } from '../widgets/debrief-extras.js';
import { drawSymbol } from '../widgets/symbols.js';
const SPEEDS = [30, 120, 480];
@@ -14,7 +16,14 @@ function teamColor(team: string, player: boolean): string {
* After-action review: replay of the true tracks with a timeline, the player's own
* track and TMA solutions overlaid for comparison, and per-player statistics.
*/
/** Only one debrief at a time: a re-sent debrief (reconnect, server restart) updates it instead of stacking a new one at 00:00. */
let current: { update(nd: Debrief): void; el: HTMLElement } | undefined;
export function debriefOverlay(d: Debrief, onClose: () => void, live = false): { update(nd: Debrief): void } {
if (current && document.body.contains(current.el)) {
current.update(d);
return current;
}
const ownId = store.snap?.own.id;
const el = h(`<div class="overlay"><div class="panel" style="max-width:1200px;width:96vw;max-height:94vh;display:grid;grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);gap:10px">
<div style="min-width:0">
@@ -79,9 +88,8 @@ export function debriefOverlay(d: Debrief, onClose: () => void, live = false): {
const m = (e.target as HTMLElement).closest<HTMLElement>('[data-ev]');
if (m) t = Math.max(0, d.events[Number(m.dataset.ev)]!.t - 30);
});
q('#db-events').addEventListener('mousedown', (e) => {
const row = (e.target as HTMLElement).closest<HTMLElement>('[data-ev]');
if (row) t = Math.max(0, d.events[Number(row.dataset.ev)]!.t - 30);
onTap(q('#db-events'), '[data-ev]', (row) => {
t = Math.max(0, d.events[Number(row.dataset.ev)]!.t - 30);
});
cv.addEventListener('wheel', (e) => {
e.preventDefault();
@@ -101,6 +109,7 @@ export function debriefOverlay(d: Debrief, onClose: () => void, live = false): {
q<HTMLButtonElement>('#db-close').onclick = () => {
cancelAnimationFrame(raf);
el.remove();
current = undefined;
onClose();
};
@@ -122,6 +131,17 @@ export function debriefOverlay(d: Debrief, onClose: () => void, live = false): {
}
function draw(): void {
// Always keep the loop alive, even if one frame fails on odd data
raf = requestAnimationFrame(draw);
try {
frame();
} catch (e) {
console.error('Nachbesprechung:', e);
}
}
function frame(): void {
if (!document.body.contains(el)) return cancelAnimationFrame(raf);
const now = performance.now();
if (playing) {
t = Math.min(d.duration, t + ((now - last) / 1000) * SPEEDS[speedIdx]!);
@@ -193,12 +213,13 @@ export function debriefOverlay(d: Debrief, onClose: () => void, live = false): {
const c = teamColor(s.team, s.player);
ctx.fillStyle = e[3] ? c : '#5f7a72';
ctx.strokeStyle = ctx.fillStyle;
if (CLASSES[s.cls].submarine) {
ctx.beginPath(); ctx.arc(p.x, p.y, 5, 0, 7); ctx.fill();
} else {
const v = headingVec(e[2]);
ctx.beginPath(); ctx.moveTo(p.x + v.x * 7, p.y - v.y * 7); ctx.lineTo(p.x - v.y * 4, p.y - v.x * 4); ctx.lineTo(p.x + v.y * 4, p.y + v.x * 4); ctx.closePath(); ctx.fill();
}
// APP-6 frames from the viewer's side: friend circle, hostile diamond; submerged boats as lower halves
const myTeam = d.ships.find((x) => x.id === ownId)?.team ?? 'west';
ctx.lineWidth = 1.8;
drawSymbol(ctx, p.x, p.y, s.team === myTeam ? 'friend' : 'hostile', CLASSES[s.cls].submarine ? 'subsurface' : 'surface', s.cls === 'merchant' ? 4 : 6, true);
const v = headingVec(e[2]);
ctx.beginPath(); ctx.moveTo(p.x + v.x * 6, p.y - v.y * 6); ctx.lineTo(p.x + v.x * 12, p.y - v.y * 12); ctx.stroke();
ctx.lineWidth = 1;
if (!e[3]) ctx.fillText('†', p.x + 6, p.y - 6);
if (s.player || s.id === ownId) ctx.fillText(s.name, p.x + 8, p.y + 4);
}
@@ -216,10 +237,10 @@ export function debriefOverlay(d: Debrief, onClose: () => void, live = false): {
}
ctx.fillStyle = COL.dim;
ctx.fillText(`RASTER 5 SM`, 8, H - 8);
raf = requestAnimationFrame(draw);
}
raf = requestAnimationFrame(draw);
return {
const api = {
el,
update(nd: Debrief) {
// Live view: follow the newest frame unless the viewer scrubbed back
const following = t >= d.duration - 1;
@@ -229,4 +250,6 @@ export function debriefOverlay(d: Debrief, onClose: () => void, live = false): {
renderLists();
},
};
current = api;
return api;
}
+48 -17
View File
@@ -1,10 +1,11 @@
import { CLASSES, type ServerMsg } from '@tk/shared';
import { CLASSES, type ServerMsg, type Snapshot } from '@tk/shared';
import { audio } from '../audio.js';
import { net } from '../net.js';
import { store } from '../store.js';
import { diveEngineStation } from '../stations/sub/dive-engine.js';
import { fireControlStation } from '../stations/sub/fire-control.js';
import { periscopeStation } from '../stations/sub/periscope.js';
import { bridgeStation } from '../stations/frigate/bridge.js';
import { subSonarStation } from '../stations/sub/sonar.js';
import { opsCenterStation } from '../stations/frigate/ops-center.js';
import { frigateSonarStation } from '../stations/frigate/sonar.js';
@@ -18,6 +19,8 @@ import { debriefOverlay } from './debrief.js';
import { helpOverlay } from './help.js';
import { radioLog } from '../widgets/radio-log.js';
import { isKey, stationKey } from '../widgets/keys.js';
import { bindSortable, filterChips, getFilters } from '../widgets/sortable.js';
import { hitCam } from '../widgets/hit-cam.js';
import { mountHelm } from './helm.js';
import { mountAssistant } from '../widgets/assistant.js';
import { showBriefing } from '../widgets/briefing.js';
@@ -43,7 +46,7 @@ export function gameScreen(root: HTMLElement, onExit: () => void): () => void {
<div class="tabs" id="tabs"></div>
<div class="status">
<span id="ship" class="st-ship"></span>
<span class="st-prog" title="Versenkte und angekommene Konvoi-Tonnage"><span class="pbar"><i id="pb-sunk"></i><i id="pb-arr"></i></span><span id="pb-txt" class="dim"></span></span>
<span class="st-prog"><span class="dim pb-lbl">KONVOI</span><span class="pbar"><i id="pb-sunk"></i><i id="pb-arr"></i><b class="pb-mid"></b><b class="pb-30"></b></span><span id="pb-txt"></span></span>
<span id="clock" class="st-clock"></span>
</div>
<button id="mute" class="icon" title="Ton an/aus (M)"></button>
@@ -55,7 +58,7 @@ export function gameScreen(root: HTMLElement, onExit: () => void): () => void {
<div class="side">
<div class="panel helm" id="helm"></div>
<div class="panel" id="damage"></div>
<div class="panel alerts"><div class="hd"><span>Meldungen</span><span class="dim">KLICK = HINGEHEN</span></div><div id="alerts"></div></div>
<div class="panel alerts"><div class="hd"><span>Meldungen</span><span class="dim">KLICK = HINGEHEN</span></div><div id="alert-chips"></div><div id="alerts"></div></div>
<div class="panel"><div class="hd"><span>Funk</span><span id="radio-state" class="dim"></span></div>
<div class="radio" id="radio"></div>
<div style="display:flex;gap:4px;margin-top:6px"><input id="rtext" maxlength="200" placeholder="Konvoi Peilung 052" style="flex:1;min-width:0"><button id="rsend">Senden</button></div>
@@ -66,6 +69,29 @@ export function gameScreen(root: HTMLElement, onExit: () => void): () => void {
root.replaceChildren(el);
const q = <T extends HTMLElement>(s: string) => el.querySelector<T>(s)!;
const showRadio = radioLog(q('#radio'));
const cam = hitCam(el);
// Alert log with level filter chips (none on = everything)
const LOG_ID = 'alerts';
const logChips = () => (q('#alert-chips').innerHTML = filterChips(LOG_ID, [
{ key: 'alarm', label: 'ALARM' }, { key: 'warn', label: 'WARNUNG' }, { key: 'info', label: 'INFO' },
]));
const renderLog = (s: Snapshot) => {
const f = getFilters(LOG_ID);
const rows = callouts.log.map((e, i) => ({ e, i })).filter(({ e }) => !f.size || f.has(e.level)).reverse();
const logHtml = (store.lastError ? `<div class="amber">${esc(store.lastError)}</div>` : '') +
(callouts.log.length ? (rows.length ? '' : '<div class="dim">KEINE MELDUNGEN FÜR DIESEN FILTER</div>') : '<div class="dim">KEINE MELDUNGEN · RUHIGE SEE</div>') + rows.map(({ e, i }) => {
const fresh = s.time - e.time < 30;
const color = e.level === 'alarm' ? 'red' : e.level === 'warn' ? 'amber' : '';
const go = e.label !== undefined || e.station !== undefined;
return `<div class="logrow ${color} ${fresh && e.level === 'alarm' ? 'blink' : ''} ${go ? 'clickable' : ''}" data-log="${i}">${clock(e.time)} ${esc(e.text)}</div>`;
}).join('');
if (q('#alerts').innerHTML !== logHtml) q('#alerts').innerHTML = logHtml;
};
logChips();
bindSortable(q('#alert-chips'), LOG_ID, { key: 'time', dir: -1 }, () => {
logChips();
if (store.snap) renderLog(store.snap);
});
let stations: Station[] = [];
let current = 0;
@@ -138,7 +164,7 @@ export function gameScreen(root: HTMLElement, onExit: () => void): () => void {
}
stations = sub
? [subSonarStation(), periscopeStation(), fireControlStation(), diveEngineStation()]
: [opsCenterStation(), frigateSonarStation(), weaponsStation(), radarEsmStation()];
: [opsCenterStation(), frigateSonarStation(), weaponsStation(), radarEsmStation(), bridgeStation()];
tabs.innerHTML = stations.map((s, i) => `<button data-i="${i}" title="Taste ${i + 1}">${i + 1} · ${s.title}</button>`).join('');
tabs.querySelectorAll<HTMLButtonElement>('button').forEach((b) => (b.onclick = () => show(Number(b.dataset.i))));
q('#quick').innerHTML = (sub ? ['Konvoi gesichtet', 'Greife an', 'Werde gejagt', 'Position'] : ['Kontakt', 'Torpedo im Wasser', 'Suche Sektor', 'Position'])
@@ -204,19 +230,22 @@ export function gameScreen(root: HTMLElement, onExit: () => void): () => void {
q('#clock').textContent = `${hh}${s.env.rain ? '🌧 ' : ''}${wx} · REST ${clock(s.score.timeLeftS)}`;
const pct = (x: number) => Math.round((100 * x) / Math.max(1, s.score.totalTons));
q('#ship').textContent = `${CLASS_LABEL[s.own.cls]} ${s.own.name}${s.crew.length > 1 ? ` · AN BORD: ${s.crew.join(', ')}` : ''}`;
q('#pb-sunk').style.width = `${pct(s.score.sunkTons)}%`;
q('#pb-arr').style.width = `${pct(s.score.arrivedTons)}%`;
const prog = s.score.totalTons > 0 ? `VERSENKT ${pct(s.score.sunkTons)} % · AM ZIEL ${pct(s.score.arrivedTons)} %` : '';
q('#pb-txt').textContent = prog;
q('.st-prog').title = prog;
const logHtml = (store.lastError ? `<div class="amber">${esc(store.lastError)}</div>` : '') +
(callouts.log.length ? '' : '<div class="dim">KEINE MELDUNGEN · RUHIGE SEE</div>') + [...callouts.log].reverse().map((e, i) => {
const fresh = s.time - e.time < 30;
const color = e.level === 'alarm' ? 'red' : e.level === 'warn' ? 'amber' : '';
const go = e.label !== undefined || e.station !== undefined;
return `<div class="logrow ${color} ${fresh && e.level === 'alarm' ? 'blink' : ''} ${go ? 'clickable' : ''}" data-log="${callouts.log.length - 1 - i}">${clock(e.time)} ${esc(e.text)}</div>`;
}).join('');
if (q('#alerts').innerHTML !== logHtml) q('#alerts').innerHTML = logHtml;
// Convoy tonnage bar: red grows from the left (sunk), blue from the right (safe in port);
// whoever passes the middle mark (50 %) wins at once, the 30 % mark decides at the time limit
const sunk = pct(s.score.sunkTons);
const safe = pct(s.score.arrivedTons);
q('.st-prog').style.display = s.score.totalTons > 0 ? '' : 'none';
q('#pb-sunk').style.width = `${sunk}%`;
q('#pb-arr').style.width = `${safe}%`;
const escort = s.own.team === 'west';
const txt = q('#pb-txt');
txt.innerHTML = escort
? `<span class="red">VERLOREN ${sunk} %</span> · <span class="blue">SICHER ${safe} %</span> <span class="dim">· SIEG: ÜBER 50 % SICHER</span>`
: `<span class="red">VERSENKT ${sunk} %</span> · <span class="blue">ENTKOMMEN ${safe} %</span> <span class="dim">· SIEG: 50 % VERSENKT</span>`;
q('.st-prog').title = escort
? `Konvoi-Tonnage. Rot: versenkt (${sunk} %), blau: sicher im Zielhafen (${safe} %). Mehr als die Hälfte im Ziel = Sieg, die Hälfte versenkt = Niederlage. Bei Zeitablauf verliert der Geleitschutz ab 30 % Verlust (Strich).`
: `Konvoi-Tonnage. Rot: von uns versenkt (${sunk} %), blau: entkommen (${safe} %). Die Hälfte versenkt = Sieg; kommt mehr als die Hälfte an, ist die Partie verloren. Bei Zeitablauf reichen 30 % (Strich).`;
renderLog(s);
showRadio(s.radio, s.own.name);
const sub = CLASSES[s.own.cls].submarine;
q('#radio-state').innerHTML = sub ? (s.own.mastUp ? '<span class="amber">MAST OBEN · PEILBAR</span>' : 'MAST UNTEN · KEIN FUNK') : 'DATALINK';
@@ -246,6 +275,7 @@ export function gameScreen(root: HTMLElement, onExit: () => void): () => void {
setTimeout(() => document.body.classList.remove('hit'), 800);
}
callouts.update(m.s);
cam.snap(m.s);
stations[current]?.snap?.();
helm.update();
tutorial?.update();
@@ -292,6 +322,7 @@ export function gameScreen(root: HTMLElement, onExit: () => void): () => void {
let raf = 0;
const loop = () => {
stations[current]?.frame();
cam.frame(store.snap);
helm.frame();
raf = requestAnimationFrame(loop);
};
+73 -19
View File
@@ -18,23 +18,42 @@ export function lobbyScreen(root: HTMLElement, me: { playerId: string; callsign:
const el = h(`<div class="center"></div>`);
root.replaceChildren(el);
let shownList = '';
function renderList(): void {
el.querySelector('#merr')!.textContent = error;
const key = JSON.stringify(matches);
if (key === shownList) return;
shownList = key;
const list = el.querySelector<HTMLElement>('#mlist')!;
list.innerHTML = `<div class="hd"><span>Offene Partien</span><span>${matches.length}</span></div>
${matches.length === 0 ? '<div class="dim" style="padding:8px 0">Keine offenen Partien. Erstelle eine.</div>' : ''}
${matches.map((m) => `
<div class="slot"><span>${esc(m.name)} <span class="dim">· ${m.players}/${m.maxPlayers} · ${m.state === 'lobby' ? 'WARTET' : 'LÄUFT'}</span></span>
<span>${m.state === 'lobby' ? `<button data-join="${m.id}" data-team="west">Westbund</button> <button data-join="${m.id}" data-team="east">Ostpakt</button>` : `<button data-watch="${m.id}" title="Verzögert zuschauen">Zuschauen</button>`}</span></div>`).join('')}`;
list.querySelectorAll<HTMLButtonElement>('[data-watch]').forEach((b) => (b.onclick = () => net.send({ t: 'spectate', matchId: b.dataset.watch! })));
list.querySelectorAll<HTMLButtonElement>('[data-join]').forEach((b) => {
b.onclick = () => net.send({ t: 'join', matchId: b.dataset.join!, team: b.dataset.team as 'west' | 'east' });
});
}
function render(): void {
if (!match) {
// Built once; lobby broadcasts only refresh the match list, so taps elsewhere never hit a replaced button
if (el.dataset.view === 'list') return renderList();
el.dataset.view = 'list';
shownList = '';
el.innerHTML = `
<div class="title">TIEFENKONTAKT</div>
<div class="dim" style="margin-bottom:16px">EINGELOGGT ALS ${esc(me.callsign)}</div>
<div class="panel">
<div class="hd"><span>Offene Partien</span><span>${matches.length}</span></div>
${matches.length === 0 ? '<div class="dim" style="padding:8px 0">Keine offenen Partien. Erstelle eine.</div>' : ''}
${matches.map((m) => `
<div class="slot"><span>${esc(m.name)} <span class="dim">· ${m.players}/${m.maxPlayers} · ${m.state === 'lobby' ? 'WARTET' : 'LÄUFT'}</span></span>
<span>${m.state === 'lobby' ? `<button data-join="${m.id}" data-team="west">Westbund</button> <button data-join="${m.id}" data-team="east">Ostpakt</button>` : `<button data-watch="${m.id}" title="Verzögert zuschauen">Zuschauen</button>`}</span></div>`).join('')}
<div style="display:flex;gap:6px;margin-top:10px">
<input id="mname" placeholder="Grönland-Lücke" maxlength="40" style="flex:1">
<div id="mlist"></div>
<div class="newmatch">
<input id="mname" placeholder="Grönland-Lücke" maxlength="40">
<label class="dim" title="Nicht in der Liste; nur per Einladungslink"><input type="checkbox" id="mpriv"> PRIVAT</label>
<button id="create">Partie erstellen</button>
<button id="quick" class="on" title="Einer offenen Partie beitreten oder eine neue eröffnen">Schnelles Spiel</button>
</div>
<div class="err">${esc(error)}</div>
<div class="err" id="merr"></div>
</div>
<div class="panel" style="margin-top:10px">
<div class="hd"><span>Ausbildung</span><span class="dim">EINZELSPIELER · MIT ANLEITUNG</span></div>
@@ -53,28 +72,27 @@ export function lobbyScreen(root: HTMLElement, me: { playerId: string; callsign:
});
el.querySelector<HTMLButtonElement>('#create')!.onclick = () => {
const name = el.querySelector<HTMLInputElement>('#mname')!.value.trim() || t('Grönland-Lücke');
net.send({ t: 'create_match', name });
net.send({ t: 'create_match', name, private: el.querySelector<HTMLInputElement>('#mpriv')!.checked });
};
el.querySelector<HTMLButtonElement>('#quick')!.onclick = () => net.send({ t: 'quick' });
el.querySelectorAll<HTMLButtonElement>('[data-watch]').forEach((b) => (b.onclick = () => net.send({ t: 'spectate', matchId: b.dataset.watch! })));
el.querySelectorAll<HTMLButtonElement>('[data-join]').forEach((b) => {
b.onclick = () => net.send({ t: 'join', matchId: b.dataset.join!, team: b.dataset.team as 'west' | 'east' });
});
return;
return renderList();
}
el.dataset.view = 'match';
// Keep a half-typed chat line and the focus across re-renders
const draft = el.querySelector<HTMLInputElement>('#lc-text')?.value ?? '';
const typing = document.activeElement?.id === 'lc-text';
const mine = match.slots.find((s) => s.playerId === me.playerId);
const team = (t: 'west' | 'east') => match!.slots.filter((s) => s.team === t).map((s) => `
<div class="slot"><span>${s.rank ? `<span class="rank" title="${esc(s.rank)}">${esc(rankShort(s.rank))}</span> ` : ''}${esc(s.callsign)}${s.playerId === me.playerId ? ' <span class="dim">(DU)</span>' : ''}${s.bot ? ' <span class="dim">(KI)</span>' : ''}</span>
<div class="slot"><span>${s.rank ? `<span class="rank" title="${esc(s.rank)}">${esc(rankShort(s.rank))}</span> ` : ''}${esc(s.callsign)}${s.rating && s.rank && !s.bot ? ` <span class="dim" title="Wertung">${s.rating}</span>` : ''}${s.playerId === me.playerId ? ' <span class="dim">(DU)</span>' : ''}${s.bot ? ' <span class="dim">(KI)</span>' : ''}</span>
<span>${s.crewOf ? `<span class="dim">BESATZUNG BEI ${esc(match!.slots.find((c) => c.playerId === s.crewOf)?.callsign ?? '?')}</span>` : CLASS_NAME[s.cls].title}
${mine && s.team === mine.team && !s.bot && !s.crewOf && s.playerId !== me.playerId && mine.crewOf !== s.playerId ? `<button data-crew="${s.playerId}" title="Als Besatzung auf diesem Schiff mitfahren">Mitfahren</button>` : ''}
· ${s.ready ? '<span>BEREIT</span>' : '<span class="amber">WÄHLT</span>'}</span></div>`).join('') ||
'<div class="slot dim">Freier Platz</div>';
const classes = match.settings.mission === 'duell' || mine?.team !== 'west' ? (['ssk', 'ssn'] as const) : (['ffg'] as const);
const classes = match.settings.mission === 'duell' || mine?.team !== 'west' ? (['ssk', 'ssn', 'ssc'] as const) : (['ffg', 'kor'] as const);
el.innerHTML = `
<div class="hd" style="font-size:14px"><span>PARTIE „${esc(match.name)}“</span><span>${match.slots.length} SPIELER · KONVOI ${match.settings.merchants} FRACHTER</span></div>
<div class="invite"><span class="dim">${match.settings.private ? 'PRIVATE PARTIE · NUR PER LINK' : 'EINLADEN'}</span>
<input id="inv-link" readonly value="${esc(`${location.origin}/#join=${match.id}`)}"><button id="inv-copy">Link kopieren</button></div>
<div class="grid2" style="margin-bottom:8px">
<div class="panel"><div class="hd team-w"><span>Westbund · Geleitschutz</span><button data-switch="west">Wechseln</button></div>${team('west')}</div>
<div class="panel"><div class="hd team-e"><span>Ostpakt · Wolfsrudel</span><button data-switch="east">Wechseln</button></div>${team('east')}</div>
@@ -119,6 +137,16 @@ export function lobbyScreen(root: HTMLElement, me: { playerId: string; callsign:
</div>
<div class="err">${esc(error)}</div>`;
paintMissionCharts(el, match.settings.custom?.seabed);
el.querySelector<HTMLButtonElement>('#inv-copy')!.onclick = async (e) => {
const inp = el.querySelector<HTMLInputElement>('#inv-link')!;
try {
await navigator.clipboard.writeText(inp.value);
} catch {
inp.select();
document.execCommand('copy');
}
(e.target as HTMLButtonElement).textContent = 'Kopiert ✓';
};
const lcInput = el.querySelector<HTMLInputElement>('#lc-text')!;
lcInput.value = draft;
if (typing) lcInput.focus();
@@ -138,7 +166,7 @@ export function lobbyScreen(root: HTMLElement, me: { playerId: string; callsign:
};
});
el.querySelectorAll<HTMLButtonElement>('[data-cls]').forEach((b) => {
b.onclick = () => net.send({ t: 'pick_class', cls: b.dataset.cls as 'ffg' | 'ssn' | 'ssk' });
b.onclick = () => net.send({ t: 'pick_class', cls: b.dataset.cls as 'ffg' | 'kor' | 'ssn' | 'ssk' | 'ssc' });
});
el.querySelectorAll<HTMLButtonElement>('[data-switch]').forEach((b) => {
b.onclick = () => net.send({ t: 'join', matchId: match!.id, team: b.dataset.switch as 'west' | 'east' });
@@ -171,16 +199,42 @@ export function lobbyScreen(root: HTMLElement, me: { playerId: string; callsign:
el.querySelector<HTMLButtonElement>('#ready')!.onclick = () => net.send({ t: 'ready', ready: !mine?.ready });
el.querySelector<HTMLButtonElement>('#leave')!.onclick = () => {
match = undefined;
shownMatch = '';
net.send({ t: 'leave' });
};
}
// While a finger is down or a picker is open, hold re-renders so the tap or selection is not lost
let pressing = false;
let pending = false;
let shownMatch = '';
const flush = () => {
if (!pending || pressing || el.querySelector('select:focus')) return;
pending = false;
render();
};
el.addEventListener('pointerdown', () => (pressing = true));
const release = () => {
pressing = false;
setTimeout(flush, 50); // after the click handler has run
};
el.addEventListener('pointerup', release);
el.addEventListener('pointercancel', release);
el.addEventListener('focusout', () => setTimeout(flush, 50));
const off = net.on((m: ServerMsg) => {
if (m.t === 'lobby') matches = m.matches;
else if (m.t === 'match') match = m.match;
else if (m.t === 'error') error = m.msg;
else if (m.t === 'match') {
const key = JSON.stringify(m.match);
if (key === shownMatch && match) return;
shownMatch = key;
match = m.match;
} else if (m.t === 'error') error = m.msg;
else return;
if (m.t !== 'error') error = '';
if (match && (pressing || el.querySelector('select:focus'))) {
pending = true;
return;
}
render();
});
render();
+267
View File
@@ -0,0 +1,267 @@
import { angleDiff, lookoutRanges, type Sighting } from '@tk/shared';
import type { Periscope3D, PeriscopeTarget } from '../../widgets/periscope3d.js';
import { store } from '../../store.js';
import type { Station } from '../../screens/game.js';
import { isKey } from '../../widgets/keys.js';
import { easeAngle, moverNow, ownNow, simNow } from '../../widgets/smooth.js';
import { deg3, fitCanvas, h, km } from '../../widgets/format.js';
const H = 380;
const WIDE_FOV = 75;
const GLASS_FOV = 7;
/** Visual contacts stay in the picture this long after the last sighting (s). */
const SIGHT_HOLD = 8;
const WHAT: Record<Sighting, string> = { mast: 'SEHROHR', snorkel: 'SCHNORCHEL', surfaced: 'AUFGETAUCHT' };
/** Escorts' bridge: lookout view in 3D with 7× binoculars, own formation in sight, lookout reports. */
export function bridgeStation(): Station {
const el = h(`<div class="cols">
<div class="panel"><div class="hd"><span>Brücke · Ausguck</span><span id="b-brg" class="dim"></span></div>
<div style="position:relative"><canvas id="gl" style="position:absolute;inset:0;width:100%;height:${H}px"></canvas><canvas id="view" style="position:relative"></canvas></div>
<div style="display:flex;gap:6px;margin-top:6px;flex-wrap:wrap">
<button id="glass">Fernglas 7×</button>
<button id="left" title="Blick nach links">◀</button><button id="right" title="Blick nach rechts">▶</button>
<button id="ahead">Voraus</button><button id="report" class="warn">Auf Meldung</button><button id="tocontact">Auf Kontakt</button>
<span class="kbd" style="align-self:center">ZIEHEN DREHT · A / D</span>
</div>
</div>
<div class="panel"><div class="hd"><span>Ausguck</span><span class="dim">20 M AUGENHÖHE</span></div><div id="b-data"></div></div>
</div>`);
const view = el.querySelector<HTMLCanvasElement>('#view')!;
const glCanvas = el.querySelector<HTMLCanvasElement>('#gl')!;
let gl: Periscope3D | undefined;
let failed = false;
if (localStorage.getItem('tk_3d') !== '0') {
import('../../widgets/periscope3d.js')
.then((m) => {
if (m.Periscope3D.supported()) gl = new m.Periscope3D(glCanvas, { eye: 20, own: store.snap?.own.cls === 'kor' ? 'kor' : 'ffg' });
else failed = true;
})
.catch(() => (failed = true));
} else failed = true;
/** Look direction relative to the bow, so the view turns with the ship like a real bridge wing. */
let relTarget = 0;
let rel = 0;
let glass = false;
let last = performance.now();
const t0 = performance.now();
/** Smoothed screen positions per target (bearing, range), so 1 Hz updates glide. */
const shown = new Map<string, { b: number; r: number }>();
const fov = () => (glass ? GLASS_FOV : WIDE_FOV);
let maskCanvas: HTMLCanvasElement | undefined;
const mask = (w: number, hgt: number) => {
if (!maskCanvas) maskCanvas = document.createElement('canvas');
if (maskCanvas.width !== w || maskCanvas.height !== hgt) {
maskCanvas.width = w;
maskCanvas.height = hgt;
}
return maskCanvas;
};
const turn = (d: number) => (relTarget = ((relTarget + d + 540) % 360) - 180);
const lookAt = (bearing: number) => {
const s = store.snap;
if (s) relTarget = angleDiff(s.own.heading, bearing);
};
el.querySelector<HTMLButtonElement>('#glass')!.onclick = (e) => {
glass = !glass;
(e.target as HTMLButtonElement).classList.toggle('on', glass);
};
el.querySelector<HTMLButtonElement>('#left')!.onclick = () => turn(glass ? -3 : -20);
el.querySelector<HTMLButtonElement>('#right')!.onclick = () => turn(glass ? 3 : 20);
el.querySelector<HTMLButtonElement>('#ahead')!.onclick = () => (relTarget = 0);
el.querySelector<HTMLButtonElement>('#report')!.onclick = () => {
const a = [...(store.snap?.alerts ?? [])].reverse().find((x) => x.kind === 'sighting');
if (a?.bearing !== undefined) {
lookAt(a.bearing);
glass = true;
el.querySelector('#glass')!.classList.add('on');
}
};
el.querySelector<HTMLButtonElement>('#tocontact')!.onclick = () => {
const c = store.selectedContact();
if (c) lookAt(c.bearing);
};
let dragX: number | undefined;
view.style.cursor = 'ew-resize';
view.style.touchAction = 'none';
view.addEventListener('pointerdown', (e) => (dragX = e.clientX));
window.addEventListener('pointerup', () => (dragX = undefined));
view.addEventListener('pointermove', (e) => {
if (dragX === undefined) return;
const dx = e.clientX - dragX;
dragX = e.clientX;
turn((-dx / view.clientWidth) * fov());
rel = relTarget;
});
/** What the bridge can see: own formation within visual range, and lookout sightings. */
function targets(): PeriscopeTarget[] {
const s = store.snap;
if (!s) return [];
const env = { layerDepth: 0, layerLoss: 0, seaState: s.env.seaState, light: s.env.light, rain: s.env.rain };
const reach = Math.max(4_000, lookoutRanges(env).surfaced * 1.8);
const out: PeriscopeTarget[] = [];
// Own ship and formation extrapolated to this frame, so the picture glides between 1 Hz updates
const me = ownNow();
for (const f of s.friendlies) {
if (!f.alive || f.id === s.own.id) continue;
const fp = s.time - f.reportedAt < 3 ? moverNow(f, f.reportedAt) : f;
const dx = fp.x - me.x;
const dy = fp.y - me.y;
const r = Math.hypot(dx, dy);
if (r > reach || r < 50) continue;
out.push({ label: f.id, cls: f.cls, bearing: (Math.atan2(dx, dy) * 180) / Math.PI, range: r, course: f.heading, speedKn: f.speedKn, alpha: 1 });
}
const now = simNow();
for (const c of s.contacts) {
if (!c.sighting || c.sightedAt === undefined || c.range === undefined) continue;
const age = now - c.sightedAt;
if (age > SIGHT_HOLD) continue;
out.push({ label: c.label, cls: 'ssk', sighting: c.sighting, bearing: c.bearing, range: c.range, alpha: Math.min(1, (SIGHT_HOLD - age) / 2), speedKn: 6, course: c.bearing + 90 });
}
// Sightings only come once per sweep: glide toward the latest values
for (const tg of out) {
if (!tg.sighting) continue;
const p = shown.get(tg.label);
if (!p) shown.set(tg.label, { b: tg.bearing, r: tg.range });
else {
p.b = (p.b + angleDiff(p.b, tg.bearing) * 0.08 + 360) % 360;
p.r += (tg.range - p.r) * 0.08;
tg.bearing = p.b;
tg.range = p.r;
}
}
return out;
}
return {
title: 'Brücke',
el,
key(e) {
if (isKey(e, 'scopeLeft')) turn(glass ? -1 : -5);
else if (isKey(e, 'scopeRight')) turn(glass ? 1 : 5);
else return false;
return true;
},
snap() {
const s = store.snap!;
const env = { layerDepth: 0, layerLoss: 0, seaState: s.env.seaState, light: s.env.light, rain: s.env.rain };
const r = lookoutRanges(env);
const quality = r.mast > 1500 ? 'GUT' : r.mast > 600 ? 'MÄSSIG' : 'SCHLECHT';
const reports = s.alerts.filter((a) => a.kind === 'sighting').slice(-6).reverse();
el.querySelector('#b-data')!.innerHTML = `
<div class="row"><span class="dim">SICHT</span><span class="${quality === 'GUT' ? '' : 'amber'}">${quality}${s.env.rain ? ' · REGEN' : ''}${(s.env.light ?? 1) < 0.3 ? ' · NACHT' : ''}</span></div>
<div class="row"><span class="dim">SEHROHR (6 KN) BIS</span><span>${km(r.mast)}</span></div>
<div class="row"><span class="dim">SCHNORCHEL BIS</span><span>${km(r.snorkel)}</span></div>
<div class="row"><span class="dim">AUFGETAUCHT BIS</span><span>${km(r.surfaced)}</span></div>
<div class="dim" style="margin:8px 0 4px">MELDUNGEN</div>
${reports.length ? reports.map((a) => `<div class="row ${s.time - a.time < 60 ? 'amber' : 'dim'}"><span>${a.label ?? ''} ${WHAT[a.what ?? 'mast']}</span><span>${deg3(a.bearing ?? 0)}° · ${km(a.range ?? 0)}</span></div>`).join('') : '<div class="dim">NOCH KEINE SICHTUNG</div>'}
<div class="dim" style="margin-top:8px;line-height:1.5">Die Ausgucks melden Sehrohr-Fahnen, Schnorchel und Torpedolaufbahnen selbst. Nachts, bei Regen und hohem Seegang sehen sie kaum etwas.</div>`;
},
frame() {
const s = store.snap;
const ctx = fitCanvas(view, H);
const w = view.clientWidth;
const nowMs = performance.now();
rel = ((easeAngle(rel, relTarget, (nowMs - last) / 1000, 0.15) + 540) % 360) - 180;
last = nowMs;
const t = (nowMs - t0) / 1000;
const heading = s ? ownNow().heading : 0;
const look = (heading + rel + 360) % 360;
const f = fov();
el.querySelector('#b-brg')!.textContent = `BLICK ${deg3(look)}° · ${rel === 0 ? 'VORAUS' : `${Math.abs(Math.round(rel))}° ${rel > 0 ? 'STB' : 'BB'}`}`;
const live = !!gl && !!s;
glCanvas.style.visibility = live ? 'visible' : 'hidden';
const tg = live ? targets() : [];
if (live) {
gl!.render({
bearing: look, fovDeg: f, t, sea: s!.env.seaState, light: s!.env.light ?? 1, targets: tg,
rain: s!.env.rain, hour: s!.env.clock, pitchDeg: glass ? -0.15 : -8, ownHeading: heading, ownKn: s!.own.speedKn,
});
}
ctx.clearRect(0, 0, w, H);
if (!live) {
ctx.fillStyle = '#030504';
ctx.fillRect(0, 0, w, H);
ctx.fillStyle = '#6f8a78';
ctx.font = '12px ui-monospace, monospace';
ctx.textAlign = 'center';
ctx.fillText(failed ? 'KEINE 3D-GRAFIK (WEBGL2) · MELDUNGEN RECHTS' : 'LADE …', w / 2, H / 2);
return;
}
// Sighting markers in view
for (const c of tg) {
if (!c.sighting) continue;
const d = angleDiff(look, c.bearing);
if (Math.abs(d) > f / 2) continue;
const x = w / 2 + (Math.tan((d * Math.PI) / 180) / Math.tan((f * Math.PI) / 360)) * (w / 2);
// Vertical: the object sits just below the horizon by the dip from 20 m eye height
const pitch = ((glass ? -0.15 : -8) * Math.PI) / 180;
const tanV = Math.tan((f * Math.PI) / 360) / (w / H);
const y = H / 2 - (Math.tan(-Math.atan(20 / c.range) - pitch) / tanV) * (H / 2);
ctx.strokeStyle = `rgba(255,120,110,${c.alpha})`;
ctx.lineWidth = 1.5;
ctx.strokeRect(x - 10, y - 12, 20, 18);
ctx.fillStyle = `rgba(255,170,160,${c.alpha})`;
ctx.font = '11px ui-monospace, monospace';
ctx.textAlign = 'center';
ctx.fillText(`${c.label} · ${km(c.range)}`, x, y - 18);
}
if (glass) {
// Binocular mask: two overlapping circles
const r = Math.min(w * 0.3, H * 0.46);
// Mask on an offscreen layer: fill black, then cut out both lenses
const m = mask(w, H);
const mc = m.getContext('2d')!;
mc.globalCompositeOperation = 'source-over';
mc.fillStyle = '#020303';
mc.fillRect(0, 0, w, H);
mc.globalCompositeOperation = 'destination-out';
const lens = mc.createRadialGradient(0, 0, r * 0.82, 0, 0, r);
lens.addColorStop(0, 'rgba(0,0,0,1)');
lens.addColorStop(1, 'rgba(0,0,0,0)');
for (const dx of [-0.55, 0.55]) {
mc.save();
mc.translate(w / 2 + dx * r, H / 2);
mc.fillStyle = lens;
mc.beginPath(); mc.arc(0, 0, r, 0, Math.PI * 2); mc.fill();
mc.restore();
}
ctx.drawImage(m, 0, 0, w, H);
} else {
// Open bridge roof: no window frame, only spray on the lens of the eye in rain
if (s!.env.rain) {
ctx.fillStyle = 'rgba(200,215,220,0.18)';
for (let i = 0; i < 40; i++) {
const x = ((i * 97.3 + t * 3) % 1) * w;
const y = ((i * 41.7 + t * (20 + (i % 5) * 6)) % H);
ctx.fillRect(x, y, 1.5, 6);
}
}
}
// Bearing tape
ctx.fillStyle = 'rgba(3,8,8,0.6)';
ctx.fillRect(0, 0, w, 16);
ctx.strokeStyle = '#9fd8c4';
ctx.fillStyle = '#9fd8c4';
ctx.font = '10px ui-monospace, monospace';
ctx.textAlign = 'center';
const step = glass ? 1 : 5;
for (let a = Math.ceil((look - f / 2) / step) * step; a <= look + f / 2; a += step) {
const x = w / 2 + (angleDiff(look, a) / (f / 2)) * (w / 2);
const major = a % (glass ? 5 : 30) === 0;
ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, major ? 7 : 4); ctx.stroke();
if (major) ctx.fillText(String(((a % 360) + 360) % 360).padStart(3, '0'), x, 15);
}
// Bow marker on the tape
const bx = w / 2 + (angleDiff(look, heading) / (f / 2)) * (w / 2);
if (bx > 0 && bx < w) {
ctx.fillStyle = '#e8c37a';
ctx.beginPath(); ctx.moveTo(bx, 1); ctx.lineTo(bx - 5, 9); ctx.lineTo(bx + 5, 9); ctx.fill();
}
},
};
}
+109 -94
View File
@@ -1,138 +1,153 @@
import { NM, headingVec } from '@tk/shared';
import { NM, angleDiff, headingVec } from '@tk/shared';
import { net } from '../../net.js';
import { store } from '../../store.js';
import type { Station } from '../../screens/game.js';
import { COL, deg3, esc, fitCanvas, h } from '../../widgets/format.js';
import { deg3, esc, fitCanvas, h } from '../../widgets/format.js';
import { RadarScope, SCOPE } from '../../widgets/radar-scope.js';
import { onTap } from '../../widgets/touch.js';
const RANGE = 12 * NM;
const RPM = 24;
const RANGES = [3, 6, 12, 24] as const;
/** How far an enemy ESM receiver hears this radar (sensors.ts ESM_RANGE). */
const ESM_HEARS_NM = 40;
/** PPI with rotating sweep and phosphor persistence, painted from radar contacts only. */
/** Radar room: phosphor PPI with range scales, radar status and an ESM bearing rose. */
export function radarEsmStation(): Station {
const el = h(`<div class="cols">
<div class="panel"><div class="hd"><span>Luft-/Seeraumradar · 12 SM</span><span id="rs" class="dim"></span></div><canvas id="ppi"></canvas>
<div style="display:flex;gap:6px;margin-top:6px"><button id="radar">Radar</button><span class="dim" style="align-self:center">RADAR VERRÄT DIE FREGATTE AUF GROSSE ENTFERNUNG (ESM)</span></div>
<div class="panel"><div class="hd"><span>Luft-/Seeraumradar · <span id="rng">12</span> SM</span><span id="rs" class="dim"></span></div><canvas id="ppi"></canvas>
<div style="display:flex;gap:6px;margin-top:6px;flex-wrap:wrap;align-items:center">
<button id="radar">Radar</button>
${RANGES.map((r) => `<button data-rng="${r}" title="Bereich ${r} SM">${r} SM</button>`).join('')}
<span class="dim">KLICK AUF ECHO WÄHLT</span>
</div>
</div>
<div style="display:flex;flex-direction:column;gap:8px">
<div class="panel"><div class="hd"><span>Radarstatus</span><span id="emit" class="dim"></span></div><div id="status"></div></div>
<div class="panel"><div class="hd"><span>ESM · Funkpeilung</span><span class="dim">ROSE UND LISTE</span></div>
<canvas id="rose" style="display:block;margin:0 auto"></canvas><div id="esm"></div></div>
<div class="panel"><div class="hd"><span>Radarspuren</span></div><div id="tracks"></div></div>
<div class="panel"><div class="hd"><span>ESM / Funkpeilung</span></div><div id="esm"></div></div>
</div>
</div>`);
const canvas = el.querySelector<HTMLCanvasElement>('#ppi')!;
const phos = document.createElement('canvas');
phos.width = 520;
phos.height = 520;
const pc = phos.getContext('2d')!;
pc.fillStyle = COL.bg;
pc.fillRect(0, 0, 520, 520);
let sweep = 0;
const rose = el.querySelector<HTMLCanvasElement>('#rose')!;
const scope = new RadarScope();
let rangeNm: number = Number(localStorage.getItem('tk_radar_rng')) || 12;
let last = performance.now();
let geo = { ox: 0, oy: 0, k: 1 };
const setRange = (r: number) => {
rangeNm = r;
localStorage.setItem('tk_radar_rng', String(r));
el.querySelector('#rng')!.textContent = String(r);
el.querySelectorAll<HTMLButtonElement>('[data-rng]').forEach((b) => b.classList.toggle('on', Number(b.dataset.rng) === r));
};
setRange(rangeNm);
el.querySelectorAll<HTMLButtonElement>('[data-rng]').forEach((b) => (b.onclick = () => setRange(Number(b.dataset.rng))));
el.querySelector<HTMLButtonElement>('#radar')!.onclick = () => net.send({ t: 'toggle', what: 'radar', on: !store.snap?.own.radarOn });
canvas.style.cursor = 'pointer';
canvas.onmousedown = (e) => {
canvas.addEventListener('click', (e) => {
const s = store.snap;
if (!s) return;
const r = canvas.getBoundingClientRect();
const size = Math.min(r.width, 520);
const k = size / 520;
const mx = (e.clientX - r.left - (r.width - size) / 2) / k - 260;
const my = 260 - (e.clientY - r.top) / k;
const mx = (e.clientX - r.left - geo.ox) / geo.k - SCOPE.C;
const my = SCOPE.C - (e.clientY - r.top - geo.oy) / geo.k;
let best: string | undefined;
let bd = 12;
let bd = 14;
for (const c of s.contacts) {
if (!c.sensors.includes('radar') || c.range === undefined) continue;
const v = headingVec(c.bearing);
const rr = (c.range / RANGE) * 250;
const rr = (c.range / (rangeNm * NM)) * SCOPE.R;
const d = Math.hypot(v.x * rr - mx, v.y * rr - my);
if (d < bd) [best, bd] = [c.label, d];
}
if (best) store.selected = best;
};
el.querySelector<HTMLButtonElement>('#radar')!.onclick = () => net.send({ t: 'toggle', what: 'radar', on: !store.snap?.own.radarOn });
});
const tracksEl = el.querySelector<HTMLElement>('#tracks')!;
onTap(tracksEl, '[data-c]', (row) => (store.selected = row.dataset.c));
/** ESM rose: intercepted emitters as strobes around the own ship, newest brightest. */
function drawRose(): void {
const s = store.snap;
const size = 170;
const ctx = fitCanvas(rose, size);
const w = rose.clientWidth;
const cx = w / 2, cy = size / 2, r = size / 2 - 16;
ctx.fillStyle = '#030807';
ctx.fillRect(0, 0, w, size);
ctx.strokeStyle = 'rgba(93,202,165,0.3)';
for (const f of [0.5, 1]) { ctx.beginPath(); ctx.arc(cx, cy, r * f, 0, 7); ctx.stroke(); }
ctx.fillStyle = 'rgba(159,230,204,0.7)';
ctx.font = '10px ui-monospace, monospace';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
for (const [d, l] of [[0, 'N'], [90, 'O'], [180, 'S'], [270, 'W']] as const) {
const a = ((d - 90) * Math.PI) / 180;
ctx.fillText(l, cx + Math.cos(a) * (r + 9), cy + Math.sin(a) * (r + 9));
}
if (!s) return;
const hm = ((s.own.heading - 90) * Math.PI) / 180;
ctx.strokeStyle = 'rgba(232,195,122,0.7)';
ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(cx + Math.cos(hm) * r * 0.5, cy + Math.sin(hm) * r * 0.5); ctx.stroke();
const t = performance.now() / 1000;
for (const c of s.contacts) {
if (!c.sensors.includes('esm')) continue;
const age = s.time - c.lastSeen;
if (age > 600) continue;
const a = ((c.bearing - 90) * Math.PI) / 180;
const fresh = age < 20;
ctx.strokeStyle = `rgba(240,149,149,${fresh ? 0.6 + 0.4 * Math.sin(t * 6) : Math.max(0.15, 0.8 - age / 700)})`;
ctx.lineWidth = fresh ? 3 : 2;
ctx.beginPath(); ctx.moveTo(cx + Math.cos(a) * r * 0.15, cy + Math.sin(a) * r * 0.15); ctx.lineTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r); ctx.stroke();
ctx.lineWidth = 1;
ctx.fillStyle = '#f09595';
ctx.fillText(c.label, cx + Math.cos(a) * (r - 12) + 10, cy + Math.sin(a) * (r - 12));
}
}
return {
title: 'Radar/ESM',
el,
snap() {
const s = store.snap!;
el.querySelector('#radar')!.classList.toggle('on', s.own.radarOn);
el.querySelector('#rs')!.textContent = s.own.radarOn ? `SENDET · ${RPM} U/MIN` : 'AUS';
const on = s.own.radarOn;
el.querySelector('#radar')!.classList.toggle('on', on);
el.querySelector('#rs')!.textContent = on ? `SENDET · ${RPM} U/MIN` : 'STANDBY';
const emit = el.querySelector<HTMLElement>('#emit')!;
emit.textContent = on ? '● ABSTRAHLUNG' : '○ STILL';
emit.className = on ? 'red blink' : 'dim';
const radar = s.contacts.filter((c) => c.via === 'own' && c.sensors.includes('radar') && s.time - c.lastSeen < 30);
el.querySelector('#tracks')!.innerHTML = radar.length
? radar.map((c) => `<div class="row ${s.time - c.lastSeen > 5 ? 'amber' : ''}"><span>${esc(c.label)}</span><span>${deg3(c.bearing)}° ${c.range ? (c.range / NM).toFixed(1) + ' SM' : ''}</span><span class="dim">${s.time - c.lastSeen > 5 ? 'KURZ ERFASST' : 'SPUR'}</span></div>`).join('')
: '<div class="dim">KEINE SPUREN</div>';
const esm = s.contacts.filter((c) => c.sensors.includes('esm'));
const friends = radar.filter((c) => s.friendlies.some((f) => {
const v = headingVec(c.bearing);
return Math.hypot(f.x - (s.own.x + v.x * (c.range ?? 0)), f.y - (s.own.y + v.y * (c.range ?? 0))) < 600;
}));
el.querySelector('#status')!.innerHTML = `
<div class="row"><span class="dim">SENDER</span><span class="${on ? 'red' : ''}">${on ? 'EIN · SENDET' : 'AUS · STANDBY'}</span></div>
<div class="row"><span class="dim">BEREICH / ANTENNE</span><span>${rangeNm} SM · ${RPM} U/MIN</span></div>
<div class="row"><span class="dim">ECHOS</span><span>${radar.length} · DAVON EIGENE ${friends.length}</span></div>
<div class="row"><span class="dim">SEEGANG-STÖRUNG</span><span>${['GERING', 'GERING', 'MÄSSIG', 'MÄSSIG', 'STARK', 'STARK', 'SEHR STARK'][s.env.seaState] ?? '—'}${s.env.rain ? ' · REGEN' : ''}</span></div>
<div class="row"><span class="dim">GEGNER-ESM HÖRT UNS</span><span class="${on ? 'amber' : 'dim'}">${on ? `BIS ${ESM_HEARS_NM} SM` : '—'}</span></div>
<div class="dim" style="margin-top:6px;line-height:1.5">${on ? 'Jede U-Boot-Funkpeilantenne in 40 SM peilt uns jetzt. Schnorchel und Sehrohre zeigt das Radar nur auf kurze Distanz.' : 'Ohne Radar bleibt die Fregatte still. Kurz einschalten, Lage aufnehmen, wieder aus.'}</div>`;
tracksEl.innerHTML = radar.length
? radar.map((c) => {
const fr = friends.includes(c);
const rel = angleDiff(s.own.heading, c.bearing);
return `<div class="row clickable ${c.label === store.selected ? 'amber selrow' : fr ? 'dim' : ''}" data-c="${esc(c.label)}"><span>${esc(c.label)}${fr ? ' · EIGEN' : ''}</span><span>${deg3(c.bearing)}° ${c.range ? (c.range / NM).toFixed(1) + ' SM' : ''}</span><span class="dim">${rel >= 0 ? 'STB' : 'BB'} ${Math.abs(Math.round(rel))}° · ${s.time - c.lastSeen > 5 ? 'KURZ' : 'SPUR'}</span></div>`;
}).join('')
: `<div class="dim">${on ? 'KEINE SPUREN' : 'RADAR AUS · KEINE SPUREN'}</div>`;
const esm = s.contacts.filter((c) => c.sensors.includes('esm')).sort((a, b) => b.lastSeen - a.lastSeen);
el.querySelector('#esm')!.innerHTML = esm.length
? esm.map((c) => `<div class="row red"><span>${esc(c.label)}</span><span>${deg3(c.bearing)}°</span><span class="dim">VOR ${Math.round(s.time - c.lastSeen)} S</span></div>`).join('')
: '<div class="dim">KEINE FUNKPEILUNGEN</div>';
? esm.map((c) => `<div class="row ${s.time - c.lastSeen < 60 ? 'red' : 'dim'}"><span>${esc(c.label)}</span><span>${deg3(c.bearing)}°</span><span class="dim">VOR ${Math.round(s.time - c.lastSeen)} S</span></div>`).join('')
: '<div class="dim">KEINE FUNKPEILUNGEN · ALLES STILL</div>';
},
frame() {
const s = store.snap;
const now = performance.now();
const dt = (now - last) / 1000;
const dt = Math.min(0.1, (now - last) / 1000);
last = now;
const prev = sweep;
sweep = (sweep + dt * RPM * 6) % 360;
const C = 260;
const R = 250;
pc.save();
pc.beginPath(); pc.arc(C, C, R, 0, 7); pc.clip();
pc.fillStyle = 'rgba(8,12,11,0.03)';
pc.fillRect(0, 0, 520, 520);
if (s?.own.radarOn) {
const span = (sweep - prev + 360) % 360;
for (let i = 0; i < 40; i++) {
if (Math.random() > 0.5) continue;
const a = (prev + (span * i) / 40 - 90) * (Math.PI / 180);
const rr = Math.random() * (10 + s.env.seaState * 6);
pc.fillStyle = `rgba(93,202,165,${0.25 + Math.random() * 0.4})`;
pc.fillRect(C + Math.cos(a) * rr, C + Math.sin(a) * rr, 1.5, 1.5);
}
for (const c of s.contacts) {
if (!c.sensors.includes('radar') || c.range === undefined || s.time - c.lastSeen > 3) continue;
const d = (c.bearing - prev + 360) % 360;
if (d > span) continue;
const v = headingVec(c.bearing);
const r = (c.range / RANGE) * R;
if (r > R) continue;
const friendly = s.friendlies.some((f) => Math.hypot(f.x - (s.own.x + v.x * c.range!), f.y - (s.own.y + v.y * c.range!)) < 400);
pc.fillStyle = friendly ? COL.g2 : COL.amber;
pc.beginPath(); pc.arc(C + v.x * r, C - v.y * r, friendly ? 2.6 : 3, 0, 7); pc.fill();
}
const a = (sweep - 90) * (Math.PI / 180);
pc.strokeStyle = 'rgba(159,225,203,0.9)';
pc.lineWidth = 1.5;
pc.beginPath(); pc.moveTo(C, C); pc.lineTo(C + Math.cos(a) * R, C + Math.sin(a) * R); pc.stroke();
}
pc.restore();
const H = 520;
scope.update(s, dt, RPM, rangeNm * NM);
const H = 540;
const ctx = fitCanvas(canvas, H);
const w = canvas.clientWidth;
ctx.fillStyle = COL.bg;
ctx.fillRect(0, 0, w, H);
const size = Math.min(w, H);
const ox = (w - size) / 2;
ctx.drawImage(phos, ox, 0, size, size);
const k = size / 520;
ctx.strokeStyle = 'rgba(93,202,165,0.15)';
for (let i = 1; i <= 4; i++) {
ctx.beginPath(); ctx.arc(ox + C * k, C * k, (R * k * i) / 4, 0, 7); ctx.stroke();
}
if (s) {
for (const c of s.contacts.filter((x) => x.sensors.includes('esm') && s.time - x.lastSeen < 300)) {
const v = headingVec(c.bearing);
ctx.strokeStyle = 'rgba(240,149,149,0.7)';
ctx.setLineDash([6, 4]);
ctx.beginPath(); ctx.moveTo(ox + C * k, C * k); ctx.lineTo(ox + (C + v.x * R) * k, (C - v.y * R) * k); ctx.stroke();
ctx.setLineDash([]);
}
}
ctx.font = '11px ui-monospace, monospace';
ctx.fillStyle = COL.g;
ctx.textAlign = 'center';
ctx.fillText('000', ox + C * k, 10);
ctx.fillText('180', ox + C * k, H - 2);
ctx.fillText('3 SM', ox + C * k + (R * k) / 4 + 14, C * k - 4);
geo = scope.draw(ctx, canvas.clientWidth, H, s, rangeNm, store.selected);
drawRose();
},
};
}
+4 -4
View File
@@ -1,3 +1,4 @@
import { onTap } from '../../widgets/touch.js';
import {
CHOICE_MAX_KN,
CLASSES,
@@ -174,10 +175,9 @@ export function fireControlStation(): Station {
});
};
el.querySelectorAll('input').forEach((i) => i.addEventListener('keydown', (e) => e.stopPropagation()));
q('#wires').addEventListener('mousedown', (e) => {
const b = (e.target as HTMLElement).closest<HTMLElement>('[data-steer]');
const t = b && store.snap?.torpedoes.find((x) => x.id === b.dataset.steer);
if (b && t) net.send({ t: 'steer', torpId: t.id, heading: (t.heading + Number(b.dataset.d) + 360) % 360 });
onTap(q('#wires'), '[data-steer]', (b) => {
const t = store.snap?.torpedoes.find((x) => x.id === b.dataset.steer);
if (t) net.send({ t: 'steer', torpId: t.id, heading: (t.heading + Number(b.dataset.d) + 360) % 360 });
});
return {
+1 -1
View File
@@ -7,7 +7,7 @@ import type { Station } from '../../screens/game.js';
import { isKey } from '../../widgets/keys.js';
import { CLASS_LABEL, COL, deg1, deg3, fitCanvas, h, km } from '../../widgets/format.js';
const MAST_HEIGHT: Record<ClassId, number> = { merchant: 28, ffg: 32, ssn: 8, ssk: 7 };
const MAST_HEIGHT: Record<ClassId, number> = { merchant: 28, ffg: 32, kor: 24, ssn: 8, ssk: 7, ssc: 5 };
interface Wave {
x: number;
+43 -6
View File
@@ -160,7 +160,7 @@ button.link { background: none; border: none; color: var(--dim, #6f8a78); text-t
.topbar .status { flex: 1; display: flex; align-items: center; gap: 14px; min-width: 0; justify-content: flex-end; white-space: nowrap; overflow: hidden; }
.st-ship { color: var(--g2); overflow: hidden; text-overflow: ellipsis; }
.st-prog { display: flex; align-items: center; gap: 6px; }
.pbar { position: relative; width: 110px; height: 8px; background: #0b1311; border: 1px solid var(--line2); overflow: hidden; }
.pbar { position: relative; width: 130px; height: 9px; background: #0b1311; border: 1px solid var(--line2); overflow: visible; }
.pbar i { position: absolute; top: 0; bottom: 0; display: block; }
.pbar #pb-sunk { left: 0; background: var(--red); }
.pbar #pb-arr { right: 0; background: var(--blue); }
@@ -194,7 +194,12 @@ body.cb .team-e { color: #ff9b45; }
body.helm-open .side .helm { transform: translateY(0); }
.langbtn { bottom: 60px; }
}
@media (max-width: 1350px) { #pb-txt { display: none; } }
@media (max-width: 1700px) { #pb-txt .dim { display: none; } }
@media (max-width: 1100px) { #pb-txt { display: none; } }
.pb-lbl { font-size: 10px; letter-spacing: 0.1em; }
.pbar .pb-mid, .pbar .pb-30 { position: absolute; top: -2px; bottom: -2px; width: 1px; background: #e8c37a; }
.pbar .pb-mid { left: 50%; width: 2px; margin-left: -1px; }
.pbar .pb-30 { left: 30%; background: rgba(232, 195, 122, 0.5); }
/* ---------- Console hardware look ---------- */
body { background:
@@ -242,14 +247,14 @@ body.hit::after { content: ''; position: fixed; inset: 0; z-index: 90; pointer-e
@media (prefers-reduced-motion: reduce) { .station > *, body.crt .panel canvas, body.hit .game { animation: none !important; } }
/* Lobby: mission cards, ranks, chat */
.mcards { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; margin-bottom: 8px; }
.mcard { text-align: left; text-transform: none; padding: 5px; display: flex; flex-direction: column; gap: 2px; }
.mcard canvas { width: 100%; height: 64px; object-fit: cover; border-radius: 3px; box-shadow: none !important; image-rendering: auto; }
.mcards { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; margin-bottom: 8px; }
.mcard { min-width: 0; overflow: hidden; overflow-wrap: break-word; hyphens: auto; text-align: left; text-transform: none; padding: 5px; display: flex; flex-direction: column; gap: 2px; }
.mcard canvas { display: block; max-width: 100%; width: 100%; height: auto; aspect-ratio: 16 / 9; border-radius: 3px; box-shadow: none !important; image-rendering: auto; }
.mcard.on { box-shadow: 0 0 0 1px var(--g), 0 0 10px rgba(93,202,165,0.25); }
.mcard-t { color: var(--g2); }
.rank { font-size: 10px; color: var(--amber); border: 1px solid #5a4a26; border-radius: 2px; padding: 0 3px; }
.lchat { max-height: 120px; overflow: auto; line-height: 1.5; }
@media (max-width: 600px) { .mcards { grid-template-columns: repeat(2, 1fr); } }
@media (max-width: 600px) { .mcards { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.tl { position: relative; height: 14px; margin: 2px 0 4px; border-bottom: 1px solid var(--line2); }
.tl i { position: absolute; bottom: 0; width: 3px; margin-left: -1px; cursor: pointer; opacity: 0.85; }
.tl i:hover { opacity: 1; width: 5px; margin-left: -2px; }
@@ -262,3 +267,35 @@ body.hit::after { content: ''; position: fixed; inset: 0; z-index: 90; pointer-e
@media (max-width: 600px) { .topbar .status { white-space: normal; } .pbar { width: 64px; } .st-clock { text-align: right; } }
@media (max-width: 600px) { body .side .helm.panel { position: fixed !important; } }
@media (max-width: 600px) { body .side .helm.panel { padding-bottom: 52px; } }
.invite { display: flex; align-items: center; gap: 6px; margin: 4px 0 8px; }
.invite input { flex: 1; min-width: 0; color: var(--dim); }
/* Lobby: new-match row wraps instead of overflowing; taps without delay or double-tap zoom */
.newmatch { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; align-items: stretch; }
.newmatch input#mname { flex: 1 1 160px; min-width: 0; }
.newmatch label { display: flex; align-items: center; gap: 4px; }
@media (max-width: 600px) { .newmatch button { flex: 1 1 40%; } .slot { flex-wrap: wrap; gap: 6px; } }
button, a, label, select, input { touch-action: manipulation; -webkit-tap-highlight-color: rgba(93, 202, 165, 0.25); }
/* Phone: language switch sits at the top of the page instead of floating over content; in game it lives in the menu */
@media (max-width: 600px) {
.langbtn { position: absolute; top: 10px; right: 10px; left: auto; bottom: auto; }
body:has(.game) .langbtn { display: none; }
.panel > .hd { flex-wrap: wrap; gap: 2px 10px; }
}
/* Sortable headers and filter chips */
.sorth { cursor: pointer; user-select: none; }
.sorth:hover, .sorth.on { color: var(--g2); }
.chips { display: flex; flex-wrap: wrap; gap: 4px; align-items: center; margin: 2px 0 6px; }
.chip { font-size: 10px; padding: 2px 7px; min-height: 0 !important; border-radius: 10px; letter-spacing: 0.08em; }
.chipcount { margin-left: auto; font-size: 10px; }
.ltable { display: grid; grid-template-columns: 28px 1.4fr 0.8fr 0.9fr 0.8fr 0.7fr 0.8fr; gap: 6px; }
.ltable span:not(:nth-child(2)) { text-align: right; }
.topbar .status .st-ship { flex-shrink: 0; }
.st-prog { min-width: 0; }
#pb-txt { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* Lookout hit inset */
.hitcam { position: fixed; right: 310px; top: 64px; z-index: 75; width: min(420px, 92vw); background: #050b0a; border: 1px solid var(--red);
box-shadow: 0 0 18px rgba(240,149,149,0.35); padding: 6px; border-radius: 4px; }
.hitcam .hd { color: var(--red); font-size: 11px; letter-spacing: 0.1em; align-items: center; }
.hitcam .hd button { padding: 0 8px; min-height: 0 !important; }
.hitcam canvas { display: block; width: 100%; height: 220px; border-radius: 2px; }
@media (max-width: 900px) { .hitcam { right: 8px; left: 8px; width: auto; top: 56px; } }
+25 -3
View File
@@ -1,4 +1,4 @@
import { CLASSES, type Snapshot } from '@tk/shared';
import { CLASSES, angleDiff, type AlertView, type Snapshot } from '@tk/shared';
import { audio } from '../audio.js';
import { lang } from '../i18n/index.js';
import { store } from '../store.js';
@@ -34,7 +34,7 @@ export function voiceOn(): boolean {
let voice: SpeechSynthesisVoice | undefined;
function pickVoice(): void {
const all = typeof speechSynthesis !== 'undefined' ? speechSynthesis.getVoices() : [];
voice = all.find((v) => v.lang.startsWith(en ? 'en' : 'de') && /male|Markus|Yannick|Daniel|Alex/i.test(v.name)) ??
voice = all.find((v) => v.lang.startsWith(en ? 'en' : 'de') && /\bmale\b|Markus|Yannick|Flo|Eddy|Reed|Rocko|Daniel|Alex|Arthur|Oliver/i.test(v.name)) ??
all.find((v) => v.lang.startsWith(en ? 'en' : 'de'));
}
if (typeof speechSynthesis !== 'undefined') {
@@ -55,7 +55,7 @@ function say(text: string, urgent: boolean): void {
speechSynthesis.speak(u);
}
const LEVEL: Record<string, LogEntry['level']> = { torpedo: 'alarm', sunk: 'alarm', ping: 'warn', esm: 'warn', transient: 'warn', hit: 'info' };
const LEVEL: Record<string, LogEntry['level']> = { sighting: 'warn', torpedo: 'alarm', sunk: 'alarm', ping: 'warn', esm: 'warn', transient: 'warn', hit: 'info' };
export class Callouts {
reset(): void {
@@ -96,6 +96,11 @@ export class Callouts {
// New contacts (own sensors only; datalink tracks are not "our" reports)
for (const c of s.contacts) {
if (this.known.has(c.label) || c.via !== 'own') continue;
// Lookout sightings are announced by their own report below
if (c.sensors.includes('visual')) {
this.known.add(c.label);
continue;
}
this.known.add(c.label);
this.report(s, { level: 'info', text: L(`Neuer Kontakt ${c.label}, Peilung ${deg3(c.bearing)}`, `New contact ${c.label}, bearing ${deg3(c.bearing)}`), label: c.label, station: sonar },
en ? `New contact ${c.label}, bearing ${digits(c.bearing)}` : `Neuer Kontakt ${c.label}, Peilung ${digits(c.bearing)}`);
@@ -106,6 +111,8 @@ export class Callouts {
if (a.kind === 'torpedo') {
const text = store.realism === 'profi' ? `HOCHFREQUENTES SCHRAUBENGERÄUSCH, SCHNELL WANDERND · PEILUNG ${deg3(a.bearing ?? 0)}` : a.text;
this.report(s, { level: 'alarm', text, station: sub ? 3 : 2 }, en ? `Torpedo in the water! Bearing ${b}!` : `Torpedo im Wasser! Peilung ${b}!`);
} else if (a.kind === 'sighting') {
this.report(s, { level: 'warn', text: a.text, label: a.label, station: sub ? undefined : 4 }, sightingCall(a, s.own.heading));
} else if (a.kind === 'ping') {
this.report(s, { level: 'warn', text: a.text }, en ? `Active sonar, bearing ${b}. We are being pinged.` : `Aktivsonar, Peilung ${b}. Wir werden angepingt.`);
} else if (a.kind === 'transient') {
@@ -169,3 +176,18 @@ export class Callouts {
export const callouts = new Callouts();
export const selectFromLog = (label: string) => (store.selected = label);
const WHAT = { mast: ['Sehrohr', 'Periscope'], snorkel: ['Schnorchel', 'Snorkel'], surfaced: ['U-Boot aufgetaucht', 'Submarine on the surface'] } as const;
/** Lookout report as sailors call it: what, side and sector relative to the bow, bearing, rough range. */
function sightingCall(a: AlertView, heading: number): string {
const rel = angleDiff(heading, a.bearing ?? heading);
const side = rel >= 0 ? (en ? 'starboard' : 'Steuerbord') : (en ? 'port' : 'Backbord');
const abs = Math.abs(rel);
const sector = abs < 30 ? (en ? 'bow' : 'voraus') : abs < 150 ? (en ? 'beam' : 'querab') : (en ? 'quarter' : 'achteraus');
const what = WHAT[a.what ?? 'mast'][en ? 1 : 0];
const m = Math.max(100, Math.round((a.range ?? 0) / 100) * 100);
const b = digits(a.bearing ?? 0);
if (abs < 8) return en ? `${what} dead ahead! Bearing ${b}, about ${m} meters!` : `${what} recht voraus! Peilung ${b}, etwa ${m} Meter!`;
return en ? `${what}, ${side} ${sector}! Bearing ${b}, about ${m} meters!` : `${what} ${side} ${sector}! Peilung ${b}, etwa ${m} Meter!`;
}
+61 -14
View File
@@ -1,22 +1,71 @@
import { onTap } from './touch.js';
import { CHOICE_LABEL, CLASS_LABEL, deg1, esc, km } from './format.js';
import { isFriendlyContact } from './friendly.js';
import { fixRange } from './contact-pos.js';
import { store } from '../store.js';
import { steadyBearing } from './smooth.js';
import { CLASSES, type SensorKind } from '@tk/shared';
import { bindSortable, filterChips, getFilters, sortHead, sortRows, type SortState } from './sortable.js';
const SENSOR_LABEL: Record<string, string> = {
hull: 'RUMPF', towed: 'SCHLEPP', active: 'AKTIV', intercept: 'PING', periscope: 'OPTIK', radar: 'RADAR', esm: 'ESM', buoy: 'BOJE',
hull: 'RUMPF', towed: 'SCHLEPP', active: 'AKTIV', intercept: 'PING', periscope: 'OPTIK', radar: 'RADAR', esm: 'ESM', buoy: 'BOJE', visual: 'AUSGUCK',
};
/** Clickable contact table; selection is shared across stations. Friendly contacts sink to the bottom. */
const ID = 'contacts';
const DEF: SortState = { key: 'label', dir: 1 };
const GROUPS: Record<string, SensorKind[]> = {
sonar: ['hull', 'towed', 'active', 'intercept', 'buoy'], radar: ['radar'], esm: ['esm'], visual: ['visual', 'periscope'],
};
const filters = new WeakMap<HTMLElement, (via: string) => boolean>();
/** Bearing as shown (towed-array side applied). */
function shownBearing(c: { label: string; bearing: number; bearingAlt?: number; lastSeen: number }): number {
const side = store.tasSide.get(c.label);
// Smoothed, so sorting by bearing doesn't reshuffle rows on every noisy update
return c.bearingAlt !== undefined && side === 'port' ? steadyBearing(c.label, c.bearingAlt, c.lastSeen) : steadyBearing(c.label, c.bearing, c.lastSeen);
}
/**
* Clickable contact table; selection is shared across stations. Columns sort on click,
* chips filter by freshness, own forces and sensor. Friendly contacts sink to the bottom.
*/
export function renderContactList(el: HTMLElement, filter: (via: string) => boolean = () => true): void {
const s = store.snap;
if (!s) return;
const rows = s.contacts
.filter((c) => filter(c.via))
filters.set(el, filter);
bindSortable(el, ID, DEF, () => renderContactList(el, filters.get(el)));
const f = getFilters(ID);
const groups = Object.keys(GROUPS).filter((g) => f.has(`g:${g}`));
const all = s.contacts.filter((c) => filter(c.via));
const whatOf = (c: (typeof all)[number], own: boolean) => {
const age = s.time - c.lastSeen;
const name = c.assigned ? CHOICE_LABEL[c.assigned] : c.classified ? CLASS_LABEL[c.classified] : '';
return own ? `EIGEN${name ? ' · ' + name : ''}` : name || (age > 30 ? `ALT ${Math.round(age)} S` : `? ${c.se.toFixed(0)} DB`);
};
const shown = all
.map((c) => ({ c, own: isFriendlyContact(c, s) }))
.sort((a, b) => Number(a.own) - Number(b.own) || a.c.label.localeCompare(b.c.label, 'de', { numeric: true }));
const head = `<div class="row dim ctable"><span>KONTAKT</span><span>PEILUNG</span><span>ENTF.</span><span>SENSOR</span><span>KLASSE</span></div>`;
el.innerHTML = rows.length
.filter(({ c, own }) => (!f.has('fresh') || s.time - c.lastSeen <= 30) && (!f.has('hostile') || !own)
&& (!groups.length || groups.some((g) => c.sensors.some((x) => GROUPS[g]!.includes(x)))));
const rows = sortRows(shown, ID, DEF, {
label: (r) => r.c.label,
brg: (r) => shownBearing(r.c),
range: (r) => fixRange(r.c, s),
sensor: (r) => r.c.sensors.map((x) => SENSOR_LABEL[x]).join('/'),
cls: (r) => whatOf(r.c, r.own),
age: (r) => s.time - r.c.lastSeen,
}).sort((a, b) => Number(a.own) - Number(b.own));
const sub = CLASSES[s.own.cls].submarine;
const chips = filterChips(ID, [
{ key: 'fresh', label: 'AKTUELL', title: 'Nur Kontakte der letzten 30 s' },
{ key: 'hostile', label: 'OHNE EIGENE', title: 'Eigene und verbündete Einheiten ausblenden' },
{ key: 'g:sonar', label: 'SONAR' },
...(sub ? [] : [{ key: 'g:radar', label: 'RADAR' }]),
{ key: 'g:esm', label: 'ESM' },
{ key: 'g:visual', label: sub ? 'OPTIK' : 'SICHT' },
]).replace('</div>', `<span class="dim chipcount">${rows.length}/${all.length}</span></div>`);
const head = `<div class="row dim ctable">${sortHead(ID, 'label', 'KONTAKT', DEF)}${sortHead(ID, 'brg', 'PEILUNG', DEF)}${sortHead(ID, 'range', 'ENTF.', DEF)}${sortHead(ID, 'sensor', 'SENSOR', DEF)}${sortHead(ID, 'cls', 'KLASSE', DEF)}</div>`;
el.innerHTML = chips + (rows.length
? head + rows.map(({ c, own }) => {
const age = s.time - c.lastSeen;
const sol = store.solutions.get(c.label);
@@ -28,24 +77,22 @@ export function renderContactList(el: HTMLElement, filter: (via: string) => bool
}
const side = store.tasSide.get(c.label);
const tasNote = c.tas?.ghost ? '<span class="red"> GEIST?</span>' : c.bearingAlt !== undefined ? (side ? ` (${side === 'stb' ? 'STB' : 'BB'})` : ' <span class="amber">S/B?</span>') : '';
const name = c.assigned ? CHOICE_LABEL[c.assigned] : c.classified ? CLASS_LABEL[c.classified] : '';
const what = own ? `EIGEN${name ? ' · ' + name : ''}` : name || (age > 30 ? `ALT ${Math.round(age)} S` : `? ${c.se.toFixed(0)} DB`);
const what = whatOf(c, own);
const color = c.assigned === 'torpedo' ? 'red' : '';
return `<div class="row ctable clickable ${cls}" data-c="${esc(c.label)}" title="Klicken zum Auswählen">
<span>${esc(c.label)}</span>
<span>${c.bearingAlt !== undefined && side ? deg1(side === 'stb' ? c.bearing : c.bearingAlt) + '°' : `${deg1(c.bearing)}°${c.bearingAlt !== undefined ? `/${deg1(c.bearingAlt)}°` : ''}`}${tasNote}${c.originX !== undefined ? ' <span class="blue">(BOJE)</span>' : ''}</span>
<span>${c.bearingAlt !== undefined && side ? deg1(steadyBearing(c.label, side === 'stb' ? c.bearing : c.bearingAlt, c.lastSeen)) + '°' : `${deg1(steadyBearing(c.label, c.bearing, c.lastSeen))}°${c.bearingAlt !== undefined ? `/${deg1(steadyBearing(c.label + '/alt', c.bearingAlt, c.lastSeen))}°` : ''}`}${tasNote}${c.originX !== undefined ? ' <span class="blue">(BOJE)</span>' : ''}</span>
<span>${range}</span>
<span>${c.sensors.map((x) => SENSOR_LABEL[x]).join('/')}</span>
<span class="${color}">${what}</span>
</div>`;
}).join('')
: '<div class="dim">KEINE KONTAKTE</div>';
: `<div class="dim">${all.length ? 'KEINE KONTAKTE FÜR DIESEN FILTER' : 'KEINE KONTAKTE'}</div>`);
if (!el.dataset.bound) {
// Delegated mousedown: rows are rebuilt on every snapshot, so per-row handlers would lose clicks
el.dataset.bound = '1';
el.addEventListener('mousedown', (e) => {
const row = (e.target as HTMLElement).closest<HTMLElement>('[data-c]');
if (row) store.selected = row.dataset.c;
onTap(el, '[data-c]', (row) => {
store.selected = row.dataset.c;
});
}
}
+3 -3
View File
@@ -1,3 +1,4 @@
import { onTap } from './touch.js';
import { CLASSES, SYSTEMS, type ShipSystem } from '@tk/shared';
import { net } from '../net.js';
import { store } from '../store.js';
@@ -27,9 +28,8 @@ export function renderDamage(el: HTMLElement): void {
: '<div class="dim">KEINE SCHÄDEN</div>');
if (!el.dataset.bound) {
el.dataset.bound = '1';
el.addEventListener('mousedown', (e) => {
const row = (e.target as HTMLElement).closest<HTMLElement>('[data-sys]');
if (row) net.send({ t: 'repair', system: row.dataset.sys as ShipSystem });
onTap(el, '[data-sys]', (row) => {
net.send({ t: 'repair', system: row.dataset.sys as ShipSystem });
});
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ export function timelineMarkers(d: Debrief): string {
/** Concrete lessons for the player from their own numbers. */
export function debriefTips(st: PlayerStats | undefined): string {
if (!st) return '';
const sub = st.cls === 'ssk' || st.cls === 'ssn';
const sub = st.cls === 'ssk' || st.cls === 'ssn' || st.cls === 'ssc';
const tips: { good: boolean; text: string }[] = [];
if (st.kills > 0) tips.push({ good: true, text: L(`${st.kills} Schiff(e) versenkt, ${Math.round(st.tonnageSunk / 1000)}k BRT.`, `${st.kills} ship(s) sunk, ${Math.round(st.tonnageSunk / 1000)}k GRT.`) });
if (st.firstContactS === undefined) tips.push({ good: false, text: L('Kein eigener Kontakt: langsamer fahren (das Eigengeräusch überdeckt alles) und das Schleppsonar nutzen.', 'No contact of your own: go slower (self noise masks everything) and use the towed array.') });
+3 -1
View File
@@ -13,7 +13,7 @@ export function clock(t: number): string {
}
export const CLASS_LABEL: Record<ClassId, string> = {
ssn: 'ATOM-U-BOOT', ssk: 'DIESEL-U-BOOT', ffg: 'FREGATTE', merchant: 'HANDELSSCHIFF',
ssn: 'ATOM-U-BOOT', ssk: 'DIESEL-U-BOOT', ssc: 'KÜSTEN-U-BOOT', ffg: 'FREGATTE', kor: 'KORVETTE', merchant: 'HANDELSSCHIFF',
};
export const CHOICE_LABEL: Record<ClassChoice, string> = {
@@ -24,6 +24,8 @@ export const CLASS_NAME: Record<Exclude<ClassId, 'merchant'>, { title: string; i
ffg: { title: 'Fregatte F-12', info: 'Rumpf- und Schleppsonar, Radar, U-Jagd-Raketen' },
ssn: { title: 'Atom-U-Boot Projekt 9', info: 'Schnell, unbegrenzte Ausdauer, laut bei hoher Fahrt' },
ssk: { title: 'Diesel-U-Boot Projekt 4', info: 'Sehr leise, begrenzte Batterie, muss schnorcheln' },
ssc: { title: 'Küsten-U-Boot Projekt 2', info: 'Extrem leise, klein und wendig; nur 4 Rohre, kleine Batterie, 200 m' },
kor: { title: 'Korvette K-7', info: 'Leise, schnell, wendig; kurzes Schleppsonar, kein Hubschrauber' },
};
/** Create an element from an HTML string. */
+1 -1
View File
@@ -1,6 +1,6 @@
import { angleDiff, bearing, type ClassChoice, type ContactTrack, type Snapshot } from '@tk/shared';
const CHOICE_OF_CLASS = { merchant: 'merchant', ffg: 'warship', ssn: 'submarine', ssk: 'submarine' } as const;
const CHOICE_OF_CLASS = { merchant: 'merchant', ffg: 'warship', kor: 'warship', ssn: 'submarine', ssk: 'submarine', ssc: 'submarine' } as const;
/**
* Datalink correlation: a sonar contact that lines up with a known friendly ship
+90
View File
@@ -0,0 +1,90 @@
import { CLASSES, angleDiff, bearing, distance, type ClassId, type Snapshot } from '@tk/shared';
import type { Periscope3D, PeriscopeTarget } from './periscope3d.js';
import { deg3, km } from './format.js';
import { lang } from '../i18n/index.js';
const L = (de: string, en: string) => (lang === 'en' ? en : de);
/**
* "Lookout reports a hit": when an explosion is seen (escorts always, boats with the mast up),
* a small 3D inset pops up wherever the player is, showing the blast through binoculars:
* water column, smoke, fire at night, the struck ship going down. Closes by itself.
*/
const SHOW_S = 14;
const MAX_RANGE = 25_000;
interface Shot { id: string; bearing: number; range: number; cls: ClassId; startMs: number }
export function hitCam(root: HTMLElement): { snap(s: Snapshot): void; frame(s: Snapshot | undefined): void } {
const box = document.createElement('div');
box.className = 'hitcam';
box.innerHTML = `<div class="hd"><span id="hc-t"></span><button id="hc-x" title="Schließen">×</button></div><canvas id="hc-gl"></canvas>`;
box.style.display = 'none';
root.appendChild(box);
const canvas = box.querySelector<HTMLCanvasElement>('#hc-gl')!;
let gl: Periscope3D | undefined;
let loading = false;
let shot: Shot | undefined;
let lastAlert = -1;
box.querySelector<HTMLButtonElement>('#hc-x')!.onclick = () => close();
function close(): void {
shot = undefined;
box.style.display = 'none';
}
function ensureGl(): void {
if (gl || loading || localStorage.getItem('tk_3d') === '0') return;
loading = true;
import('./periscope3d.js')
.then((m) => {
if (m.Periscope3D.supported()) gl = new m.Periscope3D(canvas, { eye: 18 });
})
.catch(() => undefined);
}
return {
snap(s) {
const canSee = !CLASSES[s.own.cls].submarine || s.own.mastUp;
for (const a of s.alerts) {
if (a.kind !== 'hit' || a.bearing === undefined || a.time <= lastAlert) continue;
lastAlert = a.time;
if (!canSee || s.time - a.time > 20) continue;
// Range and type from our own formation if the victim is one of ours; otherwise a guess
let range = 6_000;
let cls: ClassId = 'merchant';
let best = 6;
for (const f of s.friendlies) {
const b = bearing(s.own, f);
const d = Math.abs(angleDiff(b, a.bearing));
if (d < best) {
best = d;
range = distance(s.own, f);
cls = f.cls;
}
}
if (range > MAX_RANGE) continue;
shot = { id: `${a.time}|${a.bearing}`, bearing: a.bearing, range, cls, startMs: performance.now() };
ensureGl();
box.style.display = '';
box.querySelector('#hc-t')!.textContent = L(`AUSGUCK · TREFFER PEILUNG ${deg3(a.bearing)} · CA. ${km(range)}`, `LOOKOUT · HIT BEARING ${deg3(a.bearing)} · ABOUT ${km(range)}`);
}
},
frame(s) {
if (!shot) return;
const age = (performance.now() - shot.startMs) / 1000;
if (age > SHOW_S) return close();
box.style.opacity = String(Math.min(1, (SHOW_S - age) / 1.5));
if (!gl || !s) return;
// The struck ship is shown for a moment, then dropped: the scene lets it go down by the bow
const targets: PeriscopeTarget[] = age < 3.5 ? [{ label: shot.id, cls: shot.cls, bearing: shot.bearing, range: shot.range, alpha: 1, speedKn: 4 }] : [];
gl.render({
bearing: shot.bearing, fovDeg: Math.max(4, Math.min(14, 9000 / shot.range * 2)), t: age, sea: s.env.seaState, light: s.env.light ?? 1,
// The blast starts a moment later, once the ship stands in the scene (so it is marked to sink)
targets, rain: s.env.rain, hour: s.env.clock, effects: age > 0.4 ? [{ id: shot.id, bearing: shot.bearing, range: shot.range, age: age - 0.4 }] : [],
pitchDeg: -0.1,
});
},
};
}
+4 -4
View File
@@ -4,19 +4,19 @@
*/
export type KeyAction =
| 'station1' | 'station2' | 'station3' | 'station4'
| 'station1' | 'station2' | 'station3' | 'station4' | 'station5'
| 'left' | 'right' | 'faster' | 'slower' | 'up' | 'down'
| 'scopeLeft' | 'scopeRight' | 'help' | 'mute';
export const KEY_LABEL: Record<KeyAction, string> = {
station1: 'Station 1', station2: 'Station 2', station3: 'Station 3', station4: 'Station 4',
station1: 'Station 1', station2: 'Station 2', station3: 'Station 3', station4: 'Station 4', station5: 'Station 5',
left: 'Kurs links', right: 'Kurs rechts', faster: 'Fahrt +1 kn', slower: 'Fahrt −1 kn',
up: 'Tiefe −10 m (auftauchen)', down: 'Tiefe +10 m (tauchen)',
scopeLeft: 'Sehrohr links', scopeRight: 'Sehrohr rechts', help: 'Hilfe', mute: 'Ton an/aus',
};
export const DEFAULT_KEYS: Record<KeyAction, string> = {
station1: 'Digit1', station2: 'Digit2', station3: 'Digit3', station4: 'Digit4',
station1: 'Digit1', station2: 'Digit2', station3: 'Digit3', station4: 'Digit4', station5: 'Digit5',
left: 'ArrowLeft', right: 'ArrowRight', faster: 'ArrowUp', slower: 'ArrowDown', up: 'PageUp', down: 'PageDown',
scopeLeft: 'KeyA', scopeRight: 'KeyD', help: 'KeyH', mute: 'KeyM',
};
@@ -42,7 +42,7 @@ export function isKey(e: KeyboardEvent, action: KeyAction): boolean {
/** Station index (0-based) for the event, or -1. */
export function stationKey(e: KeyboardEvent): number {
return (['station1', 'station2', 'station3', 'station4'] as const).findIndex((a) => isKey(e, a));
return (['station1', 'station2', 'station3', 'station4', 'station5'] as const).findIndex((a) => isKey(e, a));
}
/** Readable name for a key code: "KeyA" → "A", "ArrowLeft" → "←". */
+209 -48
View File
@@ -1,7 +1,8 @@
import { depthAt, type MissionKey, type SeabedKind } from '@tk/shared';
import { esc } from './format.js';
import { drawSymbol } from './symbols.js';
interface Card { key: MissionKey; title: string; info: string; seabed: SeabedKind; kind: 'convoy' | 'duel' | 'harbour' }
interface Card { key: MissionKey; title: string; info: string; seabed: SeabedKind; kind: 'convoy' | 'duel' | 'harbour' | 'custom' }
const CARDS: Card[] = [
{ key: 'groenland', title: 'Grönland-Lücke', info: 'Tiefwasser · Konvergenzzonen', seabed: 'tief', kind: 'convoy' },
@@ -9,65 +10,225 @@ const CARDS: Card[] = [
{ key: 'fjord', title: 'Fjordausfahrt', info: 'Enger Kanal', seabed: 'fjord', kind: 'convoy' },
{ key: 'duell', title: 'U-Boot-Duell', info: 'Boot gegen Boot', seabed: 'tief', kind: 'duel' },
{ key: 'hafen', title: 'Hafenangriff', info: 'Ankerplatz in der Bucht', seabed: 'fjord', kind: 'harbour' },
{ key: 'eigene', title: 'Eigene Mission', info: 'Frei einstellbar', seabed: 'tief', kind: 'convoy' },
{ key: 'eigene', title: 'Eigene Mission', info: 'Frei einstellbar', seabed: 'tief', kind: 'custom' },
];
/** Mission picker: cards with a small chart of the sea area and the convoy route. */
/** Chart canvases are drawn at double resolution so lines and labels stay crisp on phones. */
const W = 320;
const H = 180;
const BLUE = '#85b7eb';
const RED = '#f09595';
const ROUTE = 28_000; // convoy route at the default 40 min limit (scenario.routeLength)
/** Mission picker: cards with a small tactical chart of the sea area and the starting situation. */
export function missionCards(current: MissionKey): string {
return `<div class="mcards">${CARDS.map((c) => `<button class="mcard ${c.key === current ? 'on' : ''}" data-mission="${c.key}">
<canvas data-chart="${c.key}" width="150" height="84"></canvas>
<canvas data-chart="${c.key}" width="${W}" height="${H}"></canvas>
<div class="mcard-t">${esc(c.title)}</div><div class="dim">${esc(c.info)}</div></button>`).join('')}</div>`;
}
const charts = new Map<string, ImageData>();
/** Visible sea area in meters (x east, y north). */
interface View { x0: number; x1: number; y0: number; y1: number }
const WIDE: View = { x0: -30_000, x1: 30_000, y0: -3_000, y1: 30_750 };
const HARBOUR: View = { x0: -20_000, x1: 20_000, y0: 0, y1: 22_500 };
/** Draw the chart canvases rendered by missionCards (cached per mission). */
const px = (v: View, x: number) => ((x - v.x0) / (v.x1 - v.x0)) * W;
const py = (v: View, y: number) => (1 - (y - v.y0) / (v.y1 - v.y0)) * H;
const charts = new Map<string, { img: ImageData; typical: number }>();
/** Depth tint, relief shading and isobaths, computed once per sea area. */
function seaImage(ctx: CanvasRenderingContext2D, kind: SeabedKind, v: View): { img: ImageData; typical: number } {
const spec = { kind, seed: 7 };
const depth = new Float32Array(W * H);
let lo = Infinity;
let hi = -Infinity;
for (let j = 0; j < H; j++) {
for (let i = 0; i < W; i++) {
const d = depthAt(spec, v.x0 + ((i + 0.5) / W) * (v.x1 - v.x0), v.y1 - ((j + 0.5) / H) * (v.y1 - v.y0));
depth[j * W + i] = d;
if (d > 0) { lo = Math.min(lo, d); hi = Math.max(hi, d); }
}
}
const span = Math.max(40, hi - lo);
// Contour spacing adapted to the depth range so every sea shows structure
const step = span > 1500 ? 250 : span > 400 ? 100 : 25;
const img = ctx.createImageData(W, H);
const at = (i: number, j: number) => depth[Math.min(H - 1, Math.max(0, j)) * W + Math.min(W - 1, Math.max(0, i))]!;
for (let j = 0; j < H; j++) {
for (let i = 0; i < W; i++) {
const d = at(i, j);
let r: number, g: number, b: number;
if (d <= 0) {
// Land: olive, lighter inland, with a bright coastline
const coast = at(i + 1, j) > 0 || at(i - 1, j) > 0 || at(i, j + 1) > 0 || at(i, j - 1) > 0;
const k = Math.min(1, -d / 150);
[r, g, b] = coast ? [176, 160, 112] : [70 + 30 * k, 66 + 26 * k, 44 + 14 * k];
} else {
// Water: shallow teal → deep navy, relative to this sea's own range
const t = Math.min(1, Math.max(0, (d - lo) / span));
// Absolute depth dominates, so a shelf sea reads clearly lighter than the deep ocean
const abs = Math.min(1, Math.max(0, (Math.log10(Math.max(10, d)) - 1.5) / 2.1));
const m = 0.25 * t + 0.75 * abs;
r = 34 - 26 * m; g = 92 - 66 * m; b = 92 - 58 * m;
// Relief: light from the north-west
const slope = (at(i - 1, j - 1) - at(i + 1, j + 1)) / span;
const s = Math.max(-0.35, Math.min(0.35, slope * 22));
r *= 1 - s; g *= 1 - s; b *= 1 - s;
// Isobaths
if (Math.floor(d / step) !== Math.floor(at(i + 1, j) / step) || Math.floor(d / step) !== Math.floor(at(i, j + 1) / step)) {
r += 28; g += 46; b += 46;
}
}
img.data.set([r, g, b, 255], (j * W + i) * 4);
}
}
const wet = [...depth].filter((d) => d > 0).sort((a, b) => a - b);
return { img, typical: wet[Math.floor(wet.length / 2)] ?? 0 };
}
function label(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, color: string, align: CanvasTextAlign = 'left'): void {
ctx.font = '600 15px ui-monospace, Menlo, monospace';
ctx.textAlign = align;
ctx.textBaseline = 'middle';
ctx.lineWidth = 4;
ctx.strokeStyle = 'rgba(3, 10, 12, 0.85)';
ctx.strokeText(text, x, y);
ctx.fillStyle = color;
ctx.fillText(text, x, y);
}
function chartFrame(ctx: CanvasRenderingContext2D, v: View): void {
// 10 km grid
ctx.strokeStyle = 'rgba(180, 230, 220, 0.09)';
ctx.lineWidth = 1;
ctx.beginPath();
for (let x = Math.ceil(v.x0 / 10_000) * 10_000; x < v.x1; x += 10_000) { ctx.moveTo(px(v, x), 0); ctx.lineTo(px(v, x), H); }
for (let y = Math.ceil(v.y0 / 10_000) * 10_000; y < v.y1; y += 10_000) { ctx.moveTo(0, py(v, y)); ctx.lineTo(W, py(v, y)); }
ctx.stroke();
// Scale bar and north arrow
const ten = px(v, v.x0 + 10_000);
ctx.strokeStyle = '#cfe8e0';
ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(10, H - 12); ctx.lineTo(10 + ten, H - 12); ctx.moveTo(10, H - 17); ctx.lineTo(10, H - 7); ctx.moveTo(10 + ten, H - 17); ctx.lineTo(10 + ten, H - 7); ctx.stroke();
label(ctx, '10 KM', 16 + ten, H - 12, '#cfe8e0');
ctx.fillStyle = '#cfe8e0';
ctx.beginPath(); ctx.moveTo(W - 16, 8); ctx.lineTo(W - 22, 24); ctx.lineTo(W - 16, 20); ctx.lineTo(W - 10, 24); ctx.fill();
label(ctx, 'N', W - 16, 33, '#cfe8e0', 'center');
}
function sym(ctx: CanvasRenderingContext2D, x: number, y: number, aff: 'friend' | 'hostile' | 'neutral', dim: 'surface' | 'subsurface', size: number): void {
ctx.strokeStyle = ctx.fillStyle = aff === 'hostile' ? RED : aff === 'friend' ? BLUE : '#c9d4d0';
ctx.lineWidth = 2.2;
drawSymbol(ctx, x, y, aff, dim, size, true);
}
function arrow(ctx: CanvasRenderingContext2D, x: number, y: number, dx: number, dy: number, color: string): void {
ctx.strokeStyle = color;
ctx.lineWidth = 2;
ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + dx, y + dy); ctx.stroke();
const a = Math.atan2(dy, dx);
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo(x + dx, y + dy);
ctx.lineTo(x + dx - 8 * Math.cos(a - 0.45), y + dy - 8 * Math.sin(a - 0.45));
ctx.lineTo(x + dx - 8 * Math.cos(a + 0.45), y + dy - 8 * Math.sin(a + 0.45));
ctx.fill();
}
/** Convoy steaming north, escorts ahead, wolfpack waiting along the route. */
function convoyScene(ctx: CanvasRenderingContext2D, v: View): void {
const x = px(v, 0);
ctx.strokeStyle = BLUE;
ctx.lineWidth = 2;
ctx.setLineDash([7, 5]);
ctx.beginPath(); ctx.moveTo(x, py(v, 0)); ctx.lineTo(x, py(v, ROUTE)); ctx.stroke();
ctx.setLineDash([]);
// Destination
ctx.beginPath(); ctx.arc(x, py(v, ROUTE), 7, 0, Math.PI * 2); ctx.stroke();
ctx.beginPath(); ctx.arc(x, py(v, ROUTE), 2.5, 0, Math.PI * 2); ctx.fillStyle = BLUE; ctx.fill();
label(ctx, 'ZIELHAFEN', x + 12, py(v, ROUTE), BLUE);
// Merchants in columns, escorts on the flanks ahead
// Merchants as separate APP-6 neutral surface symbols (pixel spacing, so they never merge into a block)
for (let i = 0; i < 6; i++) sym(ctx, x + ((i % 3) - 1) * 22, py(v, 0) - 16 + Math.floor(i / 3) * 16, 'neutral', 'surface', 5);
label(ctx, 'KONVOI', x + 60, py(v, 0) + 2, '#c9d4d0');
for (const ex of [-1, 1]) sym(ctx, x + ex * 48, py(v, 3600), 'friend', 'surface', 6);
// Ambush zone and the pack
const zy0 = py(v, ROUTE * 0.42);
const zy1 = py(v, ROUTE * 0.78);
ctx.strokeStyle = 'rgba(240, 149, 149, 0.75)';
ctx.fillStyle = 'rgba(240, 149, 149, 0.08)';
ctx.lineWidth = 1.5;
ctx.setLineDash([5, 4]);
ctx.beginPath(); ctx.ellipse(x, (zy0 + zy1) / 2, px(v, 9_000) - x, (zy0 - zy1) / 2, 0, 0, Math.PI * 2); ctx.fill(); ctx.stroke();
ctx.setLineDash([]);
for (const [sx, sy] of [[-5_000, 0.5], [4_000, 0.62], [-1_500, 0.72]] as const) sym(ctx, px(v, sx), py(v, ROUTE * sy), 'hostile', 'subsurface', 6);
label(ctx, 'RUDEL', px(v, 9_800), (zy0 + zy1) / 2, RED);
}
function duelScene(ctx: CanvasRenderingContext2D, v: View): void {
const a = { x: px(v, -3_000), y: py(v, 2_500) };
const b = { x: px(v, 3_000), y: py(v, 25_000) };
// Sonar search arcs reaching toward each other
ctx.lineWidth = 1.5;
for (const [p, col, dir] of [[a, BLUE, -1], [b, RED, 1]] as const) {
ctx.strokeStyle = col;
for (const r of [26, 46, 66]) {
ctx.globalAlpha = 0.9 - r / 90;
ctx.beginPath(); ctx.arc(p.x, p.y, r, dir < 0 ? Math.PI * 1.2 : Math.PI * 0.2, dir < 0 ? Math.PI * 1.8 : Math.PI * 0.8); ctx.stroke();
}
ctx.globalAlpha = 1;
}
sym(ctx, a.x, a.y, 'friend', 'subsurface', 8);
sym(ctx, b.x, b.y, 'hostile', 'subsurface', 8);
ctx.strokeStyle = 'rgba(207, 232, 224, 0.5)';
ctx.setLineDash([3, 5]);
ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke();
ctx.setLineDash([]);
label(ctx, '≈ 23 KM', (a.x + b.x) / 2 + 8, (a.y + b.y) / 2, '#cfe8e0');
label(ctx, 'WESTBUND', a.x + 14, a.y + 4, BLUE);
label(ctx, 'OSTPAKT', b.x + 14, b.y + 2, RED);
}
/** Merchants at anchor deep in the bay, escorts patrol the entrance, subs come in from the sea. */
function harbourScene(ctx: CanvasRenderingContext2D, v: View): void {
for (let i = 0; i < 6; i++) sym(ctx, px(v, 0) + ((i % 3) - 1) * 22, py(v, 3000) - 6 + Math.floor(i / 3) * 16, 'neutral', 'surface', 5);
label(ctx, 'ANKERPLATZ', px(v, 0) + 34, py(v, 3000) + 2, '#c9d4d0');
const gy = py(v, 6_500);
ctx.strokeStyle = BLUE;
ctx.lineWidth = 1.5;
ctx.setLineDash([6, 4]);
ctx.beginPath(); ctx.moveTo(px(v, -4_500), gy); ctx.lineTo(px(v, 4_500), gy); ctx.stroke();
ctx.setLineDash([]);
for (const ex of [-2_500, 2_500]) sym(ctx, px(v, ex), gy, 'friend', 'surface', 6);
label(ctx, 'SPERRE', px(v, 5_000), gy, BLUE);
for (const [sx, sy] of [[-2_000, 19_000], [2_000, 20_500]] as const) {
sym(ctx, px(v, sx), py(v, sy), 'hostile', 'subsurface', 6);
arrow(ctx, px(v, sx), py(v, sy) + 12, 0, 26, RED);
}
label(ctx, 'ANGRIFF', px(v, 3_200), py(v, 20_000), RED);
}
/** Draw the chart canvases rendered by missionCards (sea area cached per mission). */
export function paintMissionCharts(root: HTMLElement, customSeabed?: SeabedKind): void {
root.querySelectorAll<HTMLCanvasElement>('canvas[data-chart]').forEach((cv) => {
const card = CARDS.find((c) => c.key === cv.dataset.chart)!;
const seabed = card.key === 'eigene' && customSeabed ? customSeabed : card.seabed;
const seabed = card.kind === 'custom' && customSeabed ? customSeabed : card.seabed;
const v = card.kind === 'harbour' ? HARBOUR : WIDE;
const ctx = cv.getContext('2d')!;
const key = `${card.key}|${seabed}`;
let img = charts.get(key);
if (!img) {
img = ctx.createImageData(cv.width, cv.height);
const spec = { kind: seabed, seed: 7 };
for (let j = 0; j < cv.height; j++) {
for (let i = 0; i < cv.width; i++) {
// 60 × 34 km around the route; north up
const d = depthAt(spec, (i / cv.width - 0.5) * 60_000, (1 - j / cv.height) * 34_000 - 4_000);
const [r, g, b] = d < 0 ? [70, 66, 48] : d < 60 ? [60, 82, 70] : d < 300 ? [20, 52, 54] : d < 2000 ? [12, 34, 40] : [8, 22, 28];
const k = (j * cv.width + i) * 4;
img.data.set([r, g, b, 255], k);
}
}
charts.set(key, img);
}
ctx.putImageData(img, 0, 0);
const W = cv.width;
const H = cv.height;
ctx.lineWidth = 1.5;
if (card.kind === 'convoy') {
ctx.strokeStyle = '#85b7eb';
ctx.setLineDash([4, 3]);
ctx.beginPath(); ctx.moveTo(W / 2, H - 6); ctx.lineTo(W / 2, 10); ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = '#85b7eb';
ctx.beginPath(); ctx.moveTo(W / 2, 4); ctx.lineTo(W / 2 - 5, 12); ctx.lineTo(W / 2 + 5, 12); ctx.fill();
for (const x of [-1, 0, 1]) ctx.fillRect(W / 2 + x * 6 - 1.5, H - 14, 3, 6);
}
if (card.kind === 'harbour') {
ctx.fillStyle = '#85b7eb';
for (let i = 0; i < 6; i++) ctx.fillRect(W / 2 - 14 + (i % 3) * 12, 18 + Math.floor(i / 3) * 8, 3, 5);
}
ctx.strokeStyle = '#f09595';
const subs = card.kind === 'duel' ? [[W * 0.5, 14]] : card.kind === 'harbour' ? [[W * 0.4, H - 16], [W * 0.6, H - 20]] : [[W * 0.35, H * 0.45], [W * 0.62, H * 0.4]];
for (const [x, y] of subs) {
ctx.beginPath(); ctx.moveTo(x! - 6, y! - 2); ctx.lineTo(x!, y! + 5); ctx.lineTo(x! + 6, y! - 2); ctx.stroke();
}
if (card.kind === 'duel') {
ctx.strokeStyle = '#85b7eb';
ctx.beginPath(); ctx.arc(W / 2, H - 14, 5, Math.PI, 0, true); ctx.stroke();
const key = `${card.kind === 'harbour' ? 'h' : 'w'}|${seabed}`;
let sea = charts.get(key);
if (!sea) charts.set(key, (sea = seaImage(ctx, seabed, v)));
ctx.putImageData(sea.img, 0, 0);
chartFrame(ctx, v);
// Typical water depth: the first thing a captain wants to know about the area
const deep = sea.typical >= 1000 ? `${(sea.typical / 1000).toFixed(1).replace('.', ',')} KM` : `${Math.round(sea.typical / 10) * 10} M`;
label(ctx, `TIEFE ~${deep}`, 10, 16, '#cfe8e0');
if (card.kind === 'duel') duelScene(ctx, v);
else if (card.kind === 'harbour') harbourScene(ctx, v);
else {
convoyScene(ctx, v);
if (card.kind === 'custom') label(ctx, '⚙ FREI', 10, 36, '#e8c37a');
}
});
}
+115 -142
View File
@@ -1,15 +1,16 @@
import * as THREE from 'three';
import type { ClassId } from '@tk/shared';
import type { ClassId, Sighting } from '@tk/shared';
import { shipModel, sightingModel } from './sea3d/models.js';
import { OCEAN_FRAG, OCEAN_VERT, SKY_FRAG, SKY_VERT } from './sea3d/shaders.js';
/**
* 3D periscope view: shader ocean with swell, sky gradient, haze, simple ship
* models positioned from (filtered) bearing/range, sunk below the horizon by
* earth curvature. The 2D reticle is drawn on top by the station.
* 3D sea view used by the periscope (eye 4 m) and the escorts' bridge (eye 20 m):
* multi-wave ocean with whitecaps and glitter, sky with clouds, sun and moon,
* ship models placed from (filtered) bearing/range and sunk by earth curvature.
* The 2D reticle or binocular mask is drawn on top by the station.
*/
const EARTH_R = 6_371_000;
/** Periscope head above the water at periscope depth (m). */
const EYE = 4;
export interface PeriscopeTarget {
label: string;
@@ -19,6 +20,8 @@ export interface PeriscopeTarget {
course?: number;
speedKn?: number;
alpha: number;
/** Lookout sighting of a submerged boat: draw what is visible of it (feather, snorkel). */
sighting?: Sighting;
}
/** A detonation seen through the optic (from a hit/sunk report): water column, smoke, fire. */
@@ -29,97 +32,9 @@ export interface PeriscopeEffect {
age: number;
}
const DEFAULT_KN: Partial<Record<ClassId, number>> = { merchant: 9, ffg: 14 };
const DEFAULT_KN: Partial<Record<ClassId, number>> = { merchant: 9, ffg: 14, kor: 14 };
/** White foam: a wake wedge behind the stern and a small bow wave. */
function wakeMesh(len: number): THREE.Group {
const g = new THREE.Group();
const mat = new THREE.MeshBasicMaterial({ color: 0xdfeef0, transparent: true, opacity: 0.45, depthWrite: false });
const wake = new THREE.Mesh(new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-6, 0.3, 0), new THREE.Vector3(6, 0.3, 0), new THREE.Vector3(len * 0.35, 0.3, len),
new THREE.Vector3(-6, 0.3, 0), new THREE.Vector3(len * 0.35, 0.3, len), new THREE.Vector3(-len * 0.35, 0.3, len),
]), mat);
wake.name = 'wake';
const bow = new THREE.Mesh(new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0.5, 0), new THREE.Vector3(9, 0.5, 14), new THREE.Vector3(-9, 0.5, 14),
]), mat);
bow.name = 'bow';
g.add(wake, bow);
return g;
}
const OCEAN_VERT = `
uniform float uTime; uniform float uAmp;
varying vec3 vPos; varying vec3 vNormal;
float wave(vec2 p, vec2 d, float f, float s) { return sin(dot(p, d) * f + uTime * s); }
void main() {
vec3 p = position;
vec2 xz = (modelMatrix * vec4(p, 1.0)).xz;
float h = uAmp * (0.55 * wave(xz, normalize(vec2(0.8, 0.6)), 0.045, 1.1)
+ 0.30 * wave(xz, normalize(vec2(-0.4, 0.9)), 0.09, 1.7)
+ 0.15 * wave(xz, normalize(vec2(0.95, -0.3)), 0.21, 2.6));
p.z += h;
float e = 0.5;
float hx = uAmp * 0.55 * wave(xz + vec2(e, 0.0), normalize(vec2(0.8, 0.6)), 0.045, 1.1) - uAmp * 0.55 * wave(xz, normalize(vec2(0.8, 0.6)), 0.045, 1.1);
float hz = uAmp * 0.30 * wave(xz + vec2(0.0, e), normalize(vec2(-0.4, 0.9)), 0.09, 1.7) - uAmp * 0.30 * wave(xz, normalize(vec2(-0.4, 0.9)), 0.09, 1.7);
vNormal = normalize(vec3(-hx / e, 1.0, -hz / e));
vec4 wp = modelMatrix * vec4(p, 1.0);
vPos = wp.xyz;
gl_Position = projectionMatrix * viewMatrix * wp;
}`;
const OCEAN_FRAG = `
uniform vec3 uDeep; uniform vec3 uSky; uniform vec3 uSun; uniform vec3 uFog; uniform float uFogDensity; uniform float uLight;
varying vec3 vPos; varying vec3 vNormal;
void main() {
vec3 view = normalize(cameraPosition - vPos);
vec3 n = normalize(vNormal);
float fres = pow(1.0 - max(dot(n, view), 0.0), 4.0);
vec3 col = mix(uDeep, uSky, clamp(fres * 0.55, 0.0, 1.0));
vec3 r = reflect(-view, n);
float spec = pow(max(dot(r, normalize(uSun)), 0.0), 220.0) * uLight;
col += vec3(1.0, 0.95, 0.85) * spec * 0.8;
float d = length(cameraPosition - vPos);
float fog = 1.0 - exp(-pow(d * uFogDensity, 2.0));
gl_FragColor = vec4(mix(col * uLight, uFog, fog), 1.0);
#include <colorspace_fragment>
}`;
const SKY_FRAG = `
uniform vec3 uTop; uniform vec3 uHorizon; varying vec3 vDir;
void main() { float h = clamp(vDir.y * 4.0, 0.0, 1.0); gl_FragColor = vec4(mix(uHorizon, uTop, h), 1.0);
#include <colorspace_fragment>
}`;
const SKY_VERT = `varying vec3 vDir; void main() { vDir = normalize(position); gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.0); }`;
function shipModel(cls: ClassId): THREE.Group {
const g = new THREE.Group();
const grey = new THREE.MeshLambertMaterial({ color: cls === 'merchant' ? 0x4a5258 : 0x5a6268, flatShading: true });
const dark = new THREE.MeshLambertMaterial({ color: 0x2e3438, flatShading: true });
const box = (w: number, h: number, l: number, x: number, y: number, z: number, m = grey) => {
const b = new THREE.Mesh(new THREE.BoxGeometry(w, h, l), m);
b.position.set(x, y, z);
g.add(b);
};
if (cls === 'merchant') {
box(20, 9, 130, 0, 3, 0, dark);
box(16, 12, 16, 0, 13, -48);
box(5, 10, 5, 0, 24, -46, dark);
for (const z of [-15, 15, 40]) box(1, 18, 1, 0, 17, z, dark);
box(18, 6, 70, 0, 10, 10, new THREE.MeshLambertMaterial({ color: 0x6b4a3a, flatShading: true }));
} else if (cls === 'ffg') {
box(14, 7, 125, 0, 2.5, 0, dark);
box(11, 9, 40, 0, 10, -5);
box(6, 6, 10, 0, 17, 0);
box(1, 20, 1, 0, 28, 2, dark);
box(8, 1, 1, 0, 34, 2, dark);
box(3, 3, 8, 0, 8, 48, dark);
} else {
box(4, 3, 60, 0, 0.5, 0, dark);
box(3, 6, 8, 0, 4, 5, dark);
}
return g;
}
interface Placed { g: THREE.Group; key: string; bearing: number }
export class Periscope3D {
private renderer: THREE.WebGLRenderer;
@@ -129,24 +44,30 @@ export class Periscope3D {
private sky: THREE.Mesh<THREE.SphereGeometry, THREE.ShaderMaterial>;
private hemi = new THREE.HemisphereLight(0xb8c8d0, 0x1a2a30, 1.2);
private sun = new THREE.DirectionalLight(0xffffff, 1.2);
private ships = new Map<string, { g: THREE.Group; cls: ClassId; bearing: number }>();
private ships = new Map<string, Placed>();
private sinking: { g: THREE.Group; since: number; y0: number }[] = [];
private effects = new Map<string, THREE.Group>();
private stars: THREE.Points;
private rain: THREE.LineSegments;
private fire = new THREE.PointLight(0xff7a30, 0, 6000, 1.2);
/** Eye height above the water (m): 4 for a periscope, about 20 on a frigate's bridge. */
private eye: number;
/** Own ship around the camera (bridge view): model and how far forward of midships the bridge is. */
private own?: { g: THREE.Group; bridgeZ: number };
constructor(private canvas: HTMLCanvasElement) {
this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
constructor(private canvas: HTMLCanvasElement, opts: { eye?: number; own?: ClassId } = {}) {
this.eye = opts.eye ?? 4;
this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' });
this.renderer.setClearColor(0x24343b);
this.camera.rotation.order = 'YXZ';
this.ocean = new THREE.Mesh(
new THREE.PlaneGeometry(40_000, 40_000, 320, 320),
new THREE.PlaneGeometry(40_000, 40_000, 256, 256),
new THREE.ShaderMaterial({
vertexShader: OCEAN_VERT, fragmentShader: OCEAN_FRAG,
uniforms: {
uTime: { value: 0 }, uAmp: { value: 1 }, uDeep: { value: new THREE.Color(0x14303a) }, uSky: { value: new THREE.Color(0x52676f) },
uSun: { value: new THREE.Vector3(0.3, 0.5, -0.8) }, uFog: { value: new THREE.Color(0x4b5f67) }, uFogDensity: { value: 0.00006 }, uLight: { value: 1 },
uTime: { value: 0 }, uAmp: { value: 1 }, uDeep: { value: new THREE.Color(0x10303a) }, uSky: { value: new THREE.Color(0x5a7078) },
uSun: { value: new THREE.Vector3(0.3, 0.5, -0.8) }, uMoon: { value: new THREE.Vector3(-0.3, 0.4, 0.8) }, uFog: { value: new THREE.Color(0x4b5f67) },
uFogDensity: { value: 0.00006 }, uLight: { value: 1 }, uFoam: { value: 0 }, uSunUp: { value: 1 },
},
}),
);
@@ -156,11 +77,13 @@ export class Periscope3D {
new THREE.SphereGeometry(50_000, 32, 16),
new THREE.ShaderMaterial({
vertexShader: SKY_VERT, fragmentShader: SKY_FRAG, side: THREE.BackSide, depthWrite: false,
uniforms: { uTop: { value: new THREE.Color(0x24343b) }, uHorizon: { value: new THREE.Color(0x56707a) } },
uniforms: {
uTop: { value: new THREE.Color(0x24343b) }, uHorizon: { value: new THREE.Color(0x56707a) }, uSun: { value: new THREE.Vector3(0, 1, 0) },
uMoon: { value: new THREE.Vector3(0, 1, 0) }, uLight: { value: 1 }, uCloud: { value: 0.4 }, uTime: { value: 0 }, uSunUp: { value: 1 },
},
}),
);
this.scene.add(this.sky);
this.sun.position.set(3, 5, -8);
this.scene.add(this.hemi, this.sun, this.fire);
// Stars on the upper sky dome (visible only at night)
const sp: number[] = [];
@@ -185,6 +108,13 @@ export class Periscope3D {
this.rain.visible = false;
this.camera.add(this.rain);
this.scene.add(this.camera);
if (opts.own) {
// Foredeck, gun and bridge front in the lower part of the picture: the eye sits on the bridge roof
const g = shipModel(opts.own);
for (const n of ['wake']) g.getObjectByName(n)?.removeFromParent();
this.own = { g, bridgeZ: opts.own === 'kor' ? 23 : 31 };
this.scene.add(g);
}
}
private effectGroup(): THREE.Group {
@@ -228,8 +158,7 @@ export class Periscope3D {
const puff = g.getObjectByName(`smoke${i}`) as THREE.Mesh<THREE.SphereGeometry, THREE.MeshLambertMaterial>;
const a = Math.max(0, e.age - 2 - i * 1.5);
puff.visible = a > 0;
const r = 8 + a * 2.5 + i * 2;
puff.scale.setScalar(r);
puff.scale.setScalar(8 + a * 2.5 + i * 2);
puff.position.set(a * 3 + i * 2, 15 + a * 6 + i * 10, Math.sin(i) * 6);
puff.material.opacity = Math.max(0, 0.75 - a / 120);
}
@@ -245,6 +174,23 @@ export class Periscope3D {
}
}
/** Funnel smoke and snorkel haze drift downwind and fade; radars turn. */
private animate(g: THREE.Group, t: number, kn: number, seed: number): void {
const sm = g.userData.smoke as { puffs: THREE.Mesh<THREE.SphereGeometry, THREE.MeshLambertMaterial>[]; origin: THREE.Vector3 } | undefined;
if (sm) {
const n = sm.puffs.length;
sm.puffs.forEach((p, i) => {
const ph = (t * 0.12 + i / n + seed) % 1;
// Apparent wind: the smoke streams aft at speed and drifts to one side
p.position.set(sm.origin.x + ph * 14, sm.origin.y + ph * 16, sm.origin.z - ph * (8 + kn * 3));
p.scale.setScalar(1.5 + ph * 7);
p.material.opacity = 0.45 * (1 - ph);
});
}
const radar = g.userData.radar as THREE.Mesh | undefined;
if (radar) radar.rotation.y = t * 2.1 + seed * 6;
}
static supported(): boolean {
try {
return !!document.createElement('canvas').getContext('webgl2');
@@ -253,10 +199,14 @@ export class Periscope3D {
}
}
render(o: { bearing: number; fovDeg: number; t: number; sea: number; light: number; targets: PeriscopeTarget[]; rain?: boolean; hour?: number; effects?: PeriscopeEffect[] }): void {
render(o: {
bearing: number; fovDeg: number; t: number; sea: number; light: number; targets: PeriscopeTarget[];
rain?: boolean; hour?: number; effects?: PeriscopeEffect[]; pitchDeg?: number; ownKn?: number; ownHeading?: number;
}): void {
const w = this.canvas.clientWidth || 400;
const h = this.canvas.clientHeight || 400;
const dpr = Math.min(2, window.devicePixelRatio || 1);
// Full retina resolution costs four times the fill rate for little gain behind scanlines
const dpr = Math.min(1.5, window.devicePixelRatio || 1);
if (this.canvas.width !== Math.round(w * dpr) || this.canvas.height !== Math.round(h * dpr)) {
this.renderer.setPixelRatio(dpr);
this.renderer.setSize(w, h, false);
@@ -266,31 +216,44 @@ export class Periscope3D {
const hf = (o.fovDeg * Math.PI) / 180;
this.camera.fov = (2 * Math.atan(Math.tan(hf / 2) / aspect) * 180) / Math.PI;
this.camera.updateProjectionMatrix();
// Slow swell: the boat (and the optic) heave, pitch and roll
// Swell: the boat (and the optic) heave, pitch and roll; a high bridge moves less but sways more
// Wave amplitude (m) by sea state: SS3 ≈ 1.4 m significant wave height
const amp = 0.12 + o.sea * 0.2;
this.camera.position.set(0, EYE + Math.sin(o.t * 0.55) * amp * 0.4, 0);
const high = this.eye > 10;
this.camera.position.set(0, this.eye + Math.sin(o.t * 0.55) * amp * (high ? 0.25 : 0.4), 0);
this.camera.rotation.y = (-o.bearing * Math.PI) / 180;
this.camera.rotation.x = Math.sin(o.t * 0.31) * 0.002 * (1 + o.sea);
this.camera.rotation.z = Math.sin(o.t * 0.4) * 0.004 * (1 + o.sea * 0.6);
this.camera.rotation.x = ((o.pitchDeg ?? 0) * Math.PI) / 180 + Math.sin(o.t * 0.31) * 0.002 * (1 + o.sea);
this.camera.rotation.z = Math.sin(o.t * 0.4) * (high ? 0.007 : 0.004) * (1 + o.sea * 0.6);
const u = this.ocean.material.uniforms;
u.uTime!.value = o.t;
u.uAmp!.value = amp;
u.uLight!.value = o.light;
u.uFogDensity!.value = 0.000022 * (1 + o.sea * 0.2);
u.uFoam!.value = Math.max(0, Math.min(1, (o.sea - 2) / 4));
const haze = new THREE.Color(0x7f939b).multiplyScalar(0.25 + 0.75 * o.light);
u.uFog!.value = haze;
// Dusk and dawn tint the horizon orange; the sun stands low in the west or east
const dusk = o.light > 0.15 && o.light < 0.9 ? 1 - Math.abs(o.light - 0.5) * 2 : 0;
const horizon = new THREE.Color(0x8fa3ab).lerp(new THREE.Color(0xd08a5a), dusk * 0.7).multiplyScalar(0.2 + 0.8 * o.light);
this.sky.material.uniforms.uHorizon!.value = o.rain ? horizon.clone().lerp(new THREE.Color(0x5c666a), 0.6) : horizon;
this.sky.material.uniforms.uTop!.value = new THREE.Color(0x3d5560).multiplyScalar((0.15 + 0.85 * o.light) * (o.rain ? 0.7 : 1));
const su = this.sky.material.uniforms;
su.uHorizon!.value = o.rain ? horizon.clone().lerp(new THREE.Color(0x5c666a), 0.6) : horizon;
su.uTop!.value = new THREE.Color(0x3d5560).multiplyScalar((0.15 + 0.85 * o.light) * (o.rain ? 0.7 : 1));
const hour = o.hour ?? 12;
const sunAz = ((hour - 6) / 12) * Math.PI; // east at 6 h, south at noon, west at 18 h
const sunEl = Math.max(0.03, Math.sin(((hour - 6) / 12) * Math.PI) * 0.8);
this.sun.position.set(Math.cos(sunAz) * 10, sunEl * 10, Math.sin(sunAz) * 10);
u.uSun!.value = this.sun.position.clone().normalize();
const sunEl = Math.sin(((hour - 6) / 12) * Math.PI) * 0.8;
this.sun.position.set(Math.cos(sunAz) * 10, Math.max(0.03, sunEl) * 10, Math.sin(sunAz) * 10);
const sunDir = new THREE.Vector3(Math.cos(sunAz), sunEl, Math.sin(sunAz)).normalize();
const moonDir = new THREE.Vector3(-Math.cos(sunAz), 0.35, -Math.sin(sunAz)).normalize();
const sunUp = Math.max(0, Math.min(1, sunEl * 6 + 0.2)) * (o.rain ? 0.2 : 1);
u.uSun!.value = sunDir;
u.uMoon!.value = moonDir;
u.uSunUp!.value = sunUp;
su.uSun!.value = sunDir;
su.uMoon!.value = moonDir;
su.uSunUp!.value = sunUp;
su.uLight!.value = o.light;
su.uTime!.value = o.t;
su.uCloud!.value = o.rain ? 0.85 : 0.3 + o.sea * 0.06;
this.sun.color = new THREE.Color(0xffffff).lerp(new THREE.Color(0xffb070), dusk);
this.hemi.intensity = 0.2 + 1.0 * o.light;
this.sun.intensity = 1.2 * o.light * (o.rain ? 0.4 : 1);
@@ -301,59 +264,69 @@ export class Periscope3D {
this.rain.visible = !!o.rain;
if (o.rain) this.rain.position.y = -((o.t * 22) % 30);
this.updateEffects(o.effects ?? [], o.light);
this.place(o.targets, o.t, o.sea, amp);
if (this.own) {
// Keep the own hull under the camera: the bridge point sits below the eye, the ship heaves and rolls with it
const c = ((o.ownHeading ?? 0) * Math.PI) / 180;
const g = this.own.g;
g.rotation.y = Math.PI - c;
g.position.set(-this.own.bridgeZ * Math.sin(c), this.camera.position.y - this.eye, this.own.bridgeZ * Math.cos(c));
g.rotation.z = this.camera.rotation.z;
this.animate(g, o.t, o.ownKn ?? 12, 0.3);
const bow = g.getObjectByName('bow');
if (bow) bow.scale.setScalar(Math.max(0.2, (o.ownKn ?? 12) / 12));
}
this.renderer.render(this.scene, this.camera);
}
private place(targets: PeriscopeTarget[], t: number, sea: number, amp: number): void {
const seen = new Set<string>();
for (const tg of o.targets) {
for (const tg of targets) {
seen.add(tg.label);
const key = `${tg.cls}|${tg.sighting ?? ''}`;
let s = this.ships.get(tg.label);
if (!s || s.cls !== tg.cls) {
if (!s || s.key !== key) {
if (s) this.scene.remove(s.g);
const g = shipModel(tg.cls);
if (tg.cls !== 'ssk' && tg.cls !== 'ssn') g.add(wakeMesh(180));
s = { g, cls: tg.cls, bearing: tg.bearing };
s = { g: tg.sighting ? sightingModel(tg.sighting, tg.cls) : shipModel(tg.cls), key, bearing: tg.bearing };
this.ships.set(tg.label, s);
this.scene.add(s.g);
}
s.bearing = tg.bearing;
// Wake length and bow wave follow the speed
const kn = tg.speedKn ?? DEFAULT_KN[tg.cls] ?? 0;
// Wake, bow wave and periscope feather follow the speed
const kn = tg.speedKn ?? DEFAULT_KN[tg.cls] ?? 4;
const wake = s.g.getObjectByName('wake');
if (wake) {
// Wake trails astern (−z), the bow wave spreads aft from the stem (+z)
wake.scale.set(1, 1, Math.max(0.05, kn / 10));
wake.rotation.y = Math.PI;
wake.position.z = -60;
const bow = s.g.getObjectByName('bow');
if (bow) {
bow.rotation.y = Math.PI;
bow.position.set(0, 0, 66);
}
}
if (wake) wake.scale.set(1, 1, Math.max(0.05, kn / 10));
const bow = s.g.getObjectByName('bow');
if (bow) bow.scale.setScalar(Math.max(0.2, kn / 12));
const feather = s.g.getObjectByName('feather');
if (feather) feather.scale.set(Math.max(0.3, kn / 6), 1, Math.max(0.2, kn / 5));
const seed = (tg.label.charCodeAt(1) || 0) / 10;
this.animate(s.g, t, kn, seed);
const b = (tg.bearing * Math.PI) / 180;
const drop = (tg.range * tg.range) / (2 * EARTH_R) - EYE * 0.5;
const bob = Math.sin(o.t * 0.5 + tg.label.length) * amp * 0.4;
// Earth curvature; the small lift keeps hulls from sinking into the wave crests at periscope height
const drop = (tg.range * tg.range) / (2 * EARTH_R) - 2;
const bob = Math.sin(t * 0.5 + tg.label.length) * amp * 0.4;
s.g.position.set(Math.sin(b) * tg.range, bob - drop, -Math.cos(b) * tg.range);
// Models are built bow toward +z; turn them so the bow points along the course (north = −z)
s.g.rotation.y = Math.PI - ((tg.course ?? tg.bearing + 90) * Math.PI) / 180;
s.g.rotation.z = Math.sin(o.t * 0.45 + tg.range) * 0.02 * (1 + o.sea * 0.5);
s.g.rotation.z = Math.sin(t * 0.45 + tg.range) * 0.02 * (1 + sea * 0.5);
s.g.visible = tg.alpha > 0.05;
}
for (const [label, s] of this.ships) {
if (!seen.has(label)) {
this.ships.delete(label);
// A ship hit shortly before it vanished goes down by the bow instead of popping away
if ((s.g.userData as { doomed?: number }).doomed !== undefined) this.sinking.push({ g: s.g, since: o.t, y0: s.g.position.y });
if ((s.g.userData as { doomed?: number }).doomed !== undefined) this.sinking.push({ g: s.g, since: t, y0: s.g.position.y });
else this.scene.remove(s.g);
}
}
this.sinking = this.sinking.filter((k) => {
const a = o.t - k.since;
const a = t - k.since;
k.g.rotation.x = Math.min(0.35, a * 0.01);
k.g.position.y = k.y0 - a * 0.35;
if (a > 90) this.scene.remove(k.g);
return a <= 90;
});
this.renderer.render(this.scene, this.camera);
}
dispose(): void {
+11 -8
View File
@@ -1,4 +1,4 @@
import { KN, NM, bearing, depthAt, distance, headingVec, ownPosAt, targetPosAt, wrap360, type Snapshot, type Vec2 } from '@tk/shared';
import { CLASSES, KN, NM, bearing, depthAt, distance, headingVec, ownPosAt, targetPosAt, wrap360, type Snapshot, type Vec2 } from '@tk/shared';
import { store } from '../store.js';
import { COL, deg3, fitCanvas, km } from './format.js';
import { isFriendlyContact } from './friendly.js';
@@ -278,10 +278,14 @@ export class Plot {
ctx.setLineDash([2, 3]);
ctx.beginPath(); ctx.moveTo(o.x, o.y); ctx.lineTo(o.x + ov.x * 40, o.y - ov.y * 40); ctx.stroke();
ctx.setLineDash([]);
// Own ship: APP-6 friendly frame (circle on the surface, lower half-circle submerged), filled, with a dot
ctx.fillStyle = COL.blue;
ctx.beginPath(); ctx.arc(o.x, o.y, 5, 0, 7); ctx.fill();
ctx.strokeStyle = COL.blue;
ctx.lineWidth = 2;
// Surface ships carry their draft in `depth`: only boats count as subsurface (and only when not surfaced)
const ownSub = CLASSES[s.own.cls].submarine && s.own.depth > 1;
drawSymbol(ctx, o.x, o.y, 'friend', ownSub ? 'subsurface' : 'surface', 8, true);
ctx.beginPath(); ctx.arc(o.x, o.y, 1.8, 0, 7); ctx.fill();
ctx.beginPath(); ctx.moveTo(o.x, o.y); ctx.lineTo(o.x + v.x * 26, o.y - v.y * 26); ctx.stroke();
ctx.lineWidth = 1;
@@ -450,13 +454,12 @@ export class Plot {
ctx.strokeStyle = ctx.fillStyle;
if (live) drawWake(ctx, p.x, p.y, f.heading, f.speedKn);
if (f.cls === 'merchant') {
ctx.save();
ctx.translate(p.x, p.y);
ctx.rotate(wrap360(f.heading) * (Math.PI / 180));
ctx.fillRect(-2, -5, 4, 10);
ctx.restore();
// APP-6 friendly surface frame (circle) with a short course leader; merchants smaller than warships
drawSymbol(ctx, p.x, p.y, 'friend', 'surface', 4, true);
const hv = headingVec(f.heading);
ctx.beginPath(); ctx.moveTo(p.x + hv.x * 4, p.y - hv.y * 4); ctx.lineTo(p.x + hv.x * 10, p.y - hv.y * 10); ctx.stroke();
} else {
drawSymbol(ctx, p.x, p.y, 'friend', f.cls === 'ssk' || f.cls === 'ssn' ? 'subsurface' : 'surface', 6);
drawSymbol(ctx, p.x, p.y, 'friend', f.cls === 'ssk' || f.cls === 'ssn' || f.cls === 'ssc' ? 'subsurface' : 'surface', 6);
const hv = headingVec(f.heading);
ctx.beginPath(); ctx.moveTo(p.x, p.y); ctx.lineTo(p.x + hv.x * 14, p.y - hv.y * 14); ctx.stroke();
const age = s.time - f.reportedAt;
+227
View File
@@ -0,0 +1,227 @@
import { depthAt, headingVec, type Snapshot } from '@tk/shared';
/**
* Surface-search radar PPI as a phosphor tube: returns are written into a persistence
* layer as the sweep passes (sea clutter, rain, coastline from the chart, contacts) and
* fade until the next revolution. Bezel with bearing ring and ship's-head marker on top.
*/
const S = 560; // persistence layer size (px)
const C = S / 2;
const R = 262;
const TAU = Math.PI * 2;
const toRad = (deg: number) => ((deg - 90) * Math.PI) / 180;
export class RadarScope {
private phos = document.createElement('canvas');
private pc: CanvasRenderingContext2D;
sweep = 0;
constructor() {
this.phos.width = S;
this.phos.height = S;
this.pc = this.phos.getContext('2d')!;
this.pc.fillStyle = '#020605';
this.pc.fillRect(0, 0, S, S);
}
/** Advance the sweep and burn new returns into the phosphor. */
update(s: Snapshot | undefined, dt: number, rpm: number, rangeM: number): void {
const pc = this.pc;
pc.save();
pc.beginPath(); pc.arc(C, C, R, 0, TAU); pc.clip();
// Persistence: a full revolution fades the picture to a faint afterglow
pc.fillStyle = `rgba(2,6,5,${Math.min(0.5, dt * (rpm / 60) * 2.2)})`;
pc.fillRect(0, 0, S, S);
const on = !!s?.own.radarOn;
if (!on || !s) {
// Standby: receiver noise only
for (let i = 0; i < 30; i++) {
pc.fillStyle = `rgba(93,202,165,${Math.random() * 0.12})`;
pc.fillRect(Math.random() * S, Math.random() * S, 1, 1);
}
pc.restore();
return;
}
const prev = this.sweep;
this.sweep = (this.sweep + dt * rpm * 6) % 360;
const span = (this.sweep - prev + 360) % 360;
const steps = Math.max(1, Math.ceil(span / 0.6));
const scale = R / rangeM;
for (let k = 0; k < steps; k++) {
const brg = prev + (span * (k + Math.random())) / steps;
const a = toRad(brg);
const ca = Math.cos(a), sa = Math.sin(a);
// Sea clutter: dense close in, growing with sea state; rain adds a speckled band
const clutter = (20 + s.env.seaState * 14) * (6 * 1852 / rangeM);
for (let i = 0; i < 6; i++) {
const rr = Math.pow(Math.random(), 2.2) * clutter;
pc.fillStyle = `rgba(110,220,180,${0.18 + Math.random() * 0.35})`;
pc.fillRect(C + ca * rr, C + sa * rr, 1.4, 1.4);
}
if (s.env.rain) {
for (let i = 0; i < 3; i++) {
const rr = R * (0.25 + Math.random() * 0.5);
pc.fillStyle = `rgba(93,202,165,${Math.random() * 0.22})`;
pc.fillRect(C + ca * rr, C + sa * rr, 2, 2);
}
}
// Coastline and islands from the public chart
if (s.env.seabed && s.env.seabed.kind === 'fjord') {
const v = headingVec(brg);
for (let i = 4; i < 60; i++) {
const r = (i / 60) * rangeM;
if (depthAt(s.env.seabed, s.own.x + v.x * r, s.own.y + v.y * r) < 0) {
pc.fillStyle = `rgba(150,235,200,${0.35 + Math.random() * 0.35})`;
pc.fillRect(C + ca * r * scale, C + sa * r * scale, 2.2, 2.2);
// Radar shadow behind the first land return
break;
}
}
}
// Receiver noise
if (Math.random() < 0.5) {
const rr = Math.random() * R;
pc.fillStyle = `rgba(93,202,165,${Math.random() * 0.18})`;
pc.fillRect(C + ca * rr, C + sa * rr, 1, 1);
}
}
// Contacts painted by this sweep segment
for (const c of s.contacts) {
if (!c.sensors.includes('radar') || c.range === undefined || s.time - c.lastSeen > 3) continue;
if ((c.bearing - prev + 360) % 360 > span) continue;
const r = c.range * scale;
if (r > R) continue;
const a = toRad(c.bearing);
const x = C + Math.cos(a) * r, y = C + Math.sin(a) * r;
// A return is an arc smeared by beam width, deeper for bigger ships
const g = pc.createRadialGradient(x, y, 0, x, y, 7);
g.addColorStop(0, 'rgba(230,255,240,0.95)');
g.addColorStop(0.4, 'rgba(120,235,190,0.6)');
g.addColorStop(1, 'rgba(93,202,165,0)');
pc.fillStyle = g;
pc.beginPath(); pc.arc(x, y, 7, 0, TAU); pc.fill();
pc.strokeStyle = 'rgba(170,250,215,0.7)';
pc.lineWidth = 2.2;
pc.beginPath(); pc.arc(C, C, r, a - 0.025, a + 0.025); pc.stroke();
}
pc.restore();
}
/** Composite the tube, sweep trail, bezel and markings into the station canvas. */
draw(ctx: CanvasRenderingContext2D, w: number, h: number, s: Snapshot | undefined, rangeNm: number, selected?: string): { ox: number; oy: number; k: number } {
ctx.fillStyle = '#030807';
ctx.fillRect(0, 0, w, h);
const size = Math.min(w, h);
const ox = (w - size) / 2;
const oy = (h - size) / 2;
const k = size / S;
const cx = ox + C * k, cy = oy + C * k, rr = R * k;
// Tube glass: dark green radial gradient
const glass = ctx.createRadialGradient(cx, cy, rr * 0.1, cx, cy, rr * 1.05);
glass.addColorStop(0, '#06140f');
glass.addColorStop(1, '#020605');
ctx.fillStyle = glass;
ctx.beginPath(); ctx.arc(cx, cy, rr, 0, TAU); ctx.fill();
ctx.save();
ctx.globalCompositeOperation = 'lighter';
ctx.drawImage(this.phos, ox, oy, size, size);
ctx.restore();
const on = !!s?.own.radarOn;
if (on) {
// Sweep with a glowing trail
const a = toRad(this.sweep);
ctx.save();
ctx.beginPath(); ctx.arc(cx, cy, rr, 0, TAU); ctx.clip();
const trail = ctx.createConicGradient(a - 0.6, cx, cy);
trail.addColorStop(0, 'rgba(93,202,165,0)');
trail.addColorStop(0.095, 'rgba(93,202,165,0.22)');
trail.addColorStop(0.0955, 'rgba(93,202,165,0)');
ctx.fillStyle = trail;
ctx.fillRect(cx - rr, cy - rr, rr * 2, rr * 2);
ctx.strokeStyle = 'rgba(190,255,225,0.95)';
ctx.lineWidth = 1.6;
ctx.shadowColor = 'rgba(120,240,190,0.9)';
ctx.shadowBlur = 8;
ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(cx + Math.cos(a) * rr, cy + Math.sin(a) * rr); ctx.stroke();
ctx.restore();
}
// Range rings with labels
ctx.strokeStyle = 'rgba(93,202,165,0.22)';
ctx.lineWidth = 1;
ctx.font = `${Math.max(9, 11 * k)}px ui-monospace, monospace`;
ctx.fillStyle = 'rgba(159,230,204,0.7)';
ctx.textAlign = 'left';
for (let i = 1; i <= 4; i++) {
ctx.beginPath(); ctx.arc(cx, cy, (rr * i) / 4, 0, TAU); ctx.stroke();
if (i < 4) ctx.fillText(`${(rangeNm * i) / 4}`, cx + 3, cy - (rr * i) / 4 + 11);
}
ctx.beginPath(); ctx.moveTo(cx - rr, cy); ctx.lineTo(cx + rr, cy); ctx.moveTo(cx, cy - rr); ctx.lineTo(cx, cy + rr); ctx.stroke();
// Bezel: bearing ring with 5° ticks, numerals every 30°
ctx.strokeStyle = 'rgba(93,202,165,0.75)';
ctx.lineWidth = 2;
ctx.beginPath(); ctx.arc(cx, cy, rr + 1, 0, TAU); ctx.stroke();
ctx.lineWidth = 1;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
for (let d = 0; d < 360; d += 5) {
const a = toRad(d);
const len = d % 30 === 0 ? 10 : d % 10 === 0 ? 6 : 3;
ctx.beginPath();
ctx.moveTo(cx + Math.cos(a) * (rr + 2), cy + Math.sin(a) * (rr + 2));
ctx.lineTo(cx + Math.cos(a) * (rr + 2 + len * k * 1.2), cy + Math.sin(a) * (rr + 2 + len * k * 1.2));
ctx.stroke();
if (d % 30 === 0) ctx.fillText(String(d).padStart(3, '0'), cx + Math.cos(a) * (rr + 22 * k + 6), cy + Math.sin(a) * (rr + 22 * k + 6));
}
ctx.textBaseline = 'alphabetic';
if (s) {
// Ship's-head marker
const hm = toRad(s.own.heading);
ctx.strokeStyle = 'rgba(232,195,122,0.8)';
ctx.setLineDash([5, 4]);
ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(cx + Math.cos(hm) * rr, cy + Math.sin(hm) * rr); ctx.stroke();
ctx.setLineDash([]);
// ESM strobes: bearing lines of intercepted emitters
for (const c of s.contacts) {
if (!c.sensors.includes('esm') || s.time - c.lastSeen > 300) continue;
const a = toRad(c.bearing);
ctx.strokeStyle = `rgba(240,149,149,${0.75 - (s.time - c.lastSeen) / 500})`;
ctx.setLineDash([6, 4]);
ctx.beginPath(); ctx.moveTo(cx, cy); ctx.lineTo(cx + Math.cos(a) * rr, cy + Math.sin(a) * rr); ctx.stroke();
ctx.setLineDash([]);
}
// Selected radar contact: amber brackets
const sel = s.contacts.find((c) => c.label === selected && c.sensors.includes('radar') && c.range !== undefined);
if (sel && on) {
const r = (sel.range! / (rangeNm * 1852)) * rr;
if (r < rr) {
const a = toRad(sel.bearing);
const x = cx + Math.cos(a) * r, y = cy + Math.sin(a) * r;
ctx.strokeStyle = '#e8c37a';
ctx.strokeRect(x - 9, y - 9, 18, 18);
ctx.fillStyle = '#e8c37a';
ctx.textAlign = 'left';
ctx.fillText(sel.label, x + 12, y - 8);
}
}
}
if (!on) {
ctx.fillStyle = 'rgba(232,195,122,0.85)';
ctx.textAlign = 'center';
ctx.font = `${Math.max(11, 14 * k)}px ui-monospace, monospace`;
ctx.fillText('STANDBY · SENDER AUS', cx, cy - 8);
ctx.fillStyle = 'rgba(159,230,204,0.6)';
ctx.font = `${Math.max(9, 11 * k)}px ui-monospace, monospace`;
ctx.fillText('ESM HÖRT WEITER MIT', cx, cy + 12);
}
// Tube vignette
const vig = ctx.createRadialGradient(cx, cy, rr * 0.7, cx, cy, rr);
vig.addColorStop(0, 'rgba(0,0,0,0)');
vig.addColorStop(1, 'rgba(0,0,0,0.45)');
ctx.fillStyle = vig;
ctx.beginPath(); ctx.arc(cx, cy, rr, 0, TAU); ctx.fill();
return { ox, oy, k };
}
}
export const SCOPE = { S, C, R };
+168
View File
@@ -0,0 +1,168 @@
import * as THREE from 'three';
import type { ClassId, Sighting } from '@tk/shared';
/**
* Low-poly ship models for the 3D sea view. Bow toward +z, waterline at y = 0.
* Groups may carry userData.smoke (puffs animated by the scene), userData.radar
* (a rotating antenna) and objects named 'wake' / 'bow' / 'feather' that follow the speed.
*/
const mat = (color: number, opts: THREE.MeshLambertMaterialParameters = {}) => new THREE.MeshLambertMaterial({ color, flatShading: true, ...opts });
const M = {
hullDark: mat(0x30363b), hullGrey: mat(0x5f686e), red: mat(0x5a2a24), deck: mat(0x4b4e4c), white: mat(0x9aa1a4),
grey: mat(0x6c757a), black: mat(0x1c1f21), cargo: mat(0x5b4334), glass: mat(0x0c1214), sub: mat(0x1f2427),
};
const FOAM = new THREE.MeshBasicMaterial({ color: 0xe6f0f2, transparent: true, opacity: 0.5, depthWrite: false, side: THREE.DoubleSide });
function add(g: THREE.Object3D, geo: THREE.BufferGeometry, m: THREE.Material, x: number, y: number, z: number): THREE.Mesh {
const mesh = new THREE.Mesh(geo, m);
mesh.position.set(x, y, z);
g.add(mesh);
return mesh;
}
const box = (g: THREE.Object3D, w: number, h: number, l: number, x: number, y: number, z: number, m: THREE.Material) => add(g, new THREE.BoxGeometry(w, h, l), m, x, y, z);
const cyl = (g: THREE.Object3D, r: number, h: number, x: number, y: number, z: number, m: THREE.Material, r2 = r) => add(g, new THREE.CylinderGeometry(r, r2, h, 10), m, x, y, z);
/** Hull from a top-view outline (pointed bow, square transom), extruded upward. */
function hull(g: THREE.Object3D, len: number, beam: number, height: number, below: number, m: THREE.Material, boot?: THREE.Material): void {
const s = new THREE.Shape();
const L = len / 2;
const B = beam / 2;
s.moveTo(-B * 0.8, L);
s.lineTo(-B, L * 0.1);
s.quadraticCurveTo(-B, -L * 0.45, 0, -L);
s.quadraticCurveTo(B, -L * 0.45, B, L * 0.1);
s.lineTo(B * 0.8, L);
s.closePath();
const geo = new THREE.ExtrudeGeometry(s, { depth: height, bevelEnabled: false });
geo.rotateX(-Math.PI / 2); // extrusion becomes height; the shape's bow (−y) ends up at +z
add(g, geo, m, 0, -below, 0);
if (boot) {
const bg = new THREE.ExtrudeGeometry(s, { depth: 1.2, bevelEnabled: false });
bg.rotateX(-Math.PI / 2);
bg.scale(1.01, 1, 1.005);
add(g, bg, boot, 0, -0.6, 0);
}
}
/** Deck following the hull outline (pointed bow), slightly inset. */
function deckCap(g: THREE.Object3D, len: number, beam: number, y: number, m: THREE.Material): void {
const s = new THREE.Shape();
const L = len / 2 - 1;
const B = beam / 2 - 0.4;
s.moveTo(-B * 0.8, L);
s.lineTo(-B, L * 0.1);
s.quadraticCurveTo(-B, -L * 0.45, 0, -L);
s.quadraticCurveTo(B, -L * 0.45, B, L * 0.1);
s.lineTo(B * 0.8, L);
s.closePath();
const geo = new THREE.ShapeGeometry(s);
geo.rotateX(-Math.PI / 2);
add(g, geo, m, 0, y + 0.05, 0);
}
/** Funnel smoke: a chain of puffs the scene drifts and fades. */
function smoke(g: THREE.Group, x: number, y: number, z: number, n: number, color = 0x3a3c3e): void {
const puffs: THREE.Mesh[] = [];
for (let i = 0; i < n; i++) {
const p = add(g, new THREE.SphereGeometry(1, 7, 5), new THREE.MeshLambertMaterial({ color, transparent: true, opacity: 0.4, depthWrite: false }), x, y, z);
puffs.push(p);
}
g.userData.smoke = { puffs, origin: new THREE.Vector3(x, y, z) };
}
/** Stern wake wedge and bow wave; scaled by speed in the scene. */
function wake(g: THREE.Group, len: number, beam: number, bowZ: number, sternZ: number): void {
const w = new THREE.Mesh(new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-beam * 0.45, 0.25, 0), new THREE.Vector3(beam * 0.45, 0.25, 0), new THREE.Vector3(len * 0.32, 0.25, -len),
new THREE.Vector3(-beam * 0.45, 0.25, 0), new THREE.Vector3(len * 0.32, 0.25, -len), new THREE.Vector3(-len * 0.32, 0.25, -len),
]), FOAM);
w.name = 'wake';
w.position.z = sternZ;
const b = new THREE.Mesh(new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0.4, 0), new THREE.Vector3(beam * 0.8, 0.4, -beam * 1.6), new THREE.Vector3(-beam * 0.8, 0.4, -beam * 1.6),
]), FOAM);
b.name = 'bow';
b.position.z = bowZ;
g.add(w, b);
}
function merchant(g: THREE.Group): void {
hull(g, 130, 20, 11, 2, M.hullDark, M.red);
box(g, 18, 0.6, 110, 0, 9.2, 4, M.deck);
for (const z of [-22, 2, 26, 46]) box(g, 13, 2.2, 16, 0, 10.6, z, M.cargo);
// Derrick posts and booms between the holds
for (const z of [-10, 14, 36]) {
cyl(g, 0.5, 16, 0, 17, z, M.black);
const boom = cyl(g, 0.25, 14, 0, 14, z + 5, M.black);
boom.rotation.x = 0.9;
}
// Superstructure aft with a bridge window band, funnel behind it
box(g, 17, 8, 15, 0, 13.5, -44, M.white);
box(g, 18, 3, 7, 0, 19, -40, M.white);
box(g, 18.2, 1, 7.2, 0, 19.6, -40, M.glass);
cyl(g, 2.6, 9, 0, 21, -52, M.black, 3);
smoke(g, 0, 26, -52, 7);
wake(g, 200, 20, 64, -64);
}
function warship(g: THREE.Group, len: number, beam: number, frigate: boolean): void {
const k = len / 125;
hull(g, len, beam, 7.5, 1.5, M.hullGrey, M.black);
deckCap(g, len, beam, 6, M.deck);
// Gun forward, bridge, mast with a turning radar, funnel, hangar aft
cyl(g, 2.2 * k, 2.4, 0, 7.6, 40 * k, M.grey, 2.6 * k);
const barrel = cyl(g, 0.25, 6 * k, 0, 8.2, 44 * k, M.grey);
barrel.rotation.x = Math.PI / 2 - 0.15;
box(g, beam * 0.75, 7, 20 * k, 0, 9.5, 18 * k, M.grey);
box(g, beam * 0.7, 3, 8 * k, 0, 14.5, 22 * k, M.grey);
box(g, beam * 0.72, 0.9, 1, 0, 15, 26 * k, M.glass);
cyl(g, 0.45, 18 * k, 0, 24 * k, 12 * k, M.black, 0.7);
box(g, 7 * k, 0.4, 0.4, 0, 28 * k, 12 * k, M.black);
const radar = box(g, 5 * k, 1.6, 0.4, 0, 32 * k, 12 * k, M.black);
g.userData.radar = radar;
box(g, beam * 0.55, 7, 9 * k, 0, 9.5, -4 * k, M.grey).rotation.x = -0.12;
smoke(g, 0, 14, -6 * k, 5, 0x4a4c4e);
if (frigate) {
box(g, beam * 0.8, 6, 16 * k, 0, 9, -26 * k, M.grey);
box(g, beam * 0.86, 0.3, 22 * k, 0, 6.6, -48 * k, M.deck);
} else box(g, beam * 0.5, 3, 10 * k, 0, 8, -24 * k, M.grey);
wake(g, frigate ? 190 : 140, beam, len / 2, -len / 2);
}
function surfacedBoat(g: THREE.Group, len: number): void {
const body = cyl(g, 4.2, len, 0, -2.4, 0, M.sub);
body.rotation.x = Math.PI / 2;
const bow = add(g, new THREE.SphereGeometry(4.2, 10, 8), M.sub, 0, -2.4, len / 2);
bow.scale.set(1, 1, 1.6);
box(g, 3, 7.5, 11, 0, 4, len * 0.12, M.sub);
box(g, 7, 0.5, 2, 0, 5, len * 0.16, M.sub);
wake(g, 90, 8, len / 2 + 4, -len / 2);
}
/** Model of a ship class seen on the surface. */
export function shipModel(cls: ClassId): THREE.Group {
const g = new THREE.Group();
if (cls === 'merchant') merchant(g);
else if (cls === 'ffg') warship(g, 125, 14, true);
else if (cls === 'kor') warship(g, 90, 11, false);
else surfacedBoat(g, cls === 'ssn' ? 100 : cls === 'ssc' ? 45 : 70);
return g;
}
/** What a lookout actually sees of a submerged boat: a periscope with its feather, or a snorkel with exhaust haze. */
export function sightingModel(what: Sighting, cls: ClassId): THREE.Group {
if (what === 'surfaced') return shipModel(cls === 'merchant' || cls === 'ffg' || cls === 'kor' ? 'ssk' : cls);
const g = new THREE.Group();
const head = cyl(g, what === 'snorkel' ? 0.6 : 0.22, what === 'snorkel' ? 2.2 : 3.4, 0, 1.3, 0, M.black);
head.name = 'head';
// Feather: a narrow white V of spray streaming aft of the mast
const f = new THREE.Mesh(new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0.35, 0.8), new THREE.Vector3(2.4, 0.3, -14), new THREE.Vector3(-2.4, 0.3, -14),
]), FOAM.clone());
f.name = 'feather';
g.add(f);
add(g, new THREE.CylinderGeometry(0.4, 1.6, 0.6, 10, 1, true), FOAM, 0, 0.3, 0);
if (what === 'snorkel') smoke(g, 0, 2.6, 0, 8, 0x6d7275);
return g;
}
+101
View File
@@ -0,0 +1,101 @@
/** GLSL for the 3D sea view: a multi-wave ocean with whitecaps and glitter, and a sky with clouds, sun and moon. */
const WAVES = `
uniform float uTime; uniform float uAmp;
float wave(vec2 p, vec2 d, float f, float s) { return sin(dot(p, normalize(d)) * f + uTime * s); }
float height(vec2 p) {
return uAmp * (0.42 * wave(p, vec2(0.8, 0.6), 0.032, 0.9)
+ 0.26 * wave(p, vec2(-0.4, 0.9), 0.071, 1.45)
+ 0.16 * wave(p, vec2(0.95, -0.3), 0.15, 2.2)
+ 0.10 * wave(p, vec2(0.2, 1.0), 0.29, 3.1)
+ 0.06 * wave(p, vec2(-0.85, -0.5), 0.53, 4.3));
}`;
export const OCEAN_VERT = `${WAVES}
varying vec3 vPos; varying vec3 vNormal; varying float vH;
void main() {
vec3 p = position;
vec2 xz = (modelMatrix * vec4(p, 1.0)).xz;
float h = height(xz);
p.z += h;
float e = 0.6;
vNormal = normalize(vec3(-(height(xz + vec2(e, 0.0)) - h) / e, 1.0, -(height(xz + vec2(0.0, e)) - h) / e));
vH = h / max(uAmp, 0.01);
vec4 wp = modelMatrix * vec4(p, 1.0);
vPos = wp.xyz;
gl_Position = projectionMatrix * viewMatrix * wp;
}`;
const NOISE = `
float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
float noise(vec2 p) {
vec2 i = floor(p); vec2 f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f);
return mix(mix(hash(i), hash(i + vec2(1, 0)), u.x), mix(hash(i + vec2(0, 1)), hash(i + vec2(1, 1)), u.x), u.y);
}
float fbm(vec2 p) { float v = 0.0; float a = 0.5; for (int i = 0; i < 4; i++) { v += a * noise(p); p *= 2.03; a *= 0.5; } return v; }`;
export const OCEAN_FRAG = `${NOISE}
uniform float uTime;
uniform vec3 uDeep; uniform vec3 uSky; uniform vec3 uSun; uniform vec3 uMoon; uniform vec3 uFog;
uniform float uFogDensity; uniform float uLight; uniform float uFoam; uniform float uSunUp;
varying vec3 vPos; varying vec3 vNormal; varying float vH;
void main() {
vec3 view = normalize(cameraPosition - vPos);
vec3 n = normalize(vNormal);
// Capillary ripples: high-frequency normal detail, fading with distance (gives the eye a sense of scale)
float dist = length(cameraPosition - vPos);
float near = 1.0 - smoothstep(60.0, 900.0, dist);
if (near > 0.0) {
vec2 q = vPos.xz * 0.9 + vec2(uTime * 0.6, uTime * 0.35);
vec2 rip = vec2(noise(q) - 0.5, noise(q * 1.7 + 4.0) - 0.5);
n = normalize(n + vec3(rip.x, 0.0, rip.y) * 0.35 * near);
}
float fres = pow(1.0 - max(dot(n, view), 0.0), 4.0);
vec3 col = mix(uDeep, uSky, clamp(fres * 0.65, 0.0, 1.0));
// Subsurface green on wave flanks facing the light
col += vec3(0.02, 0.07, 0.06) * max(0.0, vH) * uLight;
vec3 r = reflect(-view, n);
// Sun glitter: a sharp core and a broad sheen, a long path when the sun is low
float sd = max(dot(r, normalize(uSun)), 0.0);
col += vec3(1.0, 0.92, 0.8) * (pow(sd, 400.0) * 1.4 + pow(sd, 30.0) * 0.12) * uSunUp;
// Moonlight path at night
float md = max(dot(r, normalize(uMoon)), 0.0);
col += vec3(0.75, 0.8, 0.9) * pow(md, 160.0) * (1.0 - uSunUp) * 0.9;
col *= 0.35 + 0.65 * uLight;
// Whitecaps on the crests as the sea builds, streaked by the wind
if (uFoam > 0.0 && vH > 0.1) {
float streak = fbm(vPos.xz * vec2(0.08, 0.025) + vec2(uTime * 0.05, 0.0));
float foam = smoothstep(0.55, 0.95, vH + streak * 0.6) * uFoam;
col = mix(col, vec3(0.86, 0.9, 0.92) * (0.25 + 0.75 * uLight), foam * 0.8);
}
float d = length(cameraPosition - vPos);
float fog = 1.0 - exp(-pow(d * uFogDensity, 2.0));
gl_FragColor = vec4(mix(col, uFog, fog), 1.0);
#include <colorspace_fragment>
}`;
export const SKY_VERT = `varying vec3 vDir; void main() { vDir = normalize(position); gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.0); }`;
export const SKY_FRAG = `${NOISE}
uniform vec3 uTop; uniform vec3 uHorizon; uniform vec3 uSun; uniform vec3 uMoon;
uniform float uLight; uniform float uCloud; uniform float uTime; uniform float uSunUp;
varying vec3 vDir;
void main() {
vec3 d = normalize(vDir);
float h = clamp(d.y * 3.5, 0.0, 1.0);
vec3 col = mix(uHorizon, uTop, pow(h, 0.7));
// Sun disc and glow, moon disc
float s = max(dot(d, normalize(uSun)), 0.0);
col += vec3(1.0, 0.85, 0.6) * (pow(s, 900.0) * 3.0 + pow(s, 12.0) * 0.25) * uSunUp;
float m = max(dot(d, normalize(uMoon)), 0.0);
col += vec3(0.85, 0.88, 0.95) * smoothstep(0.9993, 0.9996, m) * (1.0 - uSunUp);
// Clouds: drifting fbm on a plane above, thinning toward the horizon
if (d.y > 0.0) {
vec2 uv = d.xz / (d.y + 0.08) * 1.6 + vec2(uTime * 0.004, uTime * 0.002);
float c = smoothstep(1.0 - uCloud, 1.15 - uCloud * 0.6, fbm(uv));
vec3 cloud = mix(vec3(0.55, 0.6, 0.63), vec3(0.92, 0.93, 0.94), fbm(uv * 1.7 + 3.0)) * (0.12 + 0.88 * uLight);
col = mix(col, cloud, c * smoothstep(0.0, 0.18, d.y) * 0.9);
}
gl_FragColor = vec4(col, 1.0);
#include <colorspace_fragment>
}`;
+21
View File
@@ -39,3 +39,24 @@ export function moverNow(p: { x: number; y: number; heading: number; speedKn?: n
return { x: p.x + v.x * d, y: p.y + v.y * d };
}
const steady = new Map<string, { b: number; at: number }>();
/**
* Display bearing for lists: raw sonar bearings jitter by design (noise), so lists show an
* exponentially smoothed track bearing (≈ 8 s). Big jumps (new contact, towed-array side
* change) reset it at once. TMA, waterfall and history keep using the raw measurements.
*/
export function steadyBearing(key: string, bearing: number, at: number, tauS = 8): number {
const p = steady.get(key);
if (!p || Math.abs(angleDiff(p.b, bearing)) > 15 || at < p.at) {
steady.set(key, { b: bearing, at });
return bearing;
}
if (at > p.at) {
const k = 1 - Math.exp(-(at - p.at) / tauS);
p.b = wrap360(p.b + angleDiff(p.b, bearing) * k);
p.at = at;
}
return p.b;
}
+90
View File
@@ -0,0 +1,90 @@
import { esc } from './format.js';
import { onTap } from './touch.js';
/**
* Sortable column headers and filter chips for the console lists. State lives per list id
* in localStorage, so a chosen order survives snapshots, station changes and reloads.
* Lists are rebuilt every snapshot, so clicks are delegated on the container (onTap).
*/
export interface SortState { key: string; dir: 1 | -1 }
type Value = number | string | undefined;
const KEY = (id: string) => `tk_sort_${id}`;
const FKEY = (id: string) => `tk_filter_${id}`;
export function getSort(id: string, def: SortState): SortState {
try {
const v = JSON.parse(localStorage.getItem(KEY(id)) ?? 'null') as SortState | null;
return v && typeof v.key === 'string' ? v : def;
} catch {
return def;
}
}
/** Click on a header: first click sorts by it, the next one reverses. */
export function toggleSort(id: string, key: string, def: SortState, firstDir: 1 | -1 = 1): void {
const cur = getSort(id, def);
localStorage.setItem(KEY(id), JSON.stringify(cur.key === key ? { key, dir: -cur.dir } : { key, dir: firstDir }));
}
/** A header cell; the active column shows ▲ or ▼. */
export function sortHead(id: string, key: string, label: string, def: SortState): string {
const s = getSort(id, def);
const arrow = s.key === key ? (s.dir > 0 ? ' ▲' : ' ▼') : '';
return `<span class="sorth${s.key === key ? ' on' : ''}" data-sort="${esc(key)}" title="Sortieren">${esc(label)}${arrow}</span>`;
}
/** Sort rows by the active column; missing values always go last, ties keep the previous order. */
export function sortRows<T>(rows: T[], id: string, def: SortState, get: Record<string, (r: T) => Value>): T[] {
const s = getSort(id, def);
const f = get[s.key] ?? get[def.key]!;
return rows
.map((r, i) => ({ r, i, v: f(r) }))
.sort((a, b) => {
if (a.v === undefined || b.v === undefined) return a.v === b.v ? a.i - b.i : a.v === undefined ? 1 : -1;
const c = typeof a.v === 'number' && typeof b.v === 'number' ? a.v - b.v : String(a.v).localeCompare(String(b.v), 'de', { numeric: true });
return c * s.dir || a.i - b.i;
})
.map((x) => x.r);
}
/** Active filter chips of a list (all chips off = no filtering). */
export function getFilters(id: string): Set<string> {
try {
return new Set(JSON.parse(localStorage.getItem(FKEY(id)) ?? '[]') as string[]);
} catch {
return new Set();
}
}
export function toggleFilter(id: string, chip: string, exclusive?: string[]): void {
const f = getFilters(id);
if (f.has(chip)) f.delete(chip);
else {
// Chips in an exclusive group replace each other
if (exclusive?.includes(chip)) for (const x of exclusive) f.delete(x);
f.add(chip);
}
localStorage.setItem(FKEY(id), JSON.stringify([...f]));
}
/** A row of filter chips. */
export function filterChips(id: string, chips: { key: string; label: string; title?: string }[]): string {
const f = getFilters(id);
return `<div class="chips">${chips.map((c) => `<button class="chip${f.has(c.key) ? ' on' : ''}" data-chip="${esc(c.key)}"${c.title ? ` title="${esc(c.title)}"` : ''}>${esc(c.label)}</button>`).join('')}</div>`;
}
/** Wire header and chip clicks of a container once; `redraw` repaints right away. */
export function bindSortable(el: HTMLElement, id: string, def: SortState, redraw: () => void, opts: { firstDir?: Record<string, 1 | -1>; exclusive?: string[] } = {}): void {
if (el.dataset.sortBound) return;
el.dataset.sortBound = '1';
onTap(el, '[data-sort]', (h) => {
toggleSort(id, h.dataset.sort!, def, opts.firstDir?.[h.dataset.sort!] ?? 1);
redraw();
});
onTap(el, '[data-chip]', (c) => {
toggleFilter(id, c.dataset.chip!, opts.exclusive);
redraw();
});
}
+22
View File
@@ -22,3 +22,25 @@ export function touchable(el: HTMLElement): void {
el.addEventListener('pointerup', cancel);
el.addEventListener('pointercancel', cancel);
}
/**
* Delegated tap for lists that are rebuilt on every snapshot: the target is remembered on
* pointerdown and the action fires on release, so a row replaced mid-tap still counts and a
* scroll gesture (pointercancel or movement) does not trigger it.
*/
export function onTap(el: HTMLElement, selector: string, fn: (target: HTMLElement) => void): void {
let down: { target: HTMLElement; x: number; y: number; id: number } | undefined;
el.addEventListener('pointerdown', (e) => {
if (e.button !== 0) return;
const target = (e.target as HTMLElement).closest<HTMLElement>(selector);
down = target ? { target, x: e.clientX, y: e.clientY, id: e.pointerId } : undefined;
});
el.addEventListener('pointercancel', () => (down = undefined));
// On the window: the original row may already be detached when the finger lifts
window.addEventListener('pointerup', (e) => {
const d = down;
down = undefined;
if (!d || e.pointerId !== d.id || Math.hypot(e.clientX - d.x, e.clientY - d.y) > 12) return;
fn(d.target);
});
}
+3 -3
View File
@@ -1,3 +1,4 @@
import { onTap } from './touch.js';
import { bladeCount, marksCount, rankClasses, type ClassChoice } from '@tk/shared';
import { net } from '../net.js';
import { store } from '../store.js';
@@ -30,10 +31,9 @@ export function renderVerdict(el: HTMLElement): void {
<div class="steps" style="margin-top:6px">${CHOICES.map((ch) => `<button data-cls="${ch}" class="${c.assigned === ch || (!c.assigned && ch === 'unknown') ? 'on' : ''}">${CHOICE_LABEL[ch]}</button>`).join('')}</div>`;
if (!el.dataset.bound) {
el.dataset.bound = '1';
el.addEventListener('mousedown', (e) => {
const b = (e.target as HTMLElement).closest<HTMLElement>('[data-cls]');
onTap(el, '[data-cls]', (b) => {
const label = store.selected;
if (b && label) net.send({ t: 'classify', label, choice: b.dataset.cls as ClassChoice });
if (label) net.send({ t: 'classify', label, choice: b.dataset.cls as ClassChoice });
});
}
}
+20 -5
View File
@@ -66,7 +66,7 @@ export class Waterfall {
const pl = 36;
const pt = 18;
const pw = w - pl - 8;
const ph = height - pt - 42;
const ph = height - pt - 54;
ctx.fillStyle = COL.bg;
ctx.fillRect(0, 0, w, height);
ctx.imageSmoothingEnabled = false;
@@ -103,14 +103,29 @@ export class Waterfall {
ctx.fillText('NOCH KEIN KONTAKT – LANGSAM FAHREN UND HORCHEN', pl + pw / 2, pt + ph / 2 - 8);
ctx.fillText('SCHIFFE ERSCHEINEN ALS HELLE SENKRECHTE SPUREN', pl + pw / 2, pt + ph / 2 + 8);
}
// Labels in up to three rows; what does not fit is summed up as "+N" in a fourth row
const rowEnd = [-1e9, -1e9, -1e9];
for (const c of shown) {
const overflow: { x: number; n: number }[] = [];
// The selected contact is placed first so it always gets a label
const ordered = [...shown].sort((a, b) => (b.label === selected ? 1 : 0) - (a.label === selected ? 1 : 0));
const placed: { c: typeof shown[number]; x: number; row: number }[] = [];
for (const c of ordered) {
const x = pl + (c.bearing / 360) * pw;
const row = rowEnd.findIndex((end) => Math.abs(x - end) > 26);
if (row < 0) {
const near = overflow.find((o) => Math.abs(o.x - x) < 30);
if (near) near.n++;
else overflow.push({ x, n: 1 });
} else {
rowEnd[row] = x;
placed.push({ c, x, row });
}
}
ctx.fillStyle = COL.dim;
for (const o of overflow) ctx.fillText(`+${o.n}`, o.x, pt + ph + 13 + 3 * 12);
for (const { c, x, row } of placed) {
const sel = c.label === selected;
ctx.fillStyle = sel ? COL.amber : COL.g2;
let row = rowEnd.findIndex((end) => x - end > 26);
if (row < 0) row = 2;
rowEnd[row] = x;
ctx.fillText(c.label, x, pt + ph + 13 + row * 12);
if (sel) {
ctx.strokeStyle = COL.amber;
+69
View File
@@ -0,0 +1,69 @@
import { existsSync, mkdirSync, readdirSync, statSync, unlinkSync } from 'node:fs';
import { join, resolve } from 'node:path';
import type { DatabaseSync } from 'node:sqlite';
import { log } from './log.js';
/**
* Database backups: a consistent copy via `VACUUM INTO` (safe while the server runs),
* every BACKUP_EVERY_H hours into BACKUP_DIR, keeping the newest BACKUP_KEEP files.
* Disabled when BACKUP_DIR is not set.
*/
export class Backups {
private timer?: ReturnType<typeof setInterval>;
constructor(
private db: DatabaseSync,
private dir = process.env.BACKUP_DIR,
private keep = Math.max(1, Number(process.env.BACKUP_KEEP ?? 7)),
private everyH = Math.max(1, Number(process.env.BACKUP_EVERY_H ?? 24)),
) {}
get enabled(): boolean {
return !!this.dir;
}
/** Files of this backup set, newest first. */
list(): { file: string; at: number; bytes: number }[] {
if (!this.dir || !existsSync(this.dir)) return [];
return readdirSync(this.dir)
.filter((f) => /^tiefenkontakt-\d{8}-\d{6}\.db$/.test(f))
.map((f) => {
const st = statSync(join(this.dir!, f));
return { file: f, at: st.mtimeMs, bytes: st.size };
})
.sort((a, b) => b.file.localeCompare(a.file));
}
/** Write one backup now and prune old ones. Returns the file name. */
run(now = new Date()): string | undefined {
if (!this.dir) return undefined;
mkdirSync(this.dir, { recursive: true });
const p = (n: number) => String(n).padStart(2, '0');
const stamp = `${now.getUTCFullYear()}${p(now.getUTCMonth() + 1)}${p(now.getUTCDate())}-${p(now.getUTCHours())}${p(now.getUTCMinutes())}${p(now.getUTCSeconds())}`;
const name = `tiefenkontakt-${stamp}.db`;
const target = resolve(this.dir, name);
if (existsSync(target)) return name;
// The path is built by us from digits only; quotes are doubled for SQL anyway
this.db.exec(`VACUUM INTO '${target.replaceAll("'", "''")}'`);
for (const old of this.list().slice(this.keep)) unlinkSync(join(this.dir, old.file));
return name;
}
/** Back up on start if the newest copy is older than the interval, then check hourly. */
start(): void {
if (!this.dir) return;
const due = () => {
const newest = this.list()[0];
if (!newest || Date.now() - newest.at > this.everyH * 3_600_000) {
try {
log('info', 'Backup geschrieben', { file: this.run() });
} catch (e) {
log('error', 'Backup fehlgeschlagen', { error: (e as Error).message });
}
}
};
due();
this.timer = setInterval(due, 3_600_000);
this.timer.unref();
}
}
+5 -3
View File
@@ -22,9 +22,11 @@ import {
export type BotSkill = 'leicht' | 'normal' | 'schwer';
export const SKILL = {
leicht: { think: 4, tmaQuality: 70, salvo: 1, pack: false, reactS: 40 },
normal: { think: 2, tmaQuality: 55, salvo: 2, pack: true, reactS: 15 },
schwer: { think: 1, tmaQuality: 40, salvo: 2, pack: true, reactS: 5 },
// Submarines: TMA quality before a shot, salvo size, pack reports.
// Escorts: aim error of rockets/helo torpedoes (m), use of dipping sonar and patrol aircraft, fire rate.
leicht: { think: 4, subThink: 4, tmaQuality: 55, salvo: 2, pack: true, reactS: 40, aimErr: 500, air: true, fireRate: 0.67, pingDuty: 120 },
normal: { think: 2, subThink: 2, tmaQuality: 55, salvo: 2, pack: true, reactS: 15, aimErr: 250, air: true, fireRate: 1, pingDuty: 120 },
schwer: { think: 1, subThink: 2, tmaQuality: 55, salvo: 2, pack: true, reactS: 5, aimErr: 0, air: true, fireRate: 2, pingDuty: 240 },
} as const;
export interface BotMemory {
+13 -8
View File
@@ -1,4 +1,5 @@
import {
isEscort,
KN,
bearing,
depthAt,
@@ -25,7 +26,7 @@ const PROSECUTE_MAX = 16_000; // m from the convoy: beyond that, return to the s
/** Escorts alternate between the starboard (+1) and port (-1) flank of the convoy. */
function flankOf(w: World, s: Ship): number {
const escorts = w.ships.filter((x) => x.team === s.team && x.cls === 'ffg').map((x) => x.id).sort();
const escorts = w.ships.filter((x) => x.team === s.team && isEscort(x.cls)).map((x) => x.id).sort();
return escorts.indexOf(s.id) % 2 === 0 ? 1 : -1;
}
@@ -89,7 +90,7 @@ export function thinkFrigate(w: World, m: BotMemory, s: Ship, skill: BotSkill):
const target = subs[0];
const leadB = target ? target.bearing : m.lead && now - m.lead.t < 900 ? m.lead.b : undefined;
const prosecuting = leadB !== undefined && distance(s.pos, center) < PROSECUTE_MAX;
s.activeSonar = now < m.alertUntil || prosecuting || now % 600 < 120;
s.activeSonar = now < m.alertUntil || prosecuting || now % 600 < SKILL[skill].pingDuty;
if (prosecuting) {
m.alertUntil = Math.max(m.alertUntil, now + 300);
@@ -102,10 +103,10 @@ export function thinkFrigate(w: World, m: BotMemory, s: Ship, skill: BotSkill):
const drop = { x: s.pos.x + v.x * Math.min(est, 20_000), y: s.pos.y + v.y * Math.min(est, 20_000) };
// Helicopter: alternate dipping sonar and buoys along the bearing
const deep = (s.btLayer ?? 0) > 0;
if (Math.floor(now / 400) % 2 === 0) sendDip(w, s, drop, deep && Math.floor(now / 800) % 2 === 1);
if (SKILL[skill].air && Math.floor(now / 400) % 2 === 0) sendDip(w, s, drop, deep && Math.floor(now / 800) % 2 === 1);
else if (w.air?.buoys.every((b) => distance(b.pos, drop) > 3000)) sendBuoy(w, s, drop, deep);
// A radio/transient lead far out: ask the patrol aircraft for a buoy line across it
if (!target && m.lead && now - m.lead.t < 300) {
if (SKILL[skill].air && !target && m.lead && now - m.lead.t < 300) {
const lv = headingVec(m.lead.b);
callMpa(w, s, { x: m.lead.x + lv.x * 15_000, y: m.lead.y + lv.y * 15_000 }, m.lead.b);
}
@@ -129,11 +130,15 @@ export function thinkFrigate(w: World, m: BotMemory, s: Ship, skill: BotSkill):
s.order.speedKn = distance(s.pos, station) > 4000 ? 18 : 12;
}
if (now - m.lastShot < ROCKET_COOLDOWN / (skill === 'schwer' ? 1.5 : 1)) return;
if (now - m.lastShot < ROCKET_COOLDOWN / SKILL[skill].fireRate) return;
const friends = w.ships.filter((f) => f.team === s.team && f.alive);
// Weaker captains aim worse
const err = SKILL[skill].aimErr;
const scatter = (p: Vec2): Vec2 => (err ? { x: p.x + w.rng.gauss(0, err), y: p.y + w.rng.gauss(0, err) } : p);
// A lightweight torpedo searches a wide circle: never fire near own ships
const shoot = (p: Vec2) => {
if (friends.some((f) => distance(f.pos, p) < 3000)) return false;
const shoot = (aim: Vec2) => {
if (friends.some((f) => distance(f.pos, aim) < 3000)) return false;
const p = scatter(aim);
if (launchAswRocket(w, s, p) !== true) return false;
m.lastShot = now;
return true;
@@ -149,7 +154,7 @@ export function thinkFrigate(w: World, m: BotMemory, s: Ship, skill: BotSkill):
const fix = { x: at.x + v.x * echo.r!, y: at.y + v.y * echo.r! };
if (shoot(fix)) return;
// Out of rocket range or rockets gone: the helicopter delivers
if (!friends.some((f) => distance(f.pos, fix) < 3000) && sendHeloTorpedo(w, s, fix) === true) {
if (!friends.some((f) => distance(f.pos, fix) < 3000) && sendHeloTorpedo(w, s, scatter(fix)) === true) {
m.lastShot = now;
return;
}
+3 -2
View File
@@ -56,8 +56,9 @@ export class BotCrew {
recordTrack(m, ship, w.time);
this.readEvents(w, m);
if (w.time < m.nextThink) continue;
m.nextThink = w.time + k.think;
if (CLASSES[ship.cls].submarine) thinkSub(w, m, ship, this.skill, this.pack);
const sub = CLASSES[ship.cls].submarine;
m.nextThink = w.time + (sub ? k.subThink : k.think);
if (sub) thinkSub(w, m, ship, this.skill, this.pack);
else thinkFrigate(w, m, ship, this.skill);
}
this.pack = this.pack.filter((r) => w.time - r.t < 3600);
+16
View File
@@ -0,0 +1,16 @@
/**
* Real client address behind reverse proxies. Each proxy appends the address it saw to
* X-Forwarded-For, so only the rightmost entries are trustworthy: with TRUST_PROXY=n
* (number of proxies in front, `1` for a single nginx) the n-th entry from the right is
* the client. Entries further left are whatever the client sent and are ignored.
*/
export function clientIpFrom(forwarded: string | string[] | undefined, remote: string | undefined, trustProxy = process.env.TRUST_PROXY): string {
const hops = Number(trustProxy ?? 0);
const header = Array.isArray(forwarded) ? forwarded.join(',') : forwarded;
if (hops > 0 && header) {
const list = header.split(',').map((s) => s.trim()).filter(Boolean);
const ip = list[list.length - hops];
if (ip) return ip;
}
return remote ?? '?';
}
+61 -26
View File
@@ -8,9 +8,15 @@ import { AuthStore, RateLimiter, parseCookies, type User } from './auth.js';
import { parseClientMsg } from './input.js';
import { Lobby } from './lobby.js';
import { MatchStore } from './match-store.js';
import { createMailer } from './mailer.js';
import { createMailer, SmtpMailer } from './mailer.js';
import { resetMail, verifyMail } from './mail-templates.js';
import { handleAdmin } from './admin.js';
import { ModerationStore } from './moderation.js';
import { Backups } from './backup.js';
import { Ratings } from './rating.js';
import { log } from './log.js';
import { clientIpFrom } from './client-ip.js';
import { metrics } from './metrics.js';
import { StatsStore, rankFor, userIdOf } from './stats.js';
import type { Conn } from './match.js';
@@ -24,13 +30,16 @@ export const lobby = new Lobby();
const store = new MatchStore();
const stats = new StatsStore(auth.db);
const mod = new ModerationStore(auth.db);
const backups = new Backups(auth.db);
const ratings = new Ratings(auth.db);
backups.start();
lobby.onReport = (conn, m, from, reason) => {
const s = m.senderOf(from);
if (!s) return 'Absender nicht gefunden';
if (s.playerId === conn.playerId) return 'Du kannst dich nicht selbst melden';
const reported = m.slots.find((x) => x.playerId === s.playerId)?.callsign ?? from;
const fresh = mod.report({ reporter: conn.callsign, reported, reportedId: s.playerId, matchId: m.id, reason, evidence: s.evidence });
console.log(`[Meldung] ${conn.callsign} meldet ${reported}: ${reason}`);
log('info', 'Meldung', { reporter: conn.callsign, reported, reason });
return fresh ? undefined : 'Bereits gemeldet';
};
const LESSON_STEP: Record<string, string> = { klassifizieren: 'l1', tma: 'l2', angriff: 'l3', ujagd: 'l4' };
@@ -44,18 +53,19 @@ lobby.onFinish = (m, d) => {
return;
}
stats.record(d, m.settings.mission, m.settings.timeOfDay);
ratings.update(d);
};
lobby.onLessonDone = (playerId, lesson) => {
const uid = userIdOf(playerId);
if (uid !== undefined && LESSON_STEP[lesson]) stats.complete(uid, LESSON_STEP[lesson]!);
};
const restored = store.loadAll(lobby);
if (restored) console.log(`${restored} laufende Partie(n) wiederhergestellt`);
if (restored) log('info', 'Partien wiederhergestellt', { count: restored });
lobby.onDrop = (m) => store.remove(m.id);
setInterval(() => {
lobby.prune();
store.saveAll(lobby);
}, 5000).unref();
// Running matches are saved every MATCH_SAVE_S seconds (raise it on SD cards to save writes)
const SAVE_S = Math.max(2, Number(process.env.MATCH_SAVE_S ?? 5));
setInterval(() => lobby.prune(), 5000).unref();
setInterval(() => store.saveAll(lobby), SAVE_S * 1000).unref();
for (const sig of ['SIGINT', 'SIGTERM'] as const) {
process.on(sig, () => {
store.saveAll(lobby);
@@ -64,15 +74,17 @@ for (const sig of ['SIGINT', 'SIGTERM'] as const) {
}
const authLimiter = new RateLimiter(10, 60_000);
const mailer = createMailer();
if (mailer instanceof SmtpMailer) {
const c = mailer.cfg;
log('info', 'Mailversand über SMTP', { host: c.host, port: c.port, security: c.security, from: c.from, login: c.user ? 'ja' : 'nein' });
} else log('info', 'Kein Mailserver eingestellt: Bestätigungs- und Reset-Links stehen im Log');
const PUBLIC_URL = process.env.PUBLIC_URL ?? 'http://localhost:5173';
const HOUR = 3_600_000;
async function sendVerify(userId: number, email: string): Promise<void> {
async function sendVerify(userId: number, email: string, callsign: string): Promise<void> {
const t = auth.createToken(userId, 'verify', 48 * HOUR);
await mailer.send({
to: email, subject: 'Tiefenkontakt: E-Mail bestätigen / verify your email',
text: `Willkommen an Bord. Bitte bestätige deine Adresse (der Link gilt 48 Stunden).\nWelcome aboard. Please verify your address (the link is valid for 48 hours).\n\n${PUBLIC_URL}/#verify=${t}\n`,
});
await mailer.send(verifyMail(email, callsign, `${PUBLIC_URL}/#verify=${t}`));
log('info', 'Bestätigungsmail gesendet', { userId });
}
function json(res: ServerResponse, status: number, body: unknown, cookie?: string): void {
@@ -104,6 +116,24 @@ async function handleApi(req: IncomingMessage, res: ServerResponse): Promise<voi
const token = parseCookies(req.headers.cookie)[COOKIE];
const ip = clientIp(req);
if (req.url === '/api/health') return json(res, 200, { ok: true });
if (req.url?.startsWith('/api/metrics')) {
// METRICS_TOKEN as bearer token (for a monitoring system), or a moderator session
const bearer = req.headers.authorization?.replace(/^Bearer /, '');
const ok = (!!process.env.METRICS_TOKEN && bearer === process.env.METRICS_TOKEN) || mod.isAdmin(auth.userForToken(token)?.callsign);
if (!ok) return json(res, 403, { error: 'Nur für Moderatoren' });
const all = lobby.allMatches();
const extra = {
matchesRunning: all.filter((m) => m.state === 'running').length,
matchesLobby: all.filter((m) => m.state === 'lobby').length,
playersConnected: all.reduce((a, m) => a + m.connected, 0),
connections: wss.clients.size,
};
if (req.url.includes('format=prom')) {
res.writeHead(200, { 'content-type': 'text/plain; version=0.0.4' }).end(metrics.prometheus(extra));
return;
}
return json(res, 200, metrics.snapshot(extra));
}
if (req.url === '/api/me' && req.method === 'GET') {
const u = auth.userForToken(token);
return u ? json(res, 200, { ...publicUser(u), email: u.email, verified: auth.isVerified(u.id), admin: mod.isAdmin(u.callsign) }) : json(res, 401, { error: 'Nicht angemeldet' });
@@ -118,6 +148,10 @@ async function handleApi(req: IncomingMessage, res: ServerResponse): Promise<voi
return json(res, 400, { error: 'Ungültige Anfrage' });
}
}
if (req.url === '/api/admin/backup' && req.method === 'POST') {
if (!backups.enabled) return json(res, 400, { error: 'BACKUP_DIR ist nicht gesetzt' });
return json(res, 200, { file: backups.run(), backups: backups.list() });
}
return handleAdmin(req, body, (status, b) => json(res, status, b), lobby, mod);
}
if (req.url === '/api/leaderboard' && req.method === 'GET') return json(res, 200, stats.leaderboard());
@@ -125,7 +159,7 @@ async function handleApi(req: IncomingMessage, res: ServerResponse): Promise<voi
if (req.url === '/api/stats' && req.method === 'GET') {
const u = auth.userForToken(token);
if (!u) return json(res, 401, { error: 'Nur mit Konto' });
return json(res, 200, { summary: stats.summary(u.id), campaign: stats.campaign(u.id) });
return json(res, 200, { summary: stats.summary(u.id), campaign: stats.campaign(u.id), rating: ratings.get(u.id) });
}
if (req.method !== 'POST') return json(res, 404, { error: 'Nicht gefunden' });
if (req.url === '/api/logout') {
@@ -147,7 +181,7 @@ async function handleApi(req: IncomingMessage, res: ServerResponse): Promise<voi
case '/api/login': {
const r = req.url === '/api/register' ? await auth.register(body) : await auth.login(body);
if ('error' in r) return json(res, 400, r);
if (req.url === '/api/register') await sendVerify(r.user.id, r.user.email).catch((e) => console.warn('Mail:', (e as Error).message));
if (req.url === '/api/register') await sendVerify(r.user.id, r.user.email, r.user.callsign).catch((e) => log('warn', 'Mailversand fehlgeschlagen', { error: (e as Error).message }));
return json(res, 200, publicUser(r.user), sessionCookie(r.token, 30 * 86_400));
}
case '/api/password/forgot': {
@@ -155,11 +189,9 @@ async function handleApi(req: IncomingMessage, res: ServerResponse): Promise<voi
const u = auth.findByEmail(body.email);
if (u) {
const t = auth.createToken(u.id, 'reset', HOUR);
await mailer.send({
to: u.email, subject: 'Tiefenkontakt: Passwort zurücksetzen / reset your password',
text: `Neues Passwort setzen (der Link gilt eine Stunde):\nSet a new password (the link is valid for one hour):\n\n${PUBLIC_URL}/#reset=${t}\n\nWenn du das nicht angefordert hast, ignoriere diese Mail.\nIf you did not ask for this, ignore this email.\n`,
})
.catch((e) => console.warn('Mail:', (e as Error).message));
await mailer.send(resetMail(u.email, u.callsign, `${PUBLIC_URL}/#reset=${t}`))
.then(() => log('info', 'Reset-Mail gesendet', { userId: u.id }))
.catch((e) => log('warn', 'Mailversand fehlgeschlagen', { error: (e as Error).message }));
}
return json(res, 200, { ok: true });
}
@@ -186,7 +218,7 @@ async function handleApi(req: IncomingMessage, res: ServerResponse): Promise<voi
}
case '/api/verify/resend': {
if (!me) return json(res, 401, { error: 'Nicht angemeldet' });
if (!auth.isVerified(me.id)) await sendVerify(me.id, me.email).catch((e) => console.warn('Mail:', (e as Error).message));
if (!auth.isVerified(me.id)) await sendVerify(me.id, me.email, me.callsign).catch((e) => log('warn', 'Mailversand fehlgeschlagen', { error: (e as Error).message }));
return json(res, 200, { ok: true });
}
case '/api/account/delete': {
@@ -199,11 +231,9 @@ async function handleApi(req: IncomingMessage, res: ServerResponse): Promise<voi
return json(res, 404, { error: 'Nicht gefunden' });
}
/** Real client address: the first X-Forwarded-For entry when TRUST_PROXY=1 (behind your reverse proxy). */
/** Real client address: the entry your reverse proxy appended to X-Forwarded-For (TRUST_PROXY = number of proxies). */
function clientIp(req: IncomingMessage): string {
const fwd = req.headers['x-forwarded-for'];
if (process.env.TRUST_PROXY === '1' && typeof fwd === 'string') return fwd.split(',')[0]!.trim();
return req.socket.remoteAddress ?? '?';
return clientIpFrom(req.headers['x-forwarded-for'], req.socket.remoteAddress);
}
const CLIENT_DIST = process.env.CLIENT_DIST ?? (process.env.NODE_ENV === 'production' ? resolve('../client/dist') : '');
@@ -268,13 +298,17 @@ wss.on('connection', (ws: WebSocket, req) => {
const conn: Conn = {
...identity(user, url.searchParams.get('guest'), url.searchParams.get('gid')),
send: (msg: ServerMsg) => {
if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(msg, roundNumbers));
if (ws.readyState !== ws.OPEN) return;
const text = JSON.stringify(msg, roundNumbers);
metrics.sent(text.length);
ws.send(text);
},
close: (reason: string, code = 4000) => {
if (ws.readyState === ws.OPEN) ws.close(code, reason);
},
ip: clientIp(req),
rank: user ? rankFor(stats.summary(user.id)?.points ?? 0) : undefined,
rating: ratings.get(user?.id),
};
const ban = mod.bannedFor(conn.playerId, conn.ip);
if (ban) {
@@ -294,6 +328,7 @@ wss.on('connection', (ws: WebSocket, req) => {
count = 0;
}
if (++count > MAX_MSGS_PER_SEC) return;
metrics.msgsReceived++;
const msg = parseClientMsg(data.toString());
if (!msg) return conn.send({ t: 'error', msg: 'Ungültige Nachricht' });
lobby.handle(conn, msg);
@@ -310,4 +345,4 @@ server.on('error', (e: NodeJS.ErrnoException) => {
}
throw e;
});
server.listen(PORT, () => console.log(`Tiefenkontakt-Server auf http://localhost:${PORT}`));
server.listen(PORT, () => log('info', `Tiefenkontakt-Server auf http://localhost:${PORT}`, { port: PORT }));
+4 -3
View File
@@ -24,10 +24,11 @@ const deg = z.number().finite().min(0).max(360);
const team = z.enum(['west', 'east']);
export const clientMsgSchema = z.discriminatedUnion('t', [
z.object({ t: z.literal('create_match'), name: z.string().trim().min(1).max(40) }),
z.object({ t: z.literal('create_match'), name: z.string().trim().min(1).max(40), private: z.boolean().optional() }),
z.object({ t: z.literal('join_code'), matchId: z.string().regex(/^[a-f0-9]{8}$/) }),
z.object({ t: z.literal('join'), matchId: z.string().max(40), team }),
z.object({ t: z.literal('leave') }),
z.object({ t: z.literal('pick_class'), cls: z.enum(['ssn', 'ssk', 'ffg']) }),
z.object({ t: z.literal('pick_class'), cls: z.enum(['ssn', 'ssk', 'ssc', 'ffg', 'kor']) }),
z.object({ t: z.literal('ready'), ready: z.boolean() }),
z.object({ t: z.literal('order'), heading: deg.optional(), speedKn: z.number().finite().min(0).max(40).optional(), depth: z.number().finite().min(0).max(500).optional() }),
z.object({ t: z.literal('toggle'), what: z.enum(['mast', 'snorkel', 'radar', 'active', 'decoy']), on: z.boolean() }),
@@ -46,7 +47,7 @@ export const clientMsgSchema = z.discriminatedUnion('t', [
z.object({ t: z.literal('pulse'), pulse: z.enum(['cw', 'lfm']) }),
z.object({ t: z.literal('bt') }),
z.object({ t: z.literal('lesson_done') }),
z.object({ t: z.literal('station'), index: z.number().int().min(0).max(3) }),
z.object({ t: z.literal('station'), index: z.number().int().min(0).max(4) }),
z.object({ t: z.literal('quick') }),
z.object({ t: z.literal('spectate'), matchId: z.string().max(40) }),
z.object({
+21 -3
View File
@@ -51,8 +51,15 @@ export class Lobby {
/** Quick match: join the open lobby with room, on the team that needs players; else open one. */
private quick(conn: Conn): string | undefined {
const open = [...this.matches.values()].filter((m) => m.state === 'lobby' && !m.settings.lesson && m.slots.length < MAX_PER_TEAM * 2);
open.sort((a, b) => b.slots.length - a.slots.length);
const open = [...this.matches.values()].filter((m) => m.state === 'lobby' && !m.settings.lesson && !m.settings.private && m.slots.length < MAX_PER_TEAM * 2);
// Skill matchmaking: prefer lobbies whose players are close to my rating, then fuller ones
const mine = conn.rating ?? 1000;
const avg = (m: Match) => {
const r = m.slots.filter((s) => !s.bot).map((s) => s.rating ?? 1000);
return r.length ? r.reduce((a, b) => a + b, 0) / r.length : mine;
};
const score = (m: Match) => Math.abs(avg(m) - mine) - 40 * m.slots.length;
open.sort((a, b) => score(a) - score(b));
const m = open[0];
if (!m) {
const created = this.create('Schnelles Spiel');
@@ -84,7 +91,7 @@ export class Lobby {
}
private listMsg(): ServerMsg {
return { t: 'lobby', matches: [...this.matches.values()].filter((m) => !m.settings.lesson).map((m) => m.summary()) };
return { t: 'lobby', matches: [...this.matches.values()].filter((m) => !m.settings.lesson && !m.settings.private).map((m) => m.summary()) };
}
private broadcastList(): void {
@@ -182,10 +189,21 @@ export class Lobby {
case 'create_match': {
const m = this.create(msg.name);
if (typeof m === 'string') return void err(m);
if (msg.private) m.settings.private = true;
this.leaveCurrent(conn.playerId);
this.playerMatch.set(conn.playerId, m.id);
return void err(m.join(conn, 'west'));
}
case 'join_code': {
// Invite link: join the team with fewer human players
const m = this.matches.get(msg.matchId);
if (!m || m.state !== 'lobby') return void err('Einladung ungültig oder Partie läuft schon');
const humans = (t: string) => m.slots.filter((s) => s.team === t && !s.bot).length;
if (this.playerMatch.get(conn.playerId) !== m.id) this.leaveCurrent(conn.playerId);
const e = m.join(conn, humans('west') <= humans('east') ? 'west' : 'east');
if (!e) this.playerMatch.set(conn.playerId, m.id);
return void err(e);
}
case 'join': {
const m = this.matches.get(msg.matchId);
if (!m) return void err('Partie nicht gefunden');
+18
View File
@@ -0,0 +1,18 @@
/**
* Minimal structured logging. LOG_FORMAT=json writes one JSON object per line (for log
* collectors); otherwise readable lines. LOG_LEVEL=debug|info|warn|error (default info).
*/
type Level = 'debug' | 'info' | 'warn' | 'error';
const ORDER: Record<Level, number> = { debug: 10, info: 20, warn: 30, error: 40 };
export function log(level: Level, msg: string, fields: Record<string, unknown> = {}): void {
const min = ORDER[(process.env.LOG_LEVEL as Level) ?? 'info'] ?? 20;
if (ORDER[level] < min) return;
const out = level === 'error' || level === 'warn' ? console.error : console.log;
if (process.env.LOG_FORMAT === 'json') {
out(JSON.stringify({ t: new Date().toISOString(), level, msg, ...fields }));
} else {
const extra = Object.entries(fields).map(([k, v]) => `${k}=${typeof v === 'string' ? v : JSON.stringify(v)}`).join(' ');
out(`${level === 'info' ? '' : `[${level.toUpperCase()}] `}${msg}${extra ? ` ${extra}` : ''}`);
}
}
+152
View File
@@ -0,0 +1,152 @@
import { deflateSync } from 'node:zlib';
/**
* Header picture for account mails, drawn procedurally (no image file, no native code):
* a sonar PPI scope with sweep, range rings and contacts, next to a broadband waterfall,
* with phosphor glow, scanlines and vignette. Encoded as PNG once and cached.
*/
export const HEADER_W = 1200;
export const HEADER_H = 300;
const CRC = new Uint32Array(256).map((_, n) => {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
return c >>> 0;
});
function crc32(buf: Buffer): number {
let c = 0xffffffff;
for (const b of buf) c = CRC[(c ^ b) & 0xff]! ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
function chunk(type: string, data: Buffer): Buffer {
const len = Buffer.alloc(4);
len.writeUInt32BE(data.length);
const td = Buffer.concat([Buffer.from(type, 'ascii'), data]);
const crc = Buffer.alloc(4);
crc.writeUInt32BE(crc32(td));
return Buffer.concat([len, td, crc]);
}
/** Minimal RGB PNG encoder. */
export function encodePng(w: number, h: number, rgb: Uint8Array): Buffer {
const raw = Buffer.alloc((w * 3 + 1) * h);
for (let y = 0; y < h; y++) {
raw[y * (w * 3 + 1)] = 0;
Buffer.from(rgb.buffer, rgb.byteOffset + y * w * 3, w * 3).copy(raw, y * (w * 3 + 1) + 1);
}
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(w, 0);
ihdr.writeUInt32BE(h, 4);
ihdr[8] = 8; // bit depth
ihdr[9] = 2; // RGB
return Buffer.concat([
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
chunk('IHDR', ihdr), chunk('IDAT', deflateSync(raw, { level: 9 })), chunk('IEND', Buffer.alloc(0)),
]);
}
/** Deterministic hash noise in [0, 1). */
function hash(x: number, y: number): number {
let h = Math.imul(x, 374761393) ^ Math.imul(y, 668265263);
h = Math.imul(h ^ (h >>> 13), 1274126177);
return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}
function smooth(x: number, y: number): number {
const xi = Math.floor(x), yi = Math.floor(y);
const fx = x - xi, fy = y - yi;
const u = fx * fx * (3 - 2 * fx), v = fy * fy * (3 - 2 * fy);
const a = hash(xi, yi), b = hash(xi + 1, yi), c = hash(xi, yi + 1), d = hash(xi + 1, yi + 1);
return a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v;
}
const TAU = Math.PI * 2;
/** Phosphor green. */
const G = [93, 202, 165] as const;
const AMBER = [232, 195, 122] as const;
function headerPixels(): Uint8Array {
const W = HEADER_W, H = HEADER_H;
const px = new Uint8Array(W * H * 3);
const cx = 170, cy = H / 2, R = 128;
const sweep = (-50 * Math.PI) / 180; // sweep hand direction (screen angle)
const blips = [[0.55, 0.9], [0.8, 2.6], [0.35, 4.1]] as const; // [range fraction, angle]
// Contact traces in the waterfall: bearing column that wanders with time (row)
const traces = [{ x: 0.22, drift: 0.04, w: 2.2, k: 1 }, { x: 0.47, drift: -0.02, w: 1.6, k: 0.8 }, { x: 0.71, drift: 0.07, w: 3, k: 1.2 }, { x: 0.86, drift: 0, w: 1.3, k: 0.5 }];
const wf0 = 340, wf1 = W - 30, wfTop = 34, wfBot = H - 34;
for (let y = 0; y < H; y++) {
for (let x = 0; x < W; x++) {
// Background: deep sea-green black with faint grid
let r = 4, g = 14, b = 13;
if (x % 40 === 0 || y % 40 === 0) { g += 6; b += 5; }
let glow = 0;
let amber = 0;
// PPI scope
const dx = x - cx, dy = y - cy;
const d = Math.hypot(dx, dy);
if (d < R + 6) {
if (d < R) {
r = 2; g = 12; b = 10;
const a = Math.atan2(dy, dx);
// Afterglow behind the sweep hand (counter-clockwise trail)
const behind = ((sweep - a) % TAU + TAU) % TAU;
glow += Math.exp(-behind * 2.2) * 0.55;
if (behind < 0.012) glow += 1;
// Range rings and bearing spokes
for (const rr of [R / 3, (2 * R) / 3]) if (Math.abs(d - rr) < 0.8) glow += 0.35;
const spoke = ((a % (Math.PI / 6)) + Math.PI / 6) % (Math.PI / 6);
if (Math.min(spoke, Math.PI / 6 - spoke) * d < 0.6) glow += 0.18;
// Sea clutter near the centre, speckle everywhere
glow += Math.max(0, 0.5 - d / R) * hash(x, y) * 0.5 + (hash(x + 7, y * 3) > 0.985 ? 0.25 : 0);
for (const [f, ang] of blips) {
const bx = cx + Math.cos(ang) * f * R, by = cy + Math.sin(ang) * f * R;
const bd = Math.hypot(x - bx, y - by);
const fade = Math.exp(-(((sweep - ang) % TAU + TAU) % TAU) * 0.6);
glow += Math.exp(-bd * bd / 10) * (0.6 + 1.2 * fade);
}
}
if (Math.abs(d - R) < 1.6) glow += 0.8; // bezel ring
// Bearing ticks on the bezel
const a2 = Math.atan2(dy, dx);
const tick = ((a2 + TAU) % (TAU / 36));
if (d > R && d < R + 6 && Math.min(tick, TAU / 36 - tick) * d < 0.9) glow += 0.5;
}
// Waterfall
if (x >= wf0 && x <= wf1 && y >= wfTop && y <= wfBot) {
const u = (x - wf0) / (wf1 - wf0);
const t = (y - wfTop) / (wfBot - wfTop);
let v = 0.08 + smooth(u * 140, t * 90) * 0.18 + hash(x, y) * 0.12;
for (const tr of traces) {
const tx = (tr.x + tr.drift * t + 0.006 * Math.sin(t * 9 + tr.x * 20)) * (wf1 - wf0);
const dd = Math.abs(x - wf0 - tx);
v += Math.exp(-dd * dd / (tr.w * tr.w)) * tr.k * (0.6 + 0.4 * smooth(t * 30, tr.x * 10));
}
// Newest rows (top) brightest; edges fade into the background
v *= (1 - t * 0.55) * Math.min(1, u * 12, (1 - u) * 12, (y - wfTop) / 6, (wfBot - y) / 6);
glow += v * 0.9;
if (y === wfTop || y === wfBot) glow += 0.25;
}
// Amber bearing cursor on one trace, and a short marker under the scope
if (x > wf0 && Math.abs(x - (wf0 + 0.71 * (wf1 - wf0))) < 0.8 && y < wfTop - 4 && y > wfTop - 16) amber += 0.9;
// Phosphor glow mapping
r += G[0] * glow * 0.75 + AMBER[0] * amber;
g += G[1] * glow * 0.75 + AMBER[1] * amber;
b += G[2] * glow * 0.75 + AMBER[2] * amber;
// Scanlines and vignette
const scan = y % 3 === 0 ? 0.78 : 1;
const vx = x / W - 0.5, vy = y / H - 0.5;
const vig = 1 - Math.min(0.55, (vx * vx * 0.9 + vy * vy * 1.6) * 1.1);
const k = (y * W + x) * 3;
px[k] = Math.min(255, r * scan * vig);
px[k + 1] = Math.min(255, g * scan * vig);
px[k + 2] = Math.min(255, b * scan * vig);
}
}
return px;
}
let cached: Buffer | undefined;
/** The header PNG (1200 × 300, shown at 600 × 150). */
export function headerPng(): Buffer {
return (cached ??= encodePng(HEADER_W, HEADER_H, headerPixels()));
}
+129
View File
@@ -0,0 +1,129 @@
import { HEADER_H, HEADER_W, headerPng } from './mail-art.js';
import type { Mail } from './mailer.js';
/**
* Account mails styled as a naval signal: phosphor-green console look, a sonar
* header picture (inline, so it shows without loading remote images), German
* with English below. Plain-text part for clients that don't show HTML.
* Email HTML: tables and inline styles only, no web fonts, no SVG.
*/
const HEADER_CID = 'sonar-header@tiefenkontakt';
const C = { bg: '#020807', panel: '#06120f', line: '#1d4a3e', g: '#5dcaa5', g2: '#9fe6cc', dim: '#5f7d72', amber: '#e8c37a', text: '#cfe8e0' };
const MONO = "'SF Mono', Menlo, Consolas, 'Courier New', monospace";
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
/** NATO date-time group, e.g. 221430Z NOV 26. */
export function dtg(d = new Date()): string {
const p = (n: number) => String(n).padStart(2, '0');
const mon = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'][d.getUTCMonth()];
return `${p(d.getUTCDate())}${p(d.getUTCHours())}${p(d.getUTCMinutes())}Z ${mon} ${p(d.getUTCFullYear() % 100)}`;
}
interface Signal {
/** Precedence shown in the header strip, e.g. ROUTINE or DRINGEND. */
precedence: string;
to: string;
subjectLine: string;
de: string[];
en: string[];
button?: { label: string; url: string };
validity?: string;
footerDe: string;
footerEn: string;
}
function html(s: Signal): string {
const row = (k: string, v: string, color = C.text) =>
`<tr><td style="padding:2px 0;color:${C.dim};font:12px/1.5 ${MONO};letter-spacing:1px;width:70px">${k}</td><td style="padding:2px 0;color:${color};font:12px/1.5 ${MONO};letter-spacing:1px">${v}</td></tr>`;
const para = (p: string, color: string, size: number) => `<p style="margin:0 0 12px;color:${color};font:${size}px/1.6 ${MONO}">${p}</p>`;
const button = s.button
? `<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:8px 0 18px"><tr>
<td bgcolor="#12302a" style="border:1px solid ${C.g};border-radius:3px;box-shadow:0 0 12px rgba(93,202,165,.35)">
<a href="${esc(s.button.url)}" style="display:inline-block;padding:13px 26px;color:#d8fff0;font:bold 14px ${MONO};letter-spacing:3px;text-decoration:none">${esc(s.button.label)} &#9656;</a>
</td></tr></table>
<p style="margin:0 0 4px;color:${C.dim};font:11px/1.5 ${MONO}">Falls der Knopf nicht geht / if the button does not work:</p>
<p style="margin:0 0 16px;font:11px/1.5 ${MONO};word-break:break-all"><a href="${esc(s.button.url)}" style="color:${C.g}">${esc(s.button.url)}</a></p>`
: '';
return `<!DOCTYPE html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="color-scheme" content="dark"><meta name="supported-color-schemes" content="dark"><title>Tiefenkontakt</title></head>
<body style="margin:0;padding:0;background:${C.bg}" bgcolor="${C.bg}">
<div style="display:none;max-height:0;overflow:hidden">${esc(s.de[0] ?? '')}</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="${C.bg}" style="background:${C.bg}"><tr><td align="center" style="padding:24px 10px">
<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" bgcolor="${C.panel}" style="width:100%;max-width:600px;background:${C.panel};border:1px solid ${C.line};border-radius:4px">
<tr><td style="padding:10px 18px;border-bottom:1px solid ${C.line}">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"><tr>
<td style="color:${C.amber};font:11px ${MONO};letter-spacing:2px">FUNKSPRUCH &middot; ${esc(s.precedence)}</td>
<td align="right" style="color:${C.dim};font:11px ${MONO};letter-spacing:2px">DTG ${dtg()}</td>
</tr></table></td></tr>
<tr><td style="line-height:0;font-size:0"><img src="cid:${HEADER_CID}" width="600" height="${Math.round((600 * HEADER_H) / HEADER_W)}" alt="Sonar" style="display:block;width:100%;max-width:600px;height:auto;border:0"></td></tr>
<tr><td style="padding:20px 26px 6px">
<div style="color:${C.g};font:bold 26px ${MONO};letter-spacing:8px;text-shadow:0 0 8px rgba(93,202,165,.5)">TIEFENKONTAKT</div>
<div style="color:${C.dim};font:11px ${MONO};letter-spacing:3px;margin-top:4px">NORDATLANTIK &middot; KALTER KRIEG</div>
</td></tr>
<tr><td style="padding:14px 26px 4px">
<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="border-top:1px dashed ${C.line};border-bottom:1px dashed ${C.line};width:100%;padding:8px 0">
${row('VON', 'FLOTTENKOMMANDO TIEFENKONTAKT')}
${row('AN', esc(s.to.toUpperCase()), C.g2)}
${row('BETR', esc(s.subjectLine), C.amber)}
</table></td></tr>
<tr><td style="padding:16px 26px 4px">
${s.de.map((p) => para(p, C.text, 14)).join('')}
${button}
${s.validity ? `<p style="margin:0 0 18px;color:${C.amber};font:11px ${MONO};letter-spacing:2px">&#9632; ${esc(s.validity)}</p>` : ''}
<div style="border-top:1px solid ${C.line};padding-top:12px;margin-top:4px">${s.en.map((p) => para(p, C.dim, 12)).join('')}</div>
</td></tr>
<tr><td style="padding:10px 26px 18px;border-top:1px solid ${C.line}">
<p style="margin:0 0 6px;color:${C.g};font:11px ${MONO};letter-spacing:3px">+++ ENDE DER NACHRICHT +++</p>
<p style="margin:0;color:${C.dim};font:10px/1.6 ${MONO}">${esc(s.footerDe)}<br>${esc(s.footerEn)}</p>
</td></tr>
</table></td></tr></table></body></html>`;
}
function text(s: Signal): string {
return [
`FUNKSPRUCH · ${s.precedence} · DTG ${dtg()}`, `VON: FLOTTENKOMMANDO TIEFENKONTAKT`, `AN: ${s.to.toUpperCase()}`, `BETR: ${s.subjectLine}`, '',
...s.de, ...(s.button ? ['', s.button.url] : []), ...(s.validity ? ['', s.validity] : []), '', '---', ...s.en, '',
'+++ ENDE DER NACHRICHT +++', s.footerDe, s.footerEn, '',
].join('\n');
}
function build(to: string, subject: string, s: Signal): Mail {
return {
to, subject, text: text(s), html: html(s),
inline: [{ cid: HEADER_CID, type: 'image/png', filename: 'sonar.png', data: headerPng() }],
};
}
export function verifyMail(to: string, callsign: string, url: string): Mail {
return build(to, 'Tiefenkontakt: E-Mail bestätigen / verify your email', {
precedence: 'ROUTINE', to: `Kapitän ${callsign}`, subjectLine: 'IDENTITÄT BESTÄTIGEN',
de: [`Willkommen an Bord, Kapitän ${esc(callsign)}.`, 'Dein Boot liegt klar zum Auslaufen. Bestätige deine Adresse, dann erscheinen deine Erfolge in der Rangliste und du kannst dein Passwort zurücksetzen.'],
en: [`Welcome aboard, Captain ${esc(callsign)}. Your boat is ready to sail. Confirm your address so your record appears on the leaderboard and you can reset your password.`],
button: { label: 'ADRESSE BESTÄTIGEN', url }, validity: 'GÜLTIG 48 STUNDEN · VALID FOR 48 HOURS',
footerDe: 'Automatisch gesendet. Wenn du dich nicht angemeldet hast, ignoriere diese Nachricht.',
footerEn: 'Sent automatically. If you did not sign up, ignore this message.',
});
}
export function resetMail(to: string, callsign: string, url: string): Mail {
return build(to, 'Tiefenkontakt: Passwort zurücksetzen / reset your password', {
precedence: 'DRINGEND', to: `Kapitän ${callsign}`, subjectLine: 'NEUER ZUGANGSCODE ANGEFORDERT',
de: ['Für dein Konto wurde ein neues Passwort angefordert.', 'Folge dem Link und lege einen neuen Zugangscode fest. Danach werden alle anderen Geräte abgemeldet.'],
en: ['A new password was requested for your account. Follow the link to set a new one; all other devices will be signed out.'],
button: { label: 'NEUES PASSWORT', url }, validity: 'GÜLTIG 1 STUNDE · VALID FOR 1 HOUR',
footerDe: 'Nicht von dir angefordert? Dann ignoriere diese Nachricht, dein Passwort bleibt unverändert.',
footerEn: 'Did not ask for this? Ignore this message; your password stays unchanged.',
});
}
export function testMail(to: string, url?: string): Mail {
return build(to, 'Tiefenkontakt: Testmail', {
precedence: 'ÜBUNG', to, subjectLine: 'FUNKVERBINDUNG PRÜFEN',
de: ['Funkprobe: Diese Nachricht beweist, dass der Mailversand des Servers funktioniert.'],
en: ['Radio check: this message proves the server can send mail.'],
button: url ? { label: 'ZUM SPIEL', url } : undefined,
footerDe: 'Übungsnachricht, keine Antwort nötig.', footerEn: 'Exercise message, no reply needed.',
});
}
+22
View File
@@ -0,0 +1,22 @@
import { createMailer, smtpConfigFrom } from './mailer.js';
import { testMail } from './mail-templates.js';
/** Sends one test mail with the current settings: node --import tsx src/mail-test.ts you@example.com */
const to = process.argv[2];
if (!to) {
console.error('Aufruf: mail-test <empfänger@adresse>');
process.exit(2);
}
const cfg = smtpConfigFrom();
if (!cfg) {
console.error('Kein Mailserver eingestellt (SMTP_HOST ist leer).');
process.exit(1);
}
console.log(`Sende über ${cfg.host}:${cfg.port} (${cfg.security}) als ${cfg.from}${cfg.user ? `, Login ${cfg.user}` : ', ohne Login'} …`);
createMailer()
.send(testMail(to, process.env.PUBLIC_URL))
.then(() => console.log('✓ Gesendet. Auch im Spam-Ordner nachsehen.'))
.catch((e: Error) => {
console.error(`✗ ${e.message}`);
process.exit(1);
});
+155 -39
View File
@@ -1,89 +1,205 @@
import { randomBytes } from 'node:crypto';
import { connect as netConnect, type Socket } from 'node:net';
import { connect as tlsConnect, type TLSSocket } from 'node:tls';
/**
* Minimal SMTP client for account mails (no dependency, no native code).
* SMTP_URL: smtps://user:pass@host:465 (implicit TLS) or smtp://user:pass@host:587 (STARTTLS).
* Without SMTP_URL, mails are written to the server log so an admin can pass the link on.
* Configured by SMTP_HOST / SMTP_PORT / SMTP_SECURITY / SMTP_USER / SMTP_PASS / MAIL_FROM (see .env.example),
* or the older single SMTP_URL (smtps://user:pass@host:465, smtp://user:pass@host:587).
* Without a host, mails are written to the server log so an admin can pass the link on.
*/
export interface Mail {
to: string;
subject: string;
text: string;
/** Optional HTML version; sent as multipart/alternative with the text. */
html?: string;
/** Pictures referenced from the HTML as cid:… */
inline?: { cid: string; type: string; filename: string; data: Buffer }[];
}
const b64 = (data: Buffer | string) => Buffer.from(data).toString('base64').replace(/.{76}/g, '$&\r\n');
/** MIME body (after the common headers): plain text, or text + HTML with inline pictures. */
export function mimeBody(mail: Mail): string[] {
const text = mail.text.replace(/\r?\n/g, '\r\n');
if (!mail.html) return ['Content-Type: text/plain; charset=utf-8', 'Content-Transfer-Encoding: 8bit', '', text];
const id = randomBytes(8).toString('hex');
const alt = `alt-${id}`;
const rel = `rel-${id}`;
const out = [
`Content-Type: multipart/alternative; boundary="${alt}"`, '', `--${alt}`,
'Content-Type: text/plain; charset=utf-8', 'Content-Transfer-Encoding: 8bit', '', text, `--${alt}`,
`Content-Type: multipart/related; boundary="${rel}"`, '', `--${rel}`,
'Content-Type: text/html; charset=utf-8', 'Content-Transfer-Encoding: base64', '', b64(mail.html),
];
for (const img of mail.inline ?? []) {
out.push(`--${rel}`, `Content-Type: ${img.type}; name="${img.filename}"`, 'Content-Transfer-Encoding: base64',
`Content-ID: <${img.cid}>`, `Content-Disposition: inline; filename="${img.filename}"`, '', b64(img.data));
}
out.push(`--${rel}--`, `--${alt}--`);
return out;
}
export interface Mailer {
readonly kind: 'smtp' | 'log';
send(mail: Mail): Promise<void>;
}
/** ssl = TLS from the first byte (port 465), starttls = upgrade after EHLO (587), none = plain (LAN relays only). */
export type SmtpSecurity = 'ssl' | 'starttls' | 'none';
export interface SmtpConfig {
host: string;
port: number;
security: SmtpSecurity;
user?: string;
pass?: string;
from: string;
fromName: string;
replyTo?: string;
/** Verify the server certificate (turn off only for self-signed LAN servers). */
tlsVerify: boolean;
timeoutMs: number;
}
class LogMailer implements Mailer {
readonly kind = 'log' as const;
async send(mail: Mail): Promise<void> {
console.log(`[Mail an ${mail.to}] ${mail.subject}\n${mail.text}`);
}
}
function lines(sock: Socket | TLSSocket) {
/** Full SMTP replies (multi-line "250-..." joined), one per call. */
function replies(sock: Socket | TLSSocket) {
let buf = '';
const waiting: ((l: string) => void)[] = [];
sock.on('data', (d: Buffer) => {
let acc: string[] = [];
const done: string[] = [];
const waiting: ((r: string) => void)[] = [];
const onData = (d: Buffer) => {
buf += d.toString();
let i: number;
while ((i = buf.indexOf('\r\n')) >= 0) {
const line = buf.slice(0, i);
buf = buf.slice(i + 2);
// Multi-line replies ("250-...") end with "250 ..."
if (/^\d{3} /.test(line)) waiting.shift()?.(line);
acc.push(line);
if (/^\d{3}(?: |$)/.test(line)) {
const reply = acc.join('\n');
acc = [];
const w = waiting.shift();
if (w) w(reply);
else done.push(reply);
}
}
});
return () => new Promise<string>((ok) => waiting.push(ok));
};
sock.on('data', onData);
return {
next: () => new Promise<string>((ok) => (done.length ? ok(done.shift()!) : waiting.push(ok))),
detach: () => sock.off('data', onData),
};
}
class SmtpMailer implements Mailer {
constructor(private url: URL, private from: string) {}
/** Header-safe address: no line breaks or angle brackets can be smuggled in. */
function addr(a: string): string {
if (!/^[^\s<>"]+@[^\s<>"]+$/.test(a)) throw new Error(`Ungültige Adresse: ${a}`);
return a;
}
const encWord = (s: string) => `=?UTF-8?B?${Buffer.from(s).toString('base64')}?=`;
export class SmtpMailer implements Mailer {
readonly kind = 'smtp' as const;
constructor(readonly cfg: SmtpConfig) {}
async send(mail: Mail): Promise<void> {
const host = this.url.hostname;
const implicit = this.url.protocol === 'smtps:';
const port = Number(this.url.port || (implicit ? 465 : 587));
let sock: Socket | TLSSocket = implicit ? tlsConnect({ host, port, servername: host }) : netConnect({ host, port });
let next = lines(sock);
const cmd = async (c: string | undefined, expect: string) => {
const { host, port, security, user, pass, timeoutMs } = this.cfg;
const tlsOpts = { servername: host, rejectUnauthorized: this.cfg.tlsVerify };
let sock: Socket | TLSSocket = security === 'ssl' ? tlsConnect({ host, port, ...tlsOpts }) : netConnect({ host, port });
const failed = new Promise<never>((_, fail) => {
sock.setTimeout(timeoutMs, () => fail(new Error(`SMTP: keine Antwort von ${host}:${port} (Zeitüberschreitung)`)));
sock.on('error', (e) => fail(new Error(`SMTP ${host}:${port}: ${e.message}`)));
});
failed.catch(() => undefined);
let r = replies(sock);
const cmd = async (c: string | undefined, expect: string, shown = c): Promise<string> => {
if (c !== undefined) sock.write(`${c}\r\n`);
const reply = await next();
if (!reply.startsWith(expect)) throw new Error(`SMTP: ${reply}`);
const reply = await Promise.race([r.next(), failed]);
if (!reply.startsWith(expect)) throw new Error(`SMTP ${shown?.split(' ')[0] ?? 'Begrüßung'}: ${reply.replace(/\n/g, ' ')}`);
return reply;
};
try {
await cmd(undefined, '220');
await cmd(`EHLO tiefenkontakt`, '250');
if (!implicit) {
let caps = await cmd('EHLO tiefenkontakt', '250');
if (security === 'starttls') {
if (!/STARTTLS/i.test(caps)) throw new Error('SMTP: Server bietet kein STARTTLS an (SMTP_SECURITY=ssl oder Port 465 versuchen)');
await cmd('STARTTLS', '220');
sock = tlsConnect({ socket: sock, servername: host });
next = lines(sock);
await cmd(`EHLO tiefenkontakt`, '250');
r.detach();
sock = tlsConnect({ socket: sock, ...tlsOpts });
sock.on('error', () => undefined);
r = replies(sock);
caps = await cmd('EHLO tiefenkontakt', '250');
}
if (this.url.username) {
const auth = Buffer.from(`\0${decodeURIComponent(this.url.username)}\0${decodeURIComponent(this.url.password)}`).toString('base64');
await cmd(`AUTH PLAIN ${auth}`, '235');
if (user) {
const authLine = /^250[ -]AUTH[ =](.*)$/im.exec(caps)?.[1]?.toUpperCase() ?? 'PLAIN LOGIN';
if (/\bPLAIN\b/.test(authLine) || !/\bLOGIN\b/.test(authLine)) {
await cmd(`AUTH PLAIN ${Buffer.from(`\0${user}\0${pass ?? ''}`).toString('base64')}`, '235', 'AUTH PLAIN');
} else {
await cmd('AUTH LOGIN', '334');
await cmd(Buffer.from(user).toString('base64'), '334', 'AUTH LOGIN');
await cmd(Buffer.from(pass ?? '').toString('base64'), '235', 'AUTH LOGIN');
}
}
await cmd(`MAIL FROM:<${this.from}>`, '250');
await cmd(`RCPT TO:<${mail.to}>`, '25');
const from = addr(this.cfg.from);
await cmd(`MAIL FROM:<${from}>`, '250');
await cmd(`RCPT TO:<${addr(mail.to)}>`, '25');
await cmd('DATA', '354');
const domain = from.split('@')[1];
const body = [
`From: Tiefenkontakt <${this.from}>`, `To: <${mail.to}>`, `Subject: =?UTF-8?B?${Buffer.from(mail.subject).toString('base64')}?=`,
'MIME-Version: 1.0', 'Content-Type: text/plain; charset=utf-8', 'Content-Transfer-Encoding: 8bit', '',
mail.text.replace(/^\./gm, '..'), '.',
].join('\r\n');
await cmd(body, '250');
await cmd('QUIT', '221');
`From: ${encWord(this.cfg.fromName)} <${from}>`, `To: <${mail.to}>`,
...(this.cfg.replyTo ? [`Reply-To: <${addr(this.cfg.replyTo)}>`] : []),
`Subject: ${encWord(mail.subject)}`, `Date: ${new Date().toUTCString()}`,
`Message-ID: <${randomBytes(12).toString('hex')}@${domain}>`,
'MIME-Version: 1.0', ...mimeBody(mail),
].join('\r\n').replace(/^\./gm, '..') + '\r\n.';
await cmd(body, '250', 'DATA');
await cmd('QUIT', '221').catch(() => undefined);
} finally {
sock.end();
}
}
}
export function createMailer(): Mailer {
const url = process.env.SMTP_URL;
if (!url) return new LogMailer();
return new SmtpMailer(new URL(url), process.env.MAIL_FROM ?? 'noreply@localhost');
/** Reads the SMTP settings from the environment; undefined = no mail server configured. */
export function smtpConfigFrom(env: NodeJS.ProcessEnv = process.env): SmtpConfig | undefined {
let host = env.SMTP_HOST?.trim();
let port = Number(env.SMTP_PORT) || 0;
let security = env.SMTP_SECURITY?.trim().toLowerCase() as SmtpSecurity | undefined;
let user = env.SMTP_USER;
let pass = env.SMTP_PASS;
if (!host && env.SMTP_URL) {
const u = new URL(env.SMTP_URL);
host = u.hostname;
port ||= Number(u.port) || 0;
security ??= u.protocol === 'smtps:' ? 'ssl' : 'starttls';
user ||= decodeURIComponent(u.username) || undefined;
pass ||= decodeURIComponent(u.password) || undefined;
}
if (!host) return undefined;
if (security && !['ssl', 'starttls', 'none'].includes(security)) throw new Error(`SMTP_SECURITY muss ssl, starttls oder none sein, nicht „${security}“`);
security ??= port === 465 ? 'ssl' : port === 25 ? 'none' : 'starttls';
port ||= security === 'ssl' ? 465 : security === 'none' ? 25 : 587;
return {
host, port, security, user: user || undefined, pass: pass || undefined,
// Gmail and iCloud only accept the account's own address (or a verified alias) as sender
from: env.MAIL_FROM?.trim() || user || 'noreply@localhost',
fromName: env.MAIL_FROM_NAME?.trim() || 'Tiefenkontakt',
replyTo: env.MAIL_REPLY_TO?.trim() || undefined,
tlsVerify: env.SMTP_TLS_VERIFY !== '0',
timeoutMs: (Number(env.SMTP_TIMEOUT_S) || 20) * 1000,
};
}
export function createMailer(env: NodeJS.ProcessEnv = process.env): Mailer {
const cfg = smtpConfigFrom(env);
return cfg ? new SmtpMailer(cfg) : new LogMailer();
}
+8
View File
@@ -7,6 +7,8 @@ const EXPLOSION_HEARING = 40_000;
const TRANSIENT_RANGE = { flood: 14_800, launch: 65_000 } as const;
const TRANSIENT_TEXT = { flood: 'TRANSIENT · ROHR WIRD GEFLUTET', launch: 'TRANSIENT · MECHANISCHER STARTLÄRM' } as const;
const SIGHTING_TEXT = { mast: 'SEHROHR', snorkel: 'SCHNORCHEL', surfaced: 'U-BOOT AUFGETAUCHT' } as const;
export interface AlertContext {
slots: PlayerSlot[];
shipOf(playerId: string): Ship | undefined;
@@ -22,6 +24,12 @@ export function alertsFor(w: World, fresh: GameEvent[], ctx: AlertContext): void
for (const slot of ctx.aboard(e.shipId)) {
ctx.alert(slot.playerId, { time: e.time, kind: 'torpedo', bearing: e.bearing, text: `TORPEDO PEILUNG ${e.bearing.toFixed(0).padStart(3, '0')}` });
}
} else if (e.kind === 'sighting') {
const b = e.bearing.toFixed(0).padStart(3, '0');
const r = (Math.round(e.range / 100) / 10).toFixed(1).replace('.', ',');
for (const slot of ctx.aboard(e.shipId)) {
ctx.alert(slot.playerId, { time: e.time, kind: 'sighting', bearing: e.bearing, range: e.range, what: e.what, label: e.label, text: `AUSGUCK · ${SIGHTING_TEXT[e.what]} PEILUNG ${b} · CA. ${r} KM` });
}
} else if (e.kind === 'sunk') {
const victim = shipById(w, e.shipId);
if (!victim) continue;
+2 -1
View File
@@ -1,6 +1,7 @@
import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { Lobby } from './lobby.js';
import { log } from './log.js';
import { Match, type SavedMatch } from './match.js';
/** Running matches are written to disk so a server restart doesn't end them. */
@@ -47,7 +48,7 @@ export class MatchStore {
lobby.adopt(Match.restore(data));
n++;
} catch (e) {
console.warn(`Spielstand ${name} nicht lesbar, wird verworfen:`, (e as Error).message);
log('warn', 'Spielstand nicht lesbar, wird verworfen', { file: name, error: (e as Error).message });
rmSync(f, { force: true });
}
}
+6 -3
View File
@@ -29,6 +29,7 @@ import { alertsFor } from './match-events.js';
import { computeScore, evaluate, type MatchResult } from './rules.js';
import { DEFAULT_SETTINGS, allowedClasses, buildScenario, simTimeLimit, type ScenarioSettings } from './scenario.js';
import { buildBriefing } from './briefing.js';
import { metrics } from './metrics.js';
import { buildSnapshot, classGroupKey, datalinkMates, type PlayerExtras } from './snapshot.js';
export interface Conn {
@@ -41,6 +42,8 @@ export interface Conn {
ip?: string;
/** Naval rank of an account (shown in the lobby). */
rank?: string;
/** Elo rating (guests 1000). */
rating?: number;
}
export const MAX_PER_TEAM = 6;
@@ -115,7 +118,7 @@ export class Match {
m.extras = new Map(d.extras.map(([k, x]) => [k, { ...x, reports: new Map(x.reports) }]));
m.state = 'running';
m.emptySince = Date.now();
m.timer = setInterval(() => m.tick(), SIM_DT * 1000);
m.timer = setInterval(() => metrics.timeTick(() => m.tick()), SIM_DT * 1000);
return m;
}
@@ -204,7 +207,7 @@ export class Match {
if (!existing && this.slots.filter((s) => s.team === team).length >= MAX_PER_TEAM) return 'Team ist voll';
const cls: PlayableClass = allowedClasses(this.settings.mission, team)[0]!;
if (existing) Object.assign(existing, { team, cls, ready: false, crewOf: undefined });
else this.slots.push({ playerId: conn.playerId, callsign: conn.callsign, team, cls, ready: false, rank: conn.rank });
else this.slots.push({ playerId: conn.playerId, callsign: conn.callsign, team, cls, ready: false, rank: conn.rank, rating: conn.rating });
this.conns.set(conn.playerId, conn);
this.broadcastLobby();
return undefined;
@@ -332,7 +335,7 @@ export class Match {
for (const s of this.slots) this.extras.set(s.playerId, { alerts: [], radio: [], reports: new Map(), timeScale: this.settings.timeScale });
this.state = 'running';
this.broadcastLobby();
this.timer = setInterval(() => this.tick(), SIM_DT * 1000);
this.timer = setInterval(() => metrics.timeTick(() => this.tick()), SIM_DT * 1000);
}
stop(): void {
+62
View File
@@ -0,0 +1,62 @@
import { monitorEventLoopDelay } from 'node:perf_hooks';
/** Server health numbers for /api/metrics: tick cost, event-loop lag, traffic, memory. */
class Metrics {
readonly started = Date.now();
private ticks: number[] = [];
private loop = monitorEventLoopDelay({ resolution: 10 });
bytesSent = 0;
msgsSent = 0;
msgsReceived = 0;
private window = { at: Date.now(), bytes: 0, msgs: 0 };
constructor() {
this.loop.enable();
}
/** Run one match tick and record how long it took. */
timeTick(fn: () => void): void {
const t0 = performance.now();
fn();
this.ticks.push(performance.now() - t0);
if (this.ticks.length > 3000) this.ticks.splice(0, this.ticks.length - 3000);
}
sent(bytes: number): void {
this.bytesSent += bytes;
this.msgsSent++;
}
snapshot(extra: Record<string, number>) {
const now = Date.now();
const dt = Math.max(1, (now - this.window.at) / 1000);
const rate = { bytesPerS: Math.round((this.bytesSent - this.window.bytes) / dt), msgsPerS: Math.round((this.msgsSent - this.window.msgs) / dt) };
if (now - this.window.at > 10_000) this.window = { at: now, bytes: this.bytesSent, msgs: this.msgsSent };
const sorted = [...this.ticks].sort((a, b) => a - b);
const pct = (p: number) => (sorted.length ? sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))]! : 0);
const mem = process.memoryUsage();
const out = {
uptimeS: Math.round((now - this.started) / 1000),
...extra,
tickMsAvg: sorted.length ? +(sorted.reduce((a, b) => a + b, 0) / sorted.length).toFixed(3) : 0,
tickMsP95: +pct(0.95).toFixed(3),
tickMsMax: +pct(1).toFixed(3),
eventLoopLagMsP99: +(this.loop.percentile(99) / 1e6).toFixed(2),
bytesSentTotal: this.bytesSent,
msgsSentTotal: this.msgsSent,
msgsReceivedTotal: this.msgsReceived,
bytesSentPerS: rate.bytesPerS,
msgsSentPerS: rate.msgsPerS,
rssMb: Math.round(mem.rss / 1e6),
heapMb: Math.round(mem.heapUsed / 1e6),
};
return out;
}
/** Prometheus text format of the same numbers. */
prometheus(extra: Record<string, number>): string {
return Object.entries(this.snapshot(extra)).map(([k, v]) => `tiefenkontakt_${k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)} ${v}`).join('\n') + '\n';
}
}
export const metrics = new Metrics();
+50
View File
@@ -0,0 +1,50 @@
import type { DatabaseSync } from 'node:sqlite';
import type { Debrief } from '@tk/shared';
import { userIdOf } from './stats.js';
export const START_RATING = 1000;
/**
* Elo rating per account, team against team: each player's result is compared with the
* expectation from the two team averages (guests and AI count as 1000).
* New players move faster (K 40 for the first 20 games, then 20).
*/
export class Ratings {
constructor(private db: DatabaseSync) {
db.exec('CREATE TABLE IF NOT EXISTS ratings (user_id INTEGER PRIMARY KEY, rating REAL NOT NULL, games INTEGER NOT NULL)');
}
get(userId: number | undefined): number {
if (userId === undefined) return START_RATING;
const r = this.db.prepare('SELECT rating FROM ratings WHERE user_id = ?').get(userId) as { rating: number } | undefined;
return Math.round(r?.rating ?? START_RATING);
}
private games(userId: number): number {
return (this.db.prepare('SELECT games FROM ratings WHERE user_id = ?').get(userId) as { games: number } | undefined)?.games ?? 0;
}
/** Apply a finished match. Returns the change per account player id. */
update(d: Debrief): Record<string, number> {
const teamAvg = (team: string) => {
const ps = d.stats.filter((s) => s.team === team);
return ps.length ? ps.reduce((a, s) => a + this.get(userIdOf(s.playerId)), 0) / ps.length : START_RATING;
};
const avg = { west: teamAvg('west'), east: teamAvg('east') };
const out: Record<string, number> = {};
const upsert = this.db.prepare('INSERT INTO ratings (user_id, rating, games) VALUES (?, ?, 1) ON CONFLICT(user_id) DO UPDATE SET rating = excluded.rating, games = games + 1');
for (const s of d.stats) {
const uid = userIdOf(s.playerId);
if (uid === undefined) continue;
const own = avg[s.team];
const opp = avg[s.team === 'west' ? 'east' : 'west'];
const expected = 1 / (1 + 10 ** ((opp - own) / 400));
const k = this.games(uid) < 20 ? 40 : 20;
const before = this.get(uid);
const after = before + k * ((s.won ? 1 : 0) - expected);
upsert.run(uid, after);
out[s.playerId] = Math.round(after - before);
}
return out;
}
}
+5 -3
View File
@@ -38,9 +38,9 @@ export interface CustomMission {
export const DEFAULT_CUSTOM: CustomMission = { convoyKn: 9, seabed: 'tief', subFrac: 0.5 };
/** Classes a team may pick in a mission: in the duel both sides fight with submarines. */
export function allowedClasses(mission: MissionId, team: 'west' | 'east'): ('ffg' | 'ssn' | 'ssk')[] {
if (mission === 'duell') return ['ssn', 'ssk'];
return team === 'west' ? ['ffg'] : ['ssk', 'ssn'];
export function allowedClasses(mission: MissionId, team: 'west' | 'east'): ('ffg' | 'kor' | 'ssn' | 'ssk' | 'ssc')[] {
if (mission === 'duell') return ['ssn', 'ssk', 'ssc'];
return team === 'west' ? ['ffg', 'kor'] : ['ssk', 'ssn', 'ssc'];
}
export const LIGHT: Record<TimeOfDay, number> = { tag: 1, daemmerung: 0.5, nacht: 0.12 };
@@ -63,6 +63,8 @@ export interface ScenarioSettings {
custom?: CustomMission;
/** Training lesson instead of the convoy battle. */
lesson?: LessonId;
/** Invite-only: hidden from the match list and quick match. */
private?: boolean;
}
/** layerDepth 0 = random per match (80-170 m); nobody knows it until measured. */
+6 -1
View File
@@ -5,7 +5,7 @@ import type { Debrief, PlayerStats } from '@tk/shared';
export type CampaignStep =
| { id: string; kind: 'lesson'; lesson: 'klassifizieren' | 'tma' | 'angriff' | 'ujagd'; title: string }
| { id: string; kind: 'mission'; mission: 'groenland' | 'schelf' | 'fjord'; timeOfDay: 'tag' | 'daemmerung' | 'nacht'; title: string };
| { id: string; kind: 'mission'; mission: 'groenland' | 'schelf' | 'fjord' | 'duell' | 'hafen'; timeOfDay: 'tag' | 'daemmerung' | 'nacht'; title: string };
export const CAMPAIGN: CampaignStep[] = [
{ id: 'l1', kind: 'lesson', lesson: 'klassifizieren', title: 'Ausbildung 1: Horchen und Klassifizieren' },
@@ -15,6 +15,11 @@ export const CAMPAIGN: CampaignStep[] = [
{ id: 'm1', kind: 'mission', mission: 'groenland', timeOfDay: 'tag', title: 'Einsatz 1: Grönland-Lücke bei Tag gewinnen' },
{ id: 'm2', kind: 'mission', mission: 'schelf', timeOfDay: 'daemmerung', title: 'Einsatz 2: Schelfmeer in der Dämmerung gewinnen' },
{ id: 'm3', kind: 'mission', mission: 'fjord', timeOfDay: 'nacht', title: 'Einsatz 3: Fjordausfahrt bei Nacht gewinnen' },
{ id: 'm4', kind: 'mission', mission: 'hafen', timeOfDay: 'daemmerung', title: 'Einsatz 4: Hafenangriff in der Dämmerung gewinnen' },
{ id: 'm5', kind: 'mission', mission: 'schelf', timeOfDay: 'nacht', title: 'Einsatz 5: Schelfmeer bei Nacht gewinnen' },
{ id: 'm6', kind: 'mission', mission: 'duell', timeOfDay: 'tag', title: 'Einsatz 6: U-Boot-Duell gewinnen' },
{ id: 'm7', kind: 'mission', mission: 'groenland', timeOfDay: 'nacht', title: 'Einsatz 7: Grönland-Lücke bei Nacht gewinnen' },
{ id: 'm8', kind: 'mission', mission: 'duell', timeOfDay: 'nacht', title: 'Einsatz 8: U-Boot-Duell bei Nacht gewinnen' },
];
export interface BalanceRow {
+26
View File
@@ -0,0 +1,26 @@
import { mkdtempSync } from 'node:fs';
import { DatabaseSync } from 'node:sqlite';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { Backups } from '../src/backup.js';
describe('database backups', () => {
it('writes a readable copy and keeps only the newest N', () => {
const dir = mkdtempSync(join(tmpdir(), 'tk-bak-'));
const db = new DatabaseSync(join(dir, 'live.db'));
db.exec('CREATE TABLE t (v TEXT); INSERT INTO t VALUES (\'Seewolf\')');
const b = new Backups(db, join(dir, 'bak'), 2, 24);
for (let i = 0; i < 4; i++) b.run(new Date(Date.UTC(2026, 10, 20 + i, 3, 0, 0)));
const files = b.list();
expect(files.map((f) => f.file)).toEqual(['tiefenkontakt-20261123-030000.db', 'tiefenkontakt-20261122-030000.db']);
const copy = new DatabaseSync(join(dir, 'bak', files[0]!.file));
expect(copy.prepare('SELECT v FROM t').get()).toEqual({ v: 'Seewolf' });
});
it('does nothing without BACKUP_DIR', () => {
const b = new Backups(new DatabaseSync(':memory:'), undefined);
expect(b.enabled).toBe(false);
expect(b.run()).toBeUndefined();
});
});
+19
View File
@@ -0,0 +1,19 @@
import { describe, expect, it } from 'vitest';
import { clientIpFrom } from '../src/client-ip.js';
describe('client address behind a proxy', () => {
it('takes the address the proxy appended, not one the client made up', () => {
// Client sent "X-Forwarded-For: 6.6.6.6", nginx appended the real address
expect(clientIpFrom('6.6.6.6, 84.10.20.30', '172.18.0.1', '1')).toBe('84.10.20.30');
expect(clientIpFrom('84.10.20.30', '172.18.0.1', '1')).toBe('84.10.20.30');
});
it('two proxies: the second entry from the right', () => {
expect(clientIpFrom('6.6.6.6, 84.10.20.30, 10.0.0.2', '10.0.0.3', '2')).toBe('84.10.20.30');
});
it('without TRUST_PROXY the header is ignored', () => {
expect(clientIpFrom('6.6.6.6', '84.10.20.30', undefined)).toBe('84.10.20.30');
expect(clientIpFrom(undefined, '84.10.20.30', '1')).toBe('84.10.20.30');
});
});
+117
View File
@@ -0,0 +1,117 @@
import { createServer, type Server } from 'node:net';
import { afterEach, describe, expect, it } from 'vitest';
import { SmtpMailer, smtpConfigFrom } from '../src/mailer.js';
/** Tiny fake SMTP server (plain, no TLS) that records the session. */
function fakeSmtp(authMechs: string): Promise<{ server: Server; port: number; log: string[] }> {
const log: string[] = [];
const server = createServer((s) => {
let data = false;
let buf = '';
let loginStep = 0;
s.write('220 fake ESMTP\r\n');
s.on('data', (d) => {
buf += d.toString();
let i: number;
while ((i = buf.indexOf('\r\n')) >= 0) {
const line = buf.slice(0, i);
buf = buf.slice(i + 2);
log.push(line);
if (data) {
if (line === '.') { data = false; s.write('250 queued\r\n'); }
continue;
}
if (loginStep === 1) { loginStep = 2; s.write('334 UGFzc3dvcmQ6\r\n'); continue; }
if (loginStep === 2) { loginStep = 0; s.write('235 ok\r\n'); continue; }
if (line.startsWith('EHLO')) s.write(`250-fake\r\n250-AUTH ${authMechs}\r\n250 8BITMIME\r\n`);
else if (line.startsWith('AUTH PLAIN')) s.write('235 ok\r\n');
else if (line === 'AUTH LOGIN') { loginStep = 1; s.write('334 VXNlcm5hbWU6\r\n'); }
else if (line === 'DATA') { data = true; s.write('354 go\r\n'); }
else if (line === 'QUIT') { s.write('221 bye\r\n'); s.end(); }
else s.write('250 ok\r\n');
}
});
});
return new Promise((ok) => server.listen(0, '127.0.0.1', () => ok({ server, port: (server.address() as { port: number }).port, log })));
}
let open: Server | undefined;
afterEach(() => open?.close());
const cfg = (port: number) => ({
host: '127.0.0.1', port, security: 'none' as const, user: 'me@icloud.com', pass: 'app-pass',
from: 'me@icloud.com', fromName: 'Tiefenkontakt', tlsVerify: true, timeoutMs: 3000,
});
describe('SMTP mailer', () => {
it('logs in with AUTH PLAIN and sends proper headers', async () => {
const f = await fakeSmtp('PLAIN LOGIN');
open = f.server;
await new SmtpMailer(cfg(f.port)).send({ to: 'you@example.com', subject: 'Prüfung', text: 'Hallo\n.Punkt' });
const plain = f.log.find((l) => l.startsWith('AUTH PLAIN '))!;
expect(Buffer.from(plain.slice(11), 'base64').toString()).toBe('\0me@icloud.com\0app-pass');
expect(f.log).toContain('MAIL FROM:<me@icloud.com>');
expect(f.log).toContain('RCPT TO:<you@example.com>');
expect(f.log.some((l) => l.startsWith('Message-ID: <') && l.endsWith('@icloud.com>'))).toBe(true);
expect(f.log.some((l) => l.startsWith('Date: '))).toBe(true);
expect(f.log).toContain('..Punkt');
});
it('falls back to AUTH LOGIN when PLAIN is not offered', async () => {
const f = await fakeSmtp('LOGIN');
open = f.server;
await new SmtpMailer(cfg(f.port)).send({ to: 'you@example.com', subject: 's', text: 't' });
expect(f.log).toContain('AUTH LOGIN');
expect(f.log).toContain(Buffer.from('app-pass').toString('base64'));
});
it('rejects header injection in addresses', async () => {
const f = await fakeSmtp('PLAIN');
open = f.server;
await expect(new SmtpMailer(cfg(f.port)).send({ to: 'a@b.c>\r\nBcc: x@y.z', subject: 's', text: 't' })).rejects.toThrow();
});
});
describe('SMTP settings', () => {
it('derives port and security, sender defaults to the login', () => {
expect(smtpConfigFrom({ SMTP_HOST: 'smtp.gmail.com', SMTP_USER: 'me@gmail.com', SMTP_PASS: 'x' })).toMatchObject({
host: 'smtp.gmail.com', port: 587, security: 'starttls', from: 'me@gmail.com',
});
expect(smtpConfigFrom({ SMTP_HOST: 'h', SMTP_PORT: '465' })).toMatchObject({ port: 465, security: 'ssl' });
expect(smtpConfigFrom({ SMTP_HOST: 'h', SMTP_SECURITY: 'ssl' })).toMatchObject({ port: 465 });
expect(smtpConfigFrom({})).toBeUndefined();
expect(() => smtpConfigFrom({ SMTP_HOST: 'h', SMTP_SECURITY: 'tls' })).toThrow();
});
it('still understands the old SMTP_URL, with special characters in the password', () => {
expect(smtpConfigFrom({ SMTP_URL: 'smtps://u%40x.de:p%2Fw@mail.x.de', MAIL_FROM: 'n@x.de' })).toMatchObject({
host: 'mail.x.de', port: 465, security: 'ssl', user: 'u@x.de', pass: 'p/w', from: 'n@x.de',
});
});
});
describe('graphic account mails', () => {
it('build text + HTML + inline header picture, with the link in both parts', async () => {
const { verifyMail } = await import('../src/mail-templates.js');
const { mimeBody } = await import('../src/mailer.js');
const m = verifyMail('you@example.com', 'db9', 'https://spiel.example/#verify=abc');
expect(m.text).toContain('https://spiel.example/#verify=abc');
expect(m.html).toContain('cid:sonar-header@tiefenkontakt');
expect(m.inline![0]!.data.subarray(1, 4).toString()).toBe('PNG');
const body = mimeBody(m).join('\r\n');
expect(body).toMatch(/multipart\/alternative/);
expect(body).toMatch(/multipart\/related/);
expect(body).toContain('Content-ID: <sonar-header@tiefenkontakt>');
// No line over the SMTP limit of 998 characters
expect(Math.max(...body.split('\r\n').map((l) => l.length))).toBeLessThan(998);
});
it('send through SMTP as one multipart message', async () => {
const { resetMail } = await import('../src/mail-templates.js');
const f = await fakeSmtp('PLAIN');
open = f.server;
await new SmtpMailer(cfg(f.port)).send(resetMail('you@example.com', 'db9', 'https://x/#reset=1'));
expect(f.log.some((l) => l.startsWith('Content-Type: multipart/alternative'))).toBe(true);
expect(f.log.some((l) => l.startsWith('Content-Type: image/png'))).toBe(true);
});
});
+29
View File
@@ -0,0 +1,29 @@
import { DatabaseSync } from 'node:sqlite';
import { describe, expect, it } from 'vitest';
import type { Debrief, PlayerStats } from '@tk/shared';
import { Ratings } from '../src/rating.js';
const st = (playerId: string, team: 'west' | 'east', won: boolean): PlayerStats => ({
playerId, callsign: playerId, team, cls: team === 'west' ? 'ffg' : 'ssk', survived: true, shots: 0, rockets: 0, buoys: 0, kills: 0, tonnageSunk: 0, distanceNm: 0, won,
});
const match = (stats: PlayerStats[]): Debrief => ({ ships: [], frames: [], torpedoes: [], events: [], stats, winner: stats.find((s) => s.won)?.team ?? 'west', reason: '', duration: 0 });
describe('rating', () => {
it('the winner gains what the loser loses between equals; guests are not rated', () => {
const r = new Ratings(new DatabaseSync(':memory:'));
const d = r.update(match([st('u-1', 'west', true), st('u-2', 'east', false), st('g-abc', 'east', false)]));
expect(d['u-1']).toBe(20);
expect(d['u-2']).toBe(-20);
expect(d['g-abc']).toBeUndefined();
expect(r.get(1)).toBe(1020);
expect(r.get(2)).toBe(980);
});
it('beating a stronger team pays more than beating a weaker one', () => {
const r = new Ratings(new DatabaseSync(':memory:'));
for (let i = 0; i < 10; i++) r.update(match([st('u-1', 'west', true), st('u-2', 'east', false)]));
const upset = r.update(match([st('u-2', 'east', true), st('u-1', 'west', false)]));
const expected = r.update(match([st('u-1', 'west', true), st('u-2', 'east', false)]));
expect(upset['u-2']!).toBeGreaterThan(expected['u-1']!);
});
});
+40
View File
@@ -56,3 +56,43 @@ describe('lobby extras', () => {
expect(rankFor(5000)).toBe('Kapitän zur See');
});
});
describe('private matches and matchmaking', () => {
function conn2(id: string, rating?: number): Conn & { inbox: ServerMsg[] } {
const inbox: ServerMsg[] = [];
return { playerId: id, callsign: id, inbox, send: (m) => inbox.push(m), rating };
}
const join = (lobby: Lobby, c: Conn) => {
lobby.connect(c);
lobby.resume(c);
};
it('a private match is hidden from the list and quick match, but joinable by invite', () => {
const lobby = new Lobby();
const host = conn2('h');
const other = conn2('o');
join(lobby, host);
join(lobby, other);
lobby.handle(host, { t: 'create_match', name: 'Geheim', private: true });
const m = lobby.matchOf('h')!;
const list = [...other.inbox].reverse().find((x) => x.t === 'lobby');
expect(list?.t === 'lobby' && list.matches.some((x) => x.id === m.id)).toBe(false);
lobby.handle(other, { t: 'quick' });
expect(lobby.matchOf('o')?.id).not.toBe(m.id);
lobby.handle(other, { t: 'join_code', matchId: m.id });
expect(lobby.matchOf('o')?.id).toBe(m.id);
expect(m.slots.find((s) => s.playerId === 'o')?.team).toBe('east');
});
it('quick match prefers a lobby with players of similar rating', () => {
const lobby = new Lobby();
const strong = conn2('s', 1400);
const weak = conn2('w', 800);
const me = conn2('me', 1380);
for (const c of [strong, weak, me]) join(lobby, c);
lobby.handle(weak, { t: 'create_match', name: 'Anfänger' });
lobby.handle(strong, { t: 'create_match', name: 'Profis' });
lobby.handle(me, { t: 'quick' });
expect(lobby.matchOf('me')?.id).toBe(lobby.matchOf('s')?.id);
});
});
+21 -2
View File
@@ -11,11 +11,30 @@ services:
PUBLIC_URL: ${PUBLIC_URL:-http://localhost:8787}
# Comma-separated callsigns of moderator accounts
ADMIN: ${ADMIN:-}
# smtps://user:pass@host:465 or smtp://user:pass@host:587; empty = links go to the log
# Outgoing mail (see .env.example for Gmail / iCloud); empty SMTP_HOST = links go to the log
SMTP_HOST: ${SMTP_HOST:-}
SMTP_PORT: ${SMTP_PORT:-}
SMTP_SECURITY: ${SMTP_SECURITY:-}
SMTP_USER: ${SMTP_USER:-}
SMTP_PASS: ${SMTP_PASS:-}
SMTP_TLS_VERIFY: ${SMTP_TLS_VERIFY:-1}
SMTP_TIMEOUT_S: ${SMTP_TIMEOUT_S:-20}
MAIL_FROM: ${MAIL_FROM:-}
MAIL_FROM_NAME: ${MAIL_FROM_NAME:-Tiefenkontakt}
MAIL_REPLY_TO: ${MAIL_REPLY_TO:-}
# Older single-line form, still accepted: smtps://user:pass@host:465
SMTP_URL: ${SMTP_URL:-}
MAIL_FROM: ${MAIL_FROM:-noreply@localhost}
# 1 behind an HTTPS proxy (Secure cookie); 0 for plain HTTP on localhost
COOKIE_SECURE: ${COOKIE_SECURE:-0}
# Daily database copy in the data volume (/data/backups), newest 7 kept
BACKUP_KEEP: ${BACKUP_KEEP:-7}
BACKUP_EVERY_H: ${BACKUP_EVERY_H:-24}
# Bearer token for GET /api/metrics (?format=prom for Prometheus); empty = moderators only
METRICS_TOKEN: ${METRICS_TOKEN:-}
# Seconds between saves of running matches (higher = fewer writes on SD cards)
MATCH_SAVE_S: ${MATCH_SAVE_S:-5}
# json = one JSON object per log line (for log collectors)
LOG_FORMAT: ${LOG_FORMAT:-}
volumes:
- tiefenkontakt-data:/data
stop_grace_period: 15s
+3 -1
View File
@@ -9,7 +9,9 @@
"typecheck": "tsc -p tsconfig.json --noEmit && npm -w @tk/client run typecheck",
"build": "npm run typecheck && npm -w @tk/client run build",
"test": "vitest run",
"serve": "npm run build && NODE_ENV=production npm -w @tk/server run start"
"serve": "npm run build && NODE_ENV=production npm -w @tk/server run start",
"arena": "tsx scripts/bot-arena.ts",
"loadtest": "tsx scripts/net-load-test.ts"
},
"devDependencies": {
"@types/node": "^22.10.0",
+5 -5
View File
@@ -1,5 +1,5 @@
import { ambientNoise, transmissionLoss, DT_ACTIVE, DT_PASSIVE, sourceLevelToward, targetStrengthToward } from './acoustics.js';
import { CLASSES } from './classes.js';
import { CLASSES, hasHelicopter, isEscort } from './classes.js';
import { dropLightweight } from './weapons.js';
import { bookFor } from './world.js';
import type { Ship } from './entities.js';
@@ -70,10 +70,10 @@ const MPA_SPACING = 3000;
export function installAir(w: World, buoysPerFrigate = 16): AirState {
const stock = new Map<string, number>();
for (const s of w.ships) if (s.cls === 'ffg') stock.set(s.id, buoysPerFrigate);
for (const s of w.ships) if (hasHelicopter(s.cls)) stock.set(s.id, buoysPerFrigate);
const heloTorps = new Map<string, number>();
for (const s of w.ships) if (s.cls === 'ffg') heloTorps.set(s.id, 2);
const teams = new Set(w.ships.filter((s) => s.cls === 'ffg').map((s) => s.team));
for (const s of w.ships) if (hasHelicopter(s.cls)) heloTorps.set(s.id, 2);
const teams = new Set(w.ships.filter((s) => isEscort(s.cls)).map((s) => s.team));
const mpa: AirState['mpa'] = {};
for (const t of teams) mpa[t] = { readyAt: 0, buoys: 18 };
w.air = { buoys: [], sorties: [], stock, nextId: 1, heloTorps, mpa };
@@ -84,7 +84,7 @@ export function installAir(w: World, buoysPerFrigate = 16): AirState {
/** Launch the helicopter to drop a buoy at a point. deep = below the layer. */
function heloCheck(w: World, ship: Ship, target: Vec2): string | undefined {
const air = w.air;
if (!air || ship.cls !== 'ffg') return 'Kein Hubschrauber an Bord';
if (!air || !hasHelicopter(ship.cls)) return 'Kein Hubschrauber an Bord';
if (!ship.alive) return 'Schiff ist gesunken';
if (air.sorties.some((s) => s.shipId === ship.id && s.kind !== 'mpa' && w.time < s.readyAt)) return 'Hubschrauber ist unterwegs';
if (distance(ship.pos, target) > HELO_RANGE) return 'Außer Reichweite des Hubschraubers (30 km)';
+29 -1
View File
@@ -1,6 +1,6 @@
/** Fictional Cold-War-era platform classes. All numbers are game-balance values, tunable. */
export type ClassId = 'ssn' | 'ssk' | 'ffg' | 'merchant';
export type ClassId = 'ssn' | 'ssk' | 'ssc' | 'ffg' | 'kor' | 'merchant';
export type Team = 'west' | 'east' | 'neutral';
export interface HullSonarSpec {
@@ -73,6 +73,24 @@ export const CLASSES: Record<ClassId, ClassSpec> = {
towed: { di: 24, selfNoise: 48, maxSpeedKn: 14, maxLength: 1200, settleTime: 60 },
hp: 100,
},
ssc: {
id: 'ssc', name: 'Küsten-U-Boot Projekt 2', team: 'east', submarine: true, tonnage: 900,
maxSpeedKn: 14, accel: 0.12, turnRateDeg: 3, maxDepth: 200, depthRate: 2, draft: 0,
slBase: 108, slRefKn: 4, slSlope: 50, cavKn: 6, cavDepthKn: 4,
targetStrength: 8,
hull: { di: 12, baffleHalfAngle: 35, selfNoiseBase: 54, selfNoiseRefKn: 4, activeSl: 205 },
battery: { capacityKnH: 45 },
hp: 60,
},
kor: {
id: 'kor', name: 'Korvette K-7', team: 'west', submarine: false, tonnage: 1800,
maxSpeedKn: 26, accel: 0.18, turnRateDeg: 3.4, maxDepth: 0, depthRate: 0, draft: 4,
slBase: 142, slRefKn: 15, slSlope: 45,
targetStrength: 21,
hull: { di: 14, baffleHalfAngle: 30, selfNoiseBase: 68, selfNoiseRefKn: 15, activeSl: 220 },
towed: { di: 20, selfNoise: 50, maxSpeedKn: 14, maxLength: 600, settleTime: 45 },
hp: 70,
},
merchant: {
id: 'merchant', name: 'Frachter', team: 'west', submarine: false, tonnage: 12000,
maxSpeedKn: 14, accel: 0.04, turnRateDeg: 0.8, maxDepth: 0, depthRate: 0, draft: 9,
@@ -86,3 +104,13 @@ export const CLASSES: Record<ClassId, ClassSpec> = {
export function classSpec(id: ClassId): ClassSpec {
return CLASSES[id];
}
/** Surface warship escorting the convoy (frigate or corvette). */
export function isEscort(cls: ClassId): boolean {
return cls === 'ffg' || cls === 'kor';
}
/** Carries a helicopter (dipping sonar, sonobuoys, helo torpedoes). */
export function hasHelicopter(cls: ClassId): boolean {
return cls === 'ffg';
}
+12 -1
View File
@@ -1,6 +1,7 @@
import type { ClassId } from './classes.js';
import type { Detection, SensorKind } from './sensors.js';
import type { Evidence } from './signatures.js';
import type { Sighting } from './lookout.js';
export interface BearingSample {
t: number;
@@ -26,6 +27,11 @@ export interface ContactTrack {
sensors: SensorKind[];
/** Visual identification only (periscope). */
classified?: ClassId;
/** Latest bridge-lookout sighting and when it was made. */
sighting?: Sighting;
sightedAt?: number;
/** Start of the current sighting episode (a new one begins after a minute without sightings). */
sightingSince?: number;
/** Latest passive narrowband/DEMON measurement. */
evidence?: Evidence;
evidenceAt?: number;
@@ -61,7 +67,7 @@ function resolveTas(tr: ContactTrack): void {
const HISTORY_MAX = 180;
const PREFIX: Record<SensorKind, string> = {
hull: 'S', towed: 'S', active: 'S', intercept: 'S', periscope: 'V', radar: 'R', esm: 'E', buoy: 'S',
hull: 'S', towed: 'S', active: 'S', intercept: 'S', periscope: 'V', radar: 'R', esm: 'E', buoy: 'S', visual: 'A',
};
/** Per-observer contact bookkeeping. Keyed internally by target, labels are opaque. */
@@ -111,6 +117,11 @@ export class ContactBook {
}
if (!tr.sensors.includes(d.sensor)) tr.sensors.push(d.sensor);
if (d.classified) tr.classified = d.classified;
if (d.sighting) {
if (tr.sightedAt === undefined || d.time - tr.sightedAt > 60) tr.sightingSince = d.time;
tr.sighting = d.sighting;
tr.sightedAt = d.time;
}
if (d.evidence) {
tr.evidence = d.evidence;
tr.evidenceAt = d.time;
+1
View File
@@ -5,6 +5,7 @@ export * from './entities.js';
export * from './kinematics.js';
export * from './acoustics.js';
export * from './sensors.js';
export * from './lookout.js';
export * from './contacts.js';
export * from './convoy-ai.js';
export * from './world.js';
+3 -1
View File
@@ -20,13 +20,15 @@ export interface Loadout {
const TEMPLATES: Record<ClassId, Omit<Loadout, 'tubes'> & { tubeCount: number }> = {
ssn: { heavy: 16, light: 0, rockets: 0, depthCharges: 0, noisemakers: 8, tubeCount: 4, reloadTime: 90, towedDecoy: false, xbt: 0 },
ssk: { heavy: 12, light: 0, rockets: 0, depthCharges: 0, noisemakers: 6, tubeCount: 6, reloadTime: 120, towedDecoy: false, xbt: 0 },
ssc: { heavy: 6, light: 0, rockets: 0, depthCharges: 0, noisemakers: 4, tubeCount: 4, reloadTime: 150, towedDecoy: false, xbt: 0 },
kor: { heavy: 0, light: 4, rockets: 4, depthCharges: 16, noisemakers: 0, tubeCount: 2, reloadTime: 50, towedDecoy: false, xbt: 6 },
ffg: { heavy: 0, light: 6, rockets: 8, depthCharges: 12, noisemakers: 0, tubeCount: 2, reloadTime: 60, towedDecoy: false, xbt: 8 },
merchant: { heavy: 0, light: 0, rockets: 0, depthCharges: 0, noisemakers: 0, tubeCount: 0, reloadTime: 0, towedDecoy: false, xbt: 0 },
};
export function createLoadout(cls: ClassId): Loadout {
const { tubeCount, ...rest } = TEMPLATES[cls];
const stock = cls === 'ffg' ? rest.light : rest.heavy;
const stock = cls === 'ffg' || cls === 'kor' ? rest.light : rest.heavy;
const loaded = Math.min(tubeCount, stock);
const tubes = Array.from({ length: tubeCount }, (_, i) => ({ loaded: i < loaded, reloadDoneAt: 0 }));
if (cls === 'ffg') rest.light -= loaded;
+92
View File
@@ -0,0 +1,92 @@
import type { Environment } from './acoustics.js';
import { CLASSES } from './classes.js';
import { isAtPeriscopeDepth, type Ship } from './entities.js';
import { isSnorkeling } from './kinematics.js';
import { KN, NM, bearing, distance, wrap360 } from './math.js';
import type { Rng } from './rng.js';
/**
* Bridge lookouts on surface escorts: binoculars from about 20 m eye height.
* What gives a submarine away to the eye is rarely the boat itself but the white
* "feather" a raised periscope cuts at speed, the snorkel's exhaust haze, or a
* surfaced conning tower. Night, rain and whitecaps cut these ranges hard.
*/
export type Sighting = 'mast' | 'snorkel' | 'surfaced';
/** Eye height of the bridge lookouts (m). */
export const LOOKOUT_EYE_M = 20;
/** Binocular limit for a surfaced conning tower (m). */
const SURFACED_MAX = 12_000;
/** Torpedo tracks (bubbles, turbulence) are only seen close by and in daylight (m). */
const WAKE_RANGE = 2_000;
/** Daylight and rain factor for visual search (1 = clear day). */
export function visibility(env: Environment): number {
return (0.2 + 0.8 * (env.light ?? 1)) * (env.rain ? 0.5 : 1);
}
/** Small objects vanish among whitecaps as the sea builds. */
function clutter(env: Environment): number {
return Math.max(0.15, 1 - env.seaState * 0.14);
}
const horizon = (eye: number, target: number) => 2.08 * (Math.sqrt(eye) + Math.sqrt(target)) * NM;
/** How far a submarine can currently be seen from the bridge, and by what; undefined if not at all. */
export function sightingRange(tgt: Ship, env: Environment): { what: Sighting; range: number } | undefined {
if (!tgt.alive || !CLASSES[tgt.cls].submarine) return undefined;
const vis = visibility(env);
if (tgt.depth < 2) return { what: 'surfaced', range: Math.min(horizon(LOOKOUT_EYE_M, 8), SURFACED_MAX) * vis };
if (!isAtPeriscopeDepth(tgt)) return undefined;
const kn = tgt.speed / KN;
// Diesel exhaust haze and the snorkel head's spray: seen farther, less hidden by whitecaps
if (isSnorkeling(tgt)) return { what: 'snorkel', range: (3_500 + 300 * kn) * vis * (0.5 + 0.5 * clutter(env)) };
// A periscope or mast at speed cuts a feather; almost invisible when the boat creeps
if (tgt.mastUp) return { what: 'mast', range: Math.min(4_500, 900 + 380 * kn) * vis * clutter(env) };
return undefined;
}
export interface VisualDetection {
targetId: string;
bearing: number;
range: number;
sighting: Sighting;
}
/** One lookout sweep (1 s): a chance to spot each exposed submarine, better the closer it is. */
export function lookoutSweep(obs: Ship, ships: readonly Ship[], env: Environment, rng: Rng): VisualDetection[] {
const out: VisualDetection[] = [];
if (!obs.alive || CLASSES[obs.cls].submarine || obs.cls === 'merchant') return out;
for (const tgt of ships) {
if (tgt === obs || tgt.team === obs.team) continue;
const s = sightingRange(tgt, env);
if (!s) continue;
const r = distance(obs.pos, tgt.pos);
if (r > s.range) continue;
if (rng.next() > 0.15 + 0.5 * (1 - r / s.range)) continue;
out.push({
targetId: tgt.id, sighting: s.what,
bearing: wrap360(bearing(obs.pos, tgt.pos) + rng.gauss(0, 1)),
// Range by eye and binocular reticle: rough
range: r * Math.max(0.5, 1 + rng.gauss(0, 0.15)),
});
}
return out;
}
/** Whether the lookouts can see a torpedo's track coming in (daylight, close, moderate sea). */
export function seesTorpedoTrack(obs: Ship, range: number, env: Environment): boolean {
if (CLASSES[obs.cls].submarine || (env.light ?? 1) < 0.4) return false;
return range < WAKE_RANGE * visibility(env) * clutter(env);
}
/** Current lookout ranges for the bridge display: periscope at 6 kn, snorkel, surfaced boat (m). */
export function lookoutRanges(env: Environment): { mast: number; snorkel: number; surfaced: number } {
const vis = visibility(env);
return {
mast: Math.min(4_500, 900 + 380 * 6) * vis * clutter(env),
snorkel: (3_500 + 300 * 6) * vis * (0.5 + 0.5 * clutter(env)),
surfaced: Math.min(horizon(LOOKOUT_EYE_M, 8), SURFACED_MAX) * vis,
};
}
+12 -2
View File
@@ -13,7 +13,9 @@ import type { SeekerMode } from './weapons.js';
/** Messages client -> server. Validated with zod on the server. */
export type ClientMsg =
| { t: 'create_match'; name: string }
| { t: 'create_match'; name: string; private?: boolean }
/** Join through an invite link: the server picks the team with fewer players. */
| { t: 'join_code'; matchId: string }
| { t: 'join'; matchId: string; team: Exclude<Team, 'neutral'> }
| { t: 'leave' }
| { t: 'pick_class'; cls: Exclude<ClassId, 'merchant'> }
@@ -71,6 +73,8 @@ export interface PlayerSlot {
station?: number;
/** Naval rank from the service record (accounts only). */
rank?: string;
/** Elo rating (accounts; guests 1000). */
rating?: number;
}
export interface LobbyChatLine {
@@ -101,6 +105,8 @@ export interface MatchLobby extends MatchSummary {
merchants: number;
fillBots: boolean;
botSkill: 'leicht' | 'normal' | 'schwer';
/** Not listed; joined only through an invite link. */
private?: boolean;
weather: 'wechselhaft' | 'stabil';
custom?: CustomMissionSettings;
merchantsCount?: number;
@@ -180,7 +186,11 @@ export interface RadioMsg {
export interface AlertView {
time: number;
kind: 'torpedo' | 'esm' | 'ping' | 'sunk' | 'hit' | 'transient';
kind: 'torpedo' | 'esm' | 'ping' | 'sunk' | 'hit' | 'transient' | 'sighting';
/** Lookout sightings: what, rough range and the contact label. */
what?: 'mast' | 'snorkel' | 'surfaced';
range?: number;
label?: string;
bearing?: number;
text: string;
}
+9 -1
View File
@@ -8,6 +8,7 @@ import {
type Environment,
} from './acoustics.js';
import { isSnorkeling } from './kinematics.js';
import { lookoutSweep, type Sighting } from './lookout.js';
import { measureEvidence, sigKeyOf, type Evidence, type SigKey } from './signatures.js';
import { SHALLOW_M, pathDepth } from './seabed.js';
import { CLASSES, type ClassId } from './classes.js';
@@ -16,7 +17,7 @@ import { isAtPeriscopeDepth } from './entities.js';
import { KN, NM, angleDiff, bearing, distance, headingVec, wrap360, type Vec2 } from './math.js';
import type { Rng } from './rng.js';
export type SensorKind = 'hull' | 'towed' | 'active' | 'intercept' | 'periscope' | 'radar' | 'esm' | 'buoy';
export type SensorKind = 'hull' | 'towed' | 'active' | 'intercept' | 'periscope' | 'radar' | 'esm' | 'buoy' | 'visual';
/** A single sensor measurement. targetId never leaves the server. */
export interface Detection {
@@ -31,6 +32,8 @@ export interface Detection {
se: number;
/** Only set by visual identification (periscope). Sonar never names a contact. */
classified?: ClassId;
/** Bridge lookout: what was seen (periscope feather, snorkel haze, conning tower). */
sighting?: Sighting;
/** Narrowband/DEMON measurements for passive sonar looks. */
evidence?: Evidence;
/** CW active echo: target closing speed in kn (positive = approaching). */
@@ -261,6 +264,11 @@ export function runSensors(ctx: SensorContext): Detection[] {
}
if (CLASSES[obs.cls].submarine && obs.mastUp && isAtPeriscopeDepth(obs)) periscope(obs, ctx, out);
if (obs.radarOn && !CLASSES[obs.cls].submarine) radar(obs, ctx, out);
if (!CLASSES[obs.cls].submarine) {
for (const v of lookoutSweep(obs, ctx.ships, ctx.env, ctx.rng)) {
out.push({ observerId: obs.id, targetId: v.targetId, sensor: 'visual', time: ctx.time, bearing: v.bearing, range: v.range, se: 20, sighting: v.sighting });
}
}
if (hasAntennaUp(obs)) esm(obs, ctx, out);
}
return out;
+12 -1
View File
@@ -7,7 +7,7 @@ import type { Rng } from './rng.js';
* the player's decision, helped by the class library below.
*/
export type SigKey = 'merchant' | 'ffg' | 'ssn' | 'ssk' | 'torpedo';
export type SigKey = 'merchant' | 'ffg' | 'kor' | 'ssn' | 'ssk' | 'ssc' | 'torpedo';
export type ClassChoice = 'merchant' | 'warship' | 'submarine' | 'torpedo' | 'bio' | 'unknown';
export interface Tonal {
@@ -53,6 +53,17 @@ export const SIGNATURES: Record<SigKey, Signature> = {
tonals: [{ hz: 50, level: -2 }],
snorkelTonals: [{ hz: 24, level: 8 }, { hz: 48, level: 7 }, { hz: 72, level: 5 }],
},
kor: {
key: 'kor', name: 'Korvette K-7 (Diesel)', choice: 'warship', blades: [4],
rpmPerKn: 9, rpmRange: [50, 230], tonalBand: [40, 220], maxSpeedKn: 26,
tonals: [{ hz: 75, level: 6 }, { hz: 150, level: 4 }, { hz: 225, level: 2 }],
},
ssc: {
key: 'ssc', name: 'Küsten-U-Boot Projekt 2', choice: 'submarine', blades: [5],
rpmPerKn: 12, rpmRange: [30, 170], tonalBand: [20, 80], maxSpeedKn: 14,
tonals: [{ hz: 60, level: -4 }],
snorkelTonals: [{ hz: 30, level: 7 }, { hz: 60, level: 6 }, { hz: 90, level: 4 }],
},
torpedo: {
key: 'torpedo', name: 'Schwergewichtstorpedo', choice: 'torpedo', blades: [9, 11],
rpmPerKn: 38, rpmRange: [900, 2000], tonalBand: [0, 0], maxSpeedKn: 50,
+4 -3
View File
@@ -1,5 +1,6 @@
import { seesTorpedoTrack } from './lookout.js';
import { crossesLayer, passiveExcessFrom, torpedoSourceLevel, sourceLevelToward, targetStrengthToward } from './acoustics.js';
import { CLASSES } from './classes.js';
import { CLASSES, isEscort } from './classes.js';
import type { Ship } from './entities.js';
import { applyHitDamage, reloadFactor, weaponsBroken } from './damage.js';
import { createLoadout, stepReload, type Loadout } from './loadout.js';
@@ -187,7 +188,7 @@ export function launchNoisemaker(w: World, ship: Ship): true | string {
export function setTowedDecoy(w: World, ship: Ship, on: boolean): void {
const st = ws(w);
const l = st.loadouts.get(ship.id);
if (!l || ship.cls !== 'ffg') return;
if (!l || !isEscort(ship.cls)) return;
l.towedDecoy = on;
st.decoys = st.decoys.filter((d) => d.towedBy !== ship.id);
if (on) st.decoys.push({ id: `D${st.nextId++}`, pos: { ...ship.pos }, depth: 5, sl: 155, expiresAt: Number.MAX_SAFE_INTEGER, towedBy: ship.id });
@@ -320,7 +321,7 @@ function stepTorpedo(w: World, t: Torpedo, dt: number): boolean {
for (const s of w.ships) {
if (!s.alive || t.alerted.includes(s.id) || s.cls === 'merchant') continue;
const r = distance(s.pos, t.pos);
if (r < ALERT_RANGE && (r < ALERT_CLOSE || hearsTorpedo(w, s, t, r))) {
if (r < ALERT_RANGE && (r < ALERT_CLOSE || hearsTorpedo(w, s, t, r) || seesTorpedoTrack(s, r, w.env))) {
t.alerted.push(s.id);
w.events.push({ kind: 'torpedo_alert', time: w.time, shipId: s.id, bearing: bearing(s.pos, t.pos) });
}
+11 -3
View File
@@ -10,6 +10,7 @@ import type { Ship } from './entities.js';
import { stepShip } from './kinematics.js';
import { Rng } from './rng.js';
import { interceptTransmission, runSensors, type Detection, type Emitter } from './sensors.js';
import type { Sighting } from './lookout.js';
import type { WeaponsState } from './weapons.js';
import { buoySensors, type AirState } from './aviation.js';
@@ -23,7 +24,9 @@ export type GameEvent =
| { kind: 'torpedo_alert'; time: number; shipId: string; bearing: number }
| { kind: 'transient'; time: number; sourceId: string; x: number; y: number; what: 'flood' | 'launch' }
| { kind: 'weapon'; time: number; sourceId: string; what: 'torpedo' | 'rocket' | 'dc' | 'buoy' }
| { kind: 'grounded'; time: number; shipId: string };
| { kind: 'grounded'; time: number; shipId: string }
/** Bridge lookout reports a new sighting (start of an episode, not every sweep). */
| { kind: 'sighting'; time: number; shipId: string; label: string; bearing: number; range: number; what: Sighting };
export interface World {
time: number;
@@ -63,7 +66,12 @@ export function shipById(w: World, id: string): Ship | undefined {
}
function ingest(w: World, dets: Detection[]): void {
for (const d of dets) bookFor(w, d.observerId).ingest(d);
for (const d of dets) {
const tr = bookFor(w, d.observerId).ingest(d);
if (d.sighting && tr.sightingSince === d.time) {
w.events.push({ kind: 'sighting', time: d.time, shipId: d.observerId, label: tr.label, bearing: d.bearing, range: d.range ?? 0, what: d.sighting });
}
}
}
/** Send a radio message; enemies with antennas up get an ESM bearing on the sender. */
@@ -101,7 +109,7 @@ function checkGround(w: World, s: Ship): void {
/** A submarine's hull thermometer reveals the layer when the boat crosses it. */
function learnLayer(w: World, s: Ship): void {
if (!s.alive || s.depth < 1 || w.env.layerDepth <= 0 || s.cls === 'ffg' || s.cls === 'merchant') return;
if (!s.alive || s.depth < 1 || w.env.layerDepth <= 0 || !CLASSES[s.cls].submarine) return;
const side = s.depth > w.env.layerDepth ? 'below' : 'above';
if (s.layerSide && s.layerSide !== side) s.btLayer = Math.round(w.env.layerDepth + w.rng.gauss(0, 3));
s.layerSide = side;
+44
View File
@@ -0,0 +1,44 @@
import { describe, expect, it } from 'vitest';
import {
CLASSES,
createLoadout,
createShip,
createWorld,
hasHelicopter,
installAir,
installWeapons,
isEscort,
sendDip,
setTowedDecoy,
sourceLevel,
} from '../src/index.js';
describe('corvette and coastal submarine', () => {
it('the coastal boat is the quietest submarine, the corvette quieter than the frigate', () => {
const at = (cls: 'ssk' | 'ssc' | 'ffg' | 'kor', kn: number) => {
const s = createShip({ id: cls, cls, name: cls, pos: { x: 0, y: 0 }, heading: 0, speedKn: kn, depth: CLASSES[cls].submarine ? 60 : 0 });
s.speed = kn * 0.5144;
return sourceLevel(s);
};
expect(at('ssc', 4)).toBeLessThan(at('ssk', 4));
expect(at('kor', 15)).toBeLessThan(at('ffg', 15));
});
it('the corvette escorts and streams a decoy but carries no helicopter', () => {
expect(isEscort('kor')).toBe(true);
expect(hasHelicopter('kor')).toBe(false);
const kor = createShip({ id: 'k', cls: 'kor', name: 'K', pos: { x: 0, y: 0 }, heading: 0, speedKn: 12, team: 'west' });
const w = createWorld([kor], 1);
installWeapons(w);
installAir(w);
expect(sendDip(w, kor, { x: 3000, y: 3000 }, false)).toBe('Kein Hubschrauber an Bord');
setTowedDecoy(w, kor, true);
expect(w.weapons!.decoys.some((d) => d.towedBy === 'k')).toBe(true);
});
it('loadouts: corvette fires lightweights, the coastal boat has four loaded tubes', () => {
expect(createLoadout('kor').tubes.every((t) => t.loaded)).toBe(true);
expect(createLoadout('ssc').tubes).toHaveLength(4);
expect(createLoadout('ssc').heavy).toBe(2);
});
});
+74
View File
@@ -0,0 +1,74 @@
import { describe, expect, it } from 'vitest';
import { createShip, lookoutSweep, Rng, runSensors, seesTorpedoTrack, sightingRange, type Environment } from '../src/index.js';
const day: Environment = { layerDepth: 100, layerLoss: 12, seaState: 3, light: 1 };
const night: Environment = { ...day, light: 0 };
function sub(opts: { depth: number; kn: number; mast?: boolean; snorkel?: boolean; y?: number }) {
const s = createShip({ id: 'u', cls: 'ssk', name: 'U', pos: { x: 0, y: opts.y ?? 1500 }, heading: 90, speedKn: opts.kn, depth: opts.depth, team: 'east' });
s.mastUp = !!opts.mast;
s.snorkel = !!opts.snorkel;
return s;
}
const frigate = () => createShip({ id: 'f', cls: 'ffg', name: 'F', pos: { x: 0, y: 0 }, heading: 0, speedKn: 12, team: 'west' });
describe('bridge lookouts', () => {
it('see nothing of a boat below periscope depth or with masts down', () => {
expect(sightingRange(sub({ depth: 60, kn: 4, mast: true }), day)).toBeUndefined();
expect(sightingRange(sub({ depth: 18, kn: 4 }), day)).toBeUndefined();
});
it('see a periscope feather farther the faster the boat runs', () => {
const slow = sightingRange(sub({ depth: 18, kn: 2, mast: true }), day)!;
const fast = sightingRange(sub({ depth: 18, kn: 8, mast: true }), day)!;
expect(slow.what).toBe('mast');
expect(fast.range).toBeGreaterThan(slow.range * 1.5);
expect(fast.range).toBeLessThan(4_500);
});
it('see a snorkel farther than a periscope, and a surfaced boat farthest', () => {
const mast = sightingRange(sub({ depth: 18, kn: 5, mast: true }), day)!.range;
const snort = sightingRange(sub({ depth: 18, kn: 5, snorkel: true }), day)!.range;
const surf = sightingRange(sub({ depth: 0, kn: 5 }), day)!.range;
expect(snort).toBeGreaterThan(mast);
expect(surf).toBeGreaterThan(snort);
});
it('are nearly blind at night and in heavy seas', () => {
const b = sub({ depth: 18, kn: 6, mast: true });
const d = sightingRange(b, day)!.range;
expect(sightingRange(b, night)!.range).toBeLessThan(d * 0.25);
expect(sightingRange(b, { ...day, seaState: 6 })!.range).toBeLessThan(d * 0.4);
});
it('report a close periscope within a few sweeps, with a rough range', () => {
const rng = new Rng(3);
const f = frigate();
const u = sub({ depth: 18, kn: 6, mast: true, y: 800 });
let hit;
for (let i = 0; i < 10 && !hit; i++) hit = lookoutSweep(f, [f, u], day, rng)[0];
expect(hit?.sighting).toBe('mast');
expect(hit!.range).toBeGreaterThan(300);
expect(hit!.range).toBeLessThan(1_400);
});
it('never report own-team boats and run as part of the sensor cycle', () => {
const f = frigate();
const own = createShip({ id: 'w', cls: 'ssn', name: 'W', pos: { x: 0, y: 500 }, heading: 0, speedKn: 6, depth: 18, team: 'west' });
own.mastUp = true;
const u = sub({ depth: 18, kn: 6, mast: true, y: 600 });
const rng = new Rng(1);
const seen = new Set<string>();
for (let i = 0; i < 20; i++) {
for (const d of runSensors({ ships: [f, own, u], env: day, time: i, rng })) if (d.sensor === 'visual') seen.add(d.targetId);
}
expect([...seen]).toEqual(['u']);
});
it('spot torpedo tracks only close by and in daylight', () => {
const f = frigate();
expect(seesTorpedoTrack(f, 900, day)).toBe(true);
expect(seesTorpedoTrack(f, 900, night)).toBe(false);
expect(seesTorpedoTrack(f, 3_000, day)).toBe(false);
});
});
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env bash
# Deploy Tiefenkontakt to a Raspberry Pi (or any Linux host with Docker) over SSH.
# Usage: scripts/deploy-pi.sh [user@host] [remote dir]
# Needs SSH key login (ssh-copy-id user@host once). The remote .env is never overwritten.
set -euo pipefail
HOST="${1:-speech@speech.local}"
DIR="${2:-tiefenkontakt}"
cd "$(dirname "$0")/.."
echo "▸ Kopiere Code nach $HOST:~/$DIR"
ssh "$HOST" "mkdir -p ~/$DIR"
rsync -az --delete \
--exclude node_modules --exclude dist --exclude .git --exclude .matches --exclude '*.db' --exclude '*.db-journal' \
--exclude .env --exclude .claude --exclude .DS_Store \
./ "$HOST:~/$DIR/"
echo "▸ Baue und starte den Container (beim ersten Mal einige Minuten)"
ssh "$HOST" "cd ~/$DIR && ( [ -f .env ] || cp .env.example .env ) && docker compose up -d --build"
echo "▸ Warte auf den Server"
for i in $(seq 1 60); do
if ssh "$HOST" "curl -sf localhost:\$(grep -E '^HOST_PORT=' ~/$DIR/.env | cut -d= -f2 || echo 8787)/api/health >/dev/null 2>&1 || curl -sf localhost:8787/api/health >/dev/null"; then
echo "✓ Läuft auf $HOST"
exit 0
fi
sleep 3
done
echo "✗ Server antwortet nicht – Logs:"
ssh "$HOST" "cd ~/$DIR && docker compose logs --tail 40"
exit 1
+74
View File
@@ -0,0 +1,74 @@
/**
* Load test over real WebSockets: starts a server process, opens N matches with two
* human clients each (AI fills the rest), plays for S seconds and reports wire traffic,
* snapshot rate and the server's own metrics.
* Usage: npx tsx scripts/net-load-test.ts [matches=10] [seconds=60]
*/
import { spawn } from 'node:child_process';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { WebSocket } from 'ws';
const MATCHES = Number(process.argv[2] ?? 10);
const SECONDS = Number(process.argv[3] ?? 60);
const PORT = 19_000 + Math.floor(Math.random() * 500);
const TOKEN = 'loadtest-' + Math.random().toString(36).slice(2);
const data = mkdtempSync(join(tmpdir(), 'tk-load-'));
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
const server = spawn(process.execPath, ['--import', 'tsx', 'src/index.ts'], {
cwd: resolve(import.meta.dirname, '../apps/server'),
env: { ...process.env, PORT: String(PORT), DB_PATH: join(data, 'db.sqlite'), MATCH_DIR: join(data, 'm'), METRICS_TOKEN: TOKEN, NODE_ENV: 'test' },
stdio: ['ignore', 'pipe', 'inherit'],
});
await new Promise<void>((ok) => server.stdout!.on('data', (d: Buffer) => d.toString().includes('Tiefenkontakt-Server') && ok()));
interface Client { ws: WebSocket; snaps: number; inbox: { t: string; match?: { id: string } }[] }
const open = (name: string, i: number) => new Promise<Client>((ok) => {
const gid = i.toString(16).padStart(32, 'a');
const ws = new WebSocket(`ws://localhost:${PORT}/ws?guest=${name}&gid=${gid}`);
const c: Client = { ws, snaps: 0, inbox: [] };
ws.on('message', (d) => {
const m = JSON.parse(d.toString());
if (m.t === 'snap') c.snaps++;
else c.inbox.push(m);
});
ws.on('open', () => ok(c));
});
const clients: Client[] = [];
for (let i = 0; i < MATCHES; i++) {
const a = await open(`W${i}`, i * 2);
const b = await open(`O${i}`, i * 2 + 1);
a.ws.send(JSON.stringify({ t: 'create_match', name: `Last ${i}` }));
await wait(150);
const id = a.inbox.find((m) => m.t === 'match')!.match!.id;
b.ws.send(JSON.stringify({ t: 'join', matchId: id, team: 'east' }));
await wait(100);
a.ws.send(JSON.stringify({ t: 'ready', ready: true }));
b.ws.send(JSON.stringify({ t: 'ready', ready: true }));
clients.push(a, b);
}
const t0 = Date.now();
const read0 = clients.map((c) => (c.ws as unknown as { _socket: { bytesRead: number } })._socket.bytesRead);
// Players do something: every few seconds a course change
const busy = setInterval(() => {
for (const c of clients) c.ws.send(JSON.stringify({ t: 'order', heading: Math.floor(Math.random() * 360), speedKn: 5 }));
}, 4000);
await wait(SECONDS * 1000);
clearInterval(busy);
const dt = (Date.now() - t0) / 1000;
const wire = clients.map((c, i) => ((c.ws as unknown as { _socket: { bytesRead: number } })._socket.bytesRead - read0[i]!) / dt);
const snapsPerS = clients.map((c) => c.snaps / dt);
const m = await (await fetch(`http://localhost:${PORT}/api/metrics`, { headers: { authorization: `Bearer ${TOKEN}` } })).json();
const avg = (a: number[]) => a.reduce((x, y) => x + y, 0) / a.length;
console.log(`${MATCHES} Partien, ${clients.length} Spieler (+ KI), ${dt.toFixed(0)} s`);
console.log(`Leitung pro Spieler (komprimiert): Ø ${(avg(wire) / 1024).toFixed(1)} KB/s, max ${(Math.max(...wire) / 1024).toFixed(1)} KB/s`);
console.log(`Snapshots pro Spieler: Ø ${avg(snapsPerS).toFixed(2)}/s (min ${Math.min(...snapsPerS).toFixed(2)})`);
console.log(`Server: Tick Ø ${m.tickMsAvg} ms, p95 ${m.tickMsP95} ms, max ${m.tickMsMax} ms · Event-Loop p99 ${m.eventLoopLagMsP99} ms · RSS ${m.rssMb} MB · ${m.matchesRunning} Partien laufen`);
const slow = clients.map((c, i) => ({ i, s: snapsPerS[i]!, msgs: c.inbox.map((x) => x.t + ((x as { msg?: string }).msg ? ':' + (x as { msg?: string }).msg : '')).slice(0, 8) })).filter((x) => x.s < 5);
if (slow.length) console.log('Langsame Clients:', JSON.stringify(slow));
for (const c of clients) c.ws.close();
server.kill('SIGTERM');
process.exit(0);