// Drone twin panel: the open job as a painting job a drone is flying. Set the launch point, upload a flight log (CSV), and see what the
// twin believes is painted, what is left, and what the log says about how the drone really flew. The heat map overlay is off by default.
// (Separate from the wall twin in twin.js, which fuses photos and video in millimetres.)
"use strict";
(() => {
const $ = (sel) => document.querySelector(sel);
const toggles = $("#layer-toggles"), stage = $("#stage"), anchor = $("#reasons");
if (!toggles || !stage || !anchor) return;
const st = { loaded: false, loading: false, info: null, jobId: null };
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
const num = (v) => { const n = parseFloat(v); return Number.isFinite(n) ? n : null; };
// overlay layer + switch
const chip = document.createElement("label");
chip.className = "chip";
chip.innerHTML = `Drone twin`;
toggles.appendChild(chip);
const box = chip.querySelector("input");
const img = document.createElement("img");
img.className = "layer off dtwin-layer";
img.alt = "";
img.dataset.layer = "dronetwin";
(document.querySelector('img.layer[data-layer="paint"]:not(.edge)') || $("#photo")).after(img);
// next sortie: the passes the belief still wants, drawn over the photo (own switch in the panel, off by default)
const NS = "http://www.w3.org/2000/svg";
const nextSvg = document.createElementNS(NS, "svg");
nextSvg.setAttribute("class", "layer dtwin-next");
nextSvg.setAttribute("preserveAspectRatio", "none");
nextSvg.style.display = "none";
img.after(nextSvg);
// marked pass: one line picked from the audit table, so a bad pass can be pointed at on the photo
const passSvg = document.createElementNS(NS, "svg");
passSvg.setAttribute("class", "layer dtwin-marks");
passSvg.setAttribute("preserveAspectRatio", "none");
passSvg.style.display = "none";
nextSvg.after(passSvg);
// panel
const panel = document.createElement("section");
panel.id = "dtwin-panel";
panel.innerHTML = `
Rows come from the sorties flown in this session; the twin's JSON keeps the summary.
Without a flight log the twin only knows the plan. A log adds what the drone really flew and how well; nothing here claims a wall is finished unless the belief says so and a camera has looked recently.
`;
anchor.parentNode.insertBefore(panel, anchor.nextSibling);
async function api(path, options = {}) {
const r = await fetch(path, options);
const body = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(body.error || r.statusText);
return body;
}
const j = () => (typeof job !== "undefined" && job ? job : null);
const ago = (sec) => (sec == null ? "never" : sec < 90 ? `${Math.round(sec)} s ago` : sec < 5400 ? `${Math.round(sec / 60)} min ago` : `${(sec / 3600).toFixed(1)} h ago`);
function render(info) {
const s = info.status, c = info.calibration || {};
const words = { complete: "Complete", another_sortie: "Another sortie needed", hand_finish: "Hand finish left", needs_look: "Needs a look" };
const cls = { complete: "ok", another_sortie: "warn", hand_finish: "warn", needs_look: "bad" }[s.verdict] || "";
$("#dt-status").hidden = false;
const au = info.spray_audit, arows = au && Array.isArray(au.passes) ? au.passes : [];
const starved = au ? (au.starved_passes || arows.filter((p) => (p.flags || []).includes("starved_end")).map((p) => p.id)) : [];
const heavy = au ? (au.heavy_passes || arows.filter((p) => (p.flags || []).includes("heavy_end")).map((p) => p.id)) : [];
const pct = (v) => Math.round((v || 0) * 100);
const action = {
complete: "Nothing to fly. Keep the last re-scan with the job and hand it over.",
another_sortie: "Fly the next sortie below, then upload a re-scan photo.",
needs_look: "Take a re-scan photo: the belief is old, or parts of the wall were never seen.",
hand_finish: "What is left is narrower than the fan: hand finish, then re-scan to confirm.",
}[s.verdict] || "";
const tol = 0.15 * (Number((info.setup || {}).standoff_mm) || 300); // ±15 % film budget, in mm of standoff
const sag = au && au.standoff_sag_mm != null ? Number(au.standoff_sag_mm) : null;
const sagPct = sag == null ? null : Math.max(2, Math.min(100, Math.round((sag / tol) * 100)));
const spray = sag == null ? "" : `
Spray push on the nozzle${au.reaction_n} N
40 ? "warn" : "ok"}" style="width:${sagPct}%">
sag ${sag} mm of ±${Math.round(tol)} mm budget${au.standoff_bias_mm ? ` · setpoint biased ${au.standoff_bias_mm} mm` : ""}
`;
const fixes = starved.length + heavy.length;
// when nearly every pass shares one fault, the count is useless and the cause is what matters: say it
const medSpeed = (() => {
const v = arows.map((p) => Number(p.speed_mm_s)).filter((x) => Number.isFinite(x) && x > 0).sort((a, b) => a - b);
return v.length ? v[Math.floor(v.length / 2)] : null;
})();
const share = (k) => arows.filter((p) => Number(p[k + "_share"] || 0) > 0.2).length;
const plan = Number(((au && au.design) || {}).speed_mm_s);
let diag = "";
if (arows.length >= 5 && plan > 0 && medSpeed) {
if (share("heavy") >= 0.7 * arows.length && plan > medSpeed) {
diag = `Almost every pass came out heavy: the log averages ${Math.round(medSpeed)} mm/s against the plan's ${Math.round(plan)} mm/s, so each metre got about ${(plan / medSpeed).toFixed(1)}× the paint it was planned for.`;
} else if (share("starved") >= 0.7 * arows.length && medSpeed > plan) {
diag = `Almost every pass came out thin: the log averages ${Math.round(medSpeed)} mm/s against the plan's ${Math.round(plan)} mm/s, so each metre got about ${(medSpeed / plan).toFixed(1)}× too much speed for full film.`;
}
}
const diagEl = diag ? `
${esc(diag)}
` : "";
const onT = Number(au && au.on_target_pct);
const audit = au ? `