Show live Horizon terrain and radar views in the web panel
This commit is contained in:
@@ -57,6 +57,23 @@ fn configs() -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
fn class_symbol(class: sim::Class) -> &'static str {
|
||||
match class {
|
||||
sim::Class::Drone => "drone",
|
||||
sim::Class::Jet => "jet",
|
||||
sim::Class::Cruise => "cruise",
|
||||
sim::Class::Supersonic => "supersonic",
|
||||
sim::Class::Ballistic => "ballistic",
|
||||
}
|
||||
}
|
||||
|
||||
fn contact_symbol(estimate: sim::ClassEst) -> &'static str {
|
||||
match estimate {
|
||||
sim::ClassEst::Firm(class) => class_symbol(class),
|
||||
_ => "unknown",
|
||||
}
|
||||
}
|
||||
|
||||
fn public_live(sim: &sim::Sim) -> Value {
|
||||
let now = sim.tick;
|
||||
let picture = sim.air_picture();
|
||||
@@ -69,6 +86,7 @@ fn public_live(sim: &sim::Sim) -> Value {
|
||||
"status": if t.forecast(now) { "Оценка положения" } else { "Измерено" },
|
||||
"source": (t.source != 0).then_some(t.source), "age": t.age(now),
|
||||
"quality": t.quality, "confidence": t.ident().name(), "radius": t.uncertainty(now),
|
||||
"symbol": contact_symbol(t.class),
|
||||
"vx": t.vel.x * 20.0, "vz": t.vel.z * 20.0,
|
||||
}));
|
||||
row
|
||||
@@ -80,11 +98,15 @@ fn public_live(sim: &sim::Sim) -> Value {
|
||||
.enumerate()
|
||||
.map(|(i, s)| {
|
||||
let mut row = position(s.id, format!("№{} {}", i + 1, s.kind.name()), s.pos);
|
||||
let emitting = s.radar_up();
|
||||
let radar_range = emitting.then(|| s.kind.spec().sensor * s.radar_profile().reach);
|
||||
merge(
|
||||
&mut row,
|
||||
json!({
|
||||
"status": post::state(s), "details": battery_view::sam_status(s, now),
|
||||
"health": s.health, "rounds": s.missiles, "bursts": s.bursts,
|
||||
"symbol": if s.kind == sim::SamKind::Radar { "radar" } else { "unit" },
|
||||
"radarRange": radar_range,
|
||||
"target": s.target.or(s.gun_target).filter(|id| known.contains(id)),
|
||||
}),
|
||||
);
|
||||
@@ -145,7 +167,7 @@ fn perspectives(sim: &sim::Sim, debug: bool) -> (Value, Value) {
|
||||
let mut row = position(d.id, d.kind.spec().name, d.pos);
|
||||
merge(
|
||||
&mut row,
|
||||
json!({"status": "Истина", "vx": d.vel.x * 20.0, "vz": d.vel.z * 20.0}),
|
||||
json!({"status": "Истина", "symbol": class_symbol(d.kind.spec().class), "vx": d.vel.x * 20.0, "vz": d.vel.z * 20.0}),
|
||||
);
|
||||
row
|
||||
})
|
||||
@@ -302,9 +324,7 @@ impl AirDef {
|
||||
["snapshot", nonce, privacy, raw]
|
||||
if token(nonce) && matches!(*privacy, "public" | "debug") =>
|
||||
{
|
||||
if self.world.is_none() || player().is_none() {
|
||||
return Err("Откройте игровой мир".into());
|
||||
}
|
||||
let player = player().filter(|_| self.world.is_some()).ok_or("Откройте игровой мир")?;
|
||||
if self.web.session.is_empty() {
|
||||
self.web.session = nonce.to_string();
|
||||
}
|
||||
@@ -324,7 +344,8 @@ impl AirDef {
|
||||
})
|
||||
});
|
||||
let content = json!({
|
||||
"version": 1, "nonce": nonce, "session": session, "world": self.state_key(), "tick": self.sim.tick,
|
||||
"version": 1, "nonce": nonce, "session": session, "world": self.state_key(), "terrainWorld": self.world, "tick": self.sim.tick,
|
||||
"terrainDimension": player.dimension, "mapCenter": [player.x, player.z],
|
||||
"live": public_live(&self.sim), "enemy": enemy, "truth": truth, "raids": raids, "catalog": configs(),
|
||||
"selected": selected, "canLaunch": !self.sim.planning() && !self.village_active() && self.presentation.is_live(),
|
||||
});
|
||||
@@ -402,6 +423,17 @@ mod tests {
|
||||
assert!(perspectives(&sim, false).1.is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contact_symbol_requires_a_confirmed_class() {
|
||||
use sim::{Class, ClassEst};
|
||||
|
||||
assert_eq!(contact_symbol(ClassEst::Unknown), "unknown");
|
||||
assert_eq!(contact_symbol(ClassEst::Probable(Class::Cruise)), "unknown");
|
||||
assert_eq!(contact_symbol(ClassEst::Firm(Class::Drone)), "drone");
|
||||
assert_eq!(contact_symbol(ClassEst::Firm(Class::Cruise)), "cruise");
|
||||
assert_eq!(contact_symbol(ClassEst::Firm(Class::Ballistic)), "ballistic");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_wave_as_data_and_resets_cursors_between_game_sessions() {
|
||||
let mut counts = vec!["0"; wave::KINDS.len()];
|
||||
|
||||
+20
-4
@@ -1,6 +1,6 @@
|
||||
# Веб-пульт AirDef
|
||||
|
||||
Пульт работает рядом с Horizon. На карте видны отметки сети, своя техника, объекты и перехватчики. Карточка показывает состояние, источник отметки и связанные записи. В «Истории» можно выбрать налёт, отфильтровать события по времени или ID и собрать доступные звенья цепочки контакта. Под шкалой отмечены попадания, промахи и отказы. События рядом по времени открываются списком из одного маркера. Нажатие на запись или отметку открывает детали и ближайший сохранённый кадр в пределах пяти игровых секунд. Событие хранит своё точное игровое время. Карта сохраняется примерно раз в секунду, поэтому её время может отличаться.
|
||||
Пульт работает рядом с Horizon. «Рельеф» показывает загруженные чанки цветами игровой карты. «К игроку» возвращает к текущей позиции в мире. В режиме «Радар» доступны кольца расстояния и выбор работающей станции с её номинальной дальностью. Обе подложки используют одинаковые отметки. До подтверждения класса контакт помечен знаком вопроса, затем получает силуэт соответствующего типа. На карте видны отметки сети, своя техника, объекты и перехватчики. Карточка показывает состояние, источник отметки и связанные записи. В «Истории» можно выбрать налёт, отфильтровать события по времени или ID и собрать доступные звенья цепочки контакта. Под шкалой отмечены попадания, промахи и отказы. События рядом по времени открываются списком из одного маркера. Нажатие на запись или отметку открывает детали и ближайший сохранённый кадр в пределах пяти игровых секунд. Событие хранит своё точное игровое время. Архив сохраняет отметки примерно раз в секунду. Подложка рельефа загружается отдельно и доступна для текущего мира. Если подложку уже открывали в этой вкладке, она может оставаться видимой в повторе той же сессии.
|
||||
|
||||
## Запуск на компьютере с игрой
|
||||
|
||||
@@ -20,7 +20,7 @@ python3 tools/airdef.py web
|
||||
|
||||
## Планшет
|
||||
|
||||
Укажите LAN-адрес интерфейса ПК и HTTPS-адрес, для которого у вас есть PEM-сертификат и ключ. Планшет должен доверять сертификату и открывать адрес ровно с тем именем или IP, которое в нём указано.
|
||||
Для Tailscale используйте Serve по инструкции ниже. Для прямого подключения по локальной сети укажите LAN-адрес интерфейса ПК и HTTPS-адрес, для которого у вас есть PEM-сертификат и ключ. Планшет должен доверять сертификату и открывать адрес ровно с тем именем или IP, которое в нём указано.
|
||||
|
||||
```text
|
||||
python3 tools/airdef.py web --listen 192.168.1.170 --port 8765 --origin https://airdef.home:8765 --cert cert.pem --key key.pem --allow-launch --allow-debug
|
||||
@@ -28,7 +28,23 @@ python3 tools/airdef.py web --listen 192.168.1.170 --port 8765 --origin https://
|
||||
|
||||
Замените адрес, имя и пути на свои. Используйте адрес пульта, который выводится при запуске. Для установки на Android откройте меню Chrome и выберите установку приложения. На iPad откройте Safari, меню «Поделиться» и «На экран Домой». [Требования браузеров к установке PWA](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Guides/Making_PWAs_installable).
|
||||
|
||||
Если оба устройства в одной сети Tailscale, можно использовать Tailscale IP хоста для `--listen` и полное имя `*.ts.net` для `--origin`. PEM-файлы для этого имени выдаёт команда `tailscale cert` при уже включённом HTTPS в tailnet. [Настройка HTTPS в Tailscale](https://tailscale.com/docs/how-to/set-up-https-certificates).
|
||||
### Tailscale Serve на Windows
|
||||
|
||||
Установите Tailscale на ПК и планшет, войдите на обоих в одну сеть и включите MagicDNS. В PowerShell с правами администратора на ПК запустите
|
||||
|
||||
```powershell
|
||||
tailscale serve 8765
|
||||
```
|
||||
|
||||
При первом запуске разрешите включение HTTPS, если Tailscale предложит это сделать. Скопируйте показанный адрес `https://device.tailnet.ts.net` целиком. Оставьте это окно открытым; в другом окне PowerShell из каталога AirDef запустите пульт, подставив свой адрес.
|
||||
|
||||
```powershell
|
||||
py -3 tools/airdef.py web --tailscale https://device.tailnet.ts.net --allow-launch
|
||||
```
|
||||
|
||||
Откройте показанный HTTPS-адрес на планшете и введите нужный одноразовый код с ПК. `--allow-launch` и `--allow-debug` необязательны. Для другого локального порта укажите одинаковый порт в `--port` и команде `tailscale serve`. Остановка Serve: Ctrl+C в его окне. Подробнее: [Tailscale Serve](https://tailscale.com/docs/features/tailscale-serve), [команда Serve](https://tailscale.com/docs/reference/tailscale-cli/serve).
|
||||
|
||||
Serve предоставляет доступ внутри tailnet согласно его правилам доступа; сопряжение по коду по-прежнему необходимо. Пульт слушает только `127.0.0.1`, а HTTPS завершается в Tailscale. Другие программы на самом ПК могут обращаться к локальному порту, поэтому используйте доверенный компьютер. Не включайте Funnel и не публикуйте сокет Horizon: Serve должен проксировать только порт веб-пульта. Режим `--tailscale` нельзя совмещать с `--listen` на внешнем интерфейсе, `--origin`, `--cert` или `--key`.
|
||||
|
||||
В портретной ориентации список находится под картой, в альбомной при достаточной ширине сбоку. Перетаскивание смещает карту, жест двумя пальцами меняет масштаб. Без связи виден последний загруженный снимок и уже открытая история. Устройство сохраняет положение карты, выбранную карточку и черновик. Для запуска требуется связь с игрой.
|
||||
|
||||
@@ -36,7 +52,7 @@ python3 tools/airdef.py web --listen 192.168.1.170 --port 8765 --origin https://
|
||||
|
||||
Сервер хранит журнал в `airdef-panel/history.sqlite3` внутри каталога игры. Он переживает перезапуск игры и пульта. Хранятся до 3 600 снимков карты, 30 000 событий и 400 налётов. В интерфейсе видны пропуски журнала и ограничения хранения. Браузер дополнительно хранит до 600 загруженных событий, 20 открытых исторических кадров и отметки шкалы последних восьми просмотренных налётов. Отвязка устройства очищает браузерный архив.
|
||||
|
||||
Для присоединения к уже запущенному Horizon укажите `--attach путь_к_локальному_сокету`. На Windows это JSON-файл с локальным портом и токеном Horizon. Для `--dev-mod` путь к данным мода можно задать через `--mod-data`. Пульт опрашивает игру из одного фонового потока. После первой загрузки браузер получает изменения карты от своей версии. После долгого обрыва связи, перезапуска пульта или смены мира браузер получает полный снимок. Сам сокет Horizon доступен только на ПК. Внутренние команды мода экспортируют ограниченный снимок и подтверждают структурированный сценарий. Сериализация HTTP, обработка подключений и запись архива происходят в процессе пульта.
|
||||
Для присоединения к уже запущенному Horizon укажите `--attach путь_к_локальному_сокету`. На Windows это JSON-файл с локальным портом и токеном Horizon. Для `--dev-mod` путь к данным мода можно задать через `--mod-data`. Пульт запрашивает снимок игры каждые 0,5 секунды при нормальной связи. Открытая вкладка проверяет обновления каждые 0,65 секунды, в фоновой вкладке опрос приостанавливается. Рельеф запрашивается отдельными фрагментами по мере просмотра. После первой загрузки браузер получает изменения карты от своей версии. После долгого обрыва связи, перезапуска пульта или смены мира браузер получает полный снимок. Сам сокет Horizon доступен только на ПК. Внутренние команды мода экспортируют ограниченный снимок и подтверждают структурированный сценарий. Сериализация HTTP, обработка подключений и запись архива происходят в процессе пульта.
|
||||
|
||||
Полезные проверки из каталога проекта
|
||||
|
||||
|
||||
+1
-1
Submodule horizon updated: 0f77eb5c26...2656f35af7
+77
-3
@@ -1,5 +1,6 @@
|
||||
import http.client
|
||||
import json
|
||||
from argparse import Namespace
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
@@ -8,7 +9,7 @@ import unittest
|
||||
from urllib.parse import quote
|
||||
|
||||
from web_remote.bridge import Bridge, validate_wave
|
||||
from web_remote.server import Pairing, PanelServer
|
||||
from web_remote.server import Pairing, PanelServer, transport_options
|
||||
from web_remote.store import Store
|
||||
|
||||
|
||||
@@ -29,6 +30,7 @@ class PanelTest(unittest.TestCase):
|
||||
self.launches = []
|
||||
self.live_frame = EMPTY
|
||||
self.world_session = WORLD_SESSION
|
||||
self.dimension = "minecraft:overworld"
|
||||
self.tick = 210
|
||||
self.bridge = Bridge(None, self.home, self.store, debug=True, transport=self.transport)
|
||||
pairing = Pairing(True, True)
|
||||
@@ -53,7 +55,7 @@ class PanelTest(unittest.TestCase):
|
||||
_, nonce, _, _cursor = words[3:]
|
||||
response = {
|
||||
"version": 1, "nonce": nonce, "session": self.world_session, "world": "fixture",
|
||||
"tick": self.tick, "live": self.live_frame, "catalog": CATALOG, "canLaunch": True,
|
||||
"terrainWorld": "fixture#23", "terrainDimension": self.dimension, "tick": self.tick, "live": self.live_frame, "catalog": CATALOG, "canLaunch": True,
|
||||
"enemy": dict(EMPTY, secret="enemy-only"), "truth": [{"id": 99, "label": "truth-only"}],
|
||||
"raids": [{"id": 1, "start": 200, "length": 15, "active": True, "gap": False,
|
||||
"limited": False, "next": [1, 1, 1],
|
||||
@@ -71,7 +73,7 @@ class PanelTest(unittest.TestCase):
|
||||
(self.home / "panel-receipt-v1.json").write_text(json.dumps(
|
||||
{"id": words[4], "accepted": True, "message": "Принято"}))
|
||||
|
||||
def request(self, path, *, method="GET", body=None, cookie=None, origin=True):
|
||||
def request(self, path, *, method="GET", body=None, cookie=None, origin=True, extra_headers=None, binary=False):
|
||||
client = http.client.HTTPConnection("127.0.0.1", self.server.server_port, timeout=5)
|
||||
try:
|
||||
headers = {"Host": "127.0.0.1"}
|
||||
@@ -82,9 +84,13 @@ class PanelTest(unittest.TestCase):
|
||||
body = json.dumps(body)
|
||||
if cookie:
|
||||
headers["Cookie"] = cookie
|
||||
if extra_headers:
|
||||
headers.update(extra_headers)
|
||||
client.request(method, path, body=body, headers=headers)
|
||||
response = client.getresponse()
|
||||
raw = response.read()
|
||||
if binary:
|
||||
return response.status, response.headers, raw
|
||||
return response.status, response.getheader("Set-Cookie"), json.loads(raw) if raw else None
|
||||
finally:
|
||||
client.close()
|
||||
@@ -94,6 +100,74 @@ class PanelTest(unittest.TestCase):
|
||||
self.assertEqual(status, 200)
|
||||
return cookie.split(";", 1)[0]
|
||||
|
||||
def test_world_terrain_tiles(self):
|
||||
scope, _, _ = self.bridge.terrain_source()
|
||||
path = f"/api/terrain?scope={scope}&x=-128&z=0&step=1"
|
||||
self.assertEqual(self.request(path)[0], 401)
|
||||
viewer = self.pair("viewer")
|
||||
for invalid in (path.replace("x=-128", "x=-127"), path.replace("step=1", "step=3"),
|
||||
path.replace(scope, "af" * 8)):
|
||||
self.assertEqual(self.request(invalid, cookie=viewer)[0], 400)
|
||||
self.assertEqual(self.request(path, cookie=viewer)[0], 202)
|
||||
pixels = "4ad93fff" * (128 * 128)
|
||||
self.bridge.terrain_transport = lambda _endpoint, x, z, step: {
|
||||
"world": "fixture#23", "dimension": "minecraft:the_nether", "rgba": pixels, "known": 128 * 128,
|
||||
}
|
||||
def process_tile():
|
||||
scope, world, dimension = self.bridge.terrain_source()
|
||||
self.assertTrue(self.bridge.terrain.work(scope, lambda *tile: self.bridge.read_terrain(world, dimension, *tile)))
|
||||
process_tile()
|
||||
self.assertEqual(self.request(path, cookie=viewer)[0], 202)
|
||||
self.bridge.terrain_transport = lambda _endpoint, x, z, step: {
|
||||
"world": "fixture#23", "dimension": self.dimension, "rgba": pixels, "known": 128 * 128 if x == -128 else 0,
|
||||
}
|
||||
process_tile()
|
||||
status, headers, body = self.request(path, cookie=viewer, binary=True)
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(headers["Content-Type"], "image/png")
|
||||
self.assertTrue(body.startswith(bytes.fromhex("89504e470d0a1a0a")))
|
||||
self.assertEqual(self.request(path, cookie=viewer, extra_headers={"If-None-Match": headers["ETag"]})[0], 304)
|
||||
empty = path.replace("x=-128", "x=0")
|
||||
self.assertEqual(self.request(empty, cookie=viewer)[0], 202)
|
||||
process_tile()
|
||||
self.assertEqual(self.request(empty, cookie=viewer)[0], 204)
|
||||
self.dimension = "minecraft:the_nether"
|
||||
self.bridge.poll()
|
||||
self.assertEqual(self.request(path, cookie=viewer)[0], 400)
|
||||
|
||||
def test_tailscale_proxy_security(self):
|
||||
self.server.tailscale = True
|
||||
self.server.origin = "https://device.tailnet.ts.net"
|
||||
self.server.host_header = "device.tailnet.ts.net"
|
||||
self.server.secure = True
|
||||
headers = {"Host": self.server.host_header, "Origin": self.server.origin,
|
||||
"X-Forwarded-Host": self.server.host_header, "X-Forwarded-Proto": "https"}
|
||||
body = {"code": self.codes["viewer"]}
|
||||
self.assertEqual(self.request("/api/pair", method="POST", body=body, extra_headers={**headers, "Host": "evil.ts.net"})[0], 400)
|
||||
for changed in ({"Origin": "https://evil.ts.net"}, {"X-Forwarded-Proto": "http"},
|
||||
{"X-Forwarded-Host": "evil.ts.net"}, {"Tailscale-Funnel-Request": "?1"}):
|
||||
self.assertEqual(self.request("/api/pair", method="POST", body=body, extra_headers={**headers, **changed})[0], 403)
|
||||
self.assertEqual(self.request("/api/pair", method="POST", body=body, extra_headers={"Host": self.server.host_header})[0], 403)
|
||||
status, cookie, _ = self.request("/api/pair", method="POST", body=body, extra_headers=headers)
|
||||
self.assertEqual(status, 200)
|
||||
self.assertIn("; Secure", cookie)
|
||||
self.assertEqual(self.request("/api/session", cookie=cookie.split(";", 1)[0], extra_headers=headers)[0], 200)
|
||||
|
||||
def test_tailscale_transport_options(self):
|
||||
args = Namespace(listen="127.0.0.1", port=8765, origin=None, cert=None, key=None,
|
||||
tailscale="https://device.tailnet.ts.net")
|
||||
self.assertEqual(transport_options(args), (args.tailscale, None))
|
||||
with_slash = Namespace(**{**vars(args), "tailscale": args.tailscale + "/"})
|
||||
self.assertEqual(transport_options(with_slash), (args.tailscale, None))
|
||||
for key, value in (("listen", "0.0.0.0"), ("origin", "https://other"), ("cert", "cert.pem"),
|
||||
("tailscale", "http://device.tailnet.ts.net"),
|
||||
("tailscale", "https://device.tailnet.ts.net:443"),
|
||||
("tailscale", "https://device.tailnet.ts.net/path")):
|
||||
invalid = Namespace(**vars(args))
|
||||
setattr(invalid, key, value)
|
||||
with self.subTest(key=key, value=value), self.assertRaises(ValueError):
|
||||
transport_options(invalid)
|
||||
|
||||
def test_scoped_pairing_and_archive_exclude_hidden_views(self):
|
||||
self.assertEqual(self.request("/api/live")[0], 401)
|
||||
viewer = self.pair("viewer")
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Single local game bridge. HTTP clients only see cached projections and the archive."""
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, replace
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
@@ -10,6 +11,7 @@ import socket
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from .terrain import TerrainTiles
|
||||
|
||||
TOKEN = re.compile(r"[0-9a-f]{16,32}\Z")
|
||||
MAX_PACKET = 1 << 20
|
||||
@@ -22,6 +24,14 @@ def local_chat(endpoint: Path, text: str):
|
||||
"""Use Horizon's local transport, with no arbitrary commands from HTTP."""
|
||||
if not text.startswith("chat /airdef panel ") or "\n" in text or "\r" in text:
|
||||
raise ValueError("Invalid local bridge command")
|
||||
return _local_request(endpoint, text)
|
||||
|
||||
|
||||
def local_terrain(endpoint, x, z, step):
|
||||
return _local_request(endpoint, f"terrain-tile {x:d} {z:d} {step:d}")
|
||||
|
||||
|
||||
def _local_request(endpoint, text):
|
||||
if os.name == "nt" or endpoint.suffix == ".json":
|
||||
config = read_json(endpoint, 4096)
|
||||
port, token = config["port"], config["token"]
|
||||
@@ -84,10 +94,14 @@ def validate_wave(payload, catalog):
|
||||
|
||||
|
||||
def public_view(raw):
|
||||
world, dimension = raw.get("terrainWorld"), raw.get("terrainDimension")
|
||||
scope = f'{raw["session"]}\0{world}\0{dimension}'.encode("utf-8")
|
||||
return {
|
||||
"version": 1, "session": raw["session"], "world": raw["world"], "tick": raw["tick"],
|
||||
"frame": raw["live"], "catalog": raw["catalog"],
|
||||
"selected": raw.get("selected"), "canLaunch": raw["canLaunch"],
|
||||
"terrain": hashlib.blake2s(scope, digest_size=12).hexdigest() if world and dimension else None,
|
||||
"mapCenter": raw.get("mapCenter"),
|
||||
}
|
||||
|
||||
|
||||
@@ -154,7 +168,8 @@ class LiveRevision:
|
||||
|
||||
|
||||
class Bridge:
|
||||
def __init__(self, endpoint, data, store, *, debug=False, interval=1.0, transport=local_chat):
|
||||
def __init__(self, endpoint, data, store, *, debug=False, interval=0.5, transport=local_chat,
|
||||
terrain_transport=local_terrain):
|
||||
self.endpoint, self.data, self.store = endpoint, data, store
|
||||
self.debug, self.interval, self.transport = debug, interval, transport
|
||||
self.lock = threading.Lock()
|
||||
@@ -163,6 +178,11 @@ class Bridge:
|
||||
self.revisions = deque([LiveRevision(0, {})], maxlen=LIVE_REVISIONS)
|
||||
self.epoch = secrets.token_hex(8)
|
||||
self.cursors = {}
|
||||
self.terrain = TerrainTiles(complete_ttl=30, partial_ttl=2)
|
||||
self.terrain_transport = terrain_transport
|
||||
self.terrain_world = None
|
||||
self.terrain_dimension = None
|
||||
self.next_frame = 0.0
|
||||
self.thread = threading.Thread(target=self.worker, name="airdef-local-bridge", daemon=True)
|
||||
|
||||
def begin(self):
|
||||
@@ -175,6 +195,7 @@ class Bridge:
|
||||
|
||||
def worker(self):
|
||||
next_poll = time.monotonic()
|
||||
next_tile = next_poll
|
||||
backoff = self.interval
|
||||
while not self.stop.is_set():
|
||||
now = time.monotonic()
|
||||
@@ -187,8 +208,13 @@ class Bridge:
|
||||
self.disconnect()
|
||||
next_poll = time.monotonic() + backoff
|
||||
try:
|
||||
job = self.queue.get(timeout=min(0.25, self.interval))
|
||||
job = self.queue.get(timeout=max(0.01, min(0.10, next_poll - time.monotonic())))
|
||||
except queue.Empty:
|
||||
now = time.monotonic()
|
||||
if next_tile <= now < next_poll:
|
||||
scope, world, dimension = self.terrain_source()
|
||||
if scope and self.terrain.work(scope, lambda x, z, step: self.read_terrain(world, dimension, x, z, step)):
|
||||
next_tile = time.monotonic() + 0.34
|
||||
continue
|
||||
self.dispatch(*job)
|
||||
|
||||
@@ -202,12 +228,37 @@ class Bridge:
|
||||
if raw.get("nonce") != nonce or raw.get("version") != 1 or not TOKEN.fullmatch(raw["session"]):
|
||||
raise ValueError("Snapshot does not belong to this request")
|
||||
public = public_view(raw)
|
||||
self.store.append(raw, public)
|
||||
public["sampleMs"] = round(self.interval * 1000)
|
||||
now = time.monotonic()
|
||||
capture = raw["session"] != session or now >= self.next_frame
|
||||
self.store.append(raw, public, capture_frame=capture)
|
||||
if capture:
|
||||
self.next_frame = now + 1.0
|
||||
self.cursors = {raid["id"]: raid["next"] for raid in raw["raids"]}
|
||||
with self.lock:
|
||||
number = self.revisions[-1].number + 1
|
||||
self.terrain_world = raw.get("terrainWorld")
|
||||
self.terrain_dimension = raw.get("terrainDimension")
|
||||
self.revisions.append(LiveRevision(number, public, raw.get("enemy"), raw.get("truth"), True, time.time()))
|
||||
|
||||
def terrain_source(self):
|
||||
with self.lock:
|
||||
state = self.revisions[-1]
|
||||
return (state.network.get("terrain"), self.terrain_world, self.terrain_dimension) if state.connected else (None, None, None)
|
||||
|
||||
def read_terrain(self, world, dimension, x, z, step):
|
||||
result = self.terrain_transport(self.endpoint, x, z, step)
|
||||
if result.get("world") != world or result.get("dimension") != dimension:
|
||||
raise ValueError("Terrain belongs to a different world")
|
||||
return result
|
||||
|
||||
def terrain_tile(self, scope, x, z, step):
|
||||
with self.lock:
|
||||
state = self.revisions[-1]
|
||||
if not state.connected or state.network.get("terrain") != scope:
|
||||
raise ValueError("Рельеф доступен для текущего мира")
|
||||
return self.terrain.get(scope, x, z, step)
|
||||
|
||||
def disconnect(self):
|
||||
with self.lock:
|
||||
current = self.revisions[-1]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Optionally serve the AirDef PWA on a trusted LAN HTTPS origin."""
|
||||
import argparse
|
||||
import contextlib
|
||||
import hashlib
|
||||
from http import HTTPStatus
|
||||
from http.cookies import CookieError, SimpleCookie
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
@@ -8,6 +9,7 @@ import ipaddress
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import ssl
|
||||
import subprocess
|
||||
@@ -26,6 +28,8 @@ ASSETS = {
|
||||
"/index.html": ("index.html", "text/html; charset=utf-8"),
|
||||
"/app.js": ("app.js", "text/javascript; charset=utf-8"),
|
||||
"/map.js": ("map.js", "text/javascript; charset=utf-8"),
|
||||
"/terrain.js": ("terrain.js", "text/javascript; charset=utf-8"),
|
||||
"/symbols.js": ("symbols.js", "text/javascript; charset=utf-8"),
|
||||
"/live.js": ("live.js", "text/javascript; charset=utf-8"),
|
||||
"/timeline.js": ("timeline.js", "text/javascript; charset=utf-8"),
|
||||
"/app.css": ("app.css", "text/css; charset=utf-8"),
|
||||
@@ -62,10 +66,11 @@ class PanelServer(ThreadingHTTPServer):
|
||||
daemon_threads = True
|
||||
request_queue_size = 24
|
||||
|
||||
def __init__(self, bind, origin, store, bridge, pairing, *, tls=None, allow_launch=False, allow_debug=False):
|
||||
def __init__(self, bind, origin, store, bridge, pairing, *, tls=None, tailscale=False, allow_launch=False, allow_debug=False):
|
||||
self.origin = origin
|
||||
self.host_header = urlsplit(origin).netloc.casefold()
|
||||
self.secure = origin.startswith("https:")
|
||||
self.tailscale = tailscale
|
||||
self.store, self.bridge, self.pairing = store, bridge, pairing
|
||||
self.allow_launch, self.allow_debug = allow_launch, allow_debug
|
||||
self.connections = threading.BoundedSemaphore(24)
|
||||
@@ -112,7 +117,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
def do_DELETE(self):
|
||||
self.route("DELETE")
|
||||
|
||||
def reply(self, status, payload=None, *, content_type="application/json; charset=utf-8", cookie=None):
|
||||
def reply(self, status, payload=None, *, content_type="application/json; charset=utf-8", cookie=None, etag=None):
|
||||
if payload is None:
|
||||
content = b""
|
||||
elif isinstance(payload, bytes):
|
||||
@@ -123,6 +128,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(content)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
if etag:
|
||||
self.send_header("ETag", etag)
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
self.send_header("Cross-Origin-Resource-Policy", "same-origin")
|
||||
@@ -137,6 +144,10 @@ class Handler(BaseHTTPRequestHandler):
|
||||
try:
|
||||
if self.headers.get("Host", "").casefold() != self.server.host_header:
|
||||
raise APIError(HTTPStatus.BAD_REQUEST, "Откройте пульт по адресу, показанному на ПК")
|
||||
if self.server.tailscale and (self.headers.get_all("X-Forwarded-Proto") != ["https"]
|
||||
or [x.casefold() for x in self.headers.get_all("X-Forwarded-Host", [])] != [self.server.host_header]
|
||||
or self.headers.get("Tailscale-Funnel-Request") is not None):
|
||||
raise APIError(HTTPStatus.FORBIDDEN, "Откройте пульт через Tailscale Serve по HTTPS")
|
||||
request = urlsplit(self.path)
|
||||
if request.scheme or request.netloc or len(request.query) > 1024:
|
||||
raise APIError(HTTPStatus.BAD_REQUEST, "Неверный адрес")
|
||||
@@ -201,6 +212,24 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return self.reply(HTTPStatus.OK, data)
|
||||
if (verb, path) == ("GET", "/api/raids"):
|
||||
return self.reply(HTTPStatus.OK, self.server.store.raids())
|
||||
if (verb, path) == ("GET", "/api/terrain"):
|
||||
scope = query.get("scope", "")
|
||||
x, z, step = (int(query[key]) for key in ("x", "z", "step"))
|
||||
if step not in (1, 2, 4, 8, 16, 32, 64) or not TOKEN.fullmatch(scope):
|
||||
raise ValueError("bad terrain coordinates")
|
||||
span = 128 * step
|
||||
if any(not -30_000_000 <= v <= 30_000_000 - span or v % span for v in (x, z)):
|
||||
raise ValueError("bad terrain coordinates")
|
||||
tile = self.server.bridge.terrain_tile(scope, x, z, step)
|
||||
if tile is None:
|
||||
return self.reply(HTTPStatus.ACCEPTED)
|
||||
data, known = tile
|
||||
if not known:
|
||||
return self.reply(HTTPStatus.NO_CONTENT)
|
||||
etag = '"' + hashlib.blake2s(data, digest_size=8).hexdigest() + '"'
|
||||
if self.headers.get("If-None-Match") == etag:
|
||||
return self.reply(HTTPStatus.NOT_MODIFIED, etag=etag)
|
||||
return self.reply(HTTPStatus.OK, data, content_type="image/png", etag=etag)
|
||||
if (verb, path) == ("GET", "/api/timeline"):
|
||||
session, raid = query.get("session", ""), number(query.get("raid"))
|
||||
if not TOKEN.fullmatch(session) or raid is None:
|
||||
@@ -265,6 +294,14 @@ def number(raw):
|
||||
|
||||
def transport_options(args):
|
||||
ip = ipaddress.IPv4Address(args.listen)
|
||||
if args.tailscale:
|
||||
if str(ip) != "127.0.0.1" or args.origin or args.cert or args.key:
|
||||
raise ValueError("Tailscale Serve требует 127.0.0.1 и несовместим с --origin, --cert и --key")
|
||||
url = urlsplit(args.tailscale)
|
||||
if (url.scheme != "https" or not re.fullmatch(r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+\.ts\.net", url.netloc)
|
||||
or url.path not in ("", "/") or url.query or url.fragment or not 1 <= args.port <= 65535):
|
||||
raise ValueError("Укажите HTTPS-адрес устройства Tailscale без порта и пути: https://device.tailnet.ts.net")
|
||||
return f"https://{url.netloc}", None
|
||||
tls = None
|
||||
if args.cert or args.key:
|
||||
if not args.cert or not args.key:
|
||||
@@ -305,6 +342,7 @@ def run(argv, *, game_home, game_command, default_mod_data):
|
||||
parser.add_argument("--listen", default="127.0.0.1", help="IPv4-интерфейс веб-пульта")
|
||||
parser.add_argument("--port", type=int, default=8765)
|
||||
parser.add_argument("--origin", help="Точный HTTPS-адрес, по которому планшет открывает пульт")
|
||||
parser.add_argument("--tailscale", help="HTTPS-адрес устройства Tailscale Serve (backend только на 127.0.0.1)")
|
||||
parser.add_argument("--cert", type=Path, help="Сертификат HTTPS в PEM")
|
||||
parser.add_argument("--key", type=Path, help="Ключ сертификата PEM")
|
||||
parser.add_argument("--allow-launch", action="store_true", help="Выдать отдельный код оператору")
|
||||
@@ -329,7 +367,7 @@ def run(argv, *, game_home, game_command, default_mod_data):
|
||||
store.revoke_all()
|
||||
pairing = Pairing(args.allow_launch, args.allow_debug)
|
||||
bridge = Bridge(endpoint, data, store, debug=args.allow_debug)
|
||||
with PanelServer((args.listen, args.port), origin, store, bridge, pairing, tls=tls,
|
||||
with PanelServer((args.listen, args.port), origin, store, bridge, pairing, tls=tls, tailscale=bool(args.tailscale),
|
||||
allow_launch=args.allow_launch, allow_debug=args.allow_debug) as server:
|
||||
child = None
|
||||
if not args.attach:
|
||||
|
||||
@@ -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; }
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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)});
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -94,14 +94,15 @@ class Store:
|
||||
with self.lock, self.db:
|
||||
self.db.execute("DELETE FROM pairings")
|
||||
|
||||
def append(self, snapshot, public):
|
||||
def append(self, snapshot, public, *, capture_frame=True):
|
||||
session, world, tick = snapshot["session"], snapshot["world"], snapshot["tick"]
|
||||
active = next((raid["id"] for raid in snapshot["raids"] if raid["active"]), 0)
|
||||
now = time.time()
|
||||
frame = zlib.compress(compact(public).encode("utf-8"), level=1)
|
||||
frame = zlib.compress(compact(public).encode("utf-8"), level=1) if capture_frame else None
|
||||
with self.lock, self.db:
|
||||
self.db.execute("INSERT OR IGNORE INTO frames VALUES (?, ?, ?, ?, ?)",
|
||||
(session, tick, world, now, frame))
|
||||
if frame is not None:
|
||||
self.db.execute("INSERT OR IGNORE INTO frames VALUES (?, ?, ?, ?, ?)",
|
||||
(session, tick, world, now, frame))
|
||||
for raid in snapshot["raids"]:
|
||||
fields = (session, raid["id"], world, now, raid["start"], raid["length"],
|
||||
int(raid["active"]), int(raid["gap"] or raid["limited"]))
|
||||
@@ -122,8 +123,9 @@ class Store:
|
||||
(SELECT rowid FROM raids ORDER BY time DESC LIMIT -1 OFFSET ?)""", (MAX_RAIDS,)).rowcount
|
||||
if removed or gone:
|
||||
self.db.execute("INSERT OR REPLACE INTO metadata VALUES ('history_limited','1')")
|
||||
self.db.execute("""DELETE FROM frames WHERE rowid IN
|
||||
(SELECT rowid FROM frames ORDER BY time DESC LIMIT -1 OFFSET ?)""", (MAX_FRAMES,))
|
||||
if frame is not None:
|
||||
self.db.execute("""DELETE FROM frames WHERE rowid IN
|
||||
(SELECT rowid FROM frames ORDER BY time DESC LIMIT -1 OFFSET ?)""", (MAX_FRAMES,))
|
||||
|
||||
def raids(self):
|
||||
with self.lock:
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Bounded, asynchronous terrain tile cache for the web remote."""
|
||||
|
||||
from collections import OrderedDict, deque
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
import zlib
|
||||
|
||||
|
||||
_TILE_SIDE = 128
|
||||
_RGBA_BYTES = _TILE_SIDE * _TILE_SIDE * 4
|
||||
_SAMPLES = _TILE_SIDE * _TILE_SIDE
|
||||
|
||||
|
||||
def _chunk(kind, data):
|
||||
body = kind + data
|
||||
return struct.pack('>I', len(data)) + body + struct.pack('>I', zlib.crc32(body) & 0xffffffff)
|
||||
|
||||
|
||||
def _png(rgba):
|
||||
"""Encode a tile as a standard unfiltered RGBA PNG."""
|
||||
stride = _TILE_SIDE * 4
|
||||
rows = b''.join(b'\0' + rgba[offset:offset + stride]
|
||||
for offset in range(0, _RGBA_BYTES, stride))
|
||||
header = struct.pack('>IIBBBBB', _TILE_SIDE, _TILE_SIDE, 8, 6, 0, 0, 0)
|
||||
return (b'\x89PNG\r\n\x1a\n' + _chunk(b'IHDR', header) +
|
||||
_chunk(b'IDAT', zlib.compress(rows)) + _chunk(b'IEND', b''))
|
||||
|
||||
|
||||
class TerrainTiles:
|
||||
"""Nonblocking tile lookup; call work from the bridge's rate-limited worker.
|
||||
|
||||
``get(session, x, z, step)`` returns a PNG and sample count, or None. ``work(session,
|
||||
transport)`` processes at most one queued tile, returning True if one was
|
||||
attempted. The transport receives (x, z, step) and returns a mapping with
|
||||
an RGBA hex string and the number of known samples. Failed requests can be
|
||||
retried on a later lookup; stale cached tiles remain available.
|
||||
"""
|
||||
|
||||
def __init__(self, *, max_tiles=128, max_queue=64, complete_ttl=300,
|
||||
partial_ttl=10, empty_ttl=3):
|
||||
if max_tiles < 1 or max_queue < 1:
|
||||
raise ValueError('cache and queue limits must be positive')
|
||||
self.max_tiles, self.max_queue = max_tiles, max_queue
|
||||
self.complete_ttl, self.partial_ttl, self.empty_ttl = complete_ttl, partial_ttl, empty_ttl
|
||||
self._lock = threading.Lock()
|
||||
self._session = object()
|
||||
self._generation = 0
|
||||
self._cache = OrderedDict()
|
||||
self._queue = deque()
|
||||
self._pending = set()
|
||||
self._inflight = set()
|
||||
|
||||
def _activate(self, session):
|
||||
# Called under the lock. The generation also invalidates work already
|
||||
# outside the lock when a new game session arrives.
|
||||
if session != self._session:
|
||||
self._session = session
|
||||
self._generation += 1
|
||||
self._cache.clear()
|
||||
self._queue.clear()
|
||||
self._pending.clear()
|
||||
self._inflight.clear()
|
||||
|
||||
def get(self, session, x, z, step):
|
||||
key = (x, z, step)
|
||||
with self._lock:
|
||||
self._activate(session)
|
||||
item = self._cache.get(key)
|
||||
if item is not None:
|
||||
self._cache.move_to_end(key)
|
||||
if (item is None or time.monotonic() >= item[2]):
|
||||
if key not in self._pending and key not in self._inflight and len(self._queue) < self.max_queue:
|
||||
self._queue.append(key)
|
||||
self._pending.add(key)
|
||||
return item[:2] if item is not None else None
|
||||
|
||||
def work(self, session, transport):
|
||||
with self._lock:
|
||||
self._activate(session)
|
||||
if not self._queue:
|
||||
return False
|
||||
key = self._queue.popleft()
|
||||
self._pending.remove(key)
|
||||
self._inflight.add(key)
|
||||
generation = self._generation
|
||||
try:
|
||||
result = transport(*key)
|
||||
rgba = bytes.fromhex(result['rgba'])
|
||||
known = result['known']
|
||||
if len(rgba) != _RGBA_BYTES or not isinstance(known, int) or not 0 <= known <= _SAMPLES:
|
||||
raise ValueError('invalid terrain tile')
|
||||
png = _png(rgba) if known else b""
|
||||
ttl = self.empty_ttl if known == 0 else self.complete_ttl if known == _SAMPLES else self.partial_ttl
|
||||
except (OSError, ValueError, TypeError, KeyError, zlib.error):
|
||||
# Transport, malformed data and encoding failures must not kill the
|
||||
# bridge worker. A future lookup can retry, retaining stale data.
|
||||
with self._lock:
|
||||
if generation == self._generation:
|
||||
self._inflight.discard(key)
|
||||
item = self._cache.get(key)
|
||||
if item is not None:
|
||||
self._cache[key] = (*item[:2], time.monotonic() + self.empty_ttl)
|
||||
return True
|
||||
with self._lock:
|
||||
if generation == self._generation:
|
||||
self._inflight.discard(key)
|
||||
self._cache[key] = (png, known, time.monotonic() + ttl)
|
||||
self._cache.move_to_end(key)
|
||||
while len(self._cache) > self.max_tiles:
|
||||
self._cache.popitem(last=False)
|
||||
return True
|
||||
Reference in New Issue
Block a user