Show live Horizon terrain and radar views in the web panel

This commit is contained in:
2026-12-02 18:52:41 +03:00
parent 7612d15963
commit 20fdb23b39
15 changed files with 818 additions and 120 deletions
+52 -14
View File
@@ -2,11 +2,11 @@
color-scheme: dark;
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
font-size: 16px;
background: #0b121a;
background: #0a1018;
color: #e4edf1;
--surface: #111e29;
--surface-raised: #182936;
--border: #2b4250;
--surface: #111b26;
--surface-raised: #172534;
--border: #293a4c;
--muted: #9ab0bb;
--accent: #70d7c9;
--warning: #edbd6c;
@@ -51,9 +51,10 @@ h3 { font-size: .9rem; margin-bottom: .55rem; }
.tabs { display: flex; gap: .4rem; overflow-x: auto; padding: 0 0 .75rem; scrollbar-width: thin; }
.tabs button, .tabs a { flex: 0 0 auto; }
.tabs [aria-selected="true"], .tabs [aria-current="page"], .tabs .active { background: #1b4c4a; border-color: #70d7c9; color: #e6fffa; }
.workspace { display: grid; grid-template-columns: minmax(0, 1fr) minmax(260px, 340px); gap: .85rem; align-items: start; }
.map-column, .side-panel { min-width: 0; display: grid; gap: .75rem; }
.map-wrap { position: relative; overflow: hidden; min-height: 260px; border: 1px solid #35515d; border-radius: 12px; background: #101c24; }
.workspace { display: grid; grid-template-columns: minmax(0, 1fr) minmax(270px, 320px); gap: 1rem; align-items: start; }
.map-column, .side-panel { min-width: 0; display: grid; }
.map-column { border: 1px solid var(--border); border-radius: 14px; background: var(--surface); overflow: clip; }
.map-wrap { position: relative; overflow: hidden; min-height: 260px; border-block: 1px solid var(--border); background: #101c24; }
.map-wrap canvas { display: block; width: 100%; height: auto; touch-action: none; }
.map-tools, .toolbar, .row { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; }
.map-tools > *, .toolbar > * { flex: 0 1 auto; }
@@ -70,7 +71,7 @@ small, .muted { color: var(--muted); }
[hidden] { display: none !important; }
dialog { width: min(90vw, 540px); max-height: min(85vh, 800px); overflow: auto; padding: 1.2rem; border: 1px solid #4d6974; border-radius: 14px; background: #152630; color: inherit; box-shadow: 0 20px 70px #0009; }
dialog::backdrop { background: #02080dc9; }
@media (max-width: 800px) {
@media (max-width: 800px), (max-width: 1100px) and (orientation: portrait) {
.workspace { grid-template-columns: minmax(0, 1fr); }
.side-panel { grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr)); }
.map-wrap { min-height: 200px; }
@@ -81,11 +82,11 @@ dialog::backdrop { background: #02080dc9; }
}
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { scroll-behavior: auto !important; transition-duration: 0s !important; animation-duration: 0s !important; } }
.map-wrap canvas { height: clamp(280px, 59dvh, 690px); }
.map-tools { justify-content: space-between; }
.map-actions { display: flex; gap: .35rem; }
.map-wrap canvas { height: clamp(300px, 65dvh, 780px); }
.map-tools { padding: .65rem; gap: .5rem .85rem; }
.map-actions { display: flex; gap: .35rem; margin-left: auto; }
.map-actions button { min-width: 44px; }
.legend { display: flex; flex-wrap: wrap; gap: .65rem 1rem; padding: .65rem .85rem; }
.legend { display: flex; flex-wrap: wrap; gap: .1rem .85rem; }
.legend label { display: flex; align-items: center; min-height: 34px; cursor: pointer; }
.side-panel > .card { display: grid; gap: .7rem; }
.pairing { max-width: 410px; margin: clamp(36px, 15vh, 160px) auto 0; }
@@ -101,8 +102,8 @@ dialog::backdrop { background: #02080dc9; }
.object-card button { margin-top: .5rem; }
#history-more, #preview, #confirm-launch { color: #b6f3eb; border-color: #447672; }
#launch-status:empty, #pair-error:empty, #map-status:empty { display: none; }
@media (min-width: 801px) and (min-height: 680px) { .map-column { position: sticky; top: .75rem; } }
@media (max-width: 800px) { .map-wrap canvas { height: clamp(240px, 46dvh, 580px); } }
@media (min-width: 801px) and (min-height: 680px) and (orientation: landscape), (min-width: 1101px) and (min-height: 680px) { .map-column { position: sticky; top: .75rem; } }
@media (max-width: 800px), (max-width: 1100px) and (orientation: portrait) { .map-wrap canvas { height: clamp(270px, 49dvh, 580px); } }
.timeline-marker-rail { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: .1rem; }
.timeline-marker-slot { display: flex; justify-content: center; min-width: 0; }
@@ -116,3 +117,40 @@ dialog::backdrop { background: #02080dc9; }
.timeline-marker-heading { margin: 0; font-size: .8rem; }
.timeline-marker-choice { text-align: left; font-size: .82rem; overflow-wrap: anywhere; }
.timeline-marker-choice[aria-current="true"] { border-color: var(--accent); }
.brand { display: flex; align-items: baseline; gap: .65rem; }
.brand h1 { letter-spacing: -.035em; }
.connection-readout { display: flex; flex-wrap: wrap; align-items: center; gap: .45rem .7rem; }
#connection { display: inline-flex; align-items: center; gap: .45rem; border-radius: 99px; padding: .3rem .6rem; background: var(--surface); border: 1px solid var(--border); font-weight: 650; }
#connection::before { content: ""; height: .45rem; width: .45rem; border-radius: 50%; background: currentColor; }
#refresh-rate { color: var(--muted); font-size: .79rem; font-variant-numeric: tabular-nums; }
.tabs { gap: .2rem; }
.tabs button { background: transparent; border-color: transparent; }
.tabs [aria-current="page"] { color: #b6f2e7; background: #163332; border-color: #305b56; }
.map-mode { display: inline-flex; gap: 2px; padding: 2px; background: #0b141f; border: 1px solid var(--border); border-radius: 10px; }
.map-mode button { background: transparent; border-color: transparent; min-height: 38px; padding: .4rem .8rem; color: var(--muted); }
.map-mode button[aria-pressed="true"] { background: #234443; border-color: #3d6864; color: #d3fff3; }
.inline-field { display: flex; align-items: center; gap: .4rem; }
.inline-field select { min-width: 0; max-width: 13rem; min-height: 42px; font-size: .85rem; }
.map-footer { padding: .35rem .75rem .6rem; }
.map-readout { display: flex; flex-wrap: wrap; justify-content: space-between; gap: .25rem .75rem; min-height: 1rem; color: var(--muted); font-size: .78rem; }
#map-status { font-variant-numeric: tabular-nums; }
.legend [data-layer="units"] { accent-color: #6adcd2; }
.legend [data-layer="objects"] { accent-color: #a9baf6; }
.legend [data-layer="contacts"] { accent-color: #f0bf6a; }
.legend [data-layer="interceptors"] { accent-color: #b2e68f; }
.panel-title { margin: 0; font-size: 1.05rem; }
#object-list { max-height: min(52dvh, 510px); gap: .32rem; }
#object-list button { display: grid; gap: .2rem; border-left: 3px solid var(--marker, var(--border)); }
#object-list small { font-weight: 450; font-size: .76rem; }
#object-list [data-kind="unit"] { --marker: #6adcd2; }
#object-list [data-kind="object"] { --marker: #a9baf6; }
#object-list [data-kind="contact"] { --marker: #f0bf6a; }
#object-list [data-kind="interceptor"] { --marker: #b2e68f; }
@media (max-width: 540px) {
.map-tools { gap: .5rem; }
.inline-field { font-size: .8rem; }
.inline-field select { max-width: 45vw; }
#fit { padding-inline: .5rem; }
}
+94 -18
View File
@@ -73,6 +73,9 @@ const groups = [["units", "unit"], ["objects", "object"], ["contacts", "contact"
const prefs = read("view", {layers: {}, views: {}, selected: null});
prefs.layers ||= {};
prefs.views ||= {};
const LIVE_POLL_MS = 650;
let mapMode = prefs.mapMode === "radar" ? "radar" : "map";
let radarOptions = "";
let auth = null, network = null, live = null, historical = null, tab = "live", perspective = "network";
let selected = prefs.selected, connected = false, http = false, polling = false, catalog = null;
let events = [], raids = [], raid = null, more = false, historyGeneration = 0, frameGeneration = 0, chainGeneration = 0;
@@ -81,18 +84,22 @@ let offlineEvents = [], offlineFrames = {}, offlineRaids = {raids: []};
let offlineTimelines = {}, selectedEvent = null, timelineGeneration = 0;
const timelineRequests = new Map();
const timeline = createTimeline($("timeline-markers"), openEvent, time);
const viewKey = () => mapMode === "radar" ? `radar:${perspective}` : perspective;
const eventFields = {unit: "unit", contact: "target", object: "object"};
const eventOrder = {observations: 0, decisions: 1, events: 2};
let latestObject = {key: "", checked: 0, event: null};
const map = createMap($("map"), {
onSelect: key => select(key),
onTerrain: message => {
if ($("map-source").textContent !== message) $("map-source").textContent = message;
},
onView: view => {
if (historical) return;
prefs.views[perspective] = view;
prefs.views[viewKey()] = view;
write("view", prefs);
},
});
map.restore(prefs.views.network);
map.restore(prefs.views[viewKey()]);
function time(ticks) {
const tenths = Math.floor(Math.max(0, ticks) / 2);
@@ -111,6 +118,7 @@ function showAuth() {
option.hidden = option.value !== "network" && !auth?.permissions?.debug;
option.disabled = option.hidden;
}
$("perspective-label").hidden = !auth?.permissions?.debug;
if (!auth?.permissions?.debug) perspective = "network";
updateStatus();
}
@@ -118,9 +126,14 @@ function updateStatus() {
const status = $("connection");
const updated = live?.updated ?? network?.updated;
status.className = connected ? "success" : "warning";
status.textContent = connected ? `Игра в сети · ${when(live?.updated)}`
status.textContent = connected ? "Игра в сети"
: auth ? updated ? `Нет связи · снимок от ${when(updated)}` : "Ожидание игры"
: http ? "Ожидает подключения" : "Нет соединения";
$("refresh-rate").hidden = !connected;
if (connected) {
const rate = (live.sampleMs || 1000) / 1000;
$("refresh-rate").textContent = `Снимок каждые ${rate.toLocaleString("ru-RU")} с · получен в ${when(live.updated)}`;
}
$("logout").disabled = !http;
}
function activeFrame() {
@@ -136,9 +149,29 @@ function select(key, centre = false) {
draw();
if (centre) map.focus(key);
}
function radarStations(frame) {
return frame?.units?.filter(row => row.radarRange > 0) || [];
}
function draw() {
const frame = activeFrame();
map.draw(frame, {selected, layers: prefs.layers});
const stations = radarStations(frame);
const signature = JSON.stringify(stations.map(({id, label}) => [id, label]));
if (signature !== radarOptions) {
radarOptions = signature;
const options = [new Option("Вся сеть", ""), ...stations.map(row => new Option(`${fullname(row)} №${row.id}`, row.id))];
$("radar-site").replaceChildren(...options);
}
const station = stations.find(row => String(row.id) === prefs.radarSite);
$("radar-site").value = station ? prefs.radarSite : "";
$("radar-site-label").hidden = mapMode !== "radar" || stations.length === 0;
for (const node of document.querySelectorAll("[data-map-mode]")) {
node.setAttribute("aria-pressed", String(node.dataset.mapMode === mapMode));
}
const scope = historical ? historical.frame?.terrain : live?.terrain ?? network?.terrain;
const center = historical ? null : live?.mapCenter ?? network?.mapCenter;
$("player-center").hidden = !center;
map.draw(frame, {selected, layers: prefs.layers, mode: mapMode, radarId: $("radar-site").value, scope, center,
online: !historical && connected && Boolean(live?.terrain)});
$("return-live").hidden = !historical;
$("history-live").hidden = !historical;
$("perspective").disabled = !!historical;
@@ -164,19 +197,32 @@ function draw() {
showObject(opened, frame);
const filter = $("object-search").value.toLocaleLowerCase("ru");
const matched = data.filter(({row}) => !filter || fullname(row).toLocaleLowerCase("ru").includes(filter) || String(row.id) === filter);
const oldScroll = $("object-list").scrollTop;
const focused = document.activeElement?.dataset.objectKey;
const nodes = matched.slice(0, 130).map(({row, key}) => {
const node = button([fullname(row), row.status].filter(Boolean).join(" · "), () => select(key, true));
const list = $("object-list");
const existing = new Map([...list.children].map(node => [node.dataset.objectKey, node]));
const nodes = matched.slice(0, 130).map(({row, key, kind}) => {
const node = existing.get(key) || button("", () => select(key, true));
node.dataset.objectKey = key;
node.dataset.kind = kind;
node.setAttribute("aria-pressed", String(key === selected));
const label = fullname(row);
if (!node.firstChild) node.append(make("span", label), make("small", row.status || ""));
if (node.firstChild.textContent !== label) node.firstChild.textContent = label;
const sublabel = row.status || "";
if (node.lastChild.textContent !== sublabel) node.lastChild.textContent = sublabel;
node.lastChild.hidden = !sublabel;
return node;
});
if (matched.length > nodes.length) nodes.push(paragraph(`Показано ${nodes.length} из ${matched.length}. Уточните поиск.`));
if (!nodes.length) nodes.push(make("p", "Подходящих объектов нет", "empty"));
$("object-list").replaceChildren(...nodes);
$("object-list").scrollTop = oldScroll;
if (focused) nodes.find(node => node.dataset.objectKey === focused)?.focus({preventScroll: true});
const note = matched.length > nodes.length ? `Показано ${nodes.length} из ${matched.length}. Уточните поиск.` :
nodes.length === 0 ? "Подходящих объектов нет" : "";
if (note) {
const node = existing.get(undefined) || make("p", "", "empty");
if (node.textContent !== note) node.textContent = note;
nodes.push(node);
}
for (const [index, node] of nodes.entries()) {
if (list.children[index] !== node) list.insertBefore(node, list.children[index] ?? null);
}
while (list.children.length > nodes.length) list.lastChild.remove();
drawScenario();
}
function showObject(opened, frame) {
@@ -200,6 +246,7 @@ function showObject(opened, frame) {
if (row.age != null) nodes.push(paragraph(`Давность ${(row.age / 20).toFixed(1)} с`));
if (row.confidence) nodes.push(paragraph(`Достоверность · ${row.confidence}`));
if (row.quality != null) nodes.push(paragraph(`Качество · ${row.quality}`));
if (row.radarRange > 0) nodes.push(paragraph(`Номинальная дальность радара · ${Math.round(row.radarRange)} бл.`));
if (row.radius > 0) nodes.push(paragraph(`Область оценки · ±${Math.round(row.radius)} бл.`));
if (row.target) nodes.push(button(`Контакт №${row.target}`, () => select(`contact:${row.target}`, true)));
if (row.source) {
@@ -255,6 +302,7 @@ function forgetCachedData() {
historyGeneration++;
clearEvent();
cache("all", null);
map.clearTerrain();
network = live = historical = null;
connected = false;
latestObject = {key: "", checked: 0, event: null};
@@ -297,7 +345,9 @@ async function poll() {
if (mode === "network" && data.frame) {
if (prefs.world && prefs.world !== data.world) {
prefs.selected = null;
delete prefs.views.network;
delete prefs.radarSite;
map.clearTerrain();
prefs.views = {};
if (!historical) {
selected = null;
map.restore(null);
@@ -375,7 +425,7 @@ function chooseRaid(value) {
else {
historical = null;
selected = perspective === "network" ? prefs.selected : null;
map.restore(prefs.views[perspective]);
map.restore(prefs.views[viewKey()]);
draw();
}
refreshTimeline();
@@ -763,15 +813,41 @@ for (const node of document.querySelectorAll("[data-layer]")) {
draw();
});
}
function centerRadar() {
const station = radarStations(activeFrame()).find(row => String(row.id) === prefs.radarSite);
if (station) map.centerAt(station.x, station.z, station.radarRange);
}
for (const node of document.querySelectorAll("[data-map-mode]")) {
node.addEventListener("click", () => {
if (mapMode === node.dataset.mapMode) return;
mapMode = prefs.mapMode = node.dataset.mapMode;
if (!historical) {
map.restore(prefs.views[viewKey()]);
if (mapMode === "radar" && !prefs.views[viewKey()]) centerRadar();
}
write("view", prefs);
draw();
});
}
$("radar-site").addEventListener("change", () => {
prefs.radarSite = $("radar-site").value;
centerRadar();
write("view", prefs);
draw();
});
$("object-search").addEventListener("input", draw);
$("zoom-in").addEventListener("click", () => map.zoom(1.3));
$("zoom-out").addEventListener("click", () => map.zoom(1 / 1.3));
$("fit").addEventListener("click", map.fit);
$("player-center").addEventListener("click", () => {
const center = live?.mapCenter ?? network?.mapCenter;
if (center) map.centerAt(...center);
});
$("perspective").addEventListener("change", () => {
perspective = $("perspective").value;
selected = perspective === "network" ? prefs.selected : null;
live = perspective === "network" ? network : null;
map.restore(prefs.views[perspective]);
map.restore(prefs.views[viewKey()]);
draw();
poll();
});
@@ -784,7 +860,7 @@ function returnLive() {
perspective = "network";
$("perspective").value = "network";
live = network;
map.restore(prefs.views.network);
map.restore(prefs.views[viewKey()]);
setTab("live");
poll();
}
@@ -877,5 +953,5 @@ window.addEventListener("online", async () => {
poll();
});
document.addEventListener("visibilitychange", () => { if (!document.hidden) poll(); });
setInterval(poll, 1200);
setInterval(poll, LIVE_POLL_MS);
start();
+23 -11
View File
@@ -14,9 +14,12 @@
<body>
<main class="shell">
<header class="topbar">
<div><h1>AirDef</h1><p>Командный пункт</p></div>
<div class="brand"><h1>AirDef</h1><p>Командный пункт</p></div>
<div class="row">
<span id="connection" role="status">Подключение…</span>
<div class="connection-readout">
<span id="connection" role="status">Подключение…</span>
<span id="refresh-rate" hidden></span>
</div>
<button id="install" type="button" hidden>Установить</button>
<button id="logout" type="button" hidden>Отвязать</button>
</div>
@@ -38,29 +41,38 @@
<div class="workspace">
<section id="map-panel" class="map-column" aria-label="Карта боя">
<div class="map-tools">
<label>Ракурс<select id="perspective">
<div class="map-mode" aria-label="Подложка карты" role="group">
<button type="button" data-map-mode="map" aria-pressed="true">Рельеф</button>
<button type="button" data-map-mode="radar" aria-pressed="false">Радар</button>
</div>
<label class="inline-field" id="perspective-label" hidden>Ракурс<select id="perspective">
<option value="network">Картина игрока</option>
<option value="enemy" hidden>Что известно противнику</option>
<option value="truth" hidden>Истина · песочница</option>
</select></label>
<label class="inline-field" id="radar-site-label" hidden>Центр РЛС<select id="radar-site"></select></label>
<button type="button" id="return-live" hidden>К прямому эфиру</button>
<div class="map-actions">
<button type="button" id="zoom-in" aria-label="Приблизить">+</button>
<button type="button" id="zoom-out" aria-label="Отдалить">−</button>
<button type="button" id="fit">Вся карта</button>
<button type="button" id="fit">Все отметки</button>
<button type="button" id="player-center" hidden>К игроку</button>
</div>
</div>
<div class="map-wrap"><canvas id="map" aria-label="Карта игровых объектов"></canvas></div>
<div class="card legend" id="layer-options">
<label><input type="checkbox" data-layer="units" checked> □ Техника</label>
<label><input type="checkbox" data-layer="objects" checked> ◇ Объекты</label>
<label><input type="checkbox" data-layer="contacts" checked> ○ Контакты</label>
<label><input type="checkbox" data-layer="interceptors" checked> ▵ Перехватчики</label>
</div>
<p id="map-status" role="status"></p>
<footer class="map-footer">
<div class="legend" id="layer-options" aria-label="Слои карты" role="group">
<label><input type="checkbox" data-layer="units" checked> Техника</label>
<label><input type="checkbox" data-layer="objects" checked> Объекты</label>
<label><input type="checkbox" data-layer="contacts" checked> Контакты</label>
<label><input type="checkbox" data-layer="interceptors" checked> Перехватчики</label>
</div>
<div class="map-readout"><span id="map-source"></span><span id="map-status" role="status"></span></div>
</footer>
</section>
<aside class="side-panel">
<section id="live-panel" class="card">
<h2 class="panel-title">Объекты на карте</h2>
<div id="object-card" class="object-card" tabindex="-1"></div>
<label>Найти на карте<input id="object-search" type="search" autocomplete="off"></label>
<div id="object-list" class="list scroller" aria-label="Объекты на карте"></div>
+96 -50
View File
@@ -1,3 +1,6 @@
import {drawSymbol} from "./symbols.js";
import {createTerrain} from "./terrain.js";
const styles = [
["units", "unit", "#6adcd2"],
["objects", "object", "#a9baf6"],
@@ -6,11 +9,13 @@ const styles = [
];
const clamp = (x, low, high) => Math.min(high, Math.max(low, x));
export function createMap(canvas, {onSelect, onView}) {
export function createMap(canvas, {onSelect, onView, onTerrain}) {
const ctx = canvas.getContext("2d");
const view = {x: 0, z: 0, scale: .22};
const fingers = new Map();
let points = [], visible = [], selected, width = 1, height = 1, drawnFrame;
const terrain = createTerrain(schedule);
let mode = "map", scope, online, radarId;
let moved = false, autoFit = true, queued = false;
function paint() {
@@ -24,28 +29,67 @@ export function createMap(canvas, {onSelect, onView}) {
canvas.height = h;
}
ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
ctx.fillStyle = "#101c24";
ctx.fillRect(0, 0, width, height);
const {x, z, scale} = view;
const px = v => (v - x) * scale + width / 2;
const py = v => (v - z) * scale + height / 2;
const left = x - width / (2 * scale), top = z - height / (2 * scale);
const steps = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000];
const step = steps.find(s => s * scale >= 48) || steps.at(-1);
ctx.strokeStyle = "#233947";
const steps = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 25000];
const step = steps.find(s => s * scale >= 54) || steps.at(-1);
ctx.fillStyle = mode === "radar" ? "#071718" : "#101c27";
ctx.fillRect(0, 0, width, height);
ctx.lineWidth = 1;
ctx.beginPath();
for (let a = Math.ceil(left / step) * step; px(a) < width; a += step) {
const line = Math.round(px(a)) + .5;
ctx.moveTo(line, 0);
ctx.lineTo(line, height);
if (mode === "radar") {
const station = drawnFrame?.units?.find(unit => String(unit.id) === radarId && unit.radarRange > 0);
const cx = station ? px(station.x) : width / 2;
const cy = station ? py(station.z) : height / 2;
const spacing = step * scale;
const min = Math.max(1, Math.floor(Math.hypot(Math.max(-cx, cx - width, 0), Math.max(-cy, cy - height, 0)) / spacing));
const max = Math.ceil(Math.hypot(Math.max(Math.abs(cx), Math.abs(cx - width)), Math.max(Math.abs(cy), Math.abs(cy - height))) / spacing);
ctx.strokeStyle = "#345c54";
ctx.fillStyle = "#8ab5aa";
ctx.font = "11px system-ui, sans-serif";
for (let ring = min; ring <= max; ring++) {
const radius = ring * spacing;
ctx.beginPath();
ctx.arc(cx, cy, radius, 0, Math.PI * 2);
ctx.stroke();
ctx.fillText(`${ring * step}`, cx + 5, cy - radius + 14);
}
ctx.beginPath();
ctx.moveTo(cx, 0);
ctx.lineTo(cx, height);
ctx.moveTo(0, cy);
ctx.lineTo(width, cy);
ctx.stroke();
if (station) {
ctx.beginPath();
ctx.arc(cx, cy, station.radarRange * scale, 0, Math.PI * 2);
ctx.strokeStyle = "#73dbc5";
ctx.setLineDash([6, 5]);
ctx.stroke();
ctx.setLineDash([]);
}
onTerrain(station ? `${station.label} · номинальная дальность ${Math.round(station.radarRange)} бл.` : "Общая картина сети");
} else {
ctx.imageSmoothingEnabled = false;
const loaded = terrain.paint(ctx, view, width, height, scope, online);
ctx.imageSmoothingEnabled = true;
const left = x - width / (2 * scale), top = z - height / (2 * scale);
ctx.strokeStyle = loaded ? "#d9eff429" : "#253745";
ctx.beginPath();
for (let a = Math.ceil(left / step) * step; px(a) < width; a += step) {
const line = Math.round(px(a)) + .5;
ctx.moveTo(line, 0);
ctx.lineTo(line, height);
}
for (let a = Math.ceil(top / step) * step; py(a) < height; a += step) {
const line = Math.round(py(a)) + .5;
ctx.moveTo(0, line);
ctx.lineTo(width, line);
}
ctx.stroke();
onTerrain(online ? loaded ? "Рельеф загруженных чанков" : "Ожидание данных местности" :
loaded ? "Последний загруженный рельеф" : "Рельеф доступен в открытом мире");
}
for (let a = Math.ceil(top / step) * step; py(a) < height; a += step) {
const line = Math.round(py(a)) + .5;
ctx.moveTo(0, line);
ctx.lineTo(width, line);
}
ctx.stroke();
ctx.font = "12px system-ui, sans-serif";
ctx.fillStyle = "#b6c8d0";
ctx.fillText("↑ N", width - 36, 20);
@@ -59,25 +103,11 @@ export function createMap(canvas, {onSelect, onView}) {
const x = px(row.x), y = py(row.z);
if (x < -40 || y < -40 || x > width + 40 || y > height + 40) continue;
visible.push({...point, x, y});
const r = point.key === selected ? 8 : 5;
ctx.beginPath();
if (kind === "unit") {
ctx.rect(x - r, y - r, 2 * r, 2 * r);
} else if (kind === "contact") {
ctx.arc(x, y, r, 0, Math.PI * 2);
} else {
ctx.moveTo(x, y - r);
ctx.lineTo(x + r, kind === "object" ? y : y + r);
if (kind === "object") ctx.lineTo(x, y + r);
ctx.lineTo(x - r, kind === "object" ? y : y + r);
ctx.closePath();
}
ctx.strokeStyle = ctx.fillStyle = color;
ctx.lineWidth = 2;
if (kind !== "contact") ctx.fill();
if (row.status?.startsWith("Оценка")) ctx.setLineDash([3, 2]);
ctx.stroke();
ctx.setLineDash([]);
const heading = Math.hypot(row.vx, row.vz) > 0 ? Math.atan2(row.vx, -row.vz) : 0;
const symbol = row.symbol || (kind === "contact" ? "unknown" : kind);
drawSymbol(ctx, x, y, {
kind, symbol, color, selected: point.key === selected, uncertain: symbol === "unknown", heading,
});
if (point.key === selected && row.radius > 0) {
ctx.beginPath();
ctx.arc(x, y, Math.min(380, row.radius * scale), 0, Math.PI * 2);
@@ -86,15 +116,6 @@ export function createMap(canvas, {onSelect, onView}) {
ctx.stroke();
ctx.setLineDash([]);
}
if (Number.isFinite(row.vx) && Number.isFinite(row.vz)) {
const n = Math.hypot(row.vx, row.vz) || 1;
const length = clamp(n * scale / 3, 5, 28);
ctx.strokeStyle = color;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + row.vx / n * length, y + row.vz / n * length);
ctx.stroke();
}
}
const focus = visible.find(item => item.key === selected);
if (focus) {
@@ -123,10 +144,10 @@ export function createMap(canvas, {onSelect, onView}) {
ctx.fillStyle = "#eaf7fa";
ctx.fillText(label, left + 6, top + 16, length - 12);
}
if (!points.length) {
if (!drawnFrame) {
ctx.fillStyle = "#9ab0bb";
ctx.textAlign = "center";
ctx.fillText(drawnFrame ? "На выбранных слоях нет объектов" : "Нет снимка карты", width / 2, height / 2);
ctx.fillText("Нет снимка карты", width / 2, height / 2);
ctx.textAlign = "left";
}
}
@@ -210,7 +231,7 @@ export function createMap(canvas, {onSelect, onView}) {
let hit, distance = 21;
for (const p of visible) {
const d = Math.hypot(x - p.x, y - p.y);
if (d < distance) [hit, distance] = [p, d];
if (d <= distance) [hit, distance] = [p, d];
}
if (hit) onSelect(hit.key);
});
@@ -221,14 +242,39 @@ export function createMap(canvas, {onSelect, onView}) {
draw(frame, options) {
drawnFrame = frame;
selected = options.selected;
mode = options.mode;
scope = options.scope;
online = options.online;
radarId = options.radarId;
points = styles.flatMap(([group, kind, color]) => options.layers[group] === false ? [] : (frame?.[group] || [])
.filter(row => Number.isFinite(row.x) && Number.isFinite(row.z))
.map(row => ({row, color, kind, key: `${kind}:${row.id}`})));
if (autoFit && canvas.clientWidth > 100 && points.length) fit();
const index = points.findIndex(point => point.key === selected);
if (index >= 0) points.push(points.splice(index, 1)[0]);
if (autoFit && canvas.clientWidth > 100) {
if (points.length) {
fit();
} else if (options.center?.every(Number.isFinite)) {
view.x = options.center[0];
view.z = options.center[1];
view.scale = 1.5;
autoFit = false;
onView({...view});
}
}
schedule();
},
fit,
zoom,
clearTerrain: terrain.clear,
centerAt(x, z, radius) {
view.x = x;
view.z = z;
if (radius > 0) view.scale = clamp((Math.min(canvas.clientWidth, canvas.clientHeight) - 48) / (radius * 2), .006, 12);
autoFit = false;
onView({...view});
schedule();
},
restore(saved) {
if (saved && [saved.x, saved.z, saved.scale].every(Number.isFinite)) {
Object.assign(view, saved, {scale: clamp(saved.scale, .006, 12)});
+2 -2
View File
@@ -1,6 +1,6 @@
/* Cache only the public, versioned application shell. API responses are never cached. */
const CACHE = 'airdef-shell-v8';
const FILES = ['index.html', 'app.css', 'app.js', 'map.js', 'live.js', 'timeline.js', 'manifest.webmanifest', 'icons/icon-192.png', 'icons/icon-512.png'];
const CACHE = 'airdef-shell-v9';
const FILES = ['index.html', 'app.css', 'app.js', 'map.js', 'terrain.js', 'symbols.js', 'live.js', 'timeline.js', 'manifest.webmanifest', 'icons/icon-192.png', 'icons/icon-512.png'];
const scope = new URL(self.registration.scope);
const shellUrls = FILES.map(path => new URL(path, scope).href);
+102
View File
@@ -0,0 +1,102 @@
// Pictograms are drawn in screen pixels, independent of the map zoom. Airborne
// symbols point north before rotation; heading is clockwise radians from north.
export function drawSymbol(ctx, x, y, {kind, symbol, color = '#d6e5ea', selected = false, uncertain = false, heading} = {}) {
const type = symbol || (kind === 'contact' ? 'unknown' : kind) || 'unknown';
const airborne = ['drone', 'cruise', 'supersonic', 'ballistic', 'jet', 'interceptor'].includes(type);
ctx.save();
ctx.translate(x, y);
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
// A dark halo keeps the silhouette legible on grid lines and other tracks.
const shape = (points, fill = true) => {
ctx.beginPath();
points.forEach(([px, py], i) => i ? ctx.lineTo(px, py) : ctx.moveTo(px, py));
if (fill) ctx.closePath();
ctx.strokeStyle = '#071219';
ctx.lineWidth = 4;
ctx.stroke();
if (fill) {
ctx.fillStyle = color;
ctx.fill();
}
ctx.strokeStyle = color;
ctx.lineWidth = 1.5;
ctx.stroke();
};
const line = (...points) => shape(points, false);
const circle = (cx, cy, r, fill = false) => {
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.strokeStyle = '#071219';
ctx.lineWidth = 4;
ctx.stroke();
if (fill) { ctx.fillStyle = color; ctx.fill(); }
ctx.strokeStyle = color;
ctx.lineWidth = 1.5;
ctx.stroke();
};
if (selected || uncertain) {
ctx.beginPath();
ctx.arc(0, 0, selected ? 17 : 15, 0, Math.PI * 2);
ctx.setLineDash(uncertain ? [3, 3] : []);
ctx.strokeStyle = '#071219';
ctx.lineWidth = 4;
ctx.stroke();
ctx.strokeStyle = selected ? '#f5fbff' : color;
ctx.lineWidth = selected ? 2 : 1.5;
ctx.stroke();
ctx.setLineDash([]);
}
if (airborne && Number.isFinite(heading)) ctx.rotate(heading);
switch (type) {
case 'drone':
// Broad straight wing, slim fuselage and a visible propeller.
shape([[0,-10],[2,-5],[2,-2],[11,1],[11,3],[2,2],[2,7],[5,9],[5,10],[0,9],[-5,10],[-5,9],[-2,7],[-2,2],[-11,3],[-11,1],[-2,-2],[-2,-5]]);
line([-4,-11],[4,-11]);
break;
case 'cruise':
shape([[0,-11],[2,-6],[2,-1],[8,3],[8,5],[2,3],[2,8],[4,10],[0,9],[-4,10],[-2,8],[-2,3],[-8,5],[-8,3],[-2,-1],[-2,-6]]);
break;
case 'supersonic':
shape([[0,-12],[2,-5],[10,8],[3,6],[1,10],[-1,10],[-3,6],[-10,8],[-2,-5]]);
line([-4,10],[-4,12]); line([4,10],[4,12]);
break;
case 'ballistic':
shape([[0,-12],[3,-7],[3,5],[6,9],[3,9],[2,11],[-2,11],[-3,9],[-6,9],[-3,5],[-3,-7]]);
line([-2,13],[2,13]);
break;
case 'jet':
shape([[0,-12],[2,-6],[2,-3],[11,3],[11,5],[2,2],[2,7],[6,10],[0,9],[-6,10],[-2,7],[-2,2],[-11,5],[-11,3],[-2,-3],[-2,-6]]);
break;
case 'interceptor':
shape([[0,-12],[2,-7],[2,0],[7,6],[7,9],[2,7],[0,11],[-2,7],[-7,9],[-7,6],[-2,0],[-2,-7]]);
break;
case 'radar':
// Dish faces upper left, with a mast and base.
line([-9,-8],[1,2],[5,-2]);
line([-9,-8],[-7,-1],[-2,3],[5,4]);
line([-2,3],[-2,9]); line([-7,10],[4,10]);
circle(0, -6, 1.5, true);
break;
case 'unit':
shape([[-10,-7],[10,-7],[10,8],[-10,8],[-10,-7]], false);
line([-6,4],[6,-4]); line([-6,-4],[6,4]);
break;
case 'object':
shape([[-10,0],[0,-9],[10,0],[8,0],[8,9],[-8,9],[-8,0]]);
ctx.fillStyle = '#071219';
ctx.fillRect(-2, 3, 4, 6);
break;
default:
shape([[0,-11],[11,0],[0,11],[-11,0]]);
ctx.fillStyle = '#071219';
ctx.font = 'bold 16px system-ui, sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('?', 0, 1);
}
ctx.restore();
}
+99
View File
@@ -0,0 +1,99 @@
const steps = [1, 2, 4, 8, 16, 32, 64];
const tileSide = 128;
const worldLimit = 30000000;
export function terrainTiles(view, width, height) {
const {x, z, scale} = view;
const left = Math.max(-worldLimit, x - width / (2 * scale));
const right = Math.min(worldLimit, x + width / (2 * scale));
const top = Math.max(-worldLimit, z - height / (2 * scale));
const bottom = Math.min(worldLimit, z + height / (2 * scale));
const step = steps.find(s => {
const span = tileSide * s;
return span * scale >= 180 && (Math.ceil((right - left) / span) + 1) * (Math.ceil((bottom - top) / span) + 1) <= 16;
}) ?? steps.at(-1);
const span = tileSide * step;
const tiles = [];
for (let tz = Math.floor(top / span) * span; tz < bottom; tz += span) {
for (let tx = Math.floor(left / span) * span; tx < right; tx += span) {
if (tx < -worldLimit || tz < -worldLimit || tx + span > worldLimit || tz + span > worldLimit) continue;
tiles.push({x: tx, z: tz, step, span});
}
}
const distance = tile => (tile.x + span / 2 - x) ** 2 + (tile.z + span / 2 - z) ** 2;
return tiles.sort((a, b) => distance(a) - distance(b)).slice(0, 16);
}
export function createTerrain(onChange) {
const cache = new Map();
let pending = 0, generation = 0;
async function load(scope, tile, entry) {
const epoch = generation;
const params = new URLSearchParams({scope, x: tile.x, z: tile.z, step: tile.step});
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 3500);
pending++;
entry.busy = true;
try {
const response = await fetch(`/api/terrain?${params}`, {
cache: "no-store", signal: controller.signal, headers: entry.etag ? {"If-None-Match": entry.etag} : {},
});
if (response.status === 200) {
const bitmap = await createImageBitmap(await response.blob());
if (epoch !== generation) {
bitmap.close();
return;
}
entry.image?.close();
entry.image = bitmap;
entry.etag = response.headers.get("ETag");
}
entry.after = performance.now() + (response.status === 202 ? 650 : 3500);
} catch {
entry.after = performance.now() + 3500;
} finally {
clearTimeout(timeout);
pending--;
entry.busy = false;
if (epoch === generation) onChange();
}
}
return {
paint(ctx, view, width, height, scope, online) {
if (!scope) return 0;
let drawn = 0;
const now = performance.now();
const tiles = terrainTiles(view, width, height);
const used = new Set();
for (const tile of tiles) {
const key = `${scope}:${tile.x}:${tile.z}:${tile.step}`;
used.add(key);
const entry = cache.get(key) || {after: 0};
cache.delete(key);
cache.set(key, entry);
if (entry.image) {
const x = (tile.x - view.x) * view.scale + width / 2;
const y = (tile.z - view.z) * view.scale + height / 2;
const side = tile.span * view.scale;
ctx.drawImage(entry.image, x, y, side + .25, side + .25);
drawn++;
}
if (online && pending < 4 && !entry.busy && entry.after <= now) load(scope, tile, entry);
}
for (const [key, entry] of cache) {
if (cache.size <= 96) break;
if (entry.busy || used.has(key)) continue;
entry.image?.close();
cache.delete(key);
}
return drawn;
},
clear() {
generation++;
for (const tile of cache.values()) tile.image?.close();
cache.clear();
},
};
}