Add typed depot logistics visibility, auto-strike, 16-block reach, and web panel controls
build / mod (push) Failing after 15s

This commit is contained in:
2026-12-04 13:37:54 +03:00
parent a02b7d1177
commit 76ef94b537
31 changed files with 2225 additions and 106 deletions
+70 -5
View File
@@ -16,7 +16,7 @@ from .terrain import TerrainTiles
TOKEN = re.compile(r"[0-9a-f]{16,32}\Z")
MAX_PACKET = 1 << 20
MAX_REPLY = 1 << 18
MAP_LAYERS = ("units", "objects", "contacts", "interceptors")
MAP_LAYERS = ("units", "objects", "contacts", "interceptors", "sites")
LIVE_REVISIONS = 12
@@ -124,8 +124,8 @@ def live_delta(before, after):
{k: v for k, v in new_frame.items() if k not in MAP_LAYERS})
layers = {}
for key in MAP_LAYERS:
old = {row["id"]: row for row in old_frame[key]}
new = {row["id"]: row for row in new_frame[key]}
old = {row["id"]: row for row in old_frame.get(key, [])}
new = {row["id"]: row for row in new_frame.get(key, [])}
upsert = [row for ident, row in new.items() if ident not in old or old[ident] != row]
removed = [ident for ident in old if ident not in new]
natural_order = [ident for ident in old if ident in new] + [ident for ident in new if ident not in old]
@@ -182,6 +182,7 @@ class Bridge:
self.terrain_transport = terrain_transport
self.terrain_world = None
self.terrain_dimension = None
self.actions = {}
self.next_frame = 0.0
self.thread = threading.Thread(target=self.worker, name="airdef-local-bridge", daemon=True)
@@ -216,7 +217,11 @@ class Bridge:
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)
if job[0] == "action":
self.dispatch_action(*job[1:])
next_poll = time.monotonic() + self.interval
else:
self.dispatch(*job[1:])
def poll(self):
nonce = secrets.token_hex(12)
@@ -293,7 +298,7 @@ class Bridge:
receipt, created = self.store.reserve_launch(key, owner, session, encoded)
if created:
try:
self.queue.put_nowait((key, session, encoded))
self.queue.put_nowait(("launch", key, session, encoded))
except queue.Full:
self.store.complete_launch(key, "rejected", "Очередь занята. Проверьте состояние игры.")
return self.store.launch(key, owner)
@@ -313,3 +318,63 @@ class Bridge:
self.store.complete_launch(key, "accepted" if receipt["accepted"] else "rejected", str(receipt["message"]))
except (OSError, ValueError, TypeError, KeyError):
self.store.complete_launch(key, "unknown", "Игра могла принять сценарий. Проверьте состояние карты.")
def action(self, key, owner, session, act, value):
if act == "autostrike":
normalized = {"on": "on", "true": "on", "1": "on", "off": "off", "false": "off", "0": "off"}.get(str(value).lower())
elif act == "strike":
normalized = str(int(value)) if str(value).isdigit() and int(value) >= 1 else None
else:
normalized = None
if normalized is None:
raise ValueError("Неверные параметры команды")
with self.lock:
prior = self.actions.get((key, owner))
if prior is not None:
if prior["req"] != (session, act, normalized):
raise ValueError("Повторный ID команды с другими параметрами")
return prior["receipt"]
current = self.revisions[-1]
if not current.connected or current.network.get("session") != session:
raise ValueError("Игровая сессия изменилась. Обновите карту.")
done = threading.Event()
box = {}
try:
self.queue.put_nowait(("action", key, session, act, normalized, done, box))
except queue.Full as error:
raise ValueError("Очередь команд занята") from error
if not done.wait(3.5):
return {"id": key, "status": "pending", "accepted": False, "message": "Игра не успела подтвердить команду"}
receipt = box.get("receipt", {"id": key, "status": "unknown", "accepted": False, "message": "Нет ответа игры"})
with self.lock:
if len(self.actions) >= 64:
self.actions.pop(next(iter(self.actions)))
self.actions[(key, owner)] = {"req": (session, act, normalized), "receipt": receipt}
return receipt
def dispatch_action(self, key, session, act, value, done, box):
try:
current = self.view("network")
if not current.get("connected") or current.get("session") != session:
box["receipt"] = {"id": key, "status": "rejected", "accepted": False, "message": "Игровая сессия сменилась"}
return
self.transport(self.endpoint, f"chat /airdef panel action {key} {session} {act} {value}")
receipt = read_json(self.data / "panel-receipt-v1.json", 4096)
if receipt["id"] != key or type(receipt["accepted"]) is not bool:
raise ValueError("Receipt does not belong to this request")
accepted = receipt["accepted"]
box["receipt"] = {
"id": key,
"status": "accepted" if accepted else "rejected",
"accepted": accepted,
"message": str(receipt["message"]),
}
if accepted:
try:
self.poll()
except (OSError, ValueError, TypeError, KeyError):
pass
except (OSError, ValueError, TypeError, KeyError):
box["receipt"] = {"id": key, "status": "unknown", "accepted": False, "message": "Команда могла выполниться. Обновите карту."}
finally:
done.set()
+20
View File
@@ -262,6 +262,26 @@ class Handler(BaseHTTPRequestHandler):
if data is None:
raise APIError(HTTPStatus.NOT_FOUND, "Кадр отсутствует в сохранённой карте")
return self.reply(HTTPStatus.OK, data)
if (verb, path) == ("POST", "/api/action"):
if not launch:
raise APIError(HTTPStatus.FORBIDDEN, "Управление требует доступа оператора")
body = self.body()
key, session = body["id"], body["session"]
act, value = body["action"], body["value"]
if (
not isinstance(key, str)
or not TOKEN.fullmatch(key)
or not isinstance(session, str)
or not TOKEN.fullmatch(session)
or not isinstance(act, str)
):
raise ValueError("bad action payload")
try:
result = self.server.bridge.action(key, owner, session, act, value)
except ValueError as error:
raise APIError(HTTPStatus.CONFLICT, str(error)) from error
status = HTTPStatus.OK if result.get("accepted") or result.get("status") != "pending" else HTTPStatus.ACCEPTED
return self.reply(status, result)
if path == "/api/launch" or path.startswith("/api/launch/"):
if not launch:
raise APIError(HTTPStatus.FORBIDDEN, "Запуск требует доступа оператора")
+4
View File
@@ -140,6 +140,9 @@ dialog::backdrop { background: #02080dc9; }
.legend [data-layer="objects"] { accent-color: #a9baf6; }
.legend [data-layer="contacts"] { accent-color: #f0bf6a; }
.legend [data-layer="interceptors"] { accent-color: #b2e68f; }
.legend [data-layer="sites"] { accent-color: #ff9b52; }
#autostrike-toggle[aria-pressed="true"] { background: #234443; border-color: #3d6864; color: #d3fff3; }
#logistics-summary p { margin: .15rem 0; font-size: .82rem; }
.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)); }
@@ -148,6 +151,7 @@ dialog::backdrop { background: #02080dc9; }
#object-list [data-kind="object"] { --marker: #a9baf6; }
#object-list [data-kind="contact"] { --marker: #f0bf6a; }
#object-list [data-kind="interceptor"] { --marker: #b2e68f; }
#object-list [data-kind="site"] { --marker: #ff9b52; }
@media (max-width: 540px) {
.map-tools { gap: .5rem; }
.inline-field { font-size: .8rem; }
+66 -2
View File
@@ -69,7 +69,7 @@ async function api(path, {method = "GET", data} = {}) {
}
}
const groups = [["units", "unit"], ["objects", "object"], ["contacts", "contact"], ["interceptors", "interceptor"]];
const groups = [["units", "unit"], ["objects", "object"], ["contacts", "contact"], ["interceptors", "interceptor"], ["sites", "site"]];
const prefs = read("view", {layers: {}, views: {}, selected: null});
prefs.layers ||= {};
prefs.views ||= {};
@@ -81,7 +81,7 @@ let selected = prefs.selected, connected = false, http = false, polling = false,
let events = [], raids = [], raid = null, more = false, historyGeneration = 0, frameGeneration = 0, chainGeneration = 0;
let eventTimer, frameTimer, receiptTimer, latestRequest = read("launch-request", null), installPrompt;
let offlineEvents = [], offlineFrames = {}, offlineRaids = {raids: []};
let offlineTimelines = {}, selectedEvent = null, timelineGeneration = 0;
let offlineTimelines = {}, selectedEvent = null, timelineGeneration = 0, actionBusy = false;
const timelineRequests = new Map();
const timeline = createTimeline($("timeline-markers"), openEvent, time);
const viewKey = () => mapMode === "radar" ? `radar:${perspective}` : perspective;
@@ -185,12 +185,40 @@ function draw() {
if (frame.summary) status.push(`Сбито ${frame.summary.kills} · попаданий ${frame.summary.hits}`);
if (frame.summary?.planning) status.push("Игра готовит налёт");
if (frame.summary?.hold) status.push("Огонь запрещён");
if (frame.summary?.autoStrike) status.push("Автоудар вкл");
if (perspective === "enemy") status.push(`Донесений ${frame.contacts?.length || 0} · вылетов разведки ${frame.sorties?.length || 0}`);
if (perspective === "truth") status.push("Песочница · истинные позиции");
}
if (frame?.limited) status.push("Часть отметок за пределом отображения");
$("map-status").textContent = status.join(" · ");
const autoBtn = $("autostrike-toggle");
const showAuto = !historical && perspective === "network" && frame?.summary != null;
autoBtn.hidden = !showAuto;
if (showAuto) {
const autoOn = !!frame.summary.autoStrike;
autoBtn.setAttribute("aria-pressed", String(autoOn));
autoBtn.textContent = autoOn ? "Автоудар: вкл" : "Автоудар: выкл";
autoBtn.disabled = !auth?.permissions?.launch || !connected || !live?.session || actionBusy;
}
const logBox = $("logistics-summary");
if (!historical && perspective === "network" && frame?.logistics) {
const l = frame.logistics;
const rows = [
make("h3", "Снабжение и склады"),
paragraph(`Склады ${l.depots} · ТЗМ ${l.trucksBusy}/${l.trucks} · БК ${l.ammoTotal} · RM48U ${l.rm48uDepot}+${l.rm48uTruck} (в ПУ ${l.rm48uLoaded})`),
paragraph(`Ждут БК ${l.waitingAmmo} · ждут RM48U ${l.waitingRm48u} · перезарядка ${l.reloading}`),
];
if (l.kinds?.length) {
rows.push(paragraph(l.kinds.map(k => `${k.name}: ${k.depot + k.truck}`).join(" · ")));
}
logBox.replaceChildren(...rows);
logBox.hidden = false;
} else {
logBox.hidden = true;
}
const data = groups.flatMap(([group, kind]) => prefs.layers[group] === false ? [] : (frame?.[group] || [])
.map(row => ({row, kind, key: `${kind}:${row.id}`})));
const opened = data.find(item => item.key === selected);
@@ -247,7 +275,20 @@ function showObject(opened, frame) {
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.depotReach > 0) nodes.push(paragraph(`Зона прямой перезарядки · ${Math.round(row.depotReach)} бл.`));
if (row.supply) nodes.push(paragraph(`Снабжение · ${row.supply}`));
if (row.radius > 0) nodes.push(paragraph(`Область оценки · ±${Math.round(row.radius)} бл.`));
if (kind === "site") {
if (row.className) nodes.push(paragraph(`Тип · ${row.className}`));
if (row.accuracy) nodes.push(paragraph(`Точность · ${row.accuracy}`));
if (row.launches != null) nodes.push(paragraph(`Пусков замечено · ${row.launches}`));
if (row.aimed) nodes.push(paragraph("Ракета по ПУ уже в полёте"));
if (row.canStrike && !historical && perspective === "network" && auth?.permissions?.launch) {
const strikeBtn = button("Нанести удар", () => sendAction("strike", row.id));
strikeBtn.disabled = !connected || !live?.session || actionBusy;
nodes.push(strikeBtn);
}
}
if (row.target) nodes.push(button(`Контакт №${row.target}`, () => select(`contact:${row.target}`, true)));
if (row.source) {
const linked = frame?.units?.some(unit => unit.id === row.source);
@@ -792,6 +833,29 @@ $("confirm-launch").addEventListener("click", async () => {
}
});
$("cancel-launch").addEventListener("click", () => $("confirmation").close());
async function sendAction(action, value) {
if (!auth?.permissions?.launch || historical || !connected || !live?.session || actionBusy) return;
const id = Array.from(crypto.getRandomValues(new Uint8Array(16)), n => n.toString(16).padStart(2, "0")).join("");
actionBusy = true;
$("action-status").textContent = "Отправляем команду…";
draw();
try {
const result = await api("/action", {
method: "POST",
data: {id, session: live.session, action, value},
});
$("action-status").textContent = result?.message || "Команда отправлена";
poll();
} catch (error) {
$("action-status").textContent = error.message || "Ошибка отправки команды";
} finally {
actionBusy = false;
draw();
}
}
$("autostrike-toggle").addEventListener("click", () => {
sendAction("autostrike", activeFrame()?.summary?.autoStrike ? "off" : "on");
});
$("preset").addEventListener("change", () => {
applyDraft(catalog?.presets[Number($("preset").value)]);
write("draft", draft());
+4
View File
@@ -52,6 +52,7 @@
</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>
<button type="button" id="autostrike-toggle" hidden aria-pressed="false">Автоудар: выкл</button>
<div class="map-actions">
<button type="button" id="zoom-in" aria-label="Приблизить">+</button>
<button type="button" id="zoom-out" aria-label="Отдалить">−</button>
@@ -66,6 +67,7 @@
<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>
<label><input type="checkbox" data-layer="sites" checked> ПУ врага</label>
</div>
<div class="map-readout"><span id="map-source"></span><span id="map-status" role="status"></span></div>
</footer>
@@ -73,6 +75,8 @@
<aside class="side-panel">
<section id="live-panel" class="card">
<h2 class="panel-title">Объекты на карте</h2>
<div id="logistics-summary" class="subcard" hidden></div>
<p id="action-status" class="muted" role="status"></p>
<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 -1
View File
@@ -11,7 +11,7 @@ export function applyLiveUpdate(base, update) {
const result = {...mergeFields(base, update.change), revision: update.revision};
result.frame = mergeFields(base.frame, update.frameChange);
for (const [layer, {remove = [], upsert = [], order}] of Object.entries(update.frameChange.layers || {})) {
const entities = new Map(base.frame[layer].map(row => [row.id, row]));
const entities = new Map((base.frame[layer] || []).map(row => [row.id, row]));
for (const id of remove) entities.delete(id);
for (const entity of upsert) entities.set(entity.id, entity);
result.frame[layer] = order ? order.map(id => entities.get(id)) : [...entities.values()];
+9
View File
@@ -6,6 +6,7 @@ const styles = [
["objects", "object", "#a9baf6"],
["contacts", "contact", "#f0bf6a"],
["interceptors", "interceptor", "#b2e68f"],
["sites", "site", "#ff9b52"],
];
const clamp = (x, low, high) => Math.min(high, Math.max(low, x));
@@ -116,6 +117,14 @@ export function createMap(canvas, {onSelect, onView, onTerrain}) {
ctx.stroke();
ctx.setLineDash([]);
}
if (point.key === selected && row.depotReach > 0) {
ctx.beginPath();
ctx.arc(x, y, Math.min(380, row.depotReach * scale), 0, Math.PI * 2);
ctx.setLineDash([5, 5]);
ctx.strokeStyle = "#ffb85c";
ctx.stroke();
ctx.setLineDash([]);
}
}
const focus = visible.find(item => item.key === selected);
if (focus) {
+1 -1
View File
@@ -1,5 +1,5 @@
/* Cache only the public, versioned application shell. API responses are never cached. */
const CACHE = 'airdef-shell-v9';
const CACHE = 'airdef-shell-v10';
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);
+4
View File
@@ -90,6 +90,10 @@ export function drawSymbol(ctx, x, y, {kind, symbol, color = '#d6e5ea', selected
ctx.fillStyle = '#071219';
ctx.fillRect(-2, 3, 4, 6);
break;
case 'site':
shape([[0,-10],[10,0],[0,10],[-10,0]]);
line([-5,0],[5,0]); line([0,-5],[0,5]);
break;
default:
shape([[0,-11],[11,0],[0,11],[-11,0]]);
ctx.fillStyle = '#071219';